blob: 873159cc7cdf7fcd3d6e31f548c4eaddd33f16fa [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))
266 saved_cursor.col += ind_len - (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 }
1016 l = lead_repl_len - (endp - p);
1017 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 Moolenaare3226be2005-12-18 22:10:00 +00002150del_bytes(count, fixpos, use_delcombine)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002151 long count;
2152 int fixpos;
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;
2161
2162 oldp = ml_get(lnum);
2163 oldlen = (int)STRLEN(oldp);
2164
2165 /*
2166 * Can't do anything when the cursor is on the NUL after the line.
2167 */
2168 if (col >= oldlen)
2169 return FAIL;
2170
2171#ifdef FEAT_MBYTE
2172 /* If 'delcombine' is set and deleting (less than) one character, only
2173 * delete the last combining character. */
Bram Moolenaare3226be2005-12-18 22:10:00 +00002174 if (p_deco && use_delcombine && enc_utf8
2175 && utfc_ptr2len(oldp + col) >= count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002176 {
Bram Moolenaar362e1a32006-03-06 23:29:24 +00002177 int cc[MAX_MCO];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002178 int n;
2179
Bram Moolenaar362e1a32006-03-06 23:29:24 +00002180 (void)utfc_ptr2char(oldp + col, cc);
2181 if (cc[0] != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002182 {
2183 /* Find the last composing char, there can be several. */
2184 n = col;
2185 do
2186 {
2187 col = n;
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002188 count = utf_ptr2len(oldp + n);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002189 n += count;
2190 } while (UTF_COMPOSINGLIKE(oldp + col, oldp + n));
2191 fixpos = 0;
2192 }
2193 }
2194#endif
2195
2196 /*
2197 * When count is too big, reduce it.
2198 */
2199 movelen = (long)oldlen - (long)col - count + 1; /* includes trailing NUL */
2200 if (movelen <= 1)
2201 {
2202 /*
2203 * If we just took off the last character of a non-blank line, and
2204 * fixpos is TRUE, we don't want to end up positioned at the NUL.
2205 */
2206 if (col > 0 && fixpos)
2207 {
2208 --curwin->w_cursor.col;
2209#ifdef FEAT_VIRTUALEDIT
2210 curwin->w_cursor.coladd = 0;
2211#endif
2212#ifdef FEAT_MBYTE
2213 if (has_mbyte)
2214 curwin->w_cursor.col -=
2215 (*mb_head_off)(oldp, oldp + curwin->w_cursor.col);
2216#endif
2217 }
2218 count = oldlen - col;
2219 movelen = 1;
2220 }
2221
2222 /*
2223 * If the old line has been allocated the deletion can be done in the
2224 * existing line. Otherwise a new line has to be allocated
2225 */
2226 was_alloced = ml_line_alloced(); /* check if oldp was allocated */
2227#ifdef FEAT_NETBEANS_INTG
2228 if (was_alloced && usingNetbeans)
2229 netbeans_removed(curbuf, lnum, col, count);
2230 /* else is handled by ml_replace() */
2231#endif
2232 if (was_alloced)
2233 newp = oldp; /* use same allocated memory */
2234 else
2235 { /* need to allocate a new line */
2236 newp = alloc((unsigned)(oldlen + 1 - count));
2237 if (newp == NULL)
2238 return FAIL;
2239 mch_memmove(newp, oldp, (size_t)col);
2240 }
2241 mch_memmove(newp + col, oldp + col + count, (size_t)movelen);
2242 if (!was_alloced)
2243 ml_replace(lnum, newp, FALSE);
2244
2245 /* mark the buffer as changed and prepare for displaying */
2246 changed_bytes(lnum, curwin->w_cursor.col);
2247
2248 return OK;
2249}
2250
2251/*
2252 * Delete from cursor to end of line.
2253 * Caller must have prepared for undo.
2254 *
2255 * return FAIL for failure, OK otherwise
2256 */
2257 int
2258truncate_line(fixpos)
2259 int fixpos; /* if TRUE fix the cursor position when done */
2260{
2261 char_u *newp;
2262 linenr_T lnum = curwin->w_cursor.lnum;
2263 colnr_T col = curwin->w_cursor.col;
2264
2265 if (col == 0)
2266 newp = vim_strsave((char_u *)"");
2267 else
2268 newp = vim_strnsave(ml_get(lnum), col);
2269
2270 if (newp == NULL)
2271 return FAIL;
2272
2273 ml_replace(lnum, newp, FALSE);
2274
2275 /* mark the buffer as changed and prepare for displaying */
2276 changed_bytes(lnum, curwin->w_cursor.col);
2277
2278 /*
2279 * If "fixpos" is TRUE we don't want to end up positioned at the NUL.
2280 */
2281 if (fixpos && curwin->w_cursor.col > 0)
2282 --curwin->w_cursor.col;
2283
2284 return OK;
2285}
2286
2287/*
2288 * Delete "nlines" lines at the cursor.
2289 * Saves the lines for undo first if "undo" is TRUE.
2290 */
2291 void
2292del_lines(nlines, undo)
2293 long nlines; /* number of lines to delete */
2294 int undo; /* if TRUE, prepare for undo */
2295{
2296 long n;
2297
2298 if (nlines <= 0)
2299 return;
2300
2301 /* save the deleted lines for undo */
2302 if (undo && u_savedel(curwin->w_cursor.lnum, nlines) == FAIL)
2303 return;
2304
2305 for (n = 0; n < nlines; )
2306 {
2307 if (curbuf->b_ml.ml_flags & ML_EMPTY) /* nothing to delete */
2308 break;
2309
2310 ml_delete(curwin->w_cursor.lnum, TRUE);
2311 ++n;
2312
2313 /* If we delete the last line in the file, stop */
2314 if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
2315 break;
2316 }
2317 /* adjust marks, mark the buffer as changed and prepare for displaying */
2318 deleted_lines_mark(curwin->w_cursor.lnum, n);
2319
2320 curwin->w_cursor.col = 0;
2321 check_cursor_lnum();
2322}
2323
2324 int
2325gchar_pos(pos)
2326 pos_T *pos;
2327{
2328 char_u *ptr = ml_get_pos(pos);
2329
2330#ifdef FEAT_MBYTE
2331 if (has_mbyte)
2332 return (*mb_ptr2char)(ptr);
2333#endif
2334 return (int)*ptr;
2335}
2336
2337 int
2338gchar_cursor()
2339{
2340#ifdef FEAT_MBYTE
2341 if (has_mbyte)
2342 return (*mb_ptr2char)(ml_get_cursor());
2343#endif
2344 return (int)*ml_get_cursor();
2345}
2346
2347/*
2348 * Write a character at the current cursor position.
2349 * It is directly written into the block.
2350 */
2351 void
2352pchar_cursor(c)
2353 int c;
2354{
2355 *(ml_get_buf(curbuf, curwin->w_cursor.lnum, TRUE)
2356 + curwin->w_cursor.col) = c;
2357}
2358
2359#if 0 /* not used */
2360/*
2361 * Put *pos at end of current buffer
2362 */
2363 void
2364goto_endofbuf(pos)
2365 pos_T *pos;
2366{
2367 char_u *p;
2368
2369 pos->lnum = curbuf->b_ml.ml_line_count;
2370 pos->col = 0;
2371 p = ml_get(pos->lnum);
2372 while (*p++)
2373 ++pos->col;
2374}
2375#endif
2376
2377/*
2378 * When extra == 0: Return TRUE if the cursor is before or on the first
2379 * non-blank in the line.
2380 * When extra == 1: Return TRUE if the cursor is before the first non-blank in
2381 * the line.
2382 */
2383 int
2384inindent(extra)
2385 int extra;
2386{
2387 char_u *ptr;
2388 colnr_T col;
2389
2390 for (col = 0, ptr = ml_get_curline(); vim_iswhite(*ptr); ++col)
2391 ++ptr;
2392 if (col >= curwin->w_cursor.col + extra)
2393 return TRUE;
2394 else
2395 return FALSE;
2396}
2397
2398/*
2399 * Skip to next part of an option argument: Skip space and comma.
2400 */
2401 char_u *
2402skip_to_option_part(p)
2403 char_u *p;
2404{
2405 if (*p == ',')
2406 ++p;
2407 while (*p == ' ')
2408 ++p;
2409 return p;
2410}
2411
2412/*
2413 * changed() is called when something in the current buffer is changed.
2414 *
2415 * Most often called through changed_bytes() and changed_lines(), which also
2416 * mark the area of the display to be redrawn.
2417 */
2418 void
2419changed()
2420{
2421#if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
2422 /* The text of the preediting area is inserted, but this doesn't
2423 * mean a change of the buffer yet. That is delayed until the
2424 * text is committed. (this means preedit becomes empty) */
2425 if (im_is_preediting() && !xim_changed_while_preediting)
2426 return;
2427 xim_changed_while_preediting = FALSE;
2428#endif
2429
2430 if (!curbuf->b_changed)
2431 {
2432 int save_msg_scroll = msg_scroll;
2433
2434 change_warning(0);
2435 /* Create a swap file if that is wanted.
2436 * Don't do this for "nofile" and "nowrite" buffer types. */
2437 if (curbuf->b_may_swap
2438#ifdef FEAT_QUICKFIX
2439 && !bt_dontwrite(curbuf)
2440#endif
2441 )
2442 {
2443 ml_open_file(curbuf);
2444
2445 /* The ml_open_file() can cause an ATTENTION message.
2446 * Wait two seconds, to make sure the user reads this unexpected
2447 * message. Since we could be anywhere, call wait_return() now,
2448 * and don't let the emsg() set msg_scroll. */
2449 if (need_wait_return && emsg_silent == 0)
2450 {
2451 out_flush();
2452 ui_delay(2000L, TRUE);
2453 wait_return(TRUE);
2454 msg_scroll = save_msg_scroll;
2455 }
2456 }
2457 curbuf->b_changed = TRUE;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002458 ml_setflags(curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002459#ifdef FEAT_WINDOWS
2460 check_status(curbuf);
Bram Moolenaar997fb4b2006-02-17 21:53:23 +00002461 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002462#endif
2463#ifdef FEAT_TITLE
2464 need_maketitle = TRUE; /* set window title later */
2465#endif
2466 }
2467 ++curbuf->b_changedtick;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002468}
2469
Bram Moolenaardba8a912005-04-24 22:08:39 +00002470static void changedOneline __ARGS((buf_T *buf, linenr_T lnum));
2471static void changed_lines_buf __ARGS((buf_T *buf, linenr_T lnum, linenr_T lnume, long xtra));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002472static void changed_common __ARGS((linenr_T lnum, colnr_T col, linenr_T lnume, long xtra));
2473
2474/*
2475 * Changed bytes within a single line for the current buffer.
2476 * - marks the windows on this buffer to be redisplayed
2477 * - marks the buffer changed by calling changed()
2478 * - invalidates cached values
2479 */
2480 void
2481changed_bytes(lnum, col)
2482 linenr_T lnum;
2483 colnr_T col;
2484{
Bram Moolenaardba8a912005-04-24 22:08:39 +00002485 changedOneline(curbuf, lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002486 changed_common(lnum, col, lnum + 1, 0L);
Bram Moolenaardba8a912005-04-24 22:08:39 +00002487
2488#ifdef FEAT_DIFF
2489 /* Diff highlighting in other diff windows may need to be updated too. */
2490 if (curwin->w_p_diff)
2491 {
2492 win_T *wp;
2493 linenr_T wlnum;
2494
2495 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2496 if (wp->w_p_diff && wp != curwin)
2497 {
2498 redraw_win_later(wp, VALID);
2499 wlnum = diff_lnum_win(lnum, wp);
2500 if (wlnum > 0)
2501 changedOneline(wp->w_buffer, wlnum);
2502 }
2503 }
2504#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002505}
2506
2507 static void
Bram Moolenaardba8a912005-04-24 22:08:39 +00002508changedOneline(buf, lnum)
2509 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002510 linenr_T lnum;
2511{
Bram Moolenaardba8a912005-04-24 22:08:39 +00002512 if (buf->b_mod_set)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002513 {
2514 /* find the maximum area that must be redisplayed */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002515 if (lnum < buf->b_mod_top)
2516 buf->b_mod_top = lnum;
2517 else if (lnum >= buf->b_mod_bot)
2518 buf->b_mod_bot = lnum + 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002519 }
2520 else
2521 {
2522 /* set the area that must be redisplayed to one line */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002523 buf->b_mod_set = TRUE;
2524 buf->b_mod_top = lnum;
2525 buf->b_mod_bot = lnum + 1;
2526 buf->b_mod_xlines = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002527 }
2528}
2529
2530/*
2531 * Appended "count" lines below line "lnum" in the current buffer.
2532 * Must be called AFTER the change and after mark_adjust().
2533 * Takes care of marking the buffer to be redrawn and sets the changed flag.
2534 */
2535 void
2536appended_lines(lnum, count)
2537 linenr_T lnum;
2538 long count;
2539{
2540 changed_lines(lnum + 1, 0, lnum + 1, count);
2541}
2542
2543/*
2544 * Like appended_lines(), but adjust marks first.
2545 */
2546 void
2547appended_lines_mark(lnum, count)
2548 linenr_T lnum;
2549 long count;
2550{
2551 mark_adjust(lnum + 1, (linenr_T)MAXLNUM, count, 0L);
2552 changed_lines(lnum + 1, 0, lnum + 1, count);
2553}
2554
2555/*
2556 * Deleted "count" lines at line "lnum" in the current buffer.
2557 * Must be called AFTER the change and after mark_adjust().
2558 * Takes care of marking the buffer to be redrawn and sets the changed flag.
2559 */
2560 void
2561deleted_lines(lnum, count)
2562 linenr_T lnum;
2563 long count;
2564{
2565 changed_lines(lnum, 0, lnum + count, -count);
2566}
2567
2568/*
2569 * Like deleted_lines(), but adjust marks first.
2570 */
2571 void
2572deleted_lines_mark(lnum, count)
2573 linenr_T lnum;
2574 long count;
2575{
2576 mark_adjust(lnum, (linenr_T)(lnum + count - 1), (long)MAXLNUM, -count);
2577 changed_lines(lnum, 0, lnum + count, -count);
2578}
2579
2580/*
2581 * Changed lines for the current buffer.
2582 * Must be called AFTER the change and after mark_adjust().
2583 * - mark the buffer changed by calling changed()
2584 * - mark the windows on this buffer to be redisplayed
2585 * - invalidate cached values
2586 * "lnum" is the first line that needs displaying, "lnume" the first line
2587 * below the changed lines (BEFORE the change).
2588 * When only inserting lines, "lnum" and "lnume" are equal.
2589 * Takes care of calling changed() and updating b_mod_*.
2590 */
2591 void
2592changed_lines(lnum, col, lnume, xtra)
2593 linenr_T lnum; /* first line with change */
2594 colnr_T col; /* column in first line with change */
2595 linenr_T lnume; /* line below last changed line */
2596 long xtra; /* number of extra lines (negative when deleting) */
2597{
Bram Moolenaardba8a912005-04-24 22:08:39 +00002598 changed_lines_buf(curbuf, lnum, lnume, xtra);
2599
2600#ifdef FEAT_DIFF
2601 if (xtra == 0 && curwin->w_p_diff)
2602 {
2603 /* When the number of lines doesn't change then mark_adjust() isn't
2604 * called and other diff buffers still need to be marked for
2605 * displaying. */
2606 win_T *wp;
2607 linenr_T wlnum;
2608
2609 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2610 if (wp->w_p_diff && wp != curwin)
2611 {
2612 redraw_win_later(wp, VALID);
2613 wlnum = diff_lnum_win(lnum, wp);
2614 if (wlnum > 0)
2615 changed_lines_buf(wp->w_buffer, wlnum,
2616 lnume - lnum + wlnum, 0L);
2617 }
2618 }
2619#endif
2620
2621 changed_common(lnum, col, lnume, xtra);
2622}
2623
2624 static void
2625changed_lines_buf(buf, lnum, lnume, xtra)
2626 buf_T *buf;
2627 linenr_T lnum; /* first line with change */
2628 linenr_T lnume; /* line below last changed line */
2629 long xtra; /* number of extra lines (negative when deleting) */
2630{
2631 if (buf->b_mod_set)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002632 {
2633 /* find the maximum area that must be redisplayed */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002634 if (lnum < buf->b_mod_top)
2635 buf->b_mod_top = lnum;
2636 if (lnum < buf->b_mod_bot)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002637 {
2638 /* adjust old bot position for xtra lines */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002639 buf->b_mod_bot += xtra;
2640 if (buf->b_mod_bot < lnum)
2641 buf->b_mod_bot = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002642 }
Bram Moolenaardba8a912005-04-24 22:08:39 +00002643 if (lnume + xtra > buf->b_mod_bot)
2644 buf->b_mod_bot = lnume + xtra;
2645 buf->b_mod_xlines += xtra;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002646 }
2647 else
2648 {
2649 /* set the area that must be redisplayed */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002650 buf->b_mod_set = TRUE;
2651 buf->b_mod_top = lnum;
2652 buf->b_mod_bot = lnume + xtra;
2653 buf->b_mod_xlines = xtra;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002654 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002655}
2656
2657 static void
2658changed_common(lnum, col, lnume, xtra)
2659 linenr_T lnum;
2660 colnr_T col;
2661 linenr_T lnume;
2662 long xtra;
2663{
2664 win_T *wp;
2665 int i;
2666#ifdef FEAT_JUMPLIST
2667 int cols;
2668 pos_T *p;
2669 int add;
2670#endif
2671
2672 /* mark the buffer as modified */
2673 changed();
2674
2675 /* set the '. mark */
2676 if (!cmdmod.keepjumps)
2677 {
2678 curbuf->b_last_change.lnum = lnum;
2679 curbuf->b_last_change.col = col;
2680
2681#ifdef FEAT_JUMPLIST
2682 /* Create a new entry if a new undo-able change was started or we
2683 * don't have an entry yet. */
2684 if (curbuf->b_new_change || curbuf->b_changelistlen == 0)
2685 {
2686 if (curbuf->b_changelistlen == 0)
2687 add = TRUE;
2688 else
2689 {
2690 /* Don't create a new entry when the line number is the same
2691 * as the last one and the column is not too far away. Avoids
2692 * creating many entries for typing "xxxxx". */
2693 p = &curbuf->b_changelist[curbuf->b_changelistlen - 1];
2694 if (p->lnum != lnum)
2695 add = TRUE;
2696 else
2697 {
2698 cols = comp_textwidth(FALSE);
2699 if (cols == 0)
2700 cols = 79;
2701 add = (p->col + cols < col || col + cols < p->col);
2702 }
2703 }
2704 if (add)
2705 {
2706 /* This is the first of a new sequence of undo-able changes
2707 * and it's at some distance of the last change. Use a new
2708 * position in the changelist. */
2709 curbuf->b_new_change = FALSE;
2710
2711 if (curbuf->b_changelistlen == JUMPLISTSIZE)
2712 {
2713 /* changelist is full: remove oldest entry */
2714 curbuf->b_changelistlen = JUMPLISTSIZE - 1;
2715 mch_memmove(curbuf->b_changelist, curbuf->b_changelist + 1,
2716 sizeof(pos_T) * (JUMPLISTSIZE - 1));
2717 FOR_ALL_WINDOWS(wp)
2718 {
2719 /* Correct position in changelist for other windows on
2720 * this buffer. */
2721 if (wp->w_buffer == curbuf && wp->w_changelistidx > 0)
2722 --wp->w_changelistidx;
2723 }
2724 }
2725 FOR_ALL_WINDOWS(wp)
2726 {
2727 /* For other windows, if the position in the changelist is
2728 * at the end it stays at the end. */
2729 if (wp->w_buffer == curbuf
2730 && wp->w_changelistidx == curbuf->b_changelistlen)
2731 ++wp->w_changelistidx;
2732 }
2733 ++curbuf->b_changelistlen;
2734 }
2735 }
2736 curbuf->b_changelist[curbuf->b_changelistlen - 1] =
2737 curbuf->b_last_change;
2738 /* The current window is always after the last change, so that "g,"
2739 * takes you back to it. */
2740 curwin->w_changelistidx = curbuf->b_changelistlen;
2741#endif
2742 }
2743
2744 FOR_ALL_WINDOWS(wp)
2745 {
2746 if (wp->w_buffer == curbuf)
2747 {
2748 /* Mark this window to be redrawn later. */
2749 if (wp->w_redr_type < VALID)
2750 wp->w_redr_type = VALID;
2751
2752 /* Check if a change in the buffer has invalidated the cached
2753 * values for the cursor. */
2754#ifdef FEAT_FOLDING
2755 /*
2756 * Update the folds for this window. Can't postpone this, because
2757 * a following operator might work on the whole fold: ">>dd".
2758 */
2759 foldUpdate(wp, lnum, lnume + xtra - 1);
2760
2761 /* The change may cause lines above or below the change to become
2762 * included in a fold. Set lnum/lnume to the first/last line that
2763 * might be displayed differently.
2764 * Set w_cline_folded here as an efficient way to update it when
2765 * inserting lines just above a closed fold. */
2766 i = hasFoldingWin(wp, lnum, &lnum, NULL, FALSE, NULL);
2767 if (wp->w_cursor.lnum == lnum)
2768 wp->w_cline_folded = i;
2769 i = hasFoldingWin(wp, lnume, NULL, &lnume, FALSE, NULL);
2770 if (wp->w_cursor.lnum == lnume)
2771 wp->w_cline_folded = i;
2772
2773 /* If the changed line is in a range of previously folded lines,
2774 * compare with the first line in that range. */
2775 if (wp->w_cursor.lnum <= lnum)
2776 {
2777 i = find_wl_entry(wp, lnum);
2778 if (i >= 0 && wp->w_cursor.lnum > wp->w_lines[i].wl_lnum)
2779 changed_line_abv_curs_win(wp);
2780 }
2781#endif
2782
2783 if (wp->w_cursor.lnum > lnum)
2784 changed_line_abv_curs_win(wp);
2785 else if (wp->w_cursor.lnum == lnum && wp->w_cursor.col >= col)
2786 changed_cline_bef_curs_win(wp);
2787 if (wp->w_botline >= lnum)
2788 {
2789 /* Assume that botline doesn't change (inserted lines make
2790 * other lines scroll down below botline). */
2791 approximate_botline_win(wp);
2792 }
2793
2794 /* Check if any w_lines[] entries have become invalid.
2795 * For entries below the change: Correct the lnums for
2796 * inserted/deleted lines. Makes it possible to stop displaying
2797 * after the change. */
2798 for (i = 0; i < wp->w_lines_valid; ++i)
2799 if (wp->w_lines[i].wl_valid)
2800 {
2801 if (wp->w_lines[i].wl_lnum >= lnum)
2802 {
2803 if (wp->w_lines[i].wl_lnum < lnume)
2804 {
2805 /* line included in change */
2806 wp->w_lines[i].wl_valid = FALSE;
2807 }
2808 else if (xtra != 0)
2809 {
2810 /* line below change */
2811 wp->w_lines[i].wl_lnum += xtra;
2812#ifdef FEAT_FOLDING
2813 wp->w_lines[i].wl_lastlnum += xtra;
2814#endif
2815 }
2816 }
2817#ifdef FEAT_FOLDING
2818 else if (wp->w_lines[i].wl_lastlnum >= lnum)
2819 {
2820 /* change somewhere inside this range of folded lines,
2821 * may need to be redrawn */
2822 wp->w_lines[i].wl_valid = FALSE;
2823 }
2824#endif
2825 }
2826 }
2827 }
2828
2829 /* Call update_screen() later, which checks out what needs to be redrawn,
2830 * since it notices b_mod_set and then uses b_mod_*. */
2831 if (must_redraw < VALID)
2832 must_redraw = VALID;
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002833
2834#ifdef FEAT_AUTOCMD
2835 /* when the cursor line is changed always trigger CursorMoved */
2836 if (lnum <= curwin->w_cursor.lnum && lnume > curwin->w_cursor.lnum)
2837 last_cursormoved.lnum = 0;
2838#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002839}
2840
2841/*
2842 * unchanged() is called when the changed flag must be reset for buffer 'buf'
2843 */
2844 void
2845unchanged(buf, ff)
2846 buf_T *buf;
2847 int ff; /* also reset 'fileformat' */
2848{
2849 if (buf->b_changed || (ff && file_ff_differs(buf)))
2850 {
2851 buf->b_changed = 0;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002852 ml_setflags(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002853 if (ff)
2854 save_file_ff(buf);
2855#ifdef FEAT_WINDOWS
2856 check_status(buf);
Bram Moolenaar997fb4b2006-02-17 21:53:23 +00002857 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002858#endif
2859#ifdef FEAT_TITLE
2860 need_maketitle = TRUE; /* set window title later */
2861#endif
2862 }
2863 ++buf->b_changedtick;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002864#ifdef FEAT_NETBEANS_INTG
2865 netbeans_unmodified(buf);
2866#endif
2867}
2868
2869#if defined(FEAT_WINDOWS) || defined(PROTO)
2870/*
2871 * check_status: called when the status bars for the buffer 'buf'
2872 * need to be updated
2873 */
2874 void
2875check_status(buf)
2876 buf_T *buf;
2877{
2878 win_T *wp;
2879
2880 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2881 if (wp->w_buffer == buf && wp->w_status_height)
2882 {
2883 wp->w_redr_status = TRUE;
2884 if (must_redraw < VALID)
2885 must_redraw = VALID;
2886 }
2887}
2888#endif
2889
2890/*
2891 * If the file is readonly, give a warning message with the first change.
2892 * Don't do this for autocommands.
2893 * Don't use emsg(), because it flushes the macro buffer.
Bram Moolenaard5cdbeb2005-10-10 20:59:28 +00002894 * If we have undone all changes b_changed will be FALSE, but "b_did_warn"
Bram Moolenaar071d4272004-06-13 20:20:40 +00002895 * will be TRUE.
2896 */
2897 void
2898change_warning(col)
2899 int col; /* column for message; non-zero when in insert
2900 mode and 'showmode' is on */
2901{
2902 if (curbuf->b_did_warn == FALSE
2903 && curbufIsChanged() == 0
2904#ifdef FEAT_AUTOCMD
2905 && !autocmd_busy
2906#endif
2907 && curbuf->b_p_ro)
2908 {
2909#ifdef FEAT_AUTOCMD
2910 apply_autocmds(EVENT_FILECHANGEDRO, NULL, NULL, FALSE, curbuf);
2911 if (!curbuf->b_p_ro)
2912 return;
2913#endif
2914 /*
2915 * Do what msg() does, but with a column offset if the warning should
2916 * be after the mode message.
2917 */
2918 msg_start();
2919 if (msg_row == Rows - 1)
2920 msg_col = col;
Bram Moolenaar2df6dcc2004-07-12 15:53:54 +00002921 msg_source(hl_attr(HLF_W));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002922 MSG_PUTS_ATTR(_("W10: Warning: Changing a readonly file"),
2923 hl_attr(HLF_W) | MSG_HIST);
2924 msg_clr_eos();
2925 (void)msg_end();
2926 if (msg_silent == 0 && !silent_mode)
2927 {
2928 out_flush();
2929 ui_delay(1000L, TRUE); /* give the user time to think about it */
2930 }
2931 curbuf->b_did_warn = TRUE;
2932 redraw_cmdline = FALSE; /* don't redraw and erase the message */
2933 if (msg_row < Rows - 1)
2934 showmode();
2935 }
2936}
2937
2938/*
2939 * Ask for a reply from the user, a 'y' or a 'n'.
2940 * No other characters are accepted, the message is repeated until a valid
2941 * reply is entered or CTRL-C is hit.
2942 * If direct is TRUE, don't use vgetc() but ui_inchar(), don't get characters
2943 * from any buffers but directly from the user.
2944 *
2945 * return the 'y' or 'n'
2946 */
2947 int
2948ask_yesno(str, direct)
2949 char_u *str;
2950 int direct;
2951{
2952 int r = ' ';
2953 int save_State = State;
2954
2955 if (exiting) /* put terminal in raw mode for this question */
2956 settmode(TMODE_RAW);
2957 ++no_wait_return;
2958#ifdef USE_ON_FLY_SCROLL
2959 dont_scroll = TRUE; /* disallow scrolling here */
2960#endif
2961 State = CONFIRM; /* mouse behaves like with :confirm */
2962#ifdef FEAT_MOUSE
2963 setmouse(); /* disables mouse for xterm */
2964#endif
2965 ++no_mapping;
2966 ++allow_keys; /* no mapping here, but recognize keys */
2967
2968 while (r != 'y' && r != 'n')
2969 {
2970 /* same highlighting as for wait_return */
2971 smsg_attr(hl_attr(HLF_R), (char_u *)"%s (y/n)?", str);
2972 if (direct)
2973 r = get_keystroke();
2974 else
2975 r = safe_vgetc();
2976 if (r == Ctrl_C || r == ESC)
2977 r = 'n';
2978 msg_putchar(r); /* show what you typed */
2979 out_flush();
2980 }
2981 --no_wait_return;
2982 State = save_State;
2983#ifdef FEAT_MOUSE
2984 setmouse();
2985#endif
2986 --no_mapping;
2987 --allow_keys;
2988
2989 return r;
2990}
2991
2992/*
2993 * Get a key stroke directly from the user.
2994 * Ignores mouse clicks and scrollbar events, except a click for the left
2995 * button (used at the more prompt).
2996 * Doesn't use vgetc(), because it syncs undo and eats mapped characters.
2997 * Disadvantage: typeahead is ignored.
2998 * Translates the interrupt character for unix to ESC.
2999 */
3000 int
3001get_keystroke()
3002{
3003#define CBUFLEN 151
3004 char_u buf[CBUFLEN];
3005 int len = 0;
3006 int n;
3007 int save_mapped_ctrl_c = mapped_ctrl_c;
3008
3009 mapped_ctrl_c = FALSE; /* mappings are not used here */
3010 for (;;)
3011 {
3012 cursor_on();
3013 out_flush();
3014
3015 /* First time: blocking wait. Second time: wait up to 100ms for a
3016 * terminal code to complete. Leave some room for check_termcode() to
3017 * insert a key code into (max 5 chars plus NUL). And
3018 * fix_input_buffer() can triple the number of bytes. */
3019 n = ui_inchar(buf + len, (CBUFLEN - 6 - len) / 3,
3020 len == 0 ? -1L : 100L, 0);
3021 if (n > 0)
3022 {
3023 /* Replace zero and CSI by a special key code. */
3024 n = fix_input_buffer(buf + len, n, FALSE);
3025 len += n;
3026 }
3027
3028 /* incomplete termcode: get more characters */
3029 if ((n = check_termcode(1, buf, len)) < 0)
3030 continue;
3031 /* found a termcode: adjust length */
3032 if (n > 0)
3033 len = n;
3034 if (len == 0) /* nothing typed yet */
3035 continue;
3036
3037 /* Handle modifier and/or special key code. */
3038 n = buf[0];
3039 if (n == K_SPECIAL)
3040 {
3041 n = TO_SPECIAL(buf[1], buf[2]);
3042 if (buf[1] == KS_MODIFIER
3043 || n == K_IGNORE
3044#ifdef FEAT_MOUSE
3045 || n == K_LEFTMOUSE_NM
3046 || n == K_LEFTDRAG
3047 || n == K_LEFTRELEASE
3048 || n == K_LEFTRELEASE_NM
3049 || n == K_MIDDLEMOUSE
3050 || n == K_MIDDLEDRAG
3051 || n == K_MIDDLERELEASE
3052 || n == K_RIGHTMOUSE
3053 || n == K_RIGHTDRAG
3054 || n == K_RIGHTRELEASE
3055 || n == K_MOUSEDOWN
3056 || n == K_MOUSEUP
3057 || n == K_X1MOUSE
3058 || n == K_X1DRAG
3059 || n == K_X1RELEASE
3060 || n == K_X2MOUSE
3061 || n == K_X2DRAG
3062 || n == K_X2RELEASE
3063# ifdef FEAT_GUI
3064 || n == K_VER_SCROLLBAR
3065 || n == K_HOR_SCROLLBAR
3066# endif
3067#endif
3068 )
3069 {
3070 if (buf[1] == KS_MODIFIER)
3071 mod_mask = buf[2];
3072 len -= 3;
3073 if (len > 0)
3074 mch_memmove(buf, buf + 3, (size_t)len);
3075 continue;
3076 }
3077 }
3078#ifdef FEAT_MBYTE
3079 if (has_mbyte)
3080 {
3081 if (MB_BYTE2LEN(n) > len)
3082 continue; /* more bytes to get */
3083 buf[len >= CBUFLEN ? CBUFLEN - 1 : len] = NUL;
3084 n = (*mb_ptr2char)(buf);
3085 }
3086#endif
3087#ifdef UNIX
3088 if (n == intr_char)
3089 n = ESC;
3090#endif
3091 break;
3092 }
3093
3094 mapped_ctrl_c = save_mapped_ctrl_c;
3095 return n;
3096}
3097
3098/*
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003099 * Get a number from the user.
3100 * When "mouse_used" is not NULL allow using the mouse.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003101 */
3102 int
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003103get_number(colon, mouse_used)
3104 int colon; /* allow colon to abort */
3105 int *mouse_used;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003106{
3107 int n = 0;
3108 int c;
3109
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003110 if (mouse_used != NULL)
3111 *mouse_used = FALSE;
3112
Bram Moolenaar071d4272004-06-13 20:20:40 +00003113 /* When not printing messages, the user won't know what to type, return a
3114 * zero (as if CR was hit). */
3115 if (msg_silent != 0)
3116 return 0;
3117
3118#ifdef USE_ON_FLY_SCROLL
3119 dont_scroll = TRUE; /* disallow scrolling here */
3120#endif
3121 ++no_mapping;
3122 ++allow_keys; /* no mapping here, but recognize keys */
3123 for (;;)
3124 {
3125 windgoto(msg_row, msg_col);
3126 c = safe_vgetc();
3127 if (VIM_ISDIGIT(c))
3128 {
3129 n = n * 10 + c - '0';
3130 msg_putchar(c);
3131 }
3132 else if (c == K_DEL || c == K_KDEL || c == K_BS || c == Ctrl_H)
3133 {
3134 n /= 10;
3135 MSG_PUTS("\b \b");
3136 }
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003137#ifdef FEAT_MOUSE
3138 else if (mouse_used != NULL && c == K_LEFTMOUSE)
3139 {
3140 *mouse_used = TRUE;
3141 n = mouse_row + 1;
3142 break;
3143 }
3144#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003145 else if (n == 0 && c == ':' && colon)
3146 {
3147 stuffcharReadbuff(':');
3148 if (!exmode_active)
3149 cmdline_row = msg_row;
3150 skip_redraw = TRUE; /* skip redraw once */
3151 do_redraw = FALSE;
3152 break;
3153 }
3154 else if (c == CAR || c == NL || c == Ctrl_C || c == ESC)
3155 break;
3156 }
3157 --no_mapping;
3158 --allow_keys;
3159 return n;
3160}
3161
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003162/*
3163 * Ask the user to enter a number.
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003164 * When "mouse_used" is not NULL allow using the mouse and in that case return
3165 * the line number.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003166 */
3167 int
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003168prompt_for_number(mouse_used)
3169 int *mouse_used;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003170{
3171 int i;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003172 int save_cmdline_row;
3173 int save_State;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003174
3175 /* When using ":silent" assume that <CR> was entered. */
Bram Moolenaar42eeac32005-06-29 22:40:58 +00003176 if (mouse_used != NULL)
3177 MSG_PUTS(_("Type number or click with mouse (<Enter> cancels): "));
3178 else
3179 MSG_PUTS(_("Choice number (<Enter> cancels): "));
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003180
3181 /* Set the state such that text can be selected/copied/pasted. */
3182 save_cmdline_row = cmdline_row;
3183 cmdline_row = Rows - 1;
3184 save_State = State;
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003185 if (mouse_used == NULL)
3186 State = CMDLINE;
3187 else
3188 State = NORMAL;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003189
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003190 i = get_number(TRUE, mouse_used);
3191 if (KeyTyped)
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003192 {
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003193 /* don't call wait_return() now */
3194 /* msg_putchar('\n'); */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003195 cmdline_row = msg_row - 1;
3196 need_wait_return = FALSE;
3197 msg_didany = FALSE;
3198 }
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003199 else
3200 cmdline_row = save_cmdline_row;
3201 State = save_State;
3202
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003203 return i;
3204}
3205
Bram Moolenaar071d4272004-06-13 20:20:40 +00003206 void
3207msgmore(n)
3208 long n;
3209{
3210 long pn;
3211
3212 if (global_busy /* no messages now, wait until global is finished */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003213 || !messaging()) /* 'lazyredraw' set, don't do messages now */
3214 return;
3215
Bram Moolenaar7df2d662005-01-25 22:18:08 +00003216 /* We don't want to overwrite another important message, but do overwrite
3217 * a previous "more lines" or "fewer lines" message, so that "5dd" and
3218 * then "put" reports the last action. */
3219 if (keep_msg != NULL && !keep_msg_more)
3220 return;
3221
Bram Moolenaar071d4272004-06-13 20:20:40 +00003222 if (n > 0)
3223 pn = n;
3224 else
3225 pn = -n;
3226
3227 if (pn > p_report)
3228 {
3229 if (pn == 1)
3230 {
3231 if (n > 0)
3232 STRCPY(msg_buf, _("1 more line"));
3233 else
3234 STRCPY(msg_buf, _("1 line less"));
3235 }
3236 else
3237 {
3238 if (n > 0)
3239 sprintf((char *)msg_buf, _("%ld more lines"), pn);
3240 else
3241 sprintf((char *)msg_buf, _("%ld fewer lines"), pn);
3242 }
3243 if (got_int)
3244 STRCAT(msg_buf, _(" (Interrupted)"));
3245 if (msg(msg_buf))
3246 {
Bram Moolenaar238a5642006-02-21 22:12:05 +00003247 set_keep_msg(msg_buf, 0);
Bram Moolenaar7df2d662005-01-25 22:18:08 +00003248 keep_msg_more = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003249 }
3250 }
3251}
3252
3253/*
3254 * flush map and typeahead buffers and give a warning for an error
3255 */
3256 void
3257beep_flush()
3258{
3259 if (emsg_silent == 0)
3260 {
3261 flush_buffers(FALSE);
3262 vim_beep();
3263 }
3264}
3265
3266/*
3267 * give a warning for an error
3268 */
3269 void
3270vim_beep()
3271{
3272 if (emsg_silent == 0)
3273 {
3274 if (p_vb
3275#ifdef FEAT_GUI
3276 /* While the GUI is starting up the termcap is set for the GUI
3277 * but the output still goes to a terminal. */
3278 && !(gui.in_use && gui.starting)
3279#endif
3280 )
3281 {
3282 out_str(T_VB);
3283 }
3284 else
3285 {
3286#ifdef MSDOS
3287 /*
3288 * The number of beeps outputted is reduced to avoid having to wait
3289 * for all the beeps to finish. This is only a problem on systems
3290 * where the beeps don't overlap.
3291 */
3292 if (beep_count == 0 || beep_count == 10)
3293 {
3294 out_char(BELL);
3295 beep_count = 1;
3296 }
3297 else
3298 ++beep_count;
3299#else
3300 out_char(BELL);
3301#endif
3302 }
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003303
3304 /* When 'verbose' is set and we are sourcing a script or executing a
3305 * function give the user a hint where the beep comes from. */
3306 if (vim_strchr(p_debug, 'e') != NULL)
3307 {
3308 msg_source(hl_attr(HLF_W));
3309 msg_attr((char_u *)_("Beep!"), hl_attr(HLF_W));
3310 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003311 }
3312}
3313
3314/*
3315 * To get the "real" home directory:
3316 * - get value of $HOME
3317 * For Unix:
3318 * - go to that directory
3319 * - do mch_dirname() to get the real name of that directory.
3320 * This also works with mounts and links.
3321 * Don't do this for MS-DOS, it will change the "current dir" for a drive.
3322 */
3323static char_u *homedir = NULL;
3324
3325 void
3326init_homedir()
3327{
3328 char_u *var;
3329
Bram Moolenaar05159a02005-02-26 23:04:13 +00003330 /* In case we are called a second time (when 'encoding' changes). */
3331 vim_free(homedir);
3332 homedir = NULL;
3333
Bram Moolenaar071d4272004-06-13 20:20:40 +00003334#ifdef VMS
3335 var = mch_getenv((char_u *)"SYS$LOGIN");
3336#else
3337 var = mch_getenv((char_u *)"HOME");
3338#endif
3339
3340 if (var != NULL && *var == NUL) /* empty is same as not set */
3341 var = NULL;
3342
3343#ifdef WIN3264
3344 /*
3345 * Weird but true: $HOME may contain an indirect reference to another
3346 * variable, esp. "%USERPROFILE%". Happens when $USERPROFILE isn't set
3347 * when $HOME is being set.
3348 */
3349 if (var != NULL && *var == '%')
3350 {
3351 char_u *p;
3352 char_u *exp;
3353
3354 p = vim_strchr(var + 1, '%');
3355 if (p != NULL)
3356 {
Bram Moolenaarce0842a2005-07-18 21:58:11 +00003357 vim_strncpy(NameBuff, var + 1, p - (var + 1));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003358 exp = mch_getenv(NameBuff);
3359 if (exp != NULL && *exp != NUL
3360 && STRLEN(exp) + STRLEN(p) < MAXPATHL)
3361 {
Bram Moolenaar555b2802005-05-19 21:08:39 +00003362 vim_snprintf((char *)NameBuff, MAXPATHL, "%s%s", exp, p + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003363 var = NameBuff;
3364 /* Also set $HOME, it's needed for _viminfo. */
3365 vim_setenv((char_u *)"HOME", NameBuff);
3366 }
3367 }
3368 }
3369
3370 /*
3371 * Typically, $HOME is not defined on Windows, unless the user has
3372 * specifically defined it for Vim's sake. However, on Windows NT
3373 * platforms, $HOMEDRIVE and $HOMEPATH are automatically defined for
3374 * each user. Try constructing $HOME from these.
3375 */
3376 if (var == NULL)
3377 {
3378 char_u *homedrive, *homepath;
3379
3380 homedrive = mch_getenv((char_u *)"HOMEDRIVE");
3381 homepath = mch_getenv((char_u *)"HOMEPATH");
3382 if (homedrive != NULL && homepath != NULL
3383 && STRLEN(homedrive) + STRLEN(homepath) < MAXPATHL)
3384 {
3385 sprintf((char *)NameBuff, "%s%s", homedrive, homepath);
3386 if (NameBuff[0] != NUL)
3387 {
3388 var = NameBuff;
3389 /* Also set $HOME, it's needed for _viminfo. */
3390 vim_setenv((char_u *)"HOME", NameBuff);
3391 }
3392 }
3393 }
Bram Moolenaar05159a02005-02-26 23:04:13 +00003394
3395# if defined(FEAT_MBYTE)
3396 if (enc_utf8 && var != NULL)
3397 {
3398 int len;
3399 char_u *pp;
3400
3401 /* Convert from active codepage to UTF-8. Other conversions are
3402 * not done, because they would fail for non-ASCII characters. */
3403 acp_to_enc(var, STRLEN(var), &pp, &len);
3404 if (pp != NULL)
3405 {
3406 homedir = pp;
3407 return;
3408 }
3409 }
3410# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003411#endif
3412
3413#if defined(OS2) || defined(MSDOS) || defined(MSWIN)
3414 /*
3415 * Default home dir is C:/
3416 * Best assumption we can make in such a situation.
3417 */
3418 if (var == NULL)
3419 var = "C:/";
3420#endif
3421 if (var != NULL)
3422 {
3423#ifdef UNIX
3424 /*
3425 * Change to the directory and get the actual path. This resolves
3426 * links. Don't do it when we can't return.
3427 */
3428 if (mch_dirname(NameBuff, MAXPATHL) == OK
3429 && mch_chdir((char *)NameBuff) == 0)
3430 {
3431 if (!mch_chdir((char *)var) && mch_dirname(IObuff, IOSIZE) == OK)
3432 var = IObuff;
3433 if (mch_chdir((char *)NameBuff) != 0)
3434 EMSG(_(e_prev_dir));
3435 }
3436#endif
3437 homedir = vim_strsave(var);
3438 }
3439}
3440
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003441#if defined(EXITFREE) || defined(PROTO)
3442 void
3443free_homedir()
3444{
3445 vim_free(homedir);
3446}
3447#endif
3448
Bram Moolenaar071d4272004-06-13 20:20:40 +00003449/*
3450 * Expand environment variable with path name.
3451 * "~/" is also expanded, using $HOME. For Unix "~user/" is expanded.
3452 * Skips over "\ ", "\~" and "\$".
3453 * If anything fails no expansion is done and dst equals src.
3454 */
3455 void
3456expand_env(src, dst, dstlen)
3457 char_u *src; /* input string e.g. "$HOME/vim.hlp" */
3458 char_u *dst; /* where to put the result */
3459 int dstlen; /* maximum length of the result */
3460{
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003461 expand_env_esc(src, dst, dstlen, FALSE, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003462}
3463
3464 void
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003465expand_env_esc(srcp, dst, dstlen, esc, startstr)
3466 char_u *srcp; /* input string e.g. "$HOME/vim.hlp" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003467 char_u *dst; /* where to put the result */
3468 int dstlen; /* maximum length of the result */
3469 int esc; /* escape spaces in expanded variables */
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003470 char_u *startstr; /* start again after this (can be NULL) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003471{
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003472 char_u *src;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003473 char_u *tail;
3474 int c;
3475 char_u *var;
3476 int copy_char;
3477 int mustfree; /* var was allocated, need to free it later */
3478 int at_start = TRUE; /* at start of a name */
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003479 int startstr_len = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003480
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003481 if (startstr != NULL)
3482 startstr_len = STRLEN(startstr);
3483
3484 src = skipwhite(srcp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003485 --dstlen; /* leave one char space for "\," */
3486 while (*src && dstlen > 0)
3487 {
3488 copy_char = TRUE;
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003489 if ((*src == '$'
3490#ifdef VMS
3491 && at_start
3492#endif
3493 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003494#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3495 || *src == '%'
3496#endif
3497 || (*src == '~' && at_start))
3498 {
3499 mustfree = FALSE;
3500
3501 /*
3502 * The variable name is copied into dst temporarily, because it may
3503 * be a string in read-only memory and a NUL needs to be appended.
3504 */
3505 if (*src != '~') /* environment var */
3506 {
3507 tail = src + 1;
3508 var = dst;
3509 c = dstlen - 1;
3510
3511#ifdef UNIX
3512 /* Unix has ${var-name} type environment vars */
3513 if (*tail == '{' && !vim_isIDc('{'))
3514 {
3515 tail++; /* ignore '{' */
3516 while (c-- > 0 && *tail && *tail != '}')
3517 *var++ = *tail++;
3518 }
3519 else
3520#endif
3521 {
3522 while (c-- > 0 && *tail != NUL && ((vim_isIDc(*tail))
3523#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3524 || (*src == '%' && *tail != '%')
3525#endif
3526 ))
3527 {
3528#ifdef OS2 /* env vars only in uppercase */
3529 *var++ = TOUPPER_LOC(*tail);
3530 tail++; /* toupper() may be a macro! */
3531#else
3532 *var++ = *tail++;
3533#endif
3534 }
3535 }
3536
3537#if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
3538# ifdef UNIX
3539 if (src[1] == '{' && *tail != '}')
3540# else
3541 if (*src == '%' && *tail != '%')
3542# endif
3543 var = NULL;
3544 else
3545 {
3546# ifdef UNIX
3547 if (src[1] == '{')
3548# else
3549 if (*src == '%')
3550#endif
3551 ++tail;
3552#endif
3553 *var = NUL;
3554 var = vim_getenv(dst, &mustfree);
3555#if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
3556 }
3557#endif
3558 }
3559 /* home directory */
3560 else if ( src[1] == NUL
3561 || vim_ispathsep(src[1])
3562 || vim_strchr((char_u *)" ,\t\n", src[1]) != NULL)
3563 {
3564 var = homedir;
3565 tail = src + 1;
3566 }
3567 else /* user directory */
3568 {
3569#if defined(UNIX) || (defined(VMS) && defined(USER_HOME))
3570 /*
3571 * Copy ~user to dst[], so we can put a NUL after it.
3572 */
3573 tail = src;
3574 var = dst;
3575 c = dstlen - 1;
3576 while ( c-- > 0
3577 && *tail
3578 && vim_isfilec(*tail)
3579 && !vim_ispathsep(*tail))
3580 *var++ = *tail++;
3581 *var = NUL;
3582# ifdef UNIX
3583 /*
3584 * If the system supports getpwnam(), use it.
3585 * Otherwise, or if getpwnam() fails, the shell is used to
3586 * expand ~user. This is slower and may fail if the shell
3587 * does not support ~user (old versions of /bin/sh).
3588 */
3589# if defined(HAVE_GETPWNAM) && defined(HAVE_PWD_H)
3590 {
3591 struct passwd *pw;
3592
Bram Moolenaara40ceaf2006-01-13 22:35:40 +00003593 /* Note: memory allocated by getpwnam() is never freed.
3594 * Calling endpwent() apparently doesn't help. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003595 pw = getpwnam((char *)dst + 1);
3596 if (pw != NULL)
3597 var = (char_u *)pw->pw_dir;
3598 else
3599 var = NULL;
3600 }
3601 if (var == NULL)
3602# endif
3603 {
3604 expand_T xpc;
3605
3606 ExpandInit(&xpc);
3607 xpc.xp_context = EXPAND_FILES;
3608 var = ExpandOne(&xpc, dst, NULL,
3609 WILD_ADD_SLASH|WILD_SILENT, WILD_EXPAND_FREE);
3610 ExpandCleanup(&xpc);
3611 mustfree = TRUE;
3612 }
3613
3614# else /* !UNIX, thus VMS */
3615 /*
3616 * USER_HOME is a comma-separated list of
3617 * directories to search for the user account in.
3618 */
3619 {
3620 char_u test[MAXPATHL], paths[MAXPATHL];
3621 char_u *path, *next_path, *ptr;
3622 struct stat st;
3623
3624 STRCPY(paths, USER_HOME);
3625 next_path = paths;
3626 while (*next_path)
3627 {
3628 for (path = next_path; *next_path && *next_path != ',';
3629 next_path++);
3630 if (*next_path)
3631 *next_path++ = NUL;
3632 STRCPY(test, path);
3633 STRCAT(test, "/");
3634 STRCAT(test, dst + 1);
3635 if (mch_stat(test, &st) == 0)
3636 {
3637 var = alloc(STRLEN(test) + 1);
3638 STRCPY(var, test);
3639 mustfree = TRUE;
3640 break;
3641 }
3642 }
3643 }
3644# endif /* UNIX */
3645#else
3646 /* cannot expand user's home directory, so don't try */
3647 var = NULL;
3648 tail = (char_u *)""; /* for gcc */
3649#endif /* UNIX || VMS */
3650 }
3651
3652#ifdef BACKSLASH_IN_FILENAME
3653 /* If 'shellslash' is set change backslashes to forward slashes.
3654 * Can't use slash_adjust(), p_ssl may be set temporarily. */
3655 if (p_ssl && var != NULL && vim_strchr(var, '\\') != NULL)
3656 {
3657 char_u *p = vim_strsave(var);
3658
3659 if (p != NULL)
3660 {
3661 if (mustfree)
3662 vim_free(var);
3663 var = p;
3664 mustfree = TRUE;
3665 forward_slash(var);
3666 }
3667 }
3668#endif
3669
3670 /* If "var" contains white space, escape it with a backslash.
3671 * Required for ":e ~/tt" when $HOME includes a space. */
3672 if (esc && var != NULL && vim_strpbrk(var, (char_u *)" \t") != NULL)
3673 {
3674 char_u *p = vim_strsave_escaped(var, (char_u *)" \t");
3675
3676 if (p != NULL)
3677 {
3678 if (mustfree)
3679 vim_free(var);
3680 var = p;
3681 mustfree = TRUE;
3682 }
3683 }
3684
3685 if (var != NULL && *var != NUL
3686 && (STRLEN(var) + STRLEN(tail) + 1 < (unsigned)dstlen))
3687 {
3688 STRCPY(dst, var);
3689 dstlen -= (int)STRLEN(var);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003690 c = STRLEN(var);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003691 /* if var[] ends in a path separator and tail[] starts
3692 * with it, skip a character */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003693 if (*var != NUL && after_pathsep(dst, dst + c)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003694#if defined(BACKSLASH_IN_FILENAME) || defined(AMIGA)
3695 && dst[-1] != ':'
3696#endif
3697 && vim_ispathsep(*tail))
3698 ++tail;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003699 dst += c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003700 src = tail;
3701 copy_char = FALSE;
3702 }
3703 if (mustfree)
3704 vim_free(var);
3705 }
3706
3707 if (copy_char) /* copy at least one char */
3708 {
3709 /*
3710 * Recogize the start of a new name, for '~'.
3711 */
3712 at_start = FALSE;
3713 if (src[0] == '\\' && src[1] != NUL)
3714 {
3715 *dst++ = *src++;
3716 --dstlen;
3717 }
3718 else if (src[0] == ' ' || src[0] == ',')
3719 at_start = TRUE;
3720 *dst++ = *src++;
3721 --dstlen;
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003722
3723 if (startstr != NULL && src - startstr_len >= srcp
3724 && STRNCMP(src - startstr_len, startstr, startstr_len) == 0)
3725 at_start = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003726 }
3727 }
3728 *dst = NUL;
3729}
3730
3731/*
3732 * Vim's version of getenv().
3733 * Special handling of $HOME, $VIM and $VIMRUNTIME.
Bram Moolenaar2f6b0b82005-03-08 22:43:10 +00003734 * Also does ACP to 'enc' conversion for Win32.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003735 */
3736 char_u *
3737vim_getenv(name, mustfree)
3738 char_u *name;
3739 int *mustfree; /* set to TRUE when returned is allocated */
3740{
3741 char_u *p;
3742 char_u *pend;
3743 int vimruntime;
3744
3745#if defined(OS2) || defined(MSDOS) || defined(MSWIN)
3746 /* use "C:/" when $HOME is not set */
3747 if (STRCMP(name, "HOME") == 0)
3748 return homedir;
3749#endif
3750
3751 p = mch_getenv(name);
3752 if (p != NULL && *p == NUL) /* empty is the same as not set */
3753 p = NULL;
3754
3755 if (p != NULL)
Bram Moolenaar05159a02005-02-26 23:04:13 +00003756 {
3757#if defined(FEAT_MBYTE) && defined(WIN3264)
3758 if (enc_utf8)
3759 {
3760 int len;
3761 char_u *pp;
3762
3763 /* Convert from active codepage to UTF-8. Other conversions are
3764 * not done, because they would fail for non-ASCII characters. */
3765 acp_to_enc(p, STRLEN(p), &pp, &len);
3766 if (pp != NULL)
3767 {
3768 p = pp;
3769 *mustfree = TRUE;
3770 }
3771 }
3772#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003773 return p;
Bram Moolenaar05159a02005-02-26 23:04:13 +00003774 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003775
3776 vimruntime = (STRCMP(name, "VIMRUNTIME") == 0);
3777 if (!vimruntime && STRCMP(name, "VIM") != 0)
3778 return NULL;
3779
3780 /*
3781 * When expanding $VIMRUNTIME fails, try using $VIM/vim<version> or $VIM.
3782 * Don't do this when default_vimruntime_dir is non-empty.
3783 */
3784 if (vimruntime
3785#ifdef HAVE_PATHDEF
3786 && *default_vimruntime_dir == NUL
3787#endif
3788 )
3789 {
3790 p = mch_getenv((char_u *)"VIM");
3791 if (p != NULL && *p == NUL) /* empty is the same as not set */
3792 p = NULL;
3793 if (p != NULL)
3794 {
3795 p = vim_version_dir(p);
3796 if (p != NULL)
3797 *mustfree = TRUE;
3798 else
3799 p = mch_getenv((char_u *)"VIM");
Bram Moolenaar05159a02005-02-26 23:04:13 +00003800
3801#if defined(FEAT_MBYTE) && defined(WIN3264)
3802 if (enc_utf8)
3803 {
3804 int len;
3805 char_u *pp;
3806
3807 /* Convert from active codepage to UTF-8. Other conversions
3808 * are not done, because they would fail for non-ASCII
3809 * characters. */
3810 acp_to_enc(p, STRLEN(p), &pp, &len);
3811 if (pp != NULL)
3812 {
3813 if (mustfree)
3814 vim_free(p);
3815 p = pp;
3816 *mustfree = TRUE;
3817 }
3818 }
3819#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003820 }
3821 }
3822
3823 /*
3824 * When expanding $VIM or $VIMRUNTIME fails, try using:
3825 * - the directory name from 'helpfile' (unless it contains '$')
3826 * - the executable name from argv[0]
3827 */
3828 if (p == NULL)
3829 {
3830 if (p_hf != NULL && vim_strchr(p_hf, '$') == NULL)
3831 p = p_hf;
3832#ifdef USE_EXE_NAME
3833 /*
3834 * Use the name of the executable, obtained from argv[0].
3835 */
3836 else
3837 p = exe_name;
3838#endif
3839 if (p != NULL)
3840 {
3841 /* remove the file name */
3842 pend = gettail(p);
3843
3844 /* remove "doc/" from 'helpfile', if present */
3845 if (p == p_hf)
3846 pend = remove_tail(p, pend, (char_u *)"doc");
3847
3848#ifdef USE_EXE_NAME
3849# ifdef MACOS_X
Bram Moolenaar95e9b492006-03-15 23:04:43 +00003850 /* remove "MacOS" from exe_name and add "Resources/vim" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003851 if (p == exe_name)
3852 {
3853 char_u *pend1;
Bram Moolenaar95e9b492006-03-15 23:04:43 +00003854 char_u *pnew;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003855
Bram Moolenaar95e9b492006-03-15 23:04:43 +00003856 pend1 = remove_tail(p, pend, (char_u *)"MacOS");
3857 if (pend1 != pend)
3858 {
3859 pnew = alloc((unsigned)(pend1 - p) + 15);
3860 if (pnew != NULL)
3861 {
3862 STRNCPY(pnew, p, (pend1 - p));
3863 STRCPY(pnew + (pend1 - p), "Resources/vim");
3864 p = pnew;
3865 pend = p + STRLEN(p);
3866 }
3867 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003868 }
3869# endif
3870 /* remove "src/" from exe_name, if present */
3871 if (p == exe_name)
3872 pend = remove_tail(p, pend, (char_u *)"src");
3873#endif
3874
3875 /* for $VIM, remove "runtime/" or "vim54/", if present */
3876 if (!vimruntime)
3877 {
3878 pend = remove_tail(p, pend, (char_u *)RUNTIME_DIRNAME);
3879 pend = remove_tail(p, pend, (char_u *)VIM_VERSION_NODOT);
3880 }
3881
3882 /* remove trailing path separator */
3883#ifndef MACOS_CLASSIC
3884 /* With MacOS path (with colons) the final colon is required */
3885 /* to avoid confusion between absoulute and relative path */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003886 if (pend > p && after_pathsep(p, pend))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003887 --pend;
3888#endif
3889
Bram Moolenaar95e9b492006-03-15 23:04:43 +00003890#ifdef MACOS_X
3891 if (p == exe_name || p == p_hf)
3892#endif
3893 /* check that the result is a directory name */
3894 p = vim_strnsave(p, (int)(pend - p));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003895
3896 if (p != NULL && !mch_isdir(p))
3897 {
3898 vim_free(p);
3899 p = NULL;
3900 }
3901 else
3902 {
3903#ifdef USE_EXE_NAME
3904 /* may add "/vim54" or "/runtime" if it exists */
3905 if (vimruntime && (pend = vim_version_dir(p)) != NULL)
3906 {
3907 vim_free(p);
3908 p = pend;
3909 }
3910#endif
3911 *mustfree = TRUE;
3912 }
3913 }
3914 }
3915
3916#ifdef HAVE_PATHDEF
3917 /* When there is a pathdef.c file we can use default_vim_dir and
3918 * default_vimruntime_dir */
3919 if (p == NULL)
3920 {
3921 /* Only use default_vimruntime_dir when it is not empty */
3922 if (vimruntime && *default_vimruntime_dir != NUL)
3923 {
3924 p = default_vimruntime_dir;
3925 *mustfree = FALSE;
3926 }
3927 else if (*default_vim_dir != NUL)
3928 {
3929 if (vimruntime && (p = vim_version_dir(default_vim_dir)) != NULL)
3930 *mustfree = TRUE;
3931 else
3932 {
3933 p = default_vim_dir;
3934 *mustfree = FALSE;
3935 }
3936 }
3937 }
3938#endif
3939
3940 /*
3941 * Set the environment variable, so that the new value can be found fast
3942 * next time, and others can also use it (e.g. Perl).
3943 */
3944 if (p != NULL)
3945 {
3946 if (vimruntime)
3947 {
3948 vim_setenv((char_u *)"VIMRUNTIME", p);
3949 didset_vimruntime = TRUE;
3950#ifdef FEAT_GETTEXT
3951 {
Bram Moolenaard6754642005-01-17 22:18:45 +00003952 char_u *buf = concat_str(p, (char_u *)"/lang");
Bram Moolenaar071d4272004-06-13 20:20:40 +00003953
3954 if (buf != NULL)
3955 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00003956 bindtextdomain(VIMPACKAGE, (char *)buf);
3957 vim_free(buf);
3958 }
3959 }
3960#endif
3961 }
3962 else
3963 {
3964 vim_setenv((char_u *)"VIM", p);
3965 didset_vim = TRUE;
3966 }
3967 }
3968 return p;
3969}
3970
3971/*
3972 * Check if the directory "vimdir/<version>" or "vimdir/runtime" exists.
3973 * Return NULL if not, return its name in allocated memory otherwise.
3974 */
3975 static char_u *
3976vim_version_dir(vimdir)
3977 char_u *vimdir;
3978{
3979 char_u *p;
3980
3981 if (vimdir == NULL || *vimdir == NUL)
3982 return NULL;
3983 p = concat_fnames(vimdir, (char_u *)VIM_VERSION_NODOT, TRUE);
3984 if (p != NULL && mch_isdir(p))
3985 return p;
3986 vim_free(p);
3987 p = concat_fnames(vimdir, (char_u *)RUNTIME_DIRNAME, TRUE);
3988 if (p != NULL && mch_isdir(p))
3989 return p;
3990 vim_free(p);
3991 return NULL;
3992}
3993
3994/*
3995 * If the string between "p" and "pend" ends in "name/", return "pend" minus
3996 * the length of "name/". Otherwise return "pend".
3997 */
3998 static char_u *
3999remove_tail(p, pend, name)
4000 char_u *p;
4001 char_u *pend;
4002 char_u *name;
4003{
4004 int len = (int)STRLEN(name) + 1;
4005 char_u *newend = pend - len;
4006
4007 if (newend >= p
4008 && fnamencmp(newend, name, len - 1) == 0
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004009 && (newend == p || after_pathsep(p, newend)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004010 return newend;
4011 return pend;
4012}
4013
Bram Moolenaar071d4272004-06-13 20:20:40 +00004014/*
4015 * Call expand_env() and store the result in an allocated string.
4016 * This is not very memory efficient, this expects the result to be freed
4017 * again soon.
4018 */
4019 char_u *
4020expand_env_save(src)
4021 char_u *src;
4022{
4023 char_u *p;
4024
4025 p = alloc(MAXPATHL);
4026 if (p != NULL)
4027 expand_env(src, p, MAXPATHL);
4028 return p;
4029}
4030
4031/*
4032 * Our portable version of setenv.
4033 */
4034 void
4035vim_setenv(name, val)
4036 char_u *name;
4037 char_u *val;
4038{
4039#ifdef HAVE_SETENV
4040 mch_setenv((char *)name, (char *)val, 1);
4041#else
4042 char_u *envbuf;
4043
4044 /*
4045 * Putenv does not copy the string, it has to remain
4046 * valid. The allocated memory will never be freed.
4047 */
4048 envbuf = alloc((unsigned)(STRLEN(name) + STRLEN(val) + 2));
4049 if (envbuf != NULL)
4050 {
4051 sprintf((char *)envbuf, "%s=%s", name, val);
4052 putenv((char *)envbuf);
4053 }
4054#endif
4055}
4056
4057#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
4058/*
4059 * Function given to ExpandGeneric() to obtain an environment variable name.
4060 */
4061/*ARGSUSED*/
4062 char_u *
4063get_env_name(xp, idx)
4064 expand_T *xp;
4065 int idx;
4066{
4067# if defined(AMIGA) || defined(__MRC__) || defined(__SC__)
4068 /*
4069 * No environ[] on the Amiga and on the Mac (using MPW).
4070 */
4071 return NULL;
4072# else
4073# ifndef __WIN32__
4074 /* Borland C++ 5.2 has this in a header file. */
4075 extern char **environ;
4076# endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00004077# define ENVNAMELEN 100
4078 static char_u name[ENVNAMELEN];
Bram Moolenaar071d4272004-06-13 20:20:40 +00004079 char_u *str;
4080 int n;
4081
4082 str = (char_u *)environ[idx];
4083 if (str == NULL)
4084 return NULL;
4085
Bram Moolenaar21cf8232004-07-16 20:18:37 +00004086 for (n = 0; n < ENVNAMELEN - 1; ++n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004087 {
4088 if (str[n] == '=' || str[n] == NUL)
4089 break;
4090 name[n] = str[n];
4091 }
4092 name[n] = NUL;
4093 return name;
4094# endif
4095}
4096#endif
4097
4098/*
4099 * Replace home directory by "~" in each space or comma separated file name in
4100 * 'src'.
4101 * If anything fails (except when out of space) dst equals src.
4102 */
4103 void
4104home_replace(buf, src, dst, dstlen, one)
4105 buf_T *buf; /* when not NULL, check for help files */
4106 char_u *src; /* input file name */
4107 char_u *dst; /* where to put the result */
4108 int dstlen; /* maximum length of the result */
4109 int one; /* if TRUE, only replace one file name, include
4110 spaces and commas in the file name. */
4111{
4112 size_t dirlen = 0, envlen = 0;
4113 size_t len;
4114 char_u *homedir_env;
4115 char_u *p;
4116
4117 if (src == NULL)
4118 {
4119 *dst = NUL;
4120 return;
4121 }
4122
4123 /*
4124 * If the file is a help file, remove the path completely.
4125 */
4126 if (buf != NULL && buf->b_help)
4127 {
4128 STRCPY(dst, gettail(src));
4129 return;
4130 }
4131
4132 /*
4133 * We check both the value of the $HOME environment variable and the
4134 * "real" home directory.
4135 */
4136 if (homedir != NULL)
4137 dirlen = STRLEN(homedir);
4138
4139#ifdef VMS
4140 homedir_env = mch_getenv((char_u *)"SYS$LOGIN");
4141#else
4142 homedir_env = mch_getenv((char_u *)"HOME");
4143#endif
4144
4145 if (homedir_env != NULL && *homedir_env == NUL)
4146 homedir_env = NULL;
4147 if (homedir_env != NULL)
4148 envlen = STRLEN(homedir_env);
4149
4150 if (!one)
4151 src = skipwhite(src);
4152 while (*src && dstlen > 0)
4153 {
4154 /*
4155 * Here we are at the beginning of a file name.
4156 * First, check to see if the beginning of the file name matches
4157 * $HOME or the "real" home directory. Check that there is a '/'
4158 * after the match (so that if e.g. the file is "/home/pieter/bla",
4159 * and the home directory is "/home/piet", the file does not end up
4160 * as "~er/bla" (which would seem to indicate the file "bla" in user
4161 * er's home directory)).
4162 */
4163 p = homedir;
4164 len = dirlen;
4165 for (;;)
4166 {
4167 if ( len
4168 && fnamencmp(src, p, len) == 0
4169 && (vim_ispathsep(src[len])
4170 || (!one && (src[len] == ',' || src[len] == ' '))
4171 || src[len] == NUL))
4172 {
4173 src += len;
4174 if (--dstlen > 0)
4175 *dst++ = '~';
4176
4177 /*
4178 * If it's just the home directory, add "/".
4179 */
4180 if (!vim_ispathsep(src[0]) && --dstlen > 0)
4181 *dst++ = '/';
4182 break;
4183 }
4184 if (p == homedir_env)
4185 break;
4186 p = homedir_env;
4187 len = envlen;
4188 }
4189
4190 /* if (!one) skip to separator: space or comma */
4191 while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
4192 *dst++ = *src++;
4193 /* skip separator */
4194 while ((*src == ' ' || *src == ',') && --dstlen > 0)
4195 *dst++ = *src++;
4196 }
4197 /* if (dstlen == 0) out of space, what to do??? */
4198
4199 *dst = NUL;
4200}
4201
4202/*
4203 * Like home_replace, store the replaced string in allocated memory.
4204 * When something fails, NULL is returned.
4205 */
4206 char_u *
4207home_replace_save(buf, src)
4208 buf_T *buf; /* when not NULL, check for help files */
4209 char_u *src; /* input file name */
4210{
4211 char_u *dst;
4212 unsigned len;
4213
4214 len = 3; /* space for "~/" and trailing NUL */
4215 if (src != NULL) /* just in case */
4216 len += (unsigned)STRLEN(src);
4217 dst = alloc(len);
4218 if (dst != NULL)
4219 home_replace(buf, src, dst, len, TRUE);
4220 return dst;
4221}
4222
4223/*
4224 * Compare two file names and return:
4225 * FPC_SAME if they both exist and are the same file.
4226 * FPC_SAMEX if they both don't exist and have the same file name.
4227 * FPC_DIFF if they both exist and are different files.
4228 * FPC_NOTX if they both don't exist.
4229 * FPC_DIFFX if one of them doesn't exist.
4230 * For the first name environment variables are expanded
4231 */
4232 int
4233fullpathcmp(s1, s2, checkname)
4234 char_u *s1, *s2;
4235 int checkname; /* when both don't exist, check file names */
4236{
4237#ifdef UNIX
4238 char_u exp1[MAXPATHL];
4239 char_u full1[MAXPATHL];
4240 char_u full2[MAXPATHL];
4241 struct stat st1, st2;
4242 int r1, r2;
4243
4244 expand_env(s1, exp1, MAXPATHL);
4245 r1 = mch_stat((char *)exp1, &st1);
4246 r2 = mch_stat((char *)s2, &st2);
4247 if (r1 != 0 && r2 != 0)
4248 {
4249 /* if mch_stat() doesn't work, may compare the names */
4250 if (checkname)
4251 {
4252 if (fnamecmp(exp1, s2) == 0)
4253 return FPC_SAMEX;
4254 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4255 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4256 if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
4257 return FPC_SAMEX;
4258 }
4259 return FPC_NOTX;
4260 }
4261 if (r1 != 0 || r2 != 0)
4262 return FPC_DIFFX;
4263 if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
4264 return FPC_SAME;
4265 return FPC_DIFF;
4266#else
4267 char_u *exp1; /* expanded s1 */
4268 char_u *full1; /* full path of s1 */
4269 char_u *full2; /* full path of s2 */
4270 int retval = FPC_DIFF;
4271 int r1, r2;
4272
4273 /* allocate one buffer to store three paths (alloc()/free() is slow!) */
4274 if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
4275 {
4276 full1 = exp1 + MAXPATHL;
4277 full2 = full1 + MAXPATHL;
4278
4279 expand_env(s1, exp1, MAXPATHL);
4280 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4281 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4282
4283 /* If vim_FullName() fails, the file probably doesn't exist. */
4284 if (r1 != OK && r2 != OK)
4285 {
4286 if (checkname && fnamecmp(exp1, s2) == 0)
4287 retval = FPC_SAMEX;
4288 else
4289 retval = FPC_NOTX;
4290 }
4291 else if (r1 != OK || r2 != OK)
4292 retval = FPC_DIFFX;
4293 else if (fnamecmp(full1, full2))
4294 retval = FPC_DIFF;
4295 else
4296 retval = FPC_SAME;
4297 vim_free(exp1);
4298 }
4299 return retval;
4300#endif
4301}
4302
4303/*
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004304 * Get the tail of a path: the file name.
4305 * Fail safe: never returns NULL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004306 */
4307 char_u *
4308gettail(fname)
4309 char_u *fname;
4310{
4311 char_u *p1, *p2;
4312
4313 if (fname == NULL)
4314 return (char_u *)"";
4315 for (p1 = p2 = fname; *p2; ) /* find last part of path */
4316 {
4317 if (vim_ispathsep(*p2))
4318 p1 = p2 + 1;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004319 mb_ptr_adv(p2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004320 }
4321 return p1;
4322}
4323
4324/*
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004325 * Get pointer to tail of "fname", including path separators. Putting a NUL
4326 * here leaves the directory name. Takes care of "c:/" and "//".
4327 * Always returns a valid pointer.
4328 */
4329 char_u *
4330gettail_sep(fname)
4331 char_u *fname;
4332{
4333 char_u *p;
4334 char_u *t;
4335
4336 p = get_past_head(fname); /* don't remove the '/' from "c:/file" */
4337 t = gettail(fname);
4338 while (t > p && after_pathsep(fname, t))
4339 --t;
4340#ifdef VMS
4341 /* path separator is part of the path */
4342 ++t;
4343#endif
4344 return t;
4345}
4346
4347/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004348 * get the next path component (just after the next path separator).
4349 */
4350 char_u *
4351getnextcomp(fname)
4352 char_u *fname;
4353{
4354 while (*fname && !vim_ispathsep(*fname))
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004355 mb_ptr_adv(fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004356 if (*fname)
4357 ++fname;
4358 return fname;
4359}
4360
Bram Moolenaar071d4272004-06-13 20:20:40 +00004361/*
4362 * Get a pointer to one character past the head of a path name.
4363 * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
4364 * If there is no head, path is returned.
4365 */
4366 char_u *
4367get_past_head(path)
4368 char_u *path;
4369{
4370 char_u *retval;
4371
4372#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
4373 /* may skip "c:" */
4374 if (isalpha(path[0]) && path[1] == ':')
4375 retval = path + 2;
4376 else
4377 retval = path;
4378#else
4379# if defined(AMIGA)
4380 /* may skip "label:" */
4381 retval = vim_strchr(path, ':');
4382 if (retval == NULL)
4383 retval = path;
4384# else /* Unix */
4385 retval = path;
4386# endif
4387#endif
4388
4389 while (vim_ispathsep(*retval))
4390 ++retval;
4391
4392 return retval;
4393}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004394
4395/*
4396 * return TRUE if 'c' is a path separator.
4397 */
4398 int
4399vim_ispathsep(c)
4400 int c;
4401{
4402#ifdef RISCOS
4403 return (c == '.' || c == ':');
4404#else
4405# ifdef UNIX
4406 return (c == '/'); /* UNIX has ':' inside file names */
4407# else
4408# ifdef BACKSLASH_IN_FILENAME
4409 return (c == ':' || c == '/' || c == '\\');
4410# else
4411# ifdef VMS
4412 /* server"user passwd"::device:[full.path.name]fname.extension;version" */
4413 return (c == ':' || c == '[' || c == ']' || c == '/'
4414 || c == '<' || c == '>' || c == '"' );
Bram Moolenaar1056d982006-03-09 22:37:52 +00004415# else /* Amiga */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004416 return (c == ':' || c == '/');
Bram Moolenaar071d4272004-06-13 20:20:40 +00004417# endif /* VMS */
4418# endif
4419# endif
4420#endif /* RISC OS */
4421}
4422
4423#if defined(FEAT_SEARCHPATH) || defined(PROTO)
4424/*
4425 * return TRUE if 'c' is a path list separator.
4426 */
4427 int
4428vim_ispathlistsep(c)
4429 int c;
4430{
4431#ifdef UNIX
4432 return (c == ':');
4433#else
4434 return (c == ';'); /* might not be rigth for every system... */
4435#endif
4436}
4437#endif
4438
Bram Moolenaar900b4d72005-12-12 22:05:50 +00004439/*
4440 * Return TRUE if the directory of "fname" exists, FALSE otherwise.
4441 * Also returns TRUE if there is no directory name.
4442 * "fname" must be writable!.
4443 */
4444 int
4445dir_of_file_exists(fname)
4446 char_u *fname;
4447{
4448 char_u *p;
4449 int c;
4450 int retval;
4451
4452 p = gettail_sep(fname);
4453 if (p == fname)
4454 return TRUE;
4455 c = *p;
4456 *p = NUL;
4457 retval = mch_isdir(fname);
4458 *p = c;
4459 return retval;
4460}
4461
Bram Moolenaar071d4272004-06-13 20:20:40 +00004462#if (defined(CASE_INSENSITIVE_FILENAME) && defined(BACKSLASH_IN_FILENAME)) \
4463 || defined(PROTO)
4464/*
4465 * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally.
4466 */
4467 int
4468vim_fnamecmp(x, y)
4469 char_u *x, *y;
4470{
4471 return vim_fnamencmp(x, y, MAXPATHL);
4472}
4473
4474 int
4475vim_fnamencmp(x, y, len)
4476 char_u *x, *y;
4477 size_t len;
4478{
4479 while (len > 0 && *x && *y)
4480 {
4481 if (TOLOWER_LOC(*x) != TOLOWER_LOC(*y)
4482 && !(*x == '/' && *y == '\\')
4483 && !(*x == '\\' && *y == '/'))
4484 break;
4485 ++x;
4486 ++y;
4487 --len;
4488 }
4489 if (len == 0)
4490 return 0;
4491 return (*x - *y);
4492}
4493#endif
4494
4495/*
4496 * Concatenate file names fname1 and fname2 into allocated memory.
4497 * Only add a '/' or '\\' when 'sep' is TRUE and it is neccesary.
4498 */
4499 char_u *
4500concat_fnames(fname1, fname2, sep)
4501 char_u *fname1;
4502 char_u *fname2;
4503 int sep;
4504{
4505 char_u *dest;
4506
4507 dest = alloc((unsigned)(STRLEN(fname1) + STRLEN(fname2) + 3));
4508 if (dest != NULL)
4509 {
4510 STRCPY(dest, fname1);
4511 if (sep)
4512 add_pathsep(dest);
4513 STRCAT(dest, fname2);
4514 }
4515 return dest;
4516}
4517
Bram Moolenaard6754642005-01-17 22:18:45 +00004518#if defined(FEAT_EVAL) || defined(FEAT_GETTEXT) || defined(PROTO)
4519/*
4520 * Concatenate two strings and return the result in allocated memory.
4521 * Returns NULL when out of memory.
4522 */
4523 char_u *
4524concat_str(str1, str2)
4525 char_u *str1;
4526 char_u *str2;
4527{
4528 char_u *dest;
4529 size_t l = STRLEN(str1);
4530
4531 dest = alloc((unsigned)(l + STRLEN(str2) + 1L));
4532 if (dest != NULL)
4533 {
4534 STRCPY(dest, str1);
4535 STRCPY(dest + l, str2);
4536 }
4537 return dest;
4538}
4539#endif
4540
Bram Moolenaar071d4272004-06-13 20:20:40 +00004541/*
4542 * Add a path separator to a file name, unless it already ends in a path
4543 * separator.
4544 */
4545 void
4546add_pathsep(p)
4547 char_u *p;
4548{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004549 if (*p != NUL && !after_pathsep(p, p + STRLEN(p)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004550 STRCAT(p, PATHSEPSTR);
4551}
4552
4553/*
4554 * FullName_save - Make an allocated copy of a full file name.
4555 * Returns NULL when out of memory.
4556 */
4557 char_u *
4558FullName_save(fname, force)
4559 char_u *fname;
4560 int force; /* force expansion, even when it already looks
4561 like a full path name */
4562{
4563 char_u *buf;
4564 char_u *new_fname = NULL;
4565
4566 if (fname == NULL)
4567 return NULL;
4568
4569 buf = alloc((unsigned)MAXPATHL);
4570 if (buf != NULL)
4571 {
4572 if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
4573 new_fname = vim_strsave(buf);
4574 else
4575 new_fname = vim_strsave(fname);
4576 vim_free(buf);
4577 }
4578 return new_fname;
4579}
4580
4581#if defined(FEAT_CINDENT) || defined(FEAT_SYN_HL)
4582
4583static char_u *skip_string __ARGS((char_u *p));
4584
4585/*
4586 * Find the start of a comment, not knowing if we are in a comment right now.
4587 * Search starts at w_cursor.lnum and goes backwards.
4588 */
4589 pos_T *
4590find_start_comment(ind_maxcomment) /* XXX */
4591 int ind_maxcomment;
4592{
4593 pos_T *pos;
4594 char_u *line;
4595 char_u *p;
4596
4597 if ((pos = findmatchlimit(NULL, '*', FM_BACKWARD, ind_maxcomment)) == NULL)
4598 return NULL;
4599
4600 /*
4601 * Check if the comment start we found is inside a string.
4602 */
4603 line = ml_get(pos->lnum);
4604 for (p = line; *p && (unsigned)(p - line) < pos->col; ++p)
4605 p = skip_string(p);
4606 if ((unsigned)(p - line) > pos->col)
4607 return NULL;
4608 return pos;
4609}
4610
4611/*
4612 * Skip to the end of a "string" and a 'c' character.
4613 * If there is no string or character, return argument unmodified.
4614 */
4615 static char_u *
4616skip_string(p)
4617 char_u *p;
4618{
4619 int i;
4620
4621 /*
4622 * We loop, because strings may be concatenated: "date""time".
4623 */
4624 for ( ; ; ++p)
4625 {
4626 if (p[0] == '\'') /* 'c' or '\n' or '\000' */
4627 {
4628 if (!p[1]) /* ' at end of line */
4629 break;
4630 i = 2;
4631 if (p[1] == '\\') /* '\n' or '\000' */
4632 {
4633 ++i;
4634 while (vim_isdigit(p[i - 1])) /* '\000' */
4635 ++i;
4636 }
4637 if (p[i] == '\'') /* check for trailing ' */
4638 {
4639 p += i;
4640 continue;
4641 }
4642 }
4643 else if (p[0] == '"') /* start of string */
4644 {
4645 for (++p; p[0]; ++p)
4646 {
4647 if (p[0] == '\\' && p[1] != NUL)
4648 ++p;
4649 else if (p[0] == '"') /* end of string */
4650 break;
4651 }
4652 if (p[0] == '"')
4653 continue;
4654 }
4655 break; /* no string found */
4656 }
4657 if (!*p)
4658 --p; /* backup from NUL */
4659 return p;
4660}
4661#endif /* FEAT_CINDENT || FEAT_SYN_HL */
4662
4663#if defined(FEAT_CINDENT) || defined(PROTO)
4664
4665/*
4666 * Do C or expression indenting on the current line.
4667 */
4668 void
4669do_c_expr_indent()
4670{
4671# ifdef FEAT_EVAL
4672 if (*curbuf->b_p_inde != NUL)
4673 fixthisline(get_expr_indent);
4674 else
4675# endif
4676 fixthisline(get_c_indent);
4677}
4678
4679/*
4680 * Functions for C-indenting.
4681 * Most of this originally comes from Eric Fischer.
4682 */
4683/*
4684 * Below "XXX" means that this function may unlock the current line.
4685 */
4686
4687static char_u *cin_skipcomment __ARGS((char_u *));
4688static int cin_nocode __ARGS((char_u *));
4689static pos_T *find_line_comment __ARGS((void));
4690static int cin_islabel_skip __ARGS((char_u **));
4691static int cin_isdefault __ARGS((char_u *));
4692static char_u *after_label __ARGS((char_u *l));
4693static int get_indent_nolabel __ARGS((linenr_T lnum));
4694static int skip_label __ARGS((linenr_T, char_u **pp, int ind_maxcomment));
4695static int cin_first_id_amount __ARGS((void));
4696static int cin_get_equal_amount __ARGS((linenr_T lnum));
4697static int cin_ispreproc __ARGS((char_u *));
4698static int cin_ispreproc_cont __ARGS((char_u **pp, linenr_T *lnump));
4699static int cin_iscomment __ARGS((char_u *));
4700static int cin_islinecomment __ARGS((char_u *));
4701static int cin_isterminated __ARGS((char_u *, int, int));
4702static int cin_isinit __ARGS((void));
4703static int cin_isfuncdecl __ARGS((char_u **, linenr_T));
4704static int cin_isif __ARGS((char_u *));
4705static int cin_iselse __ARGS((char_u *));
4706static int cin_isdo __ARGS((char_u *));
4707static int cin_iswhileofdo __ARGS((char_u *, linenr_T, int));
4708static int cin_isbreak __ARGS((char_u *));
4709static int cin_is_cpp_baseclass __ARGS((char_u *line, colnr_T *col));
4710static int cin_ends_in __ARGS((char_u *, char_u *, char_u *));
4711static int cin_skip2pos __ARGS((pos_T *trypos));
4712static pos_T *find_start_brace __ARGS((int));
4713static pos_T *find_match_paren __ARGS((int, int));
4714static int corr_ind_maxparen __ARGS((int ind_maxparen, pos_T *startpos));
4715static int find_last_paren __ARGS((char_u *l, int start, int end));
4716static int find_match __ARGS((int lookfor, linenr_T ourscope, int ind_maxparen, int ind_maxcomment));
4717
4718/*
4719 * Skip over white space and C comments within the line.
4720 */
4721 static char_u *
4722cin_skipcomment(s)
4723 char_u *s;
4724{
4725 while (*s)
4726 {
4727 s = skipwhite(s);
4728 if (*s != '/')
4729 break;
4730 ++s;
4731 if (*s == '/') /* slash-slash comment continues till eol */
4732 {
4733 s += STRLEN(s);
4734 break;
4735 }
4736 if (*s != '*')
4737 break;
4738 for (++s; *s; ++s) /* skip slash-star comment */
4739 if (s[0] == '*' && s[1] == '/')
4740 {
4741 s += 2;
4742 break;
4743 }
4744 }
4745 return s;
4746}
4747
4748/*
4749 * Return TRUE if there there is no code at *s. White space and comments are
4750 * not considered code.
4751 */
4752 static int
4753cin_nocode(s)
4754 char_u *s;
4755{
4756 return *cin_skipcomment(s) == NUL;
4757}
4758
4759/*
4760 * Check previous lines for a "//" line comment, skipping over blank lines.
4761 */
4762 static pos_T *
4763find_line_comment() /* XXX */
4764{
4765 static pos_T pos;
4766 char_u *line;
4767 char_u *p;
4768
4769 pos = curwin->w_cursor;
4770 while (--pos.lnum > 0)
4771 {
4772 line = ml_get(pos.lnum);
4773 p = skipwhite(line);
4774 if (cin_islinecomment(p))
4775 {
4776 pos.col = (int)(p - line);
4777 return &pos;
4778 }
4779 if (*p != NUL)
4780 break;
4781 }
4782 return NULL;
4783}
4784
4785/*
4786 * Check if string matches "label:"; move to character after ':' if true.
4787 */
4788 static int
4789cin_islabel_skip(s)
4790 char_u **s;
4791{
4792 if (!vim_isIDc(**s)) /* need at least one ID character */
4793 return FALSE;
4794
4795 while (vim_isIDc(**s))
4796 (*s)++;
4797
4798 *s = cin_skipcomment(*s);
4799
4800 /* "::" is not a label, it's C++ */
4801 return (**s == ':' && *++*s != ':');
4802}
4803
4804/*
4805 * Recognize a label: "label:".
4806 * Note: curwin->w_cursor must be where we are looking for the label.
4807 */
4808 int
4809cin_islabel(ind_maxcomment) /* XXX */
4810 int ind_maxcomment;
4811{
4812 char_u *s;
4813
4814 s = cin_skipcomment(ml_get_curline());
4815
4816 /*
4817 * Exclude "default" from labels, since it should be indented
4818 * like a switch label. Same for C++ scope declarations.
4819 */
4820 if (cin_isdefault(s))
4821 return FALSE;
4822 if (cin_isscopedecl(s))
4823 return FALSE;
4824
4825 if (cin_islabel_skip(&s))
4826 {
4827 /*
4828 * Only accept a label if the previous line is terminated or is a case
4829 * label.
4830 */
4831 pos_T cursor_save;
4832 pos_T *trypos;
4833 char_u *line;
4834
4835 cursor_save = curwin->w_cursor;
4836 while (curwin->w_cursor.lnum > 1)
4837 {
4838 --curwin->w_cursor.lnum;
4839
4840 /*
4841 * If we're in a comment now, skip to the start of the comment.
4842 */
4843 curwin->w_cursor.col = 0;
4844 if ((trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
4845 curwin->w_cursor = *trypos;
4846
4847 line = ml_get_curline();
4848 if (cin_ispreproc(line)) /* ignore #defines, #if, etc. */
4849 continue;
4850 if (*(line = cin_skipcomment(line)) == NUL)
4851 continue;
4852
4853 curwin->w_cursor = cursor_save;
4854 if (cin_isterminated(line, TRUE, FALSE)
4855 || cin_isscopedecl(line)
4856 || cin_iscase(line)
4857 || (cin_islabel_skip(&line) && cin_nocode(line)))
4858 return TRUE;
4859 return FALSE;
4860 }
4861 curwin->w_cursor = cursor_save;
4862 return TRUE; /* label at start of file??? */
4863 }
4864 return FALSE;
4865}
4866
4867/*
4868 * Recognize structure initialization and enumerations.
4869 * Q&D-Implementation:
4870 * check for "=" at end or "[typedef] enum" at beginning of line.
4871 */
4872 static int
4873cin_isinit(void)
4874{
4875 char_u *s;
4876
4877 s = cin_skipcomment(ml_get_curline());
4878
4879 if (STRNCMP(s, "typedef", 7) == 0 && !vim_isIDc(s[7]))
4880 s = cin_skipcomment(s + 7);
4881
4882 if (STRNCMP(s, "enum", 4) == 0 && !vim_isIDc(s[4]))
4883 return TRUE;
4884
4885 if (cin_ends_in(s, (char_u *)"=", (char_u *)"{"))
4886 return TRUE;
4887
4888 return FALSE;
4889}
4890
4891/*
4892 * Recognize a switch label: "case .*:" or "default:".
4893 */
4894 int
4895cin_iscase(s)
4896 char_u *s;
4897{
4898 s = cin_skipcomment(s);
4899 if (STRNCMP(s, "case", 4) == 0 && !vim_isIDc(s[4]))
4900 {
4901 for (s += 4; *s; ++s)
4902 {
4903 s = cin_skipcomment(s);
4904 if (*s == ':')
4905 {
4906 if (s[1] == ':') /* skip over "::" for C++ */
4907 ++s;
4908 else
4909 return TRUE;
4910 }
4911 if (*s == '\'' && s[1] && s[2] == '\'')
4912 s += 2; /* skip over '.' */
4913 else if (*s == '/' && (s[1] == '*' || s[1] == '/'))
4914 return FALSE; /* stop at comment */
4915 else if (*s == '"')
4916 return FALSE; /* stop at string */
4917 }
4918 return FALSE;
4919 }
4920
4921 if (cin_isdefault(s))
4922 return TRUE;
4923 return FALSE;
4924}
4925
4926/*
4927 * Recognize a "default" switch label.
4928 */
4929 static int
4930cin_isdefault(s)
4931 char_u *s;
4932{
4933 return (STRNCMP(s, "default", 7) == 0
4934 && *(s = cin_skipcomment(s + 7)) == ':'
4935 && s[1] != ':');
4936}
4937
4938/*
4939 * Recognize a "public/private/proctected" scope declaration label.
4940 */
4941 int
4942cin_isscopedecl(s)
4943 char_u *s;
4944{
4945 int i;
4946
4947 s = cin_skipcomment(s);
4948 if (STRNCMP(s, "public", 6) == 0)
4949 i = 6;
4950 else if (STRNCMP(s, "protected", 9) == 0)
4951 i = 9;
4952 else if (STRNCMP(s, "private", 7) == 0)
4953 i = 7;
4954 else
4955 return FALSE;
4956 return (*(s = cin_skipcomment(s + i)) == ':' && s[1] != ':');
4957}
4958
4959/*
4960 * Return a pointer to the first non-empty non-comment character after a ':'.
4961 * Return NULL if not found.
4962 * case 234: a = b;
4963 * ^
4964 */
4965 static char_u *
4966after_label(l)
4967 char_u *l;
4968{
4969 for ( ; *l; ++l)
4970 {
4971 if (*l == ':')
4972 {
4973 if (l[1] == ':') /* skip over "::" for C++ */
4974 ++l;
4975 else if (!cin_iscase(l + 1))
4976 break;
4977 }
4978 else if (*l == '\'' && l[1] && l[2] == '\'')
4979 l += 2; /* skip over 'x' */
4980 }
4981 if (*l == NUL)
4982 return NULL;
4983 l = cin_skipcomment(l + 1);
4984 if (*l == NUL)
4985 return NULL;
4986 return l;
4987}
4988
4989/*
4990 * Get indent of line "lnum", skipping a label.
4991 * Return 0 if there is nothing after the label.
4992 */
4993 static int
4994get_indent_nolabel(lnum) /* XXX */
4995 linenr_T lnum;
4996{
4997 char_u *l;
4998 pos_T fp;
4999 colnr_T col;
5000 char_u *p;
5001
5002 l = ml_get(lnum);
5003 p = after_label(l);
5004 if (p == NULL)
5005 return 0;
5006
5007 fp.col = (colnr_T)(p - l);
5008 fp.lnum = lnum;
5009 getvcol(curwin, &fp, &col, NULL, NULL);
5010 return (int)col;
5011}
5012
5013/*
5014 * Find indent for line "lnum", ignoring any case or jump label.
5015 * Also return a pointer to the text (after the label).
5016 * label: if (asdf && asdfasdf)
5017 * ^
5018 */
5019 static int
5020skip_label(lnum, pp, ind_maxcomment)
5021 linenr_T lnum;
5022 char_u **pp;
5023 int ind_maxcomment;
5024{
5025 char_u *l;
5026 int amount;
5027 pos_T cursor_save;
5028
5029 cursor_save = curwin->w_cursor;
5030 curwin->w_cursor.lnum = lnum;
5031 l = ml_get_curline();
5032 /* XXX */
5033 if (cin_iscase(l) || cin_isscopedecl(l) || cin_islabel(ind_maxcomment))
5034 {
5035 amount = get_indent_nolabel(lnum);
5036 l = after_label(ml_get_curline());
5037 if (l == NULL) /* just in case */
5038 l = ml_get_curline();
5039 }
5040 else
5041 {
5042 amount = get_indent();
5043 l = ml_get_curline();
5044 }
5045 *pp = l;
5046
5047 curwin->w_cursor = cursor_save;
5048 return amount;
5049}
5050
5051/*
5052 * Return the indent of the first variable name after a type in a declaration.
5053 * int a, indent of "a"
5054 * static struct foo b, indent of "b"
5055 * enum bla c, indent of "c"
5056 * Returns zero when it doesn't look like a declaration.
5057 */
5058 static int
5059cin_first_id_amount()
5060{
5061 char_u *line, *p, *s;
5062 int len;
5063 pos_T fp;
5064 colnr_T col;
5065
5066 line = ml_get_curline();
5067 p = skipwhite(line);
5068 len = skiptowhite(p) - p;
5069 if (len == 6 && STRNCMP(p, "static", 6) == 0)
5070 {
5071 p = skipwhite(p + 6);
5072 len = skiptowhite(p) - p;
5073 }
5074 if (len == 6 && STRNCMP(p, "struct", 6) == 0)
5075 p = skipwhite(p + 6);
5076 else if (len == 4 && STRNCMP(p, "enum", 4) == 0)
5077 p = skipwhite(p + 4);
5078 else if ((len == 8 && STRNCMP(p, "unsigned", 8) == 0)
5079 || (len == 6 && STRNCMP(p, "signed", 6) == 0))
5080 {
5081 s = skipwhite(p + len);
5082 if ((STRNCMP(s, "int", 3) == 0 && vim_iswhite(s[3]))
5083 || (STRNCMP(s, "long", 4) == 0 && vim_iswhite(s[4]))
5084 || (STRNCMP(s, "short", 5) == 0 && vim_iswhite(s[5]))
5085 || (STRNCMP(s, "char", 4) == 0 && vim_iswhite(s[4])))
5086 p = s;
5087 }
5088 for (len = 0; vim_isIDc(p[len]); ++len)
5089 ;
5090 if (len == 0 || !vim_iswhite(p[len]) || cin_nocode(p))
5091 return 0;
5092
5093 p = skipwhite(p + len);
5094 fp.lnum = curwin->w_cursor.lnum;
5095 fp.col = (colnr_T)(p - line);
5096 getvcol(curwin, &fp, &col, NULL, NULL);
5097 return (int)col;
5098}
5099
5100/*
5101 * Return the indent of the first non-blank after an equal sign.
5102 * char *foo = "here";
5103 * Return zero if no (useful) equal sign found.
5104 * Return -1 if the line above "lnum" ends in a backslash.
5105 * foo = "asdf\
5106 * asdf\
5107 * here";
5108 */
5109 static int
5110cin_get_equal_amount(lnum)
5111 linenr_T lnum;
5112{
5113 char_u *line;
5114 char_u *s;
5115 colnr_T col;
5116 pos_T fp;
5117
5118 if (lnum > 1)
5119 {
5120 line = ml_get(lnum - 1);
5121 if (*line != NUL && line[STRLEN(line) - 1] == '\\')
5122 return -1;
5123 }
5124
5125 line = s = ml_get(lnum);
5126 while (*s != NUL && vim_strchr((char_u *)"=;{}\"'", *s) == NULL)
5127 {
5128 if (cin_iscomment(s)) /* ignore comments */
5129 s = cin_skipcomment(s);
5130 else
5131 ++s;
5132 }
5133 if (*s != '=')
5134 return 0;
5135
5136 s = skipwhite(s + 1);
5137 if (cin_nocode(s))
5138 return 0;
5139
5140 if (*s == '"') /* nice alignment for continued strings */
5141 ++s;
5142
5143 fp.lnum = lnum;
5144 fp.col = (colnr_T)(s - line);
5145 getvcol(curwin, &fp, &col, NULL, NULL);
5146 return (int)col;
5147}
5148
5149/*
5150 * Recognize a preprocessor statement: Any line that starts with '#'.
5151 */
5152 static int
5153cin_ispreproc(s)
5154 char_u *s;
5155{
5156 s = skipwhite(s);
5157 if (*s == '#')
5158 return TRUE;
5159 return FALSE;
5160}
5161
5162/*
5163 * Return TRUE if line "*pp" at "*lnump" is a preprocessor statement or a
5164 * continuation line of a preprocessor statement. Decrease "*lnump" to the
5165 * start and return the line in "*pp".
5166 */
5167 static int
5168cin_ispreproc_cont(pp, lnump)
5169 char_u **pp;
5170 linenr_T *lnump;
5171{
5172 char_u *line = *pp;
5173 linenr_T lnum = *lnump;
5174 int retval = FALSE;
5175
Bram Moolenaard8e9bb22005-07-09 21:14:46 +00005176 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005177 {
5178 if (cin_ispreproc(line))
5179 {
5180 retval = TRUE;
5181 *lnump = lnum;
5182 break;
5183 }
5184 if (lnum == 1)
5185 break;
5186 line = ml_get(--lnum);
5187 if (*line == NUL || line[STRLEN(line) - 1] != '\\')
5188 break;
5189 }
5190
5191 if (lnum != *lnump)
5192 *pp = ml_get(*lnump);
5193 return retval;
5194}
5195
5196/*
5197 * Recognize the start of a C or C++ comment.
5198 */
5199 static int
5200cin_iscomment(p)
5201 char_u *p;
5202{
5203 return (p[0] == '/' && (p[1] == '*' || p[1] == '/'));
5204}
5205
5206/*
5207 * Recognize the start of a "//" comment.
5208 */
5209 static int
5210cin_islinecomment(p)
5211 char_u *p;
5212{
5213 return (p[0] == '/' && p[1] == '/');
5214}
5215
5216/*
5217 * Recognize a line that starts with '{' or '}', or ends with ';', '{' or '}'.
5218 * Don't consider "} else" a terminated line.
5219 * Return the character terminating the line (ending char's have precedence if
5220 * both apply in order to determine initializations).
5221 */
5222 static int
5223cin_isterminated(s, incl_open, incl_comma)
5224 char_u *s;
5225 int incl_open; /* include '{' at the end as terminator */
5226 int incl_comma; /* recognize a trailing comma */
5227{
5228 char_u found_start = 0;
5229
5230 s = cin_skipcomment(s);
5231
5232 if (*s == '{' || (*s == '}' && !cin_iselse(s)))
5233 found_start = *s;
5234
5235 while (*s)
5236 {
5237 /* skip over comments, "" strings and 'c'haracters */
5238 s = skip_string(cin_skipcomment(s));
5239 if ((*s == ';' || (incl_open && *s == '{') || *s == '}'
5240 || (incl_comma && *s == ','))
5241 && cin_nocode(s + 1))
5242 return *s;
5243
5244 if (*s)
5245 s++;
5246 }
5247 return found_start;
5248}
5249
5250/*
5251 * Recognize the basic picture of a function declaration -- it needs to
5252 * have an open paren somewhere and a close paren at the end of the line and
5253 * no semicolons anywhere.
5254 * When a line ends in a comma we continue looking in the next line.
5255 * "sp" points to a string with the line. When looking at other lines it must
5256 * be restored to the line. When it's NULL fetch lines here.
5257 * "lnum" is where we start looking.
5258 */
5259 static int
5260cin_isfuncdecl(sp, first_lnum)
5261 char_u **sp;
5262 linenr_T first_lnum;
5263{
5264 char_u *s;
5265 linenr_T lnum = first_lnum;
5266 int retval = FALSE;
5267
5268 if (sp == NULL)
5269 s = ml_get(lnum);
5270 else
5271 s = *sp;
5272
5273 while (*s && *s != '(' && *s != ';' && *s != '\'' && *s != '"')
5274 {
5275 if (cin_iscomment(s)) /* ignore comments */
5276 s = cin_skipcomment(s);
5277 else
5278 ++s;
5279 }
5280 if (*s != '(')
5281 return FALSE; /* ';', ' or " before any () or no '(' */
5282
5283 while (*s && *s != ';' && *s != '\'' && *s != '"')
5284 {
5285 if (*s == ')' && cin_nocode(s + 1))
5286 {
5287 /* ')' at the end: may have found a match
5288 * Check for he previous line not to end in a backslash:
5289 * #if defined(x) && \
5290 * defined(y)
5291 */
5292 lnum = first_lnum - 1;
5293 s = ml_get(lnum);
5294 if (*s == NUL || s[STRLEN(s) - 1] != '\\')
5295 retval = TRUE;
5296 goto done;
5297 }
5298 if (*s == ',' && cin_nocode(s + 1))
5299 {
5300 /* ',' at the end: continue looking in the next line */
5301 if (lnum >= curbuf->b_ml.ml_line_count)
5302 break;
5303
5304 s = ml_get(++lnum);
5305 }
5306 else if (cin_iscomment(s)) /* ignore comments */
5307 s = cin_skipcomment(s);
5308 else
5309 ++s;
5310 }
5311
5312done:
5313 if (lnum != first_lnum && sp != NULL)
5314 *sp = ml_get(first_lnum);
5315
5316 return retval;
5317}
5318
5319 static int
5320cin_isif(p)
5321 char_u *p;
5322{
5323 return (STRNCMP(p, "if", 2) == 0 && !vim_isIDc(p[2]));
5324}
5325
5326 static int
5327cin_iselse(p)
5328 char_u *p;
5329{
5330 if (*p == '}') /* accept "} else" */
5331 p = cin_skipcomment(p + 1);
5332 return (STRNCMP(p, "else", 4) == 0 && !vim_isIDc(p[4]));
5333}
5334
5335 static int
5336cin_isdo(p)
5337 char_u *p;
5338{
5339 return (STRNCMP(p, "do", 2) == 0 && !vim_isIDc(p[2]));
5340}
5341
5342/*
5343 * Check if this is a "while" that should have a matching "do".
5344 * We only accept a "while (condition) ;", with only white space between the
5345 * ')' and ';'. The condition may be spread over several lines.
5346 */
5347 static int
5348cin_iswhileofdo(p, lnum, ind_maxparen) /* XXX */
5349 char_u *p;
5350 linenr_T lnum;
5351 int ind_maxparen;
5352{
5353 pos_T cursor_save;
5354 pos_T *trypos;
5355 int retval = FALSE;
5356
5357 p = cin_skipcomment(p);
5358 if (*p == '}') /* accept "} while (cond);" */
5359 p = cin_skipcomment(p + 1);
5360 if (STRNCMP(p, "while", 5) == 0 && !vim_isIDc(p[5]))
5361 {
5362 cursor_save = curwin->w_cursor;
5363 curwin->w_cursor.lnum = lnum;
5364 curwin->w_cursor.col = 0;
5365 p = ml_get_curline();
5366 while (*p && *p != 'w') /* skip any '}', until the 'w' of the "while" */
5367 {
5368 ++p;
5369 ++curwin->w_cursor.col;
5370 }
5371 if ((trypos = findmatchlimit(NULL, 0, 0, ind_maxparen)) != NULL
5372 && *cin_skipcomment(ml_get_pos(trypos) + 1) == ';')
5373 retval = TRUE;
5374 curwin->w_cursor = cursor_save;
5375 }
5376 return retval;
5377}
5378
5379 static int
5380cin_isbreak(p)
5381 char_u *p;
5382{
5383 return (STRNCMP(p, "break", 5) == 0 && !vim_isIDc(p[5]));
5384}
5385
5386/* Find the position of a C++ base-class declaration or
5387 * constructor-initialization. eg:
5388 *
5389 * class MyClass :
5390 * baseClass <-- here
5391 * class MyClass : public baseClass,
5392 * anotherBaseClass <-- here (should probably lineup ??)
5393 * MyClass::MyClass(...) :
5394 * baseClass(...) <-- here (constructor-initialization)
5395 */
5396 static int
5397cin_is_cpp_baseclass(line, col)
5398 char_u *line;
5399 colnr_T *col;
5400{
5401 char_u *s;
5402 int class_or_struct, lookfor_ctor_init, cpp_base_class;
5403
5404 *col = 0;
5405
Bram Moolenaar21cf8232004-07-16 20:18:37 +00005406 s = skipwhite(line);
5407 if (*s == '#') /* skip #define FOO x ? (x) : x */
5408 return FALSE;
5409 s = cin_skipcomment(s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005410 if (*s == NUL)
5411 return FALSE;
5412
5413 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
5414
5415 while(*s != NUL)
5416 {
5417 if (s[0] == ':')
5418 {
5419 if (s[1] == ':')
5420 {
5421 /* skip double colon. It can't be a constructor
5422 * initialization any more */
5423 lookfor_ctor_init = FALSE;
5424 s = cin_skipcomment(s + 2);
5425 }
5426 else if (lookfor_ctor_init || class_or_struct)
5427 {
5428 /* we have something found, that looks like the start of
5429 * cpp-base-class-declaration or contructor-initialization */
5430 cpp_base_class = TRUE;
5431 lookfor_ctor_init = class_or_struct = FALSE;
5432 *col = 0;
5433 s = cin_skipcomment(s + 1);
5434 }
5435 else
5436 s = cin_skipcomment(s + 1);
5437 }
5438 else if ((STRNCMP(s, "class", 5) == 0 && !vim_isIDc(s[5]))
5439 || (STRNCMP(s, "struct", 6) == 0 && !vim_isIDc(s[6])))
5440 {
5441 class_or_struct = TRUE;
5442 lookfor_ctor_init = FALSE;
5443
5444 if (*s == 'c')
5445 s = cin_skipcomment(s + 5);
5446 else
5447 s = cin_skipcomment(s + 6);
5448 }
5449 else
5450 {
5451 if (s[0] == '{' || s[0] == '}' || s[0] == ';')
5452 {
5453 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
5454 }
5455 else if (s[0] == ')')
5456 {
5457 /* Constructor-initialization is assumed if we come across
5458 * something like "):" */
5459 class_or_struct = FALSE;
5460 lookfor_ctor_init = TRUE;
5461 }
5462 else if (!vim_isIDc(s[0]))
5463 {
5464 /* if it is not an identifier, we are wrong */
5465 class_or_struct = FALSE;
5466 lookfor_ctor_init = FALSE;
5467 }
5468 else if (*col == 0)
5469 {
5470 /* it can't be a constructor-initialization any more */
5471 lookfor_ctor_init = FALSE;
5472
5473 /* the first statement starts here: lineup with this one... */
5474 if (cpp_base_class && *col == 0)
5475 *col = (colnr_T)(s - line);
5476 }
5477
5478 s = cin_skipcomment(s + 1);
5479 }
5480 }
5481
5482 return cpp_base_class;
5483}
5484
5485/*
5486 * Return TRUE if string "s" ends with the string "find", possibly followed by
5487 * white space and comments. Skip strings and comments.
5488 * Ignore "ignore" after "find" if it's not NULL.
5489 */
5490 static int
5491cin_ends_in(s, find, ignore)
5492 char_u *s;
5493 char_u *find;
5494 char_u *ignore;
5495{
5496 char_u *p = s;
5497 char_u *r;
5498 int len = (int)STRLEN(find);
5499
5500 while (*p != NUL)
5501 {
5502 p = cin_skipcomment(p);
5503 if (STRNCMP(p, find, len) == 0)
5504 {
5505 r = skipwhite(p + len);
5506 if (ignore != NULL && STRNCMP(r, ignore, STRLEN(ignore)) == 0)
5507 r = skipwhite(r + STRLEN(ignore));
5508 if (cin_nocode(r))
5509 return TRUE;
5510 }
5511 if (*p != NUL)
5512 ++p;
5513 }
5514 return FALSE;
5515}
5516
5517/*
5518 * Skip strings, chars and comments until at or past "trypos".
5519 * Return the column found.
5520 */
5521 static int
5522cin_skip2pos(trypos)
5523 pos_T *trypos;
5524{
5525 char_u *line;
5526 char_u *p;
5527
5528 p = line = ml_get(trypos->lnum);
5529 while (*p && (colnr_T)(p - line) < trypos->col)
5530 {
5531 if (cin_iscomment(p))
5532 p = cin_skipcomment(p);
5533 else
5534 {
5535 p = skip_string(p);
5536 ++p;
5537 }
5538 }
5539 return (int)(p - line);
5540}
5541
5542/*
5543 * Find the '{' at the start of the block we are in.
5544 * Return NULL if no match found.
5545 * Ignore a '{' that is in a comment, makes indenting the next three lines
5546 * work. */
5547/* foo() */
5548/* { */
5549/* } */
5550
5551 static pos_T *
5552find_start_brace(ind_maxcomment) /* XXX */
5553 int ind_maxcomment;
5554{
5555 pos_T cursor_save;
5556 pos_T *trypos;
5557 pos_T *pos;
5558 static pos_T pos_copy;
5559
5560 cursor_save = curwin->w_cursor;
5561 while ((trypos = findmatchlimit(NULL, '{', FM_BLOCKSTOP, 0)) != NULL)
5562 {
5563 pos_copy = *trypos; /* copy pos_T, next findmatch will change it */
5564 trypos = &pos_copy;
5565 curwin->w_cursor = *trypos;
5566 pos = NULL;
5567 /* ignore the { if it's in a // comment */
5568 if ((colnr_T)cin_skip2pos(trypos) == trypos->col
5569 && (pos = find_start_comment(ind_maxcomment)) == NULL) /* XXX */
5570 break;
5571 if (pos != NULL)
5572 curwin->w_cursor.lnum = pos->lnum;
5573 }
5574 curwin->w_cursor = cursor_save;
5575 return trypos;
5576}
5577
5578/*
5579 * Find the matching '(', failing if it is in a comment.
5580 * Return NULL of no match found.
5581 */
5582 static pos_T *
5583find_match_paren(ind_maxparen, ind_maxcomment) /* XXX */
5584 int ind_maxparen;
5585 int ind_maxcomment;
5586{
5587 pos_T cursor_save;
5588 pos_T *trypos;
5589 static pos_T pos_copy;
5590
5591 cursor_save = curwin->w_cursor;
5592 if ((trypos = findmatchlimit(NULL, '(', 0, ind_maxparen)) != NULL)
5593 {
5594 /* check if the ( is in a // comment */
5595 if ((colnr_T)cin_skip2pos(trypos) > trypos->col)
5596 trypos = NULL;
5597 else
5598 {
5599 pos_copy = *trypos; /* copy trypos, findmatch will change it */
5600 trypos = &pos_copy;
5601 curwin->w_cursor = *trypos;
5602 if (find_start_comment(ind_maxcomment) != NULL) /* XXX */
5603 trypos = NULL;
5604 }
5605 }
5606 curwin->w_cursor = cursor_save;
5607 return trypos;
5608}
5609
5610/*
5611 * Return ind_maxparen corrected for the difference in line number between the
5612 * cursor position and "startpos". This makes sure that searching for a
5613 * matching paren above the cursor line doesn't find a match because of
5614 * looking a few lines further.
5615 */
5616 static int
5617corr_ind_maxparen(ind_maxparen, startpos)
5618 int ind_maxparen;
5619 pos_T *startpos;
5620{
5621 long n = (long)startpos->lnum - (long)curwin->w_cursor.lnum;
5622
5623 if (n > 0 && n < ind_maxparen / 2)
5624 return ind_maxparen - (int)n;
5625 return ind_maxparen;
5626}
5627
5628/*
5629 * Set w_cursor.col to the column number of the last unmatched ')' or '{' in
5630 * line "l".
5631 */
5632 static int
5633find_last_paren(l, start, end)
5634 char_u *l;
5635 int start, end;
5636{
5637 int i;
5638 int retval = FALSE;
5639 int open_count = 0;
5640
5641 curwin->w_cursor.col = 0; /* default is start of line */
5642
5643 for (i = 0; l[i]; i++)
5644 {
5645 i = (int)(cin_skipcomment(l + i) - l); /* ignore parens in comments */
5646 i = (int)(skip_string(l + i) - l); /* ignore parens in quotes */
5647 if (l[i] == start)
5648 ++open_count;
5649 else if (l[i] == end)
5650 {
5651 if (open_count > 0)
5652 --open_count;
5653 else
5654 {
5655 curwin->w_cursor.col = i;
5656 retval = TRUE;
5657 }
5658 }
5659 }
5660 return retval;
5661}
5662
5663 int
5664get_c_indent()
5665{
5666 /*
5667 * spaces from a block's opening brace the prevailing indent for that
5668 * block should be
5669 */
5670 int ind_level = curbuf->b_p_sw;
5671
5672 /*
5673 * spaces from the edge of the line an open brace that's at the end of a
5674 * line is imagined to be.
5675 */
5676 int ind_open_imag = 0;
5677
5678 /*
5679 * spaces from the prevailing indent for a line that is not precededof by
5680 * an opening brace.
5681 */
5682 int ind_no_brace = 0;
5683
5684 /*
5685 * column where the first { of a function should be located }
5686 */
5687 int ind_first_open = 0;
5688
5689 /*
5690 * spaces from the prevailing indent a leftmost open brace should be
5691 * located
5692 */
5693 int ind_open_extra = 0;
5694
5695 /*
5696 * spaces from the matching open brace (real location for one at the left
5697 * edge; imaginary location from one that ends a line) the matching close
5698 * brace should be located
5699 */
5700 int ind_close_extra = 0;
5701
5702 /*
5703 * spaces from the edge of the line an open brace sitting in the leftmost
5704 * column is imagined to be
5705 */
5706 int ind_open_left_imag = 0;
5707
5708 /*
5709 * spaces from the switch() indent a "case xx" label should be located
5710 */
5711 int ind_case = curbuf->b_p_sw;
5712
5713 /*
5714 * spaces from the "case xx:" code after a switch() should be located
5715 */
5716 int ind_case_code = curbuf->b_p_sw;
5717
5718 /*
5719 * lineup break at end of case in switch() with case label
5720 */
5721 int ind_case_break = 0;
5722
5723 /*
5724 * spaces from the class declaration indent a scope declaration label
5725 * should be located
5726 */
5727 int ind_scopedecl = curbuf->b_p_sw;
5728
5729 /*
5730 * spaces from the scope declaration label code should be located
5731 */
5732 int ind_scopedecl_code = curbuf->b_p_sw;
5733
5734 /*
5735 * amount K&R-style parameters should be indented
5736 */
5737 int ind_param = curbuf->b_p_sw;
5738
5739 /*
5740 * amount a function type spec should be indented
5741 */
5742 int ind_func_type = curbuf->b_p_sw;
5743
5744 /*
5745 * amount a cpp base class declaration or constructor initialization
5746 * should be indented
5747 */
5748 int ind_cpp_baseclass = curbuf->b_p_sw;
5749
5750 /*
5751 * additional spaces beyond the prevailing indent a continuation line
5752 * should be located
5753 */
5754 int ind_continuation = curbuf->b_p_sw;
5755
5756 /*
5757 * spaces from the indent of the line with an unclosed parentheses
5758 */
5759 int ind_unclosed = curbuf->b_p_sw * 2;
5760
5761 /*
5762 * spaces from the indent of the line with an unclosed parentheses, which
5763 * itself is also unclosed
5764 */
5765 int ind_unclosed2 = curbuf->b_p_sw;
5766
5767 /*
5768 * suppress ignoring spaces from the indent of a line starting with an
5769 * unclosed parentheses.
5770 */
5771 int ind_unclosed_noignore = 0;
5772
5773 /*
5774 * If the opening paren is the last nonwhite character on the line, and
5775 * ind_unclosed_wrapped is nonzero, use this indent relative to the outer
5776 * context (for very long lines).
5777 */
5778 int ind_unclosed_wrapped = 0;
5779
5780 /*
5781 * suppress ignoring white space when lining up with the character after
5782 * an unclosed parentheses.
5783 */
5784 int ind_unclosed_whiteok = 0;
5785
5786 /*
5787 * indent a closing parentheses under the line start of the matching
5788 * opening parentheses.
5789 */
5790 int ind_matching_paren = 0;
5791
5792 /*
5793 * Extra indent for comments.
5794 */
5795 int ind_comment = 0;
5796
5797 /*
5798 * spaces from the comment opener when there is nothing after it.
5799 */
5800 int ind_in_comment = 3;
5801
5802 /*
5803 * boolean: if non-zero, use ind_in_comment even if there is something
5804 * after the comment opener.
5805 */
5806 int ind_in_comment2 = 0;
5807
5808 /*
5809 * max lines to search for an open paren
5810 */
5811 int ind_maxparen = 20;
5812
5813 /*
5814 * max lines to search for an open comment
5815 */
5816 int ind_maxcomment = 70;
5817
5818 /*
5819 * handle braces for java code
5820 */
5821 int ind_java = 0;
5822
5823 /*
5824 * handle blocked cases correctly
5825 */
5826 int ind_keep_case_label = 0;
5827
5828 pos_T cur_curpos;
5829 int amount;
5830 int scope_amount;
5831 int cur_amount;
5832 colnr_T col;
5833 char_u *theline;
5834 char_u *linecopy;
5835 pos_T *trypos;
5836 pos_T *tryposBrace = NULL;
5837 pos_T our_paren_pos;
5838 char_u *start;
5839 int start_brace;
5840#define BRACE_IN_COL0 1 /* '{' is in comumn 0 */
5841#define BRACE_AT_START 2 /* '{' is at start of line */
5842#define BRACE_AT_END 3 /* '{' is at end of line */
5843 linenr_T ourscope;
5844 char_u *l;
5845 char_u *look;
5846 char_u terminated;
5847 int lookfor;
5848#define LOOKFOR_INITIAL 0
5849#define LOOKFOR_IF 1
5850#define LOOKFOR_DO 2
5851#define LOOKFOR_CASE 3
5852#define LOOKFOR_ANY 4
5853#define LOOKFOR_TERM 5
5854#define LOOKFOR_UNTERM 6
5855#define LOOKFOR_SCOPEDECL 7
5856#define LOOKFOR_NOBREAK 8
5857#define LOOKFOR_CPP_BASECLASS 9
5858#define LOOKFOR_ENUM_OR_INIT 10
5859
5860 int whilelevel;
5861 linenr_T lnum;
5862 char_u *options;
5863 int fraction = 0; /* init for GCC */
5864 int divider;
5865 int n;
5866 int iscase;
5867 int lookfor_break;
5868 int cont_amount = 0; /* amount for continuation line */
5869
5870 for (options = curbuf->b_p_cino; *options; )
5871 {
5872 l = options++;
5873 if (*options == '-')
5874 ++options;
5875 n = getdigits(&options);
5876 divider = 0;
5877 if (*options == '.') /* ".5s" means a fraction */
5878 {
5879 fraction = atol((char *)++options);
5880 while (VIM_ISDIGIT(*options))
5881 {
5882 ++options;
5883 if (divider)
5884 divider *= 10;
5885 else
5886 divider = 10;
5887 }
5888 }
5889 if (*options == 's') /* "2s" means two times 'shiftwidth' */
5890 {
5891 if (n == 0 && fraction == 0)
5892 n = curbuf->b_p_sw; /* just "s" is one 'shiftwidth' */
5893 else
5894 {
5895 n *= curbuf->b_p_sw;
5896 if (divider)
5897 n += (curbuf->b_p_sw * fraction + divider / 2) / divider;
5898 }
5899 ++options;
5900 }
5901 if (l[1] == '-')
5902 n = -n;
5903 /* When adding an entry here, also update the default 'cinoptions' in
5904 * change.txt, and add explanation for it! */
5905 switch (*l)
5906 {
5907 case '>': ind_level = n; break;
5908 case 'e': ind_open_imag = n; break;
5909 case 'n': ind_no_brace = n; break;
5910 case 'f': ind_first_open = n; break;
5911 case '{': ind_open_extra = n; break;
5912 case '}': ind_close_extra = n; break;
5913 case '^': ind_open_left_imag = n; break;
5914 case ':': ind_case = n; break;
5915 case '=': ind_case_code = n; break;
5916 case 'b': ind_case_break = n; break;
5917 case 'p': ind_param = n; break;
5918 case 't': ind_func_type = n; break;
5919 case '/': ind_comment = n; break;
5920 case 'c': ind_in_comment = n; break;
5921 case 'C': ind_in_comment2 = n; break;
5922 case 'i': ind_cpp_baseclass = n; break;
5923 case '+': ind_continuation = n; break;
5924 case '(': ind_unclosed = n; break;
5925 case 'u': ind_unclosed2 = n; break;
5926 case 'U': ind_unclosed_noignore = n; break;
5927 case 'W': ind_unclosed_wrapped = n; break;
5928 case 'w': ind_unclosed_whiteok = n; break;
5929 case 'm': ind_matching_paren = n; break;
5930 case ')': ind_maxparen = n; break;
5931 case '*': ind_maxcomment = n; break;
5932 case 'g': ind_scopedecl = n; break;
5933 case 'h': ind_scopedecl_code = n; break;
5934 case 'j': ind_java = n; break;
5935 case 'l': ind_keep_case_label = n; break;
5936 }
5937 }
5938
5939 /* remember where the cursor was when we started */
5940 cur_curpos = curwin->w_cursor;
5941
5942 /* Get a copy of the current contents of the line.
5943 * This is required, because only the most recent line obtained with
5944 * ml_get is valid! */
5945 linecopy = vim_strsave(ml_get(cur_curpos.lnum));
5946 if (linecopy == NULL)
5947 return 0;
5948
5949 /*
5950 * In insert mode and the cursor is on a ')' truncate the line at the
5951 * cursor position. We don't want to line up with the matching '(' when
5952 * inserting new stuff.
5953 * For unknown reasons the cursor might be past the end of the line, thus
5954 * check for that.
5955 */
5956 if ((State & INSERT)
5957 && curwin->w_cursor.col < STRLEN(linecopy)
5958 && linecopy[curwin->w_cursor.col] == ')')
5959 linecopy[curwin->w_cursor.col] = NUL;
5960
5961 theline = skipwhite(linecopy);
5962
5963 /* move the cursor to the start of the line */
5964
5965 curwin->w_cursor.col = 0;
5966
5967 /*
5968 * #defines and so on always go at the left when included in 'cinkeys'.
5969 */
5970 if (*theline == '#' && (*linecopy == '#' || in_cinkeys('#', ' ', TRUE)))
5971 {
5972 amount = 0;
5973 }
5974
5975 /*
5976 * Is it a non-case label? Then that goes at the left margin too.
5977 */
5978 else if (cin_islabel(ind_maxcomment)) /* XXX */
5979 {
5980 amount = 0;
5981 }
5982
5983 /*
5984 * If we're inside a "//" comment and there is a "//" comment in a
5985 * previous line, lineup with that one.
5986 */
5987 else if (cin_islinecomment(theline)
5988 && (trypos = find_line_comment()) != NULL) /* XXX */
5989 {
5990 /* find how indented the line beginning the comment is */
5991 getvcol(curwin, trypos, &col, NULL, NULL);
5992 amount = col;
5993 }
5994
5995 /*
5996 * If we're inside a comment and not looking at the start of the
5997 * comment, try using the 'comments' option.
5998 */
5999 else if (!cin_iscomment(theline)
6000 && (trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
6001 {
6002 int lead_start_len = 2;
6003 int lead_middle_len = 1;
6004 char_u lead_start[COM_MAX_LEN]; /* start-comment string */
6005 char_u lead_middle[COM_MAX_LEN]; /* middle-comment string */
6006 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
6007 char_u *p;
6008 int start_align = 0;
6009 int start_off = 0;
6010 int done = FALSE;
6011
6012 /* find how indented the line beginning the comment is */
6013 getvcol(curwin, trypos, &col, NULL, NULL);
6014 amount = col;
6015
6016 p = curbuf->b_p_com;
6017 while (*p != NUL)
6018 {
6019 int align = 0;
6020 int off = 0;
6021 int what = 0;
6022
6023 while (*p != NUL && *p != ':')
6024 {
6025 if (*p == COM_START || *p == COM_END || *p == COM_MIDDLE)
6026 what = *p++;
6027 else if (*p == COM_LEFT || *p == COM_RIGHT)
6028 align = *p++;
6029 else if (VIM_ISDIGIT(*p) || *p == '-')
6030 off = getdigits(&p);
6031 else
6032 ++p;
6033 }
6034
6035 if (*p == ':')
6036 ++p;
6037 (void)copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
6038 if (what == COM_START)
6039 {
6040 STRCPY(lead_start, lead_end);
6041 lead_start_len = (int)STRLEN(lead_start);
6042 start_off = off;
6043 start_align = align;
6044 }
6045 else if (what == COM_MIDDLE)
6046 {
6047 STRCPY(lead_middle, lead_end);
6048 lead_middle_len = (int)STRLEN(lead_middle);
6049 }
6050 else if (what == COM_END)
6051 {
6052 /* If our line starts with the middle comment string, line it
6053 * up with the comment opener per the 'comments' option. */
6054 if (STRNCMP(theline, lead_middle, lead_middle_len) == 0
6055 && STRNCMP(theline, lead_end, STRLEN(lead_end)) != 0)
6056 {
6057 done = TRUE;
6058 if (curwin->w_cursor.lnum > 1)
6059 {
6060 /* If the start comment string matches in the previous
6061 * line, use the indent of that line pluss offset. If
6062 * the middle comment string matches in the previous
6063 * line, use the indent of that line. XXX */
6064 look = skipwhite(ml_get(curwin->w_cursor.lnum - 1));
6065 if (STRNCMP(look, lead_start, lead_start_len) == 0)
6066 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6067 else if (STRNCMP(look, lead_middle,
6068 lead_middle_len) == 0)
6069 {
6070 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6071 break;
6072 }
6073 /* If the start comment string doesn't match with the
6074 * start of the comment, skip this entry. XXX */
6075 else if (STRNCMP(ml_get(trypos->lnum) + trypos->col,
6076 lead_start, lead_start_len) != 0)
6077 continue;
6078 }
6079 if (start_off != 0)
6080 amount += start_off;
6081 else if (start_align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006082 amount += vim_strsize(lead_start)
6083 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006084 break;
6085 }
6086
6087 /* If our line starts with the end comment string, line it up
6088 * with the middle comment */
6089 if (STRNCMP(theline, lead_middle, lead_middle_len) != 0
6090 && STRNCMP(theline, lead_end, STRLEN(lead_end)) == 0)
6091 {
6092 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6093 /* XXX */
6094 if (off != 0)
6095 amount += off;
6096 else if (align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006097 amount += vim_strsize(lead_start)
6098 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006099 done = TRUE;
6100 break;
6101 }
6102 }
6103 }
6104
6105 /* If our line starts with an asterisk, line up with the
6106 * asterisk in the comment opener; otherwise, line up
6107 * with the first character of the comment text.
6108 */
6109 if (done)
6110 ;
6111 else if (theline[0] == '*')
6112 amount += 1;
6113 else
6114 {
6115 /*
6116 * If we are more than one line away from the comment opener, take
6117 * the indent of the previous non-empty line. If 'cino' has "CO"
6118 * and we are just below the comment opener and there are any
6119 * white characters after it line up with the text after it;
6120 * otherwise, add the amount specified by "c" in 'cino'
6121 */
6122 amount = -1;
6123 for (lnum = cur_curpos.lnum - 1; lnum > trypos->lnum; --lnum)
6124 {
6125 if (linewhite(lnum)) /* skip blank lines */
6126 continue;
6127 amount = get_indent_lnum(lnum); /* XXX */
6128 break;
6129 }
6130 if (amount == -1) /* use the comment opener */
6131 {
6132 if (!ind_in_comment2)
6133 {
6134 start = ml_get(trypos->lnum);
6135 look = start + trypos->col + 2; /* skip / and * */
6136 if (*look != NUL) /* if something after it */
6137 trypos->col = (colnr_T)(skipwhite(look) - start);
6138 }
6139 getvcol(curwin, trypos, &col, NULL, NULL);
6140 amount = col;
6141 if (ind_in_comment2 || *look == NUL)
6142 amount += ind_in_comment;
6143 }
6144 }
6145 }
6146
6147 /*
6148 * Are we inside parentheses or braces?
6149 */ /* XXX */
6150 else if (((trypos = find_match_paren(ind_maxparen, ind_maxcomment)) != NULL
6151 && ind_java == 0)
6152 || (tryposBrace = find_start_brace(ind_maxcomment)) != NULL
6153 || trypos != NULL)
6154 {
6155 if (trypos != NULL && tryposBrace != NULL)
6156 {
6157 /* Both an unmatched '(' and '{' is found. Use the one which is
6158 * closer to the current cursor position, set the other to NULL. */
6159 if (trypos->lnum != tryposBrace->lnum
6160 ? trypos->lnum < tryposBrace->lnum
6161 : trypos->col < tryposBrace->col)
6162 trypos = NULL;
6163 else
6164 tryposBrace = NULL;
6165 }
6166
6167 if (trypos != NULL)
6168 {
6169 /*
6170 * If the matching paren is more than one line away, use the indent of
6171 * a previous non-empty line that matches the same paren.
6172 */
6173 amount = -1;
6174 cur_amount = MAXCOL;
6175 our_paren_pos = *trypos;
6176 for (lnum = cur_curpos.lnum - 1; lnum > our_paren_pos.lnum; --lnum)
6177 {
6178 l = skipwhite(ml_get(lnum));
6179 if (cin_nocode(l)) /* skip comment lines */
6180 continue;
6181 if (cin_ispreproc_cont(&l, &lnum)) /* ignore #defines, #if, etc. */
6182 continue;
6183 curwin->w_cursor.lnum = lnum;
6184
6185 /* Skip a comment. XXX */
6186 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
6187 {
6188 lnum = trypos->lnum + 1;
6189 continue;
6190 }
6191
6192 /* XXX */
6193 if ((trypos = find_match_paren(
6194 corr_ind_maxparen(ind_maxparen, &cur_curpos),
6195 ind_maxcomment)) != NULL
6196 && trypos->lnum == our_paren_pos.lnum
6197 && trypos->col == our_paren_pos.col)
6198 {
6199 amount = get_indent_lnum(lnum); /* XXX */
6200
6201 if (theline[0] == ')')
6202 {
6203 if (our_paren_pos.lnum != lnum && cur_amount > amount)
6204 cur_amount = amount;
6205 amount = -1;
6206 }
6207 break;
6208 }
6209 }
6210
6211 /*
6212 * Line up with line where the matching paren is. XXX
6213 * If the line starts with a '(' or the indent for unclosed
6214 * parentheses is zero, line up with the unclosed parentheses.
6215 */
6216 if (amount == -1)
6217 {
6218 amount = skip_label(our_paren_pos.lnum, &look, ind_maxcomment);
6219 if (theline[0] == ')' || ind_unclosed == 0
6220 || (!ind_unclosed_noignore && *skipwhite(look) == '('))
6221 {
6222 /*
6223 * If we're looking at a close paren, line up right there;
6224 * otherwise, line up with the next (non-white) character.
6225 * When ind_unclosed_wrapped is set and the matching paren is
6226 * the last nonwhite character of the line, use either the
6227 * indent of the current line or the indentation of the next
6228 * outer paren and add ind_unclosed_wrapped (for very long
6229 * lines).
6230 */
6231 if (theline[0] != ')')
6232 {
6233 cur_amount = MAXCOL;
6234 l = ml_get(our_paren_pos.lnum);
6235 if (ind_unclosed_wrapped
6236 && cin_ends_in(l, (char_u *)"(", NULL))
6237 {
6238 /* look for opening unmatched paren, indent one level
6239 * for each additional level */
6240 n = 1;
6241 for (col = 0; col < our_paren_pos.col; ++col)
6242 {
6243 switch (l[col])
6244 {
6245 case '(':
6246 case '{': ++n;
6247 break;
6248
6249 case ')':
6250 case '}': if (n > 1)
6251 --n;
6252 break;
6253 }
6254 }
6255
6256 our_paren_pos.col = 0;
6257 amount += n * ind_unclosed_wrapped;
6258 }
6259 else if (ind_unclosed_whiteok)
6260 our_paren_pos.col++;
6261 else
6262 {
6263 col = our_paren_pos.col + 1;
6264 while (vim_iswhite(l[col]))
6265 col++;
6266 if (l[col] != NUL) /* In case of trailing space */
6267 our_paren_pos.col = col;
6268 else
6269 our_paren_pos.col++;
6270 }
6271 }
6272
6273 /*
6274 * Find how indented the paren is, or the character after it
6275 * if we did the above "if".
6276 */
6277 if (our_paren_pos.col > 0)
6278 {
6279 getvcol(curwin, &our_paren_pos, &col, NULL, NULL);
6280 if (cur_amount > (int)col)
6281 cur_amount = col;
6282 }
6283 }
6284
6285 if (theline[0] == ')' && ind_matching_paren)
6286 {
6287 /* Line up with the start of the matching paren line. */
6288 }
6289 else if (ind_unclosed == 0 || (!ind_unclosed_noignore
6290 && *skipwhite(look) == '('))
6291 {
6292 if (cur_amount != MAXCOL)
6293 amount = cur_amount;
6294 }
6295 else
6296 {
6297 /* add ind_unclosed2 for each '(' before our matching one */
6298 col = our_paren_pos.col;
6299 while (our_paren_pos.col > 0)
6300 {
6301 --our_paren_pos.col;
6302 switch (*ml_get_pos(&our_paren_pos))
6303 {
6304 case '(': amount += ind_unclosed2;
6305 col = our_paren_pos.col;
6306 break;
6307 case ')': amount -= ind_unclosed2;
6308 col = MAXCOL;
6309 break;
6310 }
6311 }
6312
6313 /* Use ind_unclosed once, when the first '(' is not inside
6314 * braces */
6315 if (col == MAXCOL)
6316 amount += ind_unclosed;
6317 else
6318 {
6319 curwin->w_cursor.lnum = our_paren_pos.lnum;
6320 curwin->w_cursor.col = col;
6321 if ((trypos = find_match_paren(ind_maxparen,
6322 ind_maxcomment)) != NULL)
6323 amount += ind_unclosed2;
6324 else
6325 amount += ind_unclosed;
6326 }
6327 /*
6328 * For a line starting with ')' use the minimum of the two
6329 * positions, to avoid giving it more indent than the previous
6330 * lines:
6331 * func_long_name( if (x
6332 * arg && yy
6333 * ) ^ not here ) ^ not here
6334 */
6335 if (cur_amount < amount)
6336 amount = cur_amount;
6337 }
6338 }
6339
6340 /* add extra indent for a comment */
6341 if (cin_iscomment(theline))
6342 amount += ind_comment;
6343 }
6344
6345 /*
6346 * Are we at least inside braces, then?
6347 */
6348 else
6349 {
6350 trypos = tryposBrace;
6351
6352 ourscope = trypos->lnum;
6353 start = ml_get(ourscope);
6354
6355 /*
6356 * Now figure out how indented the line is in general.
6357 * If the brace was at the start of the line, we use that;
6358 * otherwise, check out the indentation of the line as
6359 * a whole and then add the "imaginary indent" to that.
6360 */
6361 look = skipwhite(start);
6362 if (*look == '{')
6363 {
6364 getvcol(curwin, trypos, &col, NULL, NULL);
6365 amount = col;
6366 if (*start == '{')
6367 start_brace = BRACE_IN_COL0;
6368 else
6369 start_brace = BRACE_AT_START;
6370 }
6371 else
6372 {
6373 /*
6374 * that opening brace might have been on a continuation
6375 * line. if so, find the start of the line.
6376 */
6377 curwin->w_cursor.lnum = ourscope;
6378
6379 /*
6380 * position the cursor over the rightmost paren, so that
6381 * matching it will take us back to the start of the line.
6382 */
6383 lnum = ourscope;
6384 if (find_last_paren(start, '(', ')')
6385 && (trypos = find_match_paren(ind_maxparen,
6386 ind_maxcomment)) != NULL)
6387 lnum = trypos->lnum;
6388
6389 /*
6390 * It could have been something like
6391 * case 1: if (asdf &&
6392 * ldfd) {
6393 * }
6394 */
6395 if (ind_keep_case_label && cin_iscase(skipwhite(ml_get_curline())))
6396 amount = get_indent();
6397 else
6398 amount = skip_label(lnum, &l, ind_maxcomment);
6399
6400 start_brace = BRACE_AT_END;
6401 }
6402
6403 /*
6404 * if we're looking at a closing brace, that's where
6405 * we want to be. otherwise, add the amount of room
6406 * that an indent is supposed to be.
6407 */
6408 if (theline[0] == '}')
6409 {
6410 /*
6411 * they may want closing braces to line up with something
6412 * other than the open brace. indulge them, if so.
6413 */
6414 amount += ind_close_extra;
6415 }
6416 else
6417 {
6418 /*
6419 * If we're looking at an "else", try to find an "if"
6420 * to match it with.
6421 * If we're looking at a "while", try to find a "do"
6422 * to match it with.
6423 */
6424 lookfor = LOOKFOR_INITIAL;
6425 if (cin_iselse(theline))
6426 lookfor = LOOKFOR_IF;
6427 else if (cin_iswhileofdo(theline, cur_curpos.lnum, ind_maxparen))
6428 /* XXX */
6429 lookfor = LOOKFOR_DO;
6430 if (lookfor != LOOKFOR_INITIAL)
6431 {
6432 curwin->w_cursor.lnum = cur_curpos.lnum;
6433 if (find_match(lookfor, ourscope, ind_maxparen,
6434 ind_maxcomment) == OK)
6435 {
6436 amount = get_indent(); /* XXX */
6437 goto theend;
6438 }
6439 }
6440
6441 /*
6442 * We get here if we are not on an "while-of-do" or "else" (or
6443 * failed to find a matching "if").
6444 * Search backwards for something to line up with.
6445 * First set amount for when we don't find anything.
6446 */
6447
6448 /*
6449 * if the '{' is _really_ at the left margin, use the imaginary
6450 * location of a left-margin brace. Otherwise, correct the
6451 * location for ind_open_extra.
6452 */
6453
6454 if (start_brace == BRACE_IN_COL0) /* '{' is in column 0 */
6455 {
6456 amount = ind_open_left_imag;
6457 }
6458 else
6459 {
6460 if (start_brace == BRACE_AT_END) /* '{' is at end of line */
6461 amount += ind_open_imag;
6462 else
6463 {
6464 /* Compensate for adding ind_open_extra later. */
6465 amount -= ind_open_extra;
6466 if (amount < 0)
6467 amount = 0;
6468 }
6469 }
6470
6471 lookfor_break = FALSE;
6472
6473 if (cin_iscase(theline)) /* it's a switch() label */
6474 {
6475 lookfor = LOOKFOR_CASE; /* find a previous switch() label */
6476 amount += ind_case;
6477 }
6478 else if (cin_isscopedecl(theline)) /* private:, ... */
6479 {
6480 lookfor = LOOKFOR_SCOPEDECL; /* class decl is this block */
6481 amount += ind_scopedecl;
6482 }
6483 else
6484 {
6485 if (ind_case_break && cin_isbreak(theline)) /* break; ... */
6486 lookfor_break = TRUE;
6487
6488 lookfor = LOOKFOR_INITIAL;
6489 amount += ind_level; /* ind_level from start of block */
6490 }
6491 scope_amount = amount;
6492 whilelevel = 0;
6493
6494 /*
6495 * Search backwards. If we find something we recognize, line up
6496 * with that.
6497 *
6498 * if we're looking at an open brace, indent
6499 * the usual amount relative to the conditional
6500 * that opens the block.
6501 */
6502 curwin->w_cursor = cur_curpos;
6503 for (;;)
6504 {
6505 curwin->w_cursor.lnum--;
6506 curwin->w_cursor.col = 0;
6507
6508 /*
6509 * If we went all the way back to the start of our scope, line
6510 * up with it.
6511 */
6512 if (curwin->w_cursor.lnum <= ourscope)
6513 {
6514 /* we reached end of scope:
6515 * if looking for a enum or structure initialization
6516 * go further back:
6517 * if it is an initializer (enum xxx or xxx =), then
6518 * don't add ind_continuation, otherwise it is a variable
6519 * declaration:
6520 * int x,
6521 * here; <-- add ind_continuation
6522 */
6523 if (lookfor == LOOKFOR_ENUM_OR_INIT)
6524 {
6525 if (curwin->w_cursor.lnum == 0
6526 || curwin->w_cursor.lnum
6527 < ourscope - ind_maxparen)
6528 {
6529 /* nothing found (abuse ind_maxparen as limit)
6530 * assume terminated line (i.e. a variable
6531 * initialization) */
6532 if (cont_amount > 0)
6533 amount = cont_amount;
6534 else
6535 amount += ind_continuation;
6536 break;
6537 }
6538
6539 l = ml_get_curline();
6540
6541 /*
6542 * If we're in a comment now, skip to the start of the
6543 * comment.
6544 */
6545 trypos = find_start_comment(ind_maxcomment);
6546 if (trypos != NULL)
6547 {
6548 curwin->w_cursor.lnum = trypos->lnum + 1;
6549 continue;
6550 }
6551
6552 /*
6553 * Skip preprocessor directives and blank lines.
6554 */
6555 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
6556 continue;
6557
6558 if (cin_nocode(l))
6559 continue;
6560
6561 terminated = cin_isterminated(l, FALSE, TRUE);
6562
6563 /*
6564 * If we are at top level and the line looks like a
6565 * function declaration, we are done
6566 * (it's a variable declaration).
6567 */
6568 if (start_brace != BRACE_IN_COL0
6569 || !cin_isfuncdecl(&l, curwin->w_cursor.lnum))
6570 {
6571 /* if the line is terminated with another ','
6572 * it is a continued variable initialization.
6573 * don't add extra indent.
6574 * TODO: does not work, if a function
6575 * declaration is split over multiple lines:
6576 * cin_isfuncdecl returns FALSE then.
6577 */
6578 if (terminated == ',')
6579 break;
6580
6581 /* if it es a enum declaration or an assignment,
6582 * we are done.
6583 */
6584 if (terminated != ';' && cin_isinit())
6585 break;
6586
6587 /* nothing useful found */
6588 if (terminated == 0 || terminated == '{')
6589 continue;
6590 }
6591
6592 if (terminated != ';')
6593 {
6594 /* Skip parens and braces. Position the cursor
6595 * over the rightmost paren, so that matching it
6596 * will take us back to the start of the line.
6597 */ /* XXX */
6598 trypos = NULL;
6599 if (find_last_paren(l, '(', ')'))
6600 trypos = find_match_paren(ind_maxparen,
6601 ind_maxcomment);
6602
6603 if (trypos == NULL && find_last_paren(l, '{', '}'))
6604 trypos = find_start_brace(ind_maxcomment);
6605
6606 if (trypos != NULL)
6607 {
6608 curwin->w_cursor.lnum = trypos->lnum + 1;
6609 continue;
6610 }
6611 }
6612
6613 /* it's a variable declaration, add indentation
6614 * like in
6615 * int a,
6616 * b;
6617 */
6618 if (cont_amount > 0)
6619 amount = cont_amount;
6620 else
6621 amount += ind_continuation;
6622 }
6623 else if (lookfor == LOOKFOR_UNTERM)
6624 {
6625 if (cont_amount > 0)
6626 amount = cont_amount;
6627 else
6628 amount += ind_continuation;
6629 }
6630 else if (lookfor != LOOKFOR_TERM
6631 && lookfor != LOOKFOR_CPP_BASECLASS)
6632 {
6633 amount = scope_amount;
6634 if (theline[0] == '{')
6635 amount += ind_open_extra;
6636 }
6637 break;
6638 }
6639
6640 /*
6641 * If we're in a comment now, skip to the start of the comment.
6642 */ /* XXX */
6643 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
6644 {
6645 curwin->w_cursor.lnum = trypos->lnum + 1;
6646 continue;
6647 }
6648
6649 l = ml_get_curline();
6650
6651 /*
6652 * If this is a switch() label, may line up relative to that.
6653 * if this is a C++ scope declaration, do the same.
6654 */
6655 iscase = cin_iscase(l);
6656 if (iscase || cin_isscopedecl(l))
6657 {
6658 /* we are only looking for cpp base class
6659 * declaration/initialization any longer */
6660 if (lookfor == LOOKFOR_CPP_BASECLASS)
6661 break;
6662
6663 /* When looking for a "do" we are not interested in
6664 * labels. */
6665 if (whilelevel > 0)
6666 continue;
6667
6668 /*
6669 * case xx:
6670 * c = 99 + <- this indent plus continuation
6671 *-> here;
6672 */
6673 if (lookfor == LOOKFOR_UNTERM
6674 || lookfor == LOOKFOR_ENUM_OR_INIT)
6675 {
6676 if (cont_amount > 0)
6677 amount = cont_amount;
6678 else
6679 amount += ind_continuation;
6680 break;
6681 }
6682
6683 /*
6684 * case xx: <- line up with this case
6685 * x = 333;
6686 * case yy:
6687 */
6688 if ( (iscase && lookfor == LOOKFOR_CASE)
6689 || (iscase && lookfor_break)
6690 || (!iscase && lookfor == LOOKFOR_SCOPEDECL))
6691 {
6692 /*
6693 * Check that this case label is not for another
6694 * switch()
6695 */ /* XXX */
6696 if ((trypos = find_start_brace(ind_maxcomment)) ==
6697 NULL || trypos->lnum == ourscope)
6698 {
6699 amount = get_indent(); /* XXX */
6700 break;
6701 }
6702 continue;
6703 }
6704
6705 n = get_indent_nolabel(curwin->w_cursor.lnum); /* XXX */
6706
6707 /*
6708 * case xx: if (cond) <- line up with this if
6709 * y = y + 1;
6710 * -> s = 99;
6711 *
6712 * case xx:
6713 * if (cond) <- line up with this line
6714 * y = y + 1;
6715 * -> s = 99;
6716 */
6717 if (lookfor == LOOKFOR_TERM)
6718 {
6719 if (n)
6720 amount = n;
6721
6722 if (!lookfor_break)
6723 break;
6724 }
6725
6726 /*
6727 * case xx: x = x + 1; <- line up with this x
6728 * -> y = y + 1;
6729 *
6730 * case xx: if (cond) <- line up with this if
6731 * -> y = y + 1;
6732 */
6733 if (n)
6734 {
6735 amount = n;
6736 l = after_label(ml_get_curline());
6737 if (l != NULL && cin_is_cinword(l))
6738 amount += ind_level + ind_no_brace;
6739 break;
6740 }
6741
6742 /*
6743 * Try to get the indent of a statement before the switch
6744 * label. If nothing is found, line up relative to the
6745 * switch label.
6746 * break; <- may line up with this line
6747 * case xx:
6748 * -> y = 1;
6749 */
6750 scope_amount = get_indent() + (iscase /* XXX */
6751 ? ind_case_code : ind_scopedecl_code);
6752 lookfor = ind_case_break ? LOOKFOR_NOBREAK : LOOKFOR_ANY;
6753 continue;
6754 }
6755
6756 /*
6757 * Looking for a switch() label or C++ scope declaration,
6758 * ignore other lines, skip {}-blocks.
6759 */
6760 if (lookfor == LOOKFOR_CASE || lookfor == LOOKFOR_SCOPEDECL)
6761 {
6762 if (find_last_paren(l, '{', '}') && (trypos =
6763 find_start_brace(ind_maxcomment)) != NULL)
6764 curwin->w_cursor.lnum = trypos->lnum + 1;
6765 continue;
6766 }
6767
6768 /*
6769 * Ignore jump labels with nothing after them.
6770 */
6771 if (cin_islabel(ind_maxcomment))
6772 {
6773 l = after_label(ml_get_curline());
6774 if (l == NULL || cin_nocode(l))
6775 continue;
6776 }
6777
6778 /*
6779 * Ignore #defines, #if, etc.
6780 * Ignore comment and empty lines.
6781 * (need to get the line again, cin_islabel() may have
6782 * unlocked it)
6783 */
6784 l = ml_get_curline();
6785 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum)
6786 || cin_nocode(l))
6787 continue;
6788
6789 /*
6790 * Are we at the start of a cpp base class declaration or
6791 * constructor initialization?
6792 */ /* XXX */
6793 if (lookfor != LOOKFOR_TERM && ind_cpp_baseclass
6794 && cin_is_cpp_baseclass(l, &col))
6795 {
6796 if (lookfor == LOOKFOR_UNTERM)
6797 {
6798 if (cont_amount > 0)
6799 amount = cont_amount;
6800 else
6801 amount += ind_continuation;
6802 }
6803 else if (col == 0 || theline[0] == '{')
6804 {
6805 amount = get_indent();
6806 if (find_last_paren(l, '(', ')')
6807 && (trypos = find_match_paren(ind_maxparen,
6808 ind_maxcomment)) != NULL)
6809 amount = get_indent_lnum(trypos->lnum); /* XXX */
6810 if (theline[0] != '{')
6811 amount += ind_cpp_baseclass;
6812 }
6813 else
6814 {
6815 curwin->w_cursor.col = col;
6816 getvcol(curwin, &curwin->w_cursor, &col, NULL, NULL);
6817 amount = (int)col;
6818 }
6819 break;
6820 }
6821 else if (lookfor == LOOKFOR_CPP_BASECLASS)
6822 {
6823 /* only look, whether there is a cpp base class
6824 * declaration or initialization before the opening brace. */
6825 if (cin_isterminated(l, TRUE, FALSE))
6826 break;
6827 else
6828 continue;
6829 }
6830
6831 /*
6832 * What happens next depends on the line being terminated.
6833 * If terminated with a ',' only consider it terminating if
6834 * there is anoter unterminated statement behind, eg:
6835 * 123,
6836 * sizeof
6837 * here
6838 * Otherwise check whether it is a enumeration or structure
6839 * initialisation (not indented) or a variable declaration
6840 * (indented).
6841 */
6842 terminated = cin_isterminated(l, FALSE, TRUE);
6843
6844 if (terminated == 0 || (lookfor != LOOKFOR_UNTERM
6845 && terminated == ','))
6846 {
6847 /*
6848 * if we're in the middle of a paren thing,
6849 * go back to the line that starts it so
6850 * we can get the right prevailing indent
6851 * if ( foo &&
6852 * bar )
6853 */
6854 /*
6855 * position the cursor over the rightmost paren, so that
6856 * matching it will take us back to the start of the line.
6857 */
6858 (void)find_last_paren(l, '(', ')');
6859 trypos = find_match_paren(
6860 corr_ind_maxparen(ind_maxparen, &cur_curpos),
6861 ind_maxcomment);
6862
6863 /*
6864 * If we are looking for ',', we also look for matching
6865 * braces.
6866 */
6867 if (trypos == NULL && find_last_paren(l, '{', '}'))
6868 trypos = find_start_brace(ind_maxcomment);
6869
6870 if (trypos != NULL)
6871 {
6872 /*
6873 * Check if we are on a case label now. This is
6874 * handled above.
6875 * case xx: if ( asdf &&
6876 * asdf)
6877 */
6878 curwin->w_cursor.lnum = trypos->lnum;
6879 l = ml_get_curline();
6880 if (cin_iscase(l) || cin_isscopedecl(l))
6881 {
6882 ++curwin->w_cursor.lnum;
6883 continue;
6884 }
6885 }
6886
6887 /*
6888 * Skip over continuation lines to find the one to get the
6889 * indent from
6890 * char *usethis = "bla\
6891 * bla",
6892 * here;
6893 */
6894 if (terminated == ',')
6895 {
6896 while (curwin->w_cursor.lnum > 1)
6897 {
6898 l = ml_get(curwin->w_cursor.lnum - 1);
6899 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
6900 break;
6901 --curwin->w_cursor.lnum;
6902 }
6903 }
6904
6905 /*
6906 * Get indent and pointer to text for current line,
6907 * ignoring any jump label. XXX
6908 */
6909 cur_amount = skip_label(curwin->w_cursor.lnum,
6910 &l, ind_maxcomment);
6911
6912 /*
6913 * If this is just above the line we are indenting, and it
6914 * starts with a '{', line it up with this line.
6915 * while (not)
6916 * -> {
6917 * }
6918 */
6919 if (terminated != ',' && lookfor != LOOKFOR_TERM
6920 && theline[0] == '{')
6921 {
6922 amount = cur_amount;
6923 /*
6924 * Only add ind_open_extra when the current line
6925 * doesn't start with a '{', which must have a match
6926 * in the same line (scope is the same). Probably:
6927 * { 1, 2 },
6928 * -> { 3, 4 }
6929 */
6930 if (*skipwhite(l) != '{')
6931 amount += ind_open_extra;
6932
6933 if (ind_cpp_baseclass)
6934 {
6935 /* have to look back, whether it is a cpp base
6936 * class declaration or initialization */
6937 lookfor = LOOKFOR_CPP_BASECLASS;
6938 continue;
6939 }
6940 break;
6941 }
6942
6943 /*
6944 * Check if we are after an "if", "while", etc.
6945 * Also allow " } else".
6946 */
6947 if (cin_is_cinword(l) || cin_iselse(skipwhite(l)))
6948 {
6949 /*
6950 * Found an unterminated line after an if (), line up
6951 * with the last one.
6952 * if (cond)
6953 * 100 +
6954 * -> here;
6955 */
6956 if (lookfor == LOOKFOR_UNTERM
6957 || lookfor == LOOKFOR_ENUM_OR_INIT)
6958 {
6959 if (cont_amount > 0)
6960 amount = cont_amount;
6961 else
6962 amount += ind_continuation;
6963 break;
6964 }
6965
6966 /*
6967 * If this is just above the line we are indenting, we
6968 * are finished.
6969 * while (not)
6970 * -> here;
6971 * Otherwise this indent can be used when the line
6972 * before this is terminated.
6973 * yyy;
6974 * if (stat)
6975 * while (not)
6976 * xxx;
6977 * -> here;
6978 */
6979 amount = cur_amount;
6980 if (theline[0] == '{')
6981 amount += ind_open_extra;
6982 if (lookfor != LOOKFOR_TERM)
6983 {
6984 amount += ind_level + ind_no_brace;
6985 break;
6986 }
6987
6988 /*
6989 * Special trick: when expecting the while () after a
6990 * do, line up with the while()
6991 * do
6992 * x = 1;
6993 * -> here
6994 */
6995 l = skipwhite(ml_get_curline());
6996 if (cin_isdo(l))
6997 {
6998 if (whilelevel == 0)
6999 break;
7000 --whilelevel;
7001 }
7002
7003 /*
7004 * When searching for a terminated line, don't use the
7005 * one between the "if" and the "else".
7006 * Need to use the scope of this "else". XXX
7007 * If whilelevel != 0 continue looking for a "do {".
7008 */
7009 if (cin_iselse(l)
7010 && whilelevel == 0
7011 && ((trypos = find_start_brace(ind_maxcomment))
7012 == NULL
7013 || find_match(LOOKFOR_IF, trypos->lnum,
7014 ind_maxparen, ind_maxcomment) == FAIL))
7015 break;
7016 }
7017
7018 /*
7019 * If we're below an unterminated line that is not an
7020 * "if" or something, we may line up with this line or
7021 * add someting for a continuation line, depending on
7022 * the line before this one.
7023 */
7024 else
7025 {
7026 /*
7027 * Found two unterminated lines on a row, line up with
7028 * the last one.
7029 * c = 99 +
7030 * 100 +
7031 * -> here;
7032 */
7033 if (lookfor == LOOKFOR_UNTERM)
7034 {
7035 /* When line ends in a comma add extra indent */
7036 if (terminated == ',')
7037 amount += ind_continuation;
7038 break;
7039 }
7040
7041 if (lookfor == LOOKFOR_ENUM_OR_INIT)
7042 {
7043 /* Found two lines ending in ',', lineup with the
7044 * lowest one, but check for cpp base class
7045 * declaration/initialization, if it is an
7046 * opening brace or we are looking just for
7047 * enumerations/initializations. */
7048 if (terminated == ',')
7049 {
7050 if (ind_cpp_baseclass == 0)
7051 break;
7052
7053 lookfor = LOOKFOR_CPP_BASECLASS;
7054 continue;
7055 }
7056
7057 /* Ignore unterminated lines in between, but
7058 * reduce indent. */
7059 if (amount > cur_amount)
7060 amount = cur_amount;
7061 }
7062 else
7063 {
7064 /*
7065 * Found first unterminated line on a row, may
7066 * line up with this line, remember its indent
7067 * 100 +
7068 * -> here;
7069 */
7070 amount = cur_amount;
7071
7072 /*
7073 * If previous line ends in ',', check whether we
7074 * are in an initialization or enum
7075 * struct xxx =
7076 * {
7077 * sizeof a,
7078 * 124 };
7079 * or a normal possible continuation line.
7080 * but only, of no other statement has been found
7081 * yet.
7082 */
7083 if (lookfor == LOOKFOR_INITIAL && terminated == ',')
7084 {
7085 lookfor = LOOKFOR_ENUM_OR_INIT;
7086 cont_amount = cin_first_id_amount();
7087 }
7088 else
7089 {
7090 if (lookfor == LOOKFOR_INITIAL
7091 && *l != NUL
7092 && l[STRLEN(l) - 1] == '\\')
7093 /* XXX */
7094 cont_amount = cin_get_equal_amount(
7095 curwin->w_cursor.lnum);
7096 if (lookfor != LOOKFOR_TERM)
7097 lookfor = LOOKFOR_UNTERM;
7098 }
7099 }
7100 }
7101 }
7102
7103 /*
7104 * Check if we are after a while (cond);
7105 * If so: Ignore until the matching "do".
7106 */
7107 /* XXX */
7108 else if (cin_iswhileofdo(l,
7109 curwin->w_cursor.lnum, ind_maxparen))
7110 {
7111 /*
7112 * Found an unterminated line after a while ();, line up
7113 * with the last one.
7114 * while (cond);
7115 * 100 + <- line up with this one
7116 * -> here;
7117 */
7118 if (lookfor == LOOKFOR_UNTERM
7119 || lookfor == LOOKFOR_ENUM_OR_INIT)
7120 {
7121 if (cont_amount > 0)
7122 amount = cont_amount;
7123 else
7124 amount += ind_continuation;
7125 break;
7126 }
7127
7128 if (whilelevel == 0)
7129 {
7130 lookfor = LOOKFOR_TERM;
7131 amount = get_indent(); /* XXX */
7132 if (theline[0] == '{')
7133 amount += ind_open_extra;
7134 }
7135 ++whilelevel;
7136 }
7137
7138 /*
7139 * We are after a "normal" statement.
7140 * If we had another statement we can stop now and use the
7141 * indent of that other statement.
7142 * Otherwise the indent of the current statement may be used,
7143 * search backwards for the next "normal" statement.
7144 */
7145 else
7146 {
7147 /*
7148 * Skip single break line, if before a switch label. It
7149 * may be lined up with the case label.
7150 */
7151 if (lookfor == LOOKFOR_NOBREAK
7152 && cin_isbreak(skipwhite(ml_get_curline())))
7153 {
7154 lookfor = LOOKFOR_ANY;
7155 continue;
7156 }
7157
7158 /*
7159 * Handle "do {" line.
7160 */
7161 if (whilelevel > 0)
7162 {
7163 l = cin_skipcomment(ml_get_curline());
7164 if (cin_isdo(l))
7165 {
7166 amount = get_indent(); /* XXX */
7167 --whilelevel;
7168 continue;
7169 }
7170 }
7171
7172 /*
7173 * Found a terminated line above an unterminated line. Add
7174 * the amount for a continuation line.
7175 * x = 1;
7176 * y = foo +
7177 * -> here;
7178 * or
7179 * int x = 1;
7180 * int foo,
7181 * -> here;
7182 */
7183 if (lookfor == LOOKFOR_UNTERM
7184 || lookfor == LOOKFOR_ENUM_OR_INIT)
7185 {
7186 if (cont_amount > 0)
7187 amount = cont_amount;
7188 else
7189 amount += ind_continuation;
7190 break;
7191 }
7192
7193 /*
7194 * Found a terminated line above a terminated line or "if"
7195 * etc. line. Use the amount of the line below us.
7196 * x = 1; x = 1;
7197 * if (asdf) y = 2;
7198 * while (asdf) ->here;
7199 * here;
7200 * ->foo;
7201 */
7202 if (lookfor == LOOKFOR_TERM)
7203 {
7204 if (!lookfor_break && whilelevel == 0)
7205 break;
7206 }
7207
7208 /*
7209 * First line above the one we're indenting is terminated.
7210 * To know what needs to be done look further backward for
7211 * a terminated line.
7212 */
7213 else
7214 {
7215 /*
7216 * position the cursor over the rightmost paren, so
7217 * that matching it will take us back to the start of
7218 * the line. Helps for:
7219 * func(asdr,
7220 * asdfasdf);
7221 * here;
7222 */
7223term_again:
7224 l = ml_get_curline();
7225 if (find_last_paren(l, '(', ')')
7226 && (trypos = find_match_paren(ind_maxparen,
7227 ind_maxcomment)) != NULL)
7228 {
7229 /*
7230 * Check if we are on a case label now. This is
7231 * handled above.
7232 * case xx: if ( asdf &&
7233 * asdf)
7234 */
7235 curwin->w_cursor.lnum = trypos->lnum;
7236 l = ml_get_curline();
7237 if (cin_iscase(l) || cin_isscopedecl(l))
7238 {
7239 ++curwin->w_cursor.lnum;
7240 continue;
7241 }
7242 }
7243
7244 /* When aligning with the case statement, don't align
7245 * with a statement after it.
7246 * case 1: { <-- don't use this { position
7247 * stat;
7248 * }
7249 * case 2:
7250 * stat;
7251 * }
7252 */
7253 iscase = (ind_keep_case_label && cin_iscase(l));
7254
7255 /*
7256 * Get indent and pointer to text for current line,
7257 * ignoring any jump label.
7258 */
7259 amount = skip_label(curwin->w_cursor.lnum,
7260 &l, ind_maxcomment);
7261
7262 if (theline[0] == '{')
7263 amount += ind_open_extra;
7264 /* See remark above: "Only add ind_open_extra.." */
7265 if (*skipwhite(l) == '{')
7266 amount -= ind_open_extra;
7267 lookfor = iscase ? LOOKFOR_ANY : LOOKFOR_TERM;
7268
7269 /*
7270 * If we're at the end of a block, skip to the start of
7271 * that block.
7272 */
7273 curwin->w_cursor.col = 0;
7274 if (*cin_skipcomment(l) == '}'
7275 && (trypos = find_start_brace(ind_maxcomment))
7276 != NULL) /* XXX */
7277 {
7278 curwin->w_cursor.lnum = trypos->lnum;
7279 /* if not "else {" check for terminated again */
7280 /* but skip block for "} else {" */
7281 l = cin_skipcomment(ml_get_curline());
7282 if (*l == '}' || !cin_iselse(l))
7283 goto term_again;
7284 ++curwin->w_cursor.lnum;
7285 }
7286 }
7287 }
7288 }
7289 }
7290 }
7291
7292 /* add extra indent for a comment */
7293 if (cin_iscomment(theline))
7294 amount += ind_comment;
7295 }
7296
7297 /*
7298 * ok -- we're not inside any sort of structure at all!
7299 *
7300 * this means we're at the top level, and everything should
7301 * basically just match where the previous line is, except
7302 * for the lines immediately following a function declaration,
7303 * which are K&R-style parameters and need to be indented.
7304 */
7305 else
7306 {
7307 /*
7308 * if our line starts with an open brace, forget about any
7309 * prevailing indent and make sure it looks like the start
7310 * of a function
7311 */
7312
7313 if (theline[0] == '{')
7314 {
7315 amount = ind_first_open;
7316 }
7317
7318 /*
7319 * If the NEXT line is a function declaration, the current
7320 * line needs to be indented as a function type spec.
7321 * Don't do this if the current line looks like a comment
7322 * or if the current line is terminated, ie. ends in ';'.
7323 */
7324 else if (cur_curpos.lnum < curbuf->b_ml.ml_line_count
7325 && !cin_nocode(theline)
7326 && !cin_ends_in(theline, (char_u *)":", NULL)
7327 && !cin_ends_in(theline, (char_u *)",", NULL)
7328 && cin_isfuncdecl(NULL, cur_curpos.lnum + 1)
7329 && !cin_isterminated(theline, FALSE, TRUE))
7330 {
7331 amount = ind_func_type;
7332 }
7333 else
7334 {
7335 amount = 0;
7336 curwin->w_cursor = cur_curpos;
7337
7338 /* search backwards until we find something we recognize */
7339
7340 while (curwin->w_cursor.lnum > 1)
7341 {
7342 curwin->w_cursor.lnum--;
7343 curwin->w_cursor.col = 0;
7344
7345 l = ml_get_curline();
7346
7347 /*
7348 * If we're in a comment now, skip to the start of the comment.
7349 */ /* XXX */
7350 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
7351 {
7352 curwin->w_cursor.lnum = trypos->lnum + 1;
7353 continue;
7354 }
7355
7356 /*
7357 * Are we at the start of a cpp base class declaration or constructor
7358 * initialization?
7359 */ /* XXX */
7360 if (ind_cpp_baseclass != 0 && theline[0] != '{'
7361 && cin_is_cpp_baseclass(l, &col))
7362 {
7363 if (col == 0)
7364 {
7365 amount = get_indent() + ind_cpp_baseclass; /* XXX */
7366 if (find_last_paren(l, '(', ')')
7367 && (trypos = find_match_paren(ind_maxparen,
7368 ind_maxcomment)) != NULL)
7369 amount = get_indent_lnum(trypos->lnum)
7370 + ind_cpp_baseclass; /* XXX */
7371 }
7372 else
7373 {
7374 curwin->w_cursor.col = col;
7375 getvcol(curwin, &curwin->w_cursor, &col, NULL, NULL);
7376 amount = (int)col;
7377 }
7378 break;
7379 }
7380
7381 /*
7382 * Skip preprocessor directives and blank lines.
7383 */
7384 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7385 continue;
7386
7387 if (cin_nocode(l))
7388 continue;
7389
7390 /*
7391 * If the previous line ends in ',', use one level of
7392 * indentation:
7393 * int foo,
7394 * bar;
7395 * do this before checking for '}' in case of eg.
7396 * enum foobar
7397 * {
7398 * ...
7399 * } foo,
7400 * bar;
7401 */
7402 n = 0;
7403 if (cin_ends_in(l, (char_u *)",", NULL)
7404 || (*l != NUL && (n = l[STRLEN(l) - 1]) == '\\'))
7405 {
7406 /* take us back to opening paren */
7407 if (find_last_paren(l, '(', ')')
7408 && (trypos = find_match_paren(ind_maxparen,
7409 ind_maxcomment)) != NULL)
7410 curwin->w_cursor.lnum = trypos->lnum;
7411
7412 /* For a line ending in ',' that is a continuation line go
7413 * back to the first line with a backslash:
7414 * char *foo = "bla\
7415 * bla",
7416 * here;
7417 */
7418 while (n == 0 && curwin->w_cursor.lnum > 1)
7419 {
7420 l = ml_get(curwin->w_cursor.lnum - 1);
7421 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
7422 break;
7423 --curwin->w_cursor.lnum;
7424 }
7425
7426 amount = get_indent(); /* XXX */
7427
7428 if (amount == 0)
7429 amount = cin_first_id_amount();
7430 if (amount == 0)
7431 amount = ind_continuation;
7432 break;
7433 }
7434
7435 /*
7436 * If the line looks like a function declaration, and we're
7437 * not in a comment, put it the left margin.
7438 */
7439 if (cin_isfuncdecl(NULL, cur_curpos.lnum)) /* XXX */
7440 break;
7441 l = ml_get_curline();
7442
7443 /*
7444 * Finding the closing '}' of a previous function. Put
7445 * current line at the left margin. For when 'cino' has "fs".
7446 */
7447 if (*skipwhite(l) == '}')
7448 break;
7449
7450 /* (matching {)
7451 * If the previous line ends on '};' (maybe followed by
7452 * comments) align at column 0. For example:
7453 * char *string_array[] = { "foo",
7454 * / * x * / "b};ar" }; / * foobar * /
7455 */
7456 if (cin_ends_in(l, (char_u *)"};", NULL))
7457 break;
7458
7459 /*
7460 * If the PREVIOUS line is a function declaration, the current
7461 * line (and the ones that follow) needs to be indented as
7462 * parameters.
7463 */
7464 if (cin_isfuncdecl(&l, curwin->w_cursor.lnum))
7465 {
7466 amount = ind_param;
7467 break;
7468 }
7469
7470 /*
7471 * If the previous line ends in ';' and the line before the
7472 * previous line ends in ',' or '\', ident to column zero:
7473 * int foo,
7474 * bar;
7475 * indent_to_0 here;
7476 */
7477 if (cin_ends_in(l, (char_u*)";", NULL))
7478 {
7479 l = ml_get(curwin->w_cursor.lnum - 1);
7480 if (cin_ends_in(l, (char_u *)",", NULL)
7481 || (*l != NUL && l[STRLEN(l) - 1] == '\\'))
7482 break;
7483 l = ml_get_curline();
7484 }
7485
7486 /*
7487 * Doesn't look like anything interesting -- so just
7488 * use the indent of this line.
7489 *
7490 * Position the cursor over the rightmost paren, so that
7491 * matching it will take us back to the start of the line.
7492 */
7493 find_last_paren(l, '(', ')');
7494
7495 if ((trypos = find_match_paren(ind_maxparen,
7496 ind_maxcomment)) != NULL)
7497 curwin->w_cursor.lnum = trypos->lnum;
7498 amount = get_indent(); /* XXX */
7499 break;
7500 }
7501
7502 /* add extra indent for a comment */
7503 if (cin_iscomment(theline))
7504 amount += ind_comment;
7505
7506 /* add extra indent if the previous line ended in a backslash:
7507 * "asdfasdf\
7508 * here";
7509 * char *foo = "asdf\
7510 * here";
7511 */
7512 if (cur_curpos.lnum > 1)
7513 {
7514 l = ml_get(cur_curpos.lnum - 1);
7515 if (*l != NUL && l[STRLEN(l) - 1] == '\\')
7516 {
7517 cur_amount = cin_get_equal_amount(cur_curpos.lnum - 1);
7518 if (cur_amount > 0)
7519 amount = cur_amount;
7520 else if (cur_amount == 0)
7521 amount += ind_continuation;
7522 }
7523 }
7524 }
7525 }
7526
7527theend:
7528 /* put the cursor back where it belongs */
7529 curwin->w_cursor = cur_curpos;
7530
7531 vim_free(linecopy);
7532
7533 if (amount < 0)
7534 return 0;
7535 return amount;
7536}
7537
7538 static int
7539find_match(lookfor, ourscope, ind_maxparen, ind_maxcomment)
7540 int lookfor;
7541 linenr_T ourscope;
7542 int ind_maxparen;
7543 int ind_maxcomment;
7544{
7545 char_u *look;
7546 pos_T *theirscope;
7547 char_u *mightbeif;
7548 int elselevel;
7549 int whilelevel;
7550
7551 if (lookfor == LOOKFOR_IF)
7552 {
7553 elselevel = 1;
7554 whilelevel = 0;
7555 }
7556 else
7557 {
7558 elselevel = 0;
7559 whilelevel = 1;
7560 }
7561
7562 curwin->w_cursor.col = 0;
7563
7564 while (curwin->w_cursor.lnum > ourscope + 1)
7565 {
7566 curwin->w_cursor.lnum--;
7567 curwin->w_cursor.col = 0;
7568
7569 look = cin_skipcomment(ml_get_curline());
7570 if (cin_iselse(look)
7571 || cin_isif(look)
7572 || cin_isdo(look) /* XXX */
7573 || cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
7574 {
7575 /*
7576 * if we've gone outside the braces entirely,
7577 * we must be out of scope...
7578 */
7579 theirscope = find_start_brace(ind_maxcomment); /* XXX */
7580 if (theirscope == NULL)
7581 break;
7582
7583 /*
7584 * and if the brace enclosing this is further
7585 * back than the one enclosing the else, we're
7586 * out of luck too.
7587 */
7588 if (theirscope->lnum < ourscope)
7589 break;
7590
7591 /*
7592 * and if they're enclosed in a *deeper* brace,
7593 * then we can ignore it because it's in a
7594 * different scope...
7595 */
7596 if (theirscope->lnum > ourscope)
7597 continue;
7598
7599 /*
7600 * if it was an "else" (that's not an "else if")
7601 * then we need to go back to another if, so
7602 * increment elselevel
7603 */
7604 look = cin_skipcomment(ml_get_curline());
7605 if (cin_iselse(look))
7606 {
7607 mightbeif = cin_skipcomment(look + 4);
7608 if (!cin_isif(mightbeif))
7609 ++elselevel;
7610 continue;
7611 }
7612
7613 /*
7614 * if it was a "while" then we need to go back to
7615 * another "do", so increment whilelevel. XXX
7616 */
7617 if (cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
7618 {
7619 ++whilelevel;
7620 continue;
7621 }
7622
7623 /* If it's an "if" decrement elselevel */
7624 look = cin_skipcomment(ml_get_curline());
7625 if (cin_isif(look))
7626 {
7627 elselevel--;
7628 /*
7629 * When looking for an "if" ignore "while"s that
7630 * get in the way.
7631 */
7632 if (elselevel == 0 && lookfor == LOOKFOR_IF)
7633 whilelevel = 0;
7634 }
7635
7636 /* If it's a "do" decrement whilelevel */
7637 if (cin_isdo(look))
7638 whilelevel--;
7639
7640 /*
7641 * if we've used up all the elses, then
7642 * this must be the if that we want!
7643 * match the indent level of that if.
7644 */
7645 if (elselevel <= 0 && whilelevel <= 0)
7646 {
7647 return OK;
7648 }
7649 }
7650 }
7651 return FAIL;
7652}
7653
7654# if defined(FEAT_EVAL) || defined(PROTO)
7655/*
7656 * Get indent level from 'indentexpr'.
7657 */
7658 int
7659get_expr_indent()
7660{
7661 int indent;
7662 pos_T pos;
7663 int save_State;
Bram Moolenaard1f56e62006-02-22 21:25:37 +00007664 int use_sandbox = was_set_insecurely((char_u *)"indentexpr",
7665 OPT_LOCAL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007666
7667 pos = curwin->w_cursor;
7668 set_vim_var_nr(VV_LNUM, curwin->w_cursor.lnum);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00007669 if (use_sandbox)
7670 ++sandbox;
7671 ++textlock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007672 indent = eval_to_number(curbuf->b_p_inde);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00007673 if (use_sandbox)
7674 --sandbox;
7675 --textlock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007676
7677 /* Restore the cursor position so that 'indentexpr' doesn't need to.
7678 * Pretend to be in Insert mode, allow cursor past end of line for "o"
7679 * command. */
7680 save_State = State;
7681 State = INSERT;
7682 curwin->w_cursor = pos;
7683 check_cursor();
7684 State = save_State;
7685
7686 /* If there is an error, just keep the current indent. */
7687 if (indent < 0)
7688 indent = get_indent();
7689
7690 return indent;
7691}
7692# endif
7693
7694#endif /* FEAT_CINDENT */
7695
7696#if defined(FEAT_LISP) || defined(PROTO)
7697
7698static int lisp_match __ARGS((char_u *p));
7699
7700 static int
7701lisp_match(p)
7702 char_u *p;
7703{
7704 char_u buf[LSIZE];
7705 int len;
7706 char_u *word = p_lispwords;
7707
7708 while (*word != NUL)
7709 {
7710 (void)copy_option_part(&word, buf, LSIZE, ",");
7711 len = (int)STRLEN(buf);
7712 if (STRNCMP(buf, p, len) == 0 && p[len] == ' ')
7713 return TRUE;
7714 }
7715 return FALSE;
7716}
7717
7718/*
7719 * When 'p' is present in 'cpoptions, a Vi compatible method is used.
7720 * The incompatible newer method is quite a bit better at indenting
7721 * code in lisp-like languages than the traditional one; it's still
7722 * mostly heuristics however -- Dirk van Deun, dirk@rave.org
7723 *
7724 * TODO:
7725 * Findmatch() should be adapted for lisp, also to make showmatch
7726 * work correctly: now (v5.3) it seems all C/C++ oriented:
7727 * - it does not recognize the #\( and #\) notations as character literals
7728 * - it doesn't know about comments starting with a semicolon
7729 * - it incorrectly interprets '(' as a character literal
7730 * All this messes up get_lisp_indent in some rare cases.
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007731 * Update from Sergey Khorev:
7732 * I tried to fix the first two issues.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007733 */
7734 int
7735get_lisp_indent()
7736{
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007737 pos_T *pos, realpos, paren;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007738 int amount;
7739 char_u *that;
7740 colnr_T col;
7741 colnr_T firsttry;
7742 int parencount, quotecount;
7743 int vi_lisp;
7744
7745 /* Set vi_lisp to use the vi-compatible method */
7746 vi_lisp = (vim_strchr(p_cpo, CPO_LISP) != NULL);
7747
7748 realpos = curwin->w_cursor;
7749 curwin->w_cursor.col = 0;
7750
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007751 if ((pos = findmatch(NULL, '(')) == NULL)
7752 pos = findmatch(NULL, '[');
7753 else
7754 {
7755 paren = *pos;
7756 pos = findmatch(NULL, '[');
7757 if (pos == NULL || ltp(pos, &paren))
7758 pos = &paren;
7759 }
7760 if (pos != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007761 {
7762 /* Extra trick: Take the indent of the first previous non-white
7763 * line that is at the same () level. */
7764 amount = -1;
7765 parencount = 0;
7766
7767 while (--curwin->w_cursor.lnum >= pos->lnum)
7768 {
7769 if (linewhite(curwin->w_cursor.lnum))
7770 continue;
7771 for (that = ml_get_curline(); *that != NUL; ++that)
7772 {
7773 if (*that == ';')
7774 {
7775 while (*(that + 1) != NUL)
7776 ++that;
7777 continue;
7778 }
7779 if (*that == '\\')
7780 {
7781 if (*(that + 1) != NUL)
7782 ++that;
7783 continue;
7784 }
7785 if (*that == '"' && *(that + 1) != NUL)
7786 {
7787 that++;
7788 while (*that && (*that != '"' || *(that - 1) == '\\'))
7789 ++that;
7790 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007791 if (*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007792 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007793 else if (*that == ')' || *that == ']')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007794 --parencount;
7795 }
7796 if (parencount == 0)
7797 {
7798 amount = get_indent();
7799 break;
7800 }
7801 }
7802
7803 if (amount == -1)
7804 {
7805 curwin->w_cursor.lnum = pos->lnum;
7806 curwin->w_cursor.col = pos->col;
7807 col = pos->col;
7808
7809 that = ml_get_curline();
7810
7811 if (vi_lisp && get_indent() == 0)
7812 amount = 2;
7813 else
7814 {
7815 amount = 0;
7816 while (*that && col)
7817 {
7818 amount += lbr_chartabsize_adv(&that, (colnr_T)amount);
7819 col--;
7820 }
7821
7822 /*
7823 * Some keywords require "body" indenting rules (the
7824 * non-standard-lisp ones are Scheme special forms):
7825 *
7826 * (let ((a 1)) instead (let ((a 1))
7827 * (...)) of (...))
7828 */
7829
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007830 if (!vi_lisp && (*that == '(' || *that == '[')
7831 && lisp_match(that + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007832 amount += 2;
7833 else
7834 {
7835 that++;
7836 amount++;
7837 firsttry = amount;
7838
7839 while (vim_iswhite(*that))
7840 {
7841 amount += lbr_chartabsize(that, (colnr_T)amount);
7842 ++that;
7843 }
7844
7845 if (*that && *that != ';') /* not a comment line */
7846 {
7847 /* test *that != '(' to accomodate first let/do
7848 * argument if it is more than one line */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007849 if (!vi_lisp && *that != '(' && *that != '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007850 firsttry++;
7851
7852 parencount = 0;
7853 quotecount = 0;
7854
7855 if (vi_lisp
7856 || (*that != '"'
7857 && *that != '\''
7858 && *that != '#'
7859 && (*that < '0' || *that > '9')))
7860 {
7861 while (*that
7862 && (!vim_iswhite(*that)
7863 || quotecount
7864 || parencount)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007865 && (!((*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007866 && !quotecount
7867 && !parencount
7868 && vi_lisp)))
7869 {
7870 if (*that == '"')
7871 quotecount = !quotecount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007872 if ((*that == '(' || *that == '[')
7873 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007874 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007875 if ((*that == ')' || *that == ']')
7876 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007877 --parencount;
7878 if (*that == '\\' && *(that+1) != NUL)
7879 amount += lbr_chartabsize_adv(&that,
7880 (colnr_T)amount);
7881 amount += lbr_chartabsize_adv(&that,
7882 (colnr_T)amount);
7883 }
7884 }
7885 while (vim_iswhite(*that))
7886 {
7887 amount += lbr_chartabsize(that, (colnr_T)amount);
7888 that++;
7889 }
7890 if (!*that || *that == ';')
7891 amount = firsttry;
7892 }
7893 }
7894 }
7895 }
7896 }
7897 else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007898 amount = 0; /* no matching '(' or '[' found, use zero indent */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007899
7900 curwin->w_cursor = realpos;
7901
7902 return amount;
7903}
7904#endif /* FEAT_LISP */
7905
7906 void
7907prepare_to_exit()
7908{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00007909#if defined(SIGHUP) && defined(SIG_IGN)
7910 /* Ignore SIGHUP, because a dropped connection causes a read error, which
7911 * makes Vim exit and then handling SIGHUP causes various reentrance
7912 * problems. */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00007913 signal(SIGHUP, SIG_IGN);
7914#endif
7915
Bram Moolenaar071d4272004-06-13 20:20:40 +00007916#ifdef FEAT_GUI
7917 if (gui.in_use)
7918 {
7919 gui.dying = TRUE;
7920 out_trash(); /* trash any pending output */
7921 }
7922 else
7923#endif
7924 {
7925 windgoto((int)Rows - 1, 0);
7926
7927 /*
7928 * Switch terminal mode back now, so messages end up on the "normal"
7929 * screen (if there are two screens).
7930 */
7931 settmode(TMODE_COOK);
7932#ifdef WIN3264
7933 if (can_end_termcap_mode(FALSE) == TRUE)
7934#endif
7935 stoptermcap();
7936 out_flush();
7937 }
7938}
7939
7940/*
7941 * Preserve files and exit.
7942 * When called IObuff must contain a message.
7943 */
7944 void
7945preserve_exit()
7946{
7947 buf_T *buf;
7948
7949 prepare_to_exit();
7950
Bram Moolenaar4770d092006-01-12 23:22:24 +00007951 /* Setting this will prevent free() calls. That avoids calling free()
7952 * recursively when free() was invoked with a bad pointer. */
7953 really_exiting = TRUE;
7954
Bram Moolenaar071d4272004-06-13 20:20:40 +00007955 out_str(IObuff);
7956 screen_start(); /* don't know where cursor is now */
7957 out_flush();
7958
7959 ml_close_notmod(); /* close all not-modified buffers */
7960
7961 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
7962 {
7963 if (buf->b_ml.ml_mfp != NULL && buf->b_ml.ml_mfp->mf_fname != NULL)
7964 {
7965 OUT_STR(_("Vim: preserving files...\n"));
7966 screen_start(); /* don't know where cursor is now */
7967 out_flush();
7968 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
7969 break;
7970 }
7971 }
7972
7973 ml_close_all(FALSE); /* close all memfiles, without deleting */
7974
7975 OUT_STR(_("Vim: Finished.\n"));
7976
7977 getout(1);
7978}
7979
7980/*
7981 * return TRUE if "fname" exists.
7982 */
7983 int
7984vim_fexists(fname)
7985 char_u *fname;
7986{
7987 struct stat st;
7988
7989 if (mch_stat((char *)fname, &st))
7990 return FALSE;
7991 return TRUE;
7992}
7993
7994/*
7995 * Check for CTRL-C pressed, but only once in a while.
7996 * Should be used instead of ui_breakcheck() for functions that check for
7997 * each line in the file. Calling ui_breakcheck() each time takes too much
7998 * time, because it can be a system call.
7999 */
8000
8001#ifndef BREAKCHECK_SKIP
8002# ifdef FEAT_GUI /* assume the GUI only runs on fast computers */
8003# define BREAKCHECK_SKIP 200
8004# else
8005# define BREAKCHECK_SKIP 32
8006# endif
8007#endif
8008
8009static int breakcheck_count = 0;
8010
8011 void
8012line_breakcheck()
8013{
8014 if (++breakcheck_count >= BREAKCHECK_SKIP)
8015 {
8016 breakcheck_count = 0;
8017 ui_breakcheck();
8018 }
8019}
8020
8021/*
8022 * Like line_breakcheck() but check 10 times less often.
8023 */
8024 void
8025fast_breakcheck()
8026{
8027 if (++breakcheck_count >= BREAKCHECK_SKIP * 10)
8028 {
8029 breakcheck_count = 0;
8030 ui_breakcheck();
8031 }
8032}
8033
8034/*
8035 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching
8036 * 'wildignore'.
Bram Moolenaar362e1a32006-03-06 23:29:24 +00008037 * Returns OK or FAIL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008038 */
8039 int
8040expand_wildcards(num_pat, pat, num_file, file, flags)
8041 int num_pat; /* number of input patterns */
8042 char_u **pat; /* array of input patterns */
8043 int *num_file; /* resulting number of files */
8044 char_u ***file; /* array of resulting files */
8045 int flags; /* EW_DIR, etc. */
8046{
8047 int retval;
8048 int i, j;
8049 char_u *p;
8050 int non_suf_match; /* number without matching suffix */
8051
8052 retval = gen_expand_wildcards(num_pat, pat, num_file, file, flags);
8053
8054 /* When keeping all matches, return here */
8055 if (flags & EW_KEEPALL)
8056 return retval;
8057
8058#ifdef FEAT_WILDIGN
8059 /*
8060 * Remove names that match 'wildignore'.
8061 */
8062 if (*p_wig)
8063 {
8064 char_u *ffname;
8065
8066 /* check all files in (*file)[] */
8067 for (i = 0; i < *num_file; ++i)
8068 {
8069 ffname = FullName_save((*file)[i], FALSE);
8070 if (ffname == NULL) /* out of memory */
8071 break;
8072# ifdef VMS
8073 vms_remove_version(ffname);
8074# endif
8075 if (match_file_list(p_wig, (*file)[i], ffname))
8076 {
8077 /* remove this matching file from the list */
8078 vim_free((*file)[i]);
8079 for (j = i; j + 1 < *num_file; ++j)
8080 (*file)[j] = (*file)[j + 1];
8081 --*num_file;
8082 --i;
8083 }
8084 vim_free(ffname);
8085 }
8086 }
8087#endif
8088
8089 /*
8090 * Move the names where 'suffixes' match to the end.
8091 */
8092 if (*num_file > 1)
8093 {
8094 non_suf_match = 0;
8095 for (i = 0; i < *num_file; ++i)
8096 {
8097 if (!match_suffix((*file)[i]))
8098 {
8099 /*
8100 * Move the name without matching suffix to the front
8101 * of the list.
8102 */
8103 p = (*file)[i];
8104 for (j = i; j > non_suf_match; --j)
8105 (*file)[j] = (*file)[j - 1];
8106 (*file)[non_suf_match++] = p;
8107 }
8108 }
8109 }
8110
8111 return retval;
8112}
8113
8114/*
8115 * Return TRUE if "fname" matches with an entry in 'suffixes'.
8116 */
8117 int
8118match_suffix(fname)
8119 char_u *fname;
8120{
8121 int fnamelen, setsuflen;
8122 char_u *setsuf;
8123#define MAXSUFLEN 30 /* maximum length of a file suffix */
8124 char_u suf_buf[MAXSUFLEN];
8125
8126 fnamelen = (int)STRLEN(fname);
8127 setsuflen = 0;
8128 for (setsuf = p_su; *setsuf; )
8129 {
8130 setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
8131 if (fnamelen >= setsuflen
8132 && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
8133 (size_t)setsuflen) == 0)
8134 break;
8135 setsuflen = 0;
8136 }
8137 return (setsuflen != 0);
8138}
8139
8140#if !defined(NO_EXPANDPATH) || defined(PROTO)
8141
8142# ifdef VIM_BACKTICK
8143static int vim_backtick __ARGS((char_u *p));
8144static int expand_backtick __ARGS((garray_T *gap, char_u *pat, int flags));
8145# endif
8146
8147# if defined(MSDOS) || defined(FEAT_GUI_W16) || defined(WIN3264)
8148/*
8149 * File name expansion code for MS-DOS, Win16 and Win32. It's here because
8150 * it's shared between these systems.
8151 */
8152# if defined(DJGPP) || defined(PROTO)
8153# define _cdecl /* DJGPP doesn't have this */
8154# else
8155# ifdef __BORLANDC__
8156# define _cdecl _RTLENTRYF
8157# endif
8158# endif
8159
8160/*
8161 * comparison function for qsort in dos_expandpath()
8162 */
8163 static int _cdecl
8164pstrcmp(const void *a, const void *b)
8165{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00008166 return (pathcmp(*(char **)a, *(char **)b, -1));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008167}
8168
8169# ifndef WIN3264
8170 static void
8171namelowcpy(
8172 char_u *d,
8173 char_u *s)
8174{
8175# ifdef DJGPP
8176 if (USE_LONG_FNAME) /* don't lower case on Windows 95/NT systems */
8177 while (*s)
8178 *d++ = *s++;
8179 else
8180# endif
8181 while (*s)
8182 *d++ = TOLOWER_LOC(*s++);
8183 *d = NUL;
8184}
8185# endif
8186
8187/*
Bram Moolenaar231334e2005-07-25 20:46:57 +00008188 * Recursively expand one path component into all matching files and/or
8189 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008190 * Return the number of matches found.
8191 * "path" has backslashes before chars that are not to be expanded, starting
8192 * at "path[wildoff]".
Bram Moolenaar231334e2005-07-25 20:46:57 +00008193 * Return the number of matches found.
8194 * NOTE: much of this is identical to unix_expandpath(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00008195 */
8196 static int
8197dos_expandpath(
8198 garray_T *gap,
8199 char_u *path,
8200 int wildoff,
Bram Moolenaar231334e2005-07-25 20:46:57 +00008201 int flags, /* EW_* flags */
8202 int didstar) /* expaneded "**" once already */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008203{
Bram Moolenaar231334e2005-07-25 20:46:57 +00008204 char_u *buf;
8205 char_u *path_end;
8206 char_u *p, *s, *e;
8207 int start_len = gap->ga_len;
8208 char_u *pat;
8209 regmatch_T regmatch;
8210 int starts_with_dot;
8211 int matches;
8212 int len;
8213 int starstar = FALSE;
8214 static int stardepth = 0; /* depth for "**" expansion */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008215#ifdef WIN3264
8216 WIN32_FIND_DATA fb;
8217 HANDLE hFind = (HANDLE)0;
8218# ifdef FEAT_MBYTE
8219 WIN32_FIND_DATAW wfb;
8220 WCHAR *wn = NULL; /* UCS-2 name, NULL when not used. */
8221# endif
8222#else
8223 struct ffblk fb;
8224#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008225 char_u *matchname;
Bram Moolenaar231334e2005-07-25 20:46:57 +00008226 int ok;
8227
8228 /* Expanding "**" may take a long time, check for CTRL-C. */
8229 if (stardepth > 0)
8230 {
8231 ui_breakcheck();
8232 if (got_int)
8233 return 0;
8234 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008235
8236 /* make room for file name */
Bram Moolenaar231334e2005-07-25 20:46:57 +00008237 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008238 if (buf == NULL)
8239 return 0;
8240
8241 /*
8242 * Find the first part in the path name that contains a wildcard or a ~1.
8243 * Copy it into buf, including the preceding characters.
8244 */
8245 p = buf;
8246 s = buf;
8247 e = NULL;
8248 path_end = path;
8249 while (*path_end != NUL)
8250 {
8251 /* May ignore a wildcard that has a backslash before it; it will
8252 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
8253 if (path_end >= path + wildoff && rem_backslash(path_end))
8254 *p++ = *path_end++;
8255 else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
8256 {
8257 if (e != NULL)
8258 break;
8259 s = p + 1;
8260 }
8261 else if (path_end >= path + wildoff
8262 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
8263 e = p;
8264#ifdef FEAT_MBYTE
8265 if (has_mbyte)
8266 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00008267 len = (*mb_ptr2len)(path_end);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008268 STRNCPY(p, path_end, len);
8269 p += len;
8270 path_end += len;
8271 }
8272 else
8273#endif
8274 *p++ = *path_end++;
8275 }
8276 e = p;
8277 *e = NUL;
8278
8279 /* now we have one wildcard component between s and e */
8280 /* Remove backslashes between "wildoff" and the start of the wildcard
8281 * component. */
8282 for (p = buf + wildoff; p < s; ++p)
8283 if (rem_backslash(p))
8284 {
8285 STRCPY(p, p + 1);
8286 --e;
8287 --s;
8288 }
8289
Bram Moolenaar231334e2005-07-25 20:46:57 +00008290 /* Check for "**" between "s" and "e". */
8291 for (p = s; p < e; ++p)
8292 if (p[0] == '*' && p[1] == '*')
8293 starstar = TRUE;
8294
Bram Moolenaar071d4272004-06-13 20:20:40 +00008295 starts_with_dot = (*s == '.');
8296 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
8297 if (pat == NULL)
8298 {
8299 vim_free(buf);
8300 return 0;
8301 }
8302
8303 /* compile the regexp into a program */
8304 regmatch.rm_ic = TRUE; /* Always ignore case */
8305 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
8306 vim_free(pat);
8307
8308 if (regmatch.regprog == NULL)
8309 {
8310 vim_free(buf);
8311 return 0;
8312 }
8313
8314 /* remember the pattern or file name being looked for */
8315 matchname = vim_strsave(s);
8316
Bram Moolenaar231334e2005-07-25 20:46:57 +00008317 /* If "**" is by itself, this is the first time we encounter it and more
8318 * is following then find matches without any directory. */
8319 if (!didstar && stardepth < 100 && starstar && e - s == 2
8320 && *path_end == '/')
8321 {
8322 STRCPY(s, path_end + 1);
8323 ++stardepth;
8324 (void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
8325 --stardepth;
8326 }
8327
Bram Moolenaar071d4272004-06-13 20:20:40 +00008328 /* Scan all files in the directory with "dir/ *.*" */
8329 STRCPY(s, "*.*");
8330#ifdef WIN3264
8331# ifdef FEAT_MBYTE
8332 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
8333 {
8334 /* The active codepage differs from 'encoding'. Attempt using the
8335 * wide function. If it fails because it is not implemented fall back
8336 * to the non-wide version (for Windows 98) */
8337 wn = enc_to_ucs2(buf, NULL);
8338 if (wn != NULL)
8339 {
8340 hFind = FindFirstFileW(wn, &wfb);
8341 if (hFind == INVALID_HANDLE_VALUE
8342 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
8343 {
8344 vim_free(wn);
8345 wn = NULL;
8346 }
8347 }
8348 }
8349
8350 if (wn == NULL)
8351# endif
8352 hFind = FindFirstFile(buf, &fb);
8353 ok = (hFind != INVALID_HANDLE_VALUE);
8354#else
8355 /* If we are expanding wildcards we try both files and directories */
8356 ok = (findfirst((char *)buf, &fb,
8357 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
8358#endif
8359
8360 while (ok)
8361 {
8362#ifdef WIN3264
8363# ifdef FEAT_MBYTE
8364 if (wn != NULL)
8365 p = ucs2_to_enc(wfb.cFileName, NULL); /* p is allocated here */
8366 else
8367# endif
8368 p = (char_u *)fb.cFileName;
8369#else
8370 p = (char_u *)fb.ff_name;
8371#endif
8372 /* Ignore entries starting with a dot, unless when asked for. Accept
8373 * all entries found with "matchname". */
8374 if ((p[0] != '.' || starts_with_dot)
8375 && (matchname == NULL
8376 || vim_regexec(&regmatch, p, (colnr_T)0)))
8377 {
8378#ifdef WIN3264
8379 STRCPY(s, p);
8380#else
8381 namelowcpy(s, p);
8382#endif
8383 len = (int)STRLEN(buf);
Bram Moolenaar231334e2005-07-25 20:46:57 +00008384
8385 if (starstar && stardepth < 100)
8386 {
8387 /* For "**" in the pattern first go deeper in the tree to
8388 * find matches. */
8389 STRCPY(buf + len, "/**");
8390 STRCPY(buf + len + 3, path_end);
8391 ++stardepth;
8392 (void)dos_expandpath(gap, buf, len + 1, flags, TRUE);
8393 --stardepth;
8394 }
8395
Bram Moolenaar071d4272004-06-13 20:20:40 +00008396 STRCPY(buf + len, path_end);
8397 if (mch_has_exp_wildcard(path_end))
8398 {
8399 /* need to expand another component of the path */
8400 /* remove backslashes for the remaining components only */
Bram Moolenaar231334e2005-07-25 20:46:57 +00008401 (void)dos_expandpath(gap, buf, len + 1, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008402 }
8403 else
8404 {
8405 /* no more wildcards, check if there is a match */
8406 /* remove backslashes for the remaining components only */
8407 if (*path_end != 0)
8408 backslash_halve(buf + len + 1);
8409 if (mch_getperm(buf) >= 0) /* add existing file */
8410 addfile(gap, buf, flags);
8411 }
8412 }
8413
8414#ifdef WIN3264
8415# ifdef FEAT_MBYTE
8416 if (wn != NULL)
8417 {
8418 vim_free(p);
8419 ok = FindNextFileW(hFind, &wfb);
8420 }
8421 else
8422# endif
8423 ok = FindNextFile(hFind, &fb);
8424#else
8425 ok = (findnext(&fb) == 0);
8426#endif
8427
8428 /* If no more matches and no match was used, try expanding the name
8429 * itself. Finds the long name of a short filename. */
8430 if (!ok && matchname != NULL && gap->ga_len == start_len)
8431 {
8432 STRCPY(s, matchname);
8433#ifdef WIN3264
8434 FindClose(hFind);
8435# ifdef FEAT_MBYTE
8436 if (wn != NULL)
8437 {
8438 vim_free(wn);
8439 wn = enc_to_ucs2(buf, NULL);
8440 if (wn != NULL)
8441 hFind = FindFirstFileW(wn, &wfb);
8442 }
8443 if (wn == NULL)
8444# endif
8445 hFind = FindFirstFile(buf, &fb);
8446 ok = (hFind != INVALID_HANDLE_VALUE);
8447#else
8448 ok = (findfirst((char *)buf, &fb,
8449 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
8450#endif
8451 vim_free(matchname);
8452 matchname = NULL;
8453 }
8454 }
8455
8456#ifdef WIN3264
8457 FindClose(hFind);
8458# ifdef FEAT_MBYTE
8459 vim_free(wn);
8460# endif
8461#endif
8462 vim_free(buf);
8463 vim_free(regmatch.regprog);
8464 vim_free(matchname);
8465
8466 matches = gap->ga_len - start_len;
8467 if (matches > 0)
8468 qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
8469 sizeof(char_u *), pstrcmp);
8470 return matches;
8471}
8472
8473 int
8474mch_expandpath(
8475 garray_T *gap,
8476 char_u *path,
8477 int flags) /* EW_* flags */
8478{
Bram Moolenaar231334e2005-07-25 20:46:57 +00008479 return dos_expandpath(gap, path, 0, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008480}
8481# endif /* MSDOS || FEAT_GUI_W16 || WIN3264 */
8482
Bram Moolenaar231334e2005-07-25 20:46:57 +00008483#if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
8484 || defined(PROTO)
8485/*
8486 * Unix style wildcard expansion code.
8487 * It's here because it's used both for Unix and Mac.
8488 */
8489static int pstrcmp __ARGS((const void *, const void *));
8490
8491 static int
8492pstrcmp(a, b)
8493 const void *a, *b;
8494{
8495 return (pathcmp(*(char **)a, *(char **)b, -1));
8496}
8497
8498/*
8499 * Recursively expand one path component into all matching files and/or
8500 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
8501 * "path" has backslashes before chars that are not to be expanded, starting
8502 * at "path + wildoff".
8503 * Return the number of matches found.
8504 * NOTE: much of this is identical to dos_expandpath(), keep in sync!
8505 */
8506 int
8507unix_expandpath(gap, path, wildoff, flags, didstar)
8508 garray_T *gap;
8509 char_u *path;
8510 int wildoff;
8511 int flags; /* EW_* flags */
8512 int didstar; /* expanded "**" once already */
8513{
8514 char_u *buf;
8515 char_u *path_end;
8516 char_u *p, *s, *e;
8517 int start_len = gap->ga_len;
8518 char_u *pat;
8519 regmatch_T regmatch;
8520 int starts_with_dot;
8521 int matches;
8522 int len;
8523 int starstar = FALSE;
8524 static int stardepth = 0; /* depth for "**" expansion */
8525
8526 DIR *dirp;
8527 struct dirent *dp;
8528
8529 /* Expanding "**" may take a long time, check for CTRL-C. */
8530 if (stardepth > 0)
8531 {
8532 ui_breakcheck();
8533 if (got_int)
8534 return 0;
8535 }
8536
8537 /* make room for file name */
8538 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
8539 if (buf == NULL)
8540 return 0;
8541
8542 /*
8543 * Find the first part in the path name that contains a wildcard.
8544 * Copy it into "buf", including the preceding characters.
8545 */
8546 p = buf;
8547 s = buf;
8548 e = NULL;
8549 path_end = path;
8550 while (*path_end != NUL)
8551 {
8552 /* May ignore a wildcard that has a backslash before it; it will
8553 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
8554 if (path_end >= path + wildoff && rem_backslash(path_end))
8555 *p++ = *path_end++;
8556 else if (*path_end == '/')
8557 {
8558 if (e != NULL)
8559 break;
8560 s = p + 1;
8561 }
8562 else if (path_end >= path + wildoff
8563 && vim_strchr((char_u *)"*?[{~$", *path_end) != NULL)
8564 e = p;
8565#ifdef FEAT_MBYTE
8566 if (has_mbyte)
8567 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00008568 len = (*mb_ptr2len)(path_end);
Bram Moolenaar231334e2005-07-25 20:46:57 +00008569 STRNCPY(p, path_end, len);
8570 p += len;
8571 path_end += len;
8572 }
8573 else
8574#endif
8575 *p++ = *path_end++;
8576 }
8577 e = p;
8578 *e = NUL;
8579
8580 /* now we have one wildcard component between "s" and "e" */
8581 /* Remove backslashes between "wildoff" and the start of the wildcard
8582 * component. */
8583 for (p = buf + wildoff; p < s; ++p)
8584 if (rem_backslash(p))
8585 {
8586 STRCPY(p, p + 1);
8587 --e;
8588 --s;
8589 }
8590
8591 /* Check for "**" between "s" and "e". */
8592 for (p = s; p < e; ++p)
8593 if (p[0] == '*' && p[1] == '*')
8594 starstar = TRUE;
8595
8596 /* convert the file pattern to a regexp pattern */
8597 starts_with_dot = (*s == '.');
8598 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
8599 if (pat == NULL)
8600 {
8601 vim_free(buf);
8602 return 0;
8603 }
8604
8605 /* compile the regexp into a program */
Bram Moolenaarcc016f52005-12-10 20:23:46 +00008606#ifdef CASE_INSENSITIVE_FILENAME
Bram Moolenaar231334e2005-07-25 20:46:57 +00008607 regmatch.rm_ic = TRUE; /* Behave like Terminal.app */
8608#else
8609 regmatch.rm_ic = FALSE; /* Don't ever ignore case */
8610#endif
8611 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
8612 vim_free(pat);
8613
8614 if (regmatch.regprog == NULL)
8615 {
8616 vim_free(buf);
8617 return 0;
8618 }
8619
8620 /* If "**" is by itself, this is the first time we encounter it and more
8621 * is following then find matches without any directory. */
8622 if (!didstar && stardepth < 100 && starstar && e - s == 2
8623 && *path_end == '/')
8624 {
8625 STRCPY(s, path_end + 1);
8626 ++stardepth;
8627 (void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
8628 --stardepth;
8629 }
8630
8631 /* open the directory for scanning */
8632 *s = NUL;
8633 dirp = opendir(*buf == NUL ? "." : (char *)buf);
8634
8635 /* Find all matching entries */
8636 if (dirp != NULL)
8637 {
8638 for (;;)
8639 {
8640 dp = readdir(dirp);
8641 if (dp == NULL)
8642 break;
8643 if ((dp->d_name[0] != '.' || starts_with_dot)
8644 && vim_regexec(&regmatch, (char_u *)dp->d_name, (colnr_T)0))
8645 {
8646 STRCPY(s, dp->d_name);
8647 len = STRLEN(buf);
8648
8649 if (starstar && stardepth < 100)
8650 {
8651 /* For "**" in the pattern first go deeper in the tree to
8652 * find matches. */
8653 STRCPY(buf + len, "/**");
8654 STRCPY(buf + len + 3, path_end);
8655 ++stardepth;
8656 (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
8657 --stardepth;
8658 }
8659
8660 STRCPY(buf + len, path_end);
8661 if (mch_has_exp_wildcard(path_end)) /* handle more wildcards */
8662 {
8663 /* need to expand another component of the path */
8664 /* remove backslashes for the remaining components only */
8665 (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
8666 }
8667 else
8668 {
8669 /* no more wildcards, check if there is a match */
8670 /* remove backslashes for the remaining components only */
8671 if (*path_end != NUL)
8672 backslash_halve(buf + len + 1);
8673 if (mch_getperm(buf) >= 0) /* add existing file */
8674 {
Bram Moolenaar95e9b492006-03-15 23:04:43 +00008675#ifdef MACOS_CONVERT
Bram Moolenaar231334e2005-07-25 20:46:57 +00008676 size_t precomp_len = STRLEN(buf)+1;
8677 char_u *precomp_buf =
8678 mac_precompose_path(buf, precomp_len, &precomp_len);
Bram Moolenaar95e9b492006-03-15 23:04:43 +00008679
Bram Moolenaar231334e2005-07-25 20:46:57 +00008680 if (precomp_buf)
8681 {
8682 mch_memmove(buf, precomp_buf, precomp_len);
8683 vim_free(precomp_buf);
8684 }
8685#endif
8686 addfile(gap, buf, flags);
8687 }
8688 }
8689 }
8690 }
8691
8692 closedir(dirp);
8693 }
8694
8695 vim_free(buf);
8696 vim_free(regmatch.regprog);
8697
8698 matches = gap->ga_len - start_len;
8699 if (matches > 0)
8700 qsort(((char_u **)gap->ga_data) + start_len, matches,
8701 sizeof(char_u *), pstrcmp);
8702 return matches;
8703}
8704#endif
8705
Bram Moolenaar071d4272004-06-13 20:20:40 +00008706/*
8707 * Generic wildcard expansion code.
8708 *
8709 * Characters in "pat" that should not be expanded must be preceded with a
8710 * backslash. E.g., "/path\ with\ spaces/my\*star*"
8711 *
8712 * Return FAIL when no single file was found. In this case "num_file" is not
8713 * set, and "file" may contain an error message.
8714 * Return OK when some files found. "num_file" is set to the number of
8715 * matches, "file" to the array of matches. Call FreeWild() later.
8716 */
8717 int
8718gen_expand_wildcards(num_pat, pat, num_file, file, flags)
8719 int num_pat; /* number of input patterns */
8720 char_u **pat; /* array of input patterns */
8721 int *num_file; /* resulting number of files */
8722 char_u ***file; /* array of resulting files */
8723 int flags; /* EW_* flags */
8724{
8725 int i;
8726 garray_T ga;
8727 char_u *p;
8728 static int recursive = FALSE;
8729 int add_pat;
8730
8731 /*
8732 * expand_env() is called to expand things like "~user". If this fails,
8733 * it calls ExpandOne(), which brings us back here. In this case, always
8734 * call the machine specific expansion function, if possible. Otherwise,
8735 * return FAIL.
8736 */
8737 if (recursive)
8738#ifdef SPECIAL_WILDCHAR
8739 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
8740#else
8741 return FAIL;
8742#endif
8743
8744#ifdef SPECIAL_WILDCHAR
8745 /*
8746 * If there are any special wildcard characters which we cannot handle
8747 * here, call machine specific function for all the expansion. This
8748 * avoids starting the shell for each argument separately.
8749 * For `=expr` do use the internal function.
8750 */
8751 for (i = 0; i < num_pat; i++)
8752 {
8753 if (vim_strpbrk(pat[i], (char_u *)SPECIAL_WILDCHAR) != NULL
8754# ifdef VIM_BACKTICK
8755 && !(vim_backtick(pat[i]) && pat[i][1] == '=')
8756# endif
8757 )
8758 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
8759 }
8760#endif
8761
8762 recursive = TRUE;
8763
8764 /*
8765 * The matching file names are stored in a growarray. Init it empty.
8766 */
8767 ga_init2(&ga, (int)sizeof(char_u *), 30);
8768
8769 for (i = 0; i < num_pat; ++i)
8770 {
8771 add_pat = -1;
8772 p = pat[i];
8773
8774#ifdef VIM_BACKTICK
8775 if (vim_backtick(p))
8776 add_pat = expand_backtick(&ga, p, flags);
8777 else
8778#endif
8779 {
8780 /*
8781 * First expand environment variables, "~/" and "~user/".
8782 */
8783 if (vim_strpbrk(p, (char_u *)"$~") != NULL)
8784 {
8785 p = expand_env_save(p);
8786 if (p == NULL)
8787 p = pat[i];
8788#ifdef UNIX
8789 /*
8790 * On Unix, if expand_env() can't expand an environment
8791 * variable, use the shell to do that. Discard previously
8792 * found file names and start all over again.
8793 */
8794 else if (vim_strpbrk(p, (char_u *)"$~") != NULL)
8795 {
8796 vim_free(p);
8797 ga_clear(&ga);
8798 i = mch_expand_wildcards(num_pat, pat, num_file, file,
8799 flags);
8800 recursive = FALSE;
8801 return i;
8802 }
8803#endif
8804 }
8805
8806 /*
8807 * If there are wildcards: Expand file names and add each match to
8808 * the list. If there is no match, and EW_NOTFOUND is given, add
8809 * the pattern.
8810 * If there are no wildcards: Add the file name if it exists or
8811 * when EW_NOTFOUND is given.
8812 */
8813 if (mch_has_exp_wildcard(p))
8814 add_pat = mch_expandpath(&ga, p, flags);
8815 }
8816
8817 if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
8818 {
8819 char_u *t = backslash_halve_save(p);
8820
8821#if defined(MACOS_CLASSIC)
8822 slash_to_colon(t);
8823#endif
8824 /* When EW_NOTFOUND is used, always add files and dirs. Makes
8825 * "vim c:/" work. */
8826 if (flags & EW_NOTFOUND)
8827 addfile(&ga, t, flags | EW_DIR | EW_FILE);
8828 else if (mch_getperm(t) >= 0)
8829 addfile(&ga, t, flags);
8830 vim_free(t);
8831 }
8832
8833 if (p != pat[i])
8834 vim_free(p);
8835 }
8836
8837 *num_file = ga.ga_len;
8838 *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data : (char_u **)"";
8839
8840 recursive = FALSE;
8841
8842 return (ga.ga_data != NULL) ? OK : FAIL;
8843}
8844
8845# ifdef VIM_BACKTICK
8846
8847/*
8848 * Return TRUE if we can expand this backtick thing here.
8849 */
8850 static int
8851vim_backtick(p)
8852 char_u *p;
8853{
8854 return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
8855}
8856
8857/*
8858 * Expand an item in `backticks` by executing it as a command.
8859 * Currently only works when pat[] starts and ends with a `.
8860 * Returns number of file names found.
8861 */
8862 static int
8863expand_backtick(gap, pat, flags)
8864 garray_T *gap;
8865 char_u *pat;
8866 int flags; /* EW_* flags */
8867{
8868 char_u *p;
8869 char_u *cmd;
8870 char_u *buffer;
8871 int cnt = 0;
8872 int i;
8873
8874 /* Create the command: lop off the backticks. */
8875 cmd = vim_strnsave(pat + 1, (int)STRLEN(pat) - 2);
8876 if (cmd == NULL)
8877 return 0;
8878
8879#ifdef FEAT_EVAL
8880 if (*cmd == '=') /* `={expr}`: Expand expression */
Bram Moolenaar362e1a32006-03-06 23:29:24 +00008881 buffer = eval_to_string(cmd + 1, &p, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008882 else
8883#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00008884 buffer = get_cmd_output(cmd, NULL,
8885 (flags & EW_SILENT) ? SHELL_SILENT : 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008886 vim_free(cmd);
8887 if (buffer == NULL)
8888 return 0;
8889
8890 cmd = buffer;
8891 while (*cmd != NUL)
8892 {
8893 cmd = skipwhite(cmd); /* skip over white space */
8894 p = cmd;
8895 while (*p != NUL && *p != '\r' && *p != '\n') /* skip over entry */
8896 ++p;
8897 /* add an entry if it is not empty */
8898 if (p > cmd)
8899 {
8900 i = *p;
8901 *p = NUL;
8902 addfile(gap, cmd, flags);
8903 *p = i;
8904 ++cnt;
8905 }
8906 cmd = p;
8907 while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
8908 ++cmd;
8909 }
8910
8911 vim_free(buffer);
8912 return cnt;
8913}
8914# endif /* VIM_BACKTICK */
8915
8916/*
8917 * Add a file to a file list. Accepted flags:
8918 * EW_DIR add directories
8919 * EW_FILE add files
Bram Moolenaar1f35bf92006-03-07 22:38:47 +00008920 * EW_EXEC add executable files
Bram Moolenaar071d4272004-06-13 20:20:40 +00008921 * EW_NOTFOUND add even when it doesn't exist
8922 * EW_ADDSLASH add slash after directory name
8923 */
8924 void
8925addfile(gap, f, flags)
8926 garray_T *gap;
8927 char_u *f; /* filename */
8928 int flags;
8929{
8930 char_u *p;
8931 int isdir;
8932
8933 /* if the file/dir doesn't exist, may not add it */
8934 if (!(flags & EW_NOTFOUND) && mch_getperm(f) < 0)
8935 return;
8936
8937#ifdef FNAME_ILLEGAL
8938 /* if the file/dir contains illegal characters, don't add it */
8939 if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
8940 return;
8941#endif
8942
8943 isdir = mch_isdir(f);
8944 if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
8945 return;
8946
Bram Moolenaar1f35bf92006-03-07 22:38:47 +00008947 /* If the file isn't executable, may not add it. Do accept directories. */
8948 if (!isdir && (flags & EW_EXEC) && !mch_can_exe(f))
8949 return;
8950
Bram Moolenaar071d4272004-06-13 20:20:40 +00008951 /* Make room for another item in the file list. */
8952 if (ga_grow(gap, 1) == FAIL)
8953 return;
8954
8955 p = alloc((unsigned)(STRLEN(f) + 1 + isdir));
8956 if (p == NULL)
8957 return;
8958
8959 STRCPY(p, f);
8960#ifdef BACKSLASH_IN_FILENAME
8961 slash_adjust(p);
8962#endif
8963 /*
8964 * Append a slash or backslash after directory names if none is present.
8965 */
8966#ifndef DONT_ADD_PATHSEP_TO_DIR
8967 if (isdir && (flags & EW_ADDSLASH))
8968 add_pathsep(p);
8969#endif
8970 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008971}
8972#endif /* !NO_EXPANDPATH */
8973
8974#if defined(VIM_BACKTICK) || defined(FEAT_EVAL) || defined(PROTO)
8975
8976#ifndef SEEK_SET
8977# define SEEK_SET 0
8978#endif
8979#ifndef SEEK_END
8980# define SEEK_END 2
8981#endif
8982
8983/*
8984 * Get the stdout of an external command.
8985 * Returns an allocated string, or NULL for error.
8986 */
8987 char_u *
Bram Moolenaarc0197e22004-09-13 20:26:32 +00008988get_cmd_output(cmd, infile, flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008989 char_u *cmd;
Bram Moolenaarc0197e22004-09-13 20:26:32 +00008990 char_u *infile; /* optional input file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008991 int flags; /* can be SHELL_SILENT */
8992{
8993 char_u *tempname;
8994 char_u *command;
8995 char_u *buffer = NULL;
8996 int len;
8997 int i = 0;
8998 FILE *fd;
8999
9000 if (check_restricted() || check_secure())
9001 return NULL;
9002
9003 /* get a name for the temp file */
9004 if ((tempname = vim_tempname('o')) == NULL)
9005 {
9006 EMSG(_(e_notmp));
9007 return NULL;
9008 }
9009
9010 /* Add the redirection stuff */
Bram Moolenaarc0197e22004-09-13 20:26:32 +00009011 command = make_filter_cmd(cmd, infile, tempname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009012 if (command == NULL)
9013 goto done;
9014
9015 /*
9016 * Call the shell to execute the command (errors are ignored).
9017 * Don't check timestamps here.
9018 */
9019 ++no_check_timestamps;
9020 call_shell(command, SHELL_DOOUT | SHELL_EXPAND | flags);
9021 --no_check_timestamps;
9022
9023 vim_free(command);
9024
9025 /*
9026 * read the names from the file into memory
9027 */
9028# ifdef VMS
9029 /* created temporary file is not allways readable as binary */
9030 fd = mch_fopen((char *)tempname, "r");
9031# else
9032 fd = mch_fopen((char *)tempname, READBIN);
9033# endif
9034
9035 if (fd == NULL)
9036 {
9037 EMSG2(_(e_notopen), tempname);
9038 goto done;
9039 }
9040
9041 fseek(fd, 0L, SEEK_END);
9042 len = ftell(fd); /* get size of temp file */
9043 fseek(fd, 0L, SEEK_SET);
9044
9045 buffer = alloc(len + 1);
9046 if (buffer != NULL)
9047 i = (int)fread((char *)buffer, (size_t)1, (size_t)len, fd);
9048 fclose(fd);
9049 mch_remove(tempname);
9050 if (buffer == NULL)
9051 goto done;
9052#ifdef VMS
9053 len = i; /* VMS doesn't give us what we asked for... */
9054#endif
9055 if (i != len)
9056 {
9057 EMSG2(_(e_notread), tempname);
9058 vim_free(buffer);
9059 buffer = NULL;
9060 }
9061 else
9062 buffer[len] = '\0'; /* make sure the buffer is terminated */
9063
9064done:
9065 vim_free(tempname);
9066 return buffer;
9067}
9068#endif
9069
9070/*
9071 * Free the list of files returned by expand_wildcards() or other expansion
9072 * functions.
9073 */
9074 void
9075FreeWild(count, files)
9076 int count;
9077 char_u **files;
9078{
9079 if (files == NULL || count <= 0)
9080 return;
9081#if defined(__EMX__) && defined(__ALWAYS_HAS_TRAILING_NULL_POINTER) /* XXX */
9082 /*
9083 * Is this still OK for when other functions than expand_wildcards() have
9084 * been used???
9085 */
9086 _fnexplodefree((char **)files);
9087#else
9088 while (count--)
9089 vim_free(files[count]);
9090 vim_free(files);
9091#endif
9092}
9093
9094/*
9095 * return TRUE when need to go to Insert mode because of 'insertmode'.
9096 * Don't do this when still processing a command or a mapping.
9097 * Don't do this when inside a ":normal" command.
9098 */
9099 int
9100goto_im()
9101{
9102 return (p_im && stuff_empty() && typebuf_typed());
9103}