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