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