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