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