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