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