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