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