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