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