blob: 1945d0ac9b42485973df08027f121ffd941cab63 [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
Bram Moolenaar071d4272004-06-13 20:20:40 +000017static char_u *vim_version_dir __ARGS((char_u *vimdir));
18static char_u *remove_tail __ARGS((char_u *p, char_u *pend, char_u *name));
Bram Moolenaar071d4272004-06-13 20:20:40 +000019static int copy_indent __ARGS((int size, char_u *src));
20
21/*
22 * Count the size (in window cells) of the indent in the current line.
23 */
24 int
25get_indent()
26{
27 return get_indent_str(ml_get_curline(), (int)curbuf->b_p_ts);
28}
29
30/*
31 * Count the size (in window cells) of the indent in line "lnum".
32 */
33 int
34get_indent_lnum(lnum)
35 linenr_T lnum;
36{
37 return get_indent_str(ml_get(lnum), (int)curbuf->b_p_ts);
38}
39
40#if defined(FEAT_FOLDING) || defined(PROTO)
41/*
42 * Count the size (in window cells) of the indent in line "lnum" of buffer
43 * "buf".
44 */
45 int
46get_indent_buf(buf, lnum)
47 buf_T *buf;
48 linenr_T lnum;
49{
50 return get_indent_str(ml_get_buf(buf, lnum, FALSE), (int)buf->b_p_ts);
51}
52#endif
53
54/*
55 * count the size (in window cells) of the indent in line "ptr", with
56 * 'tabstop' at "ts"
57 */
Bram Moolenaar4399ef42005-02-12 14:29:27 +000058 int
Bram Moolenaar071d4272004-06-13 20:20:40 +000059get_indent_str(ptr, ts)
60 char_u *ptr;
61 int ts;
62{
63 int count = 0;
64
65 for ( ; *ptr; ++ptr)
66 {
67 if (*ptr == TAB) /* count a tab for what it is worth */
68 count += ts - (count % ts);
69 else if (*ptr == ' ')
70 ++count; /* count a space for one */
71 else
72 break;
73 }
Bram Moolenaar4399ef42005-02-12 14:29:27 +000074 return count;
Bram Moolenaar071d4272004-06-13 20:20:40 +000075}
76
77/*
78 * Set the indent of the current line.
79 * Leaves the cursor on the first non-blank in the line.
80 * Caller must take care of undo.
81 * "flags":
82 * SIN_CHANGED: call changed_bytes() if the line was changed.
83 * SIN_INSERT: insert the indent in front of the line.
84 * SIN_UNDO: save line for undo before changing it.
85 * Returns TRUE if the line was changed.
86 */
87 int
88set_indent(size, flags)
Bram Moolenaar5002c292007-07-24 13:26:15 +000089 int size; /* measured in spaces */
Bram Moolenaar071d4272004-06-13 20:20:40 +000090 int flags;
91{
92 char_u *p;
93 char_u *newline;
94 char_u *oldline;
95 char_u *s;
96 int todo;
Bram Moolenaar5002c292007-07-24 13:26:15 +000097 int ind_len; /* measured in characters */
Bram Moolenaar071d4272004-06-13 20:20:40 +000098 int line_len;
99 int doit = FALSE;
Bram Moolenaar5002c292007-07-24 13:26:15 +0000100 int ind_done = 0; /* measured in spaces */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000101 int tab_pad;
Bram Moolenaar5409c052005-03-18 20:27:04 +0000102 int retval = FALSE;
Bram Moolenaar4d64b782007-08-14 20:16:42 +0000103 int orig_char_len = -1; /* number of initial whitespace chars when
Bram Moolenaar5002c292007-07-24 13:26:15 +0000104 'et' and 'pi' are both set */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000105
106 /*
107 * First check if there is anything to do and compute the number of
108 * characters needed for the indent.
109 */
110 todo = size;
111 ind_len = 0;
112 p = oldline = ml_get_curline();
113
114 /* Calculate the buffer size for the new indent, and check to see if it
115 * isn't already set */
116
Bram Moolenaar5002c292007-07-24 13:26:15 +0000117 /* if 'expandtab' isn't set: use TABs; if both 'expandtab' and
118 * 'preserveindent' are set count the number of characters at the
119 * beginning of the line to be copied */
120 if (!curbuf->b_p_et || (!(flags & SIN_INSERT) && curbuf->b_p_pi))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000121 {
122 /* If 'preserveindent' is set then reuse as much as possible of
123 * the existing indent structure for the new indent */
124 if (!(flags & SIN_INSERT) && curbuf->b_p_pi)
125 {
126 ind_done = 0;
127
128 /* count as many characters as we can use */
129 while (todo > 0 && vim_iswhite(*p))
130 {
131 if (*p == TAB)
132 {
133 tab_pad = (int)curbuf->b_p_ts
134 - (ind_done % (int)curbuf->b_p_ts);
135 /* stop if this tab will overshoot the target */
136 if (todo < tab_pad)
137 break;
138 todo -= tab_pad;
139 ++ind_len;
140 ind_done += tab_pad;
141 }
142 else
143 {
144 --todo;
145 ++ind_len;
146 ++ind_done;
147 }
148 ++p;
149 }
150
Bram Moolenaar5002c292007-07-24 13:26:15 +0000151 /* Set initial number of whitespace chars to copy if we are
152 * preserving indent but expandtab is set */
153 if (curbuf->b_p_et)
154 orig_char_len = ind_len;
155
Bram Moolenaar071d4272004-06-13 20:20:40 +0000156 /* Fill to next tabstop with a tab, if possible */
157 tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
Bram Moolenaar4d64b782007-08-14 20:16:42 +0000158 if (todo >= tab_pad && orig_char_len == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000159 {
160 doit = TRUE;
161 todo -= tab_pad;
162 ++ind_len;
163 /* ind_done += tab_pad; */
164 }
165 }
166
167 /* count tabs required for indent */
168 while (todo >= (int)curbuf->b_p_ts)
169 {
170 if (*p != TAB)
171 doit = TRUE;
172 else
173 ++p;
174 todo -= (int)curbuf->b_p_ts;
175 ++ind_len;
176 /* ind_done += (int)curbuf->b_p_ts; */
177 }
178 }
179 /* count spaces required for indent */
180 while (todo > 0)
181 {
182 if (*p != ' ')
183 doit = TRUE;
184 else
185 ++p;
186 --todo;
187 ++ind_len;
188 /* ++ind_done; */
189 }
190
191 /* Return if the indent is OK already. */
192 if (!doit && !vim_iswhite(*p) && !(flags & SIN_INSERT))
193 return FALSE;
194
195 /* Allocate memory for the new line. */
196 if (flags & SIN_INSERT)
197 p = oldline;
198 else
199 p = skipwhite(p);
200 line_len = (int)STRLEN(p) + 1;
Bram Moolenaar5002c292007-07-24 13:26:15 +0000201
202 /* If 'preserveindent' and 'expandtab' are both set keep the original
203 * characters and allocate accordingly. We will fill the rest with spaces
204 * after the if (!curbuf->b_p_et) below. */
Bram Moolenaar4d64b782007-08-14 20:16:42 +0000205 if (orig_char_len != -1)
Bram Moolenaar5002c292007-07-24 13:26:15 +0000206 {
207 newline = alloc(orig_char_len + size - ind_done + line_len);
208 if (newline == NULL)
209 return FALSE;
Bram Moolenaar4d64b782007-08-14 20:16:42 +0000210 todo = size - ind_done;
211 ind_len = orig_char_len + todo; /* Set total length of indent in
212 * characters, which may have been
213 * undercounted until now */
Bram Moolenaar5002c292007-07-24 13:26:15 +0000214 p = oldline;
215 s = newline;
216 while (orig_char_len > 0)
217 {
218 *s++ = *p++;
219 orig_char_len--;
220 }
Bram Moolenaar913626c2008-01-03 11:43:42 +0000221
Bram Moolenaar5002c292007-07-24 13:26:15 +0000222 /* Skip over any additional white space (useful when newindent is less
223 * than old) */
224 while (vim_iswhite(*p))
Bram Moolenaar913626c2008-01-03 11:43:42 +0000225 ++p;
Bram Moolenaarcc00b952007-08-11 12:32:57 +0000226
Bram Moolenaar5002c292007-07-24 13:26:15 +0000227 }
228 else
229 {
230 todo = size;
231 newline = alloc(ind_len + line_len);
232 if (newline == NULL)
233 return FALSE;
234 s = newline;
235 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000236
237 /* Put the characters in the new line. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000238 /* if 'expandtab' isn't set: use TABs */
239 if (!curbuf->b_p_et)
240 {
241 /* If 'preserveindent' is set then reuse as much as possible of
242 * the existing indent structure for the new indent */
243 if (!(flags & SIN_INSERT) && curbuf->b_p_pi)
244 {
245 p = oldline;
246 ind_done = 0;
247
248 while (todo > 0 && vim_iswhite(*p))
249 {
250 if (*p == TAB)
251 {
252 tab_pad = (int)curbuf->b_p_ts
253 - (ind_done % (int)curbuf->b_p_ts);
254 /* stop if this tab will overshoot the target */
255 if (todo < tab_pad)
256 break;
257 todo -= tab_pad;
258 ind_done += tab_pad;
259 }
260 else
261 {
262 --todo;
263 ++ind_done;
264 }
265 *s++ = *p++;
266 }
267
268 /* Fill to next tabstop with a tab, if possible */
269 tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
270 if (todo >= tab_pad)
271 {
272 *s++ = TAB;
273 todo -= tab_pad;
274 }
275
276 p = skipwhite(p);
277 }
278
279 while (todo >= (int)curbuf->b_p_ts)
280 {
281 *s++ = TAB;
282 todo -= (int)curbuf->b_p_ts;
283 }
284 }
285 while (todo > 0)
286 {
287 *s++ = ' ';
288 --todo;
289 }
290 mch_memmove(s, p, (size_t)line_len);
291
292 /* Replace the line (unless undo fails). */
293 if (!(flags & SIN_UNDO) || u_savesub(curwin->w_cursor.lnum) == OK)
294 {
295 ml_replace(curwin->w_cursor.lnum, newline, FALSE);
296 if (flags & SIN_CHANGED)
297 changed_bytes(curwin->w_cursor.lnum, 0);
298 /* Correct saved cursor position if it's after the indent. */
299 if (saved_cursor.lnum == curwin->w_cursor.lnum
300 && saved_cursor.col >= (colnr_T)(p - oldline))
Bram Moolenaara93fa7e2006-04-17 22:14:47 +0000301 saved_cursor.col += ind_len - (colnr_T)(p - oldline);
Bram Moolenaar5409c052005-03-18 20:27:04 +0000302 retval = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000303 }
304 else
305 vim_free(newline);
306
307 curwin->w_cursor.col = ind_len;
Bram Moolenaar5409c052005-03-18 20:27:04 +0000308 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000309}
310
311/*
312 * Copy the indent from ptr to the current line (and fill to size)
313 * Leaves the cursor on the first non-blank in the line.
314 * Returns TRUE if the line was changed.
315 */
316 static int
317copy_indent(size, src)
318 int size;
319 char_u *src;
320{
321 char_u *p = NULL;
322 char_u *line = NULL;
323 char_u *s;
324 int todo;
325 int ind_len;
326 int line_len = 0;
327 int tab_pad;
328 int ind_done;
329 int round;
330
331 /* Round 1: compute the number of characters needed for the indent
332 * Round 2: copy the characters. */
333 for (round = 1; round <= 2; ++round)
334 {
335 todo = size;
336 ind_len = 0;
337 ind_done = 0;
338 s = src;
339
340 /* Count/copy the usable portion of the source line */
341 while (todo > 0 && vim_iswhite(*s))
342 {
343 if (*s == TAB)
344 {
345 tab_pad = (int)curbuf->b_p_ts
346 - (ind_done % (int)curbuf->b_p_ts);
347 /* Stop if this tab will overshoot the target */
348 if (todo < tab_pad)
349 break;
350 todo -= tab_pad;
351 ind_done += tab_pad;
352 }
353 else
354 {
355 --todo;
356 ++ind_done;
357 }
358 ++ind_len;
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000359 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000360 *p++ = *s;
361 ++s;
362 }
363
364 /* Fill to next tabstop with a tab, if possible */
365 tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
Bram Moolenaarc42e7ed2011-09-07 19:58:09 +0200366 if (todo >= tab_pad && !curbuf->b_p_et)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000367 {
368 todo -= tab_pad;
369 ++ind_len;
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000370 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000371 *p++ = TAB;
372 }
373
374 /* Add tabs required for indent */
Bram Moolenaarc42e7ed2011-09-07 19:58:09 +0200375 while (todo >= (int)curbuf->b_p_ts && !curbuf->b_p_et)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000376 {
377 todo -= (int)curbuf->b_p_ts;
378 ++ind_len;
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000379 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000380 *p++ = TAB;
381 }
382
383 /* Count/add spaces required for indent */
384 while (todo > 0)
385 {
386 --todo;
387 ++ind_len;
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000388 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000389 *p++ = ' ';
390 }
391
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000392 if (p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000393 {
394 /* Allocate memory for the result: the copied indent, new indent
395 * and the rest of the line. */
396 line_len = (int)STRLEN(ml_get_curline()) + 1;
397 line = alloc(ind_len + line_len);
398 if (line == NULL)
399 return FALSE;
400 p = line;
401 }
402 }
403
404 /* Append the original line */
405 mch_memmove(p, ml_get_curline(), (size_t)line_len);
406
407 /* Replace the line */
408 ml_replace(curwin->w_cursor.lnum, line, FALSE);
409
410 /* Put the cursor after the indent. */
411 curwin->w_cursor.col = ind_len;
412 return TRUE;
413}
414
415/*
416 * Return the indent of the current line after a number. Return -1 if no
417 * number was found. Used for 'n' in 'formatoptions': numbered list.
Bram Moolenaar86b68352004-12-27 21:59:20 +0000418 * Since a pattern is used it can actually handle more than numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000419 */
420 int
421get_number_indent(lnum)
422 linenr_T lnum;
423{
Bram Moolenaar071d4272004-06-13 20:20:40 +0000424 colnr_T col;
425 pos_T pos;
Bram Moolenaar86b68352004-12-27 21:59:20 +0000426 regmmatch_T regmatch;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000427
428 if (lnum > curbuf->b_ml.ml_line_count)
429 return -1;
Bram Moolenaar86b68352004-12-27 21:59:20 +0000430 pos.lnum = 0;
431 regmatch.regprog = vim_regcomp(curbuf->b_p_flp, RE_MAGIC);
432 if (regmatch.regprog != NULL)
433 {
434 regmatch.rmm_ic = FALSE;
Bram Moolenaar3b56eb32005-07-11 22:40:32 +0000435 regmatch.rmm_maxcol = 0;
Bram Moolenaar91a4e822008-01-19 14:59:58 +0000436 if (vim_regexec_multi(&regmatch, curwin, curbuf, lnum,
437 (colnr_T)0, NULL))
Bram Moolenaar86b68352004-12-27 21:59:20 +0000438 {
439 pos.lnum = regmatch.endpos[0].lnum + lnum;
440 pos.col = regmatch.endpos[0].col;
441#ifdef FEAT_VIRTUALEDIT
442 pos.coladd = 0;
443#endif
444 }
445 vim_free(regmatch.regprog);
446 }
447
448 if (pos.lnum == 0 || *ml_get_pos(&pos) == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000449 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000450 getvcol(curwin, &pos, &col, NULL, NULL);
451 return (int)col;
452}
453
454#if defined(FEAT_CINDENT) || defined(FEAT_SMARTINDENT)
455
456static int cin_is_cinword __ARGS((char_u *line));
457
458/*
459 * Return TRUE if the string "line" starts with a word from 'cinwords'.
460 */
461 static int
462cin_is_cinword(line)
463 char_u *line;
464{
465 char_u *cinw;
466 char_u *cinw_buf;
467 int cinw_len;
468 int retval = FALSE;
469 int len;
470
471 cinw_len = (int)STRLEN(curbuf->b_p_cinw) + 1;
472 cinw_buf = alloc((unsigned)cinw_len);
473 if (cinw_buf != NULL)
474 {
475 line = skipwhite(line);
476 for (cinw = curbuf->b_p_cinw; *cinw; )
477 {
478 len = copy_option_part(&cinw, cinw_buf, cinw_len, ",");
479 if (STRNCMP(line, cinw_buf, len) == 0
480 && (!vim_iswordc(line[len]) || !vim_iswordc(line[len - 1])))
481 {
482 retval = TRUE;
483 break;
484 }
485 }
486 vim_free(cinw_buf);
487 }
488 return retval;
489}
490#endif
491
492/*
493 * open_line: Add a new line below or above the current line.
494 *
495 * For VREPLACE mode, we only add a new line when we get to the end of the
496 * file, otherwise we just start replacing the next line.
497 *
498 * Caller must take care of undo. Since VREPLACE may affect any number of
499 * lines however, it may call u_save_cursor() again when starting to change a
500 * new line.
501 * "flags": OPENLINE_DELSPACES delete spaces after cursor
502 * OPENLINE_DO_COM format comments
503 * OPENLINE_KEEPTRAIL keep trailing spaces
504 * OPENLINE_MARKFIX adjust mark positions after the line break
505 *
506 * Return TRUE for success, FALSE for failure
507 */
508 int
509open_line(dir, flags, old_indent)
510 int dir; /* FORWARD or BACKWARD */
511 int flags;
512 int old_indent; /* indent for after ^^D in Insert mode */
513{
514 char_u *saved_line; /* copy of the original line */
515 char_u *next_line = NULL; /* copy of the next line */
516 char_u *p_extra = NULL; /* what goes to next line */
517 int less_cols = 0; /* less columns for mark in new line */
518 int less_cols_off = 0; /* columns to skip for mark adjust */
519 pos_T old_cursor; /* old cursor position */
520 int newcol = 0; /* new cursor column */
521 int newindent = 0; /* auto-indent of the new line */
522 int n;
523 int trunc_line = FALSE; /* truncate current line afterwards */
524 int retval = FALSE; /* return value, default is FAIL */
525#ifdef FEAT_COMMENTS
526 int extra_len = 0; /* length of p_extra string */
527 int lead_len; /* length of comment leader */
528 char_u *lead_flags; /* position in 'comments' for comment leader */
529 char_u *leader = NULL; /* copy of comment leader */
530#endif
531 char_u *allocated = NULL; /* allocated memory */
532#if defined(FEAT_SMARTINDENT) || defined(FEAT_VREPLACE) || defined(FEAT_LISP) \
533 || defined(FEAT_CINDENT) || defined(FEAT_COMMENTS)
534 char_u *p;
535#endif
536 int saved_char = NUL; /* init for GCC */
537#if defined(FEAT_SMARTINDENT) || defined(FEAT_COMMENTS)
538 pos_T *pos;
539#endif
540#ifdef FEAT_SMARTINDENT
541 int do_si = (!p_paste && curbuf->b_p_si
542# ifdef FEAT_CINDENT
543 && !curbuf->b_p_cin
544# endif
545 );
546 int no_si = FALSE; /* reset did_si afterwards */
547 int first_char = NUL; /* init for GCC */
548#endif
549#if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
550 int vreplace_mode;
551#endif
552 int did_append; /* appended a new line */
553 int saved_pi = curbuf->b_p_pi; /* copy of preserveindent setting */
554
555 /*
556 * make a copy of the current line so we can mess with it
557 */
558 saved_line = vim_strsave(ml_get_curline());
559 if (saved_line == NULL) /* out of memory! */
560 return FALSE;
561
562#ifdef FEAT_VREPLACE
563 if (State & VREPLACE_FLAG)
564 {
565 /*
566 * With VREPLACE we make a copy of the next line, which we will be
567 * starting to replace. First make the new line empty and let vim play
568 * with the indenting and comment leader to its heart's content. Then
569 * we grab what it ended up putting on the new line, put back the
570 * original line, and call ins_char() to put each new character onto
571 * the line, replacing what was there before and pushing the right
572 * stuff onto the replace stack. -- webb.
573 */
574 if (curwin->w_cursor.lnum < orig_line_count)
575 next_line = vim_strsave(ml_get(curwin->w_cursor.lnum + 1));
576 else
577 next_line = vim_strsave((char_u *)"");
578 if (next_line == NULL) /* out of memory! */
579 goto theend;
580
581 /*
582 * In VREPLACE mode, a NL replaces the rest of the line, and starts
583 * replacing the next line, so push all of the characters left on the
584 * line onto the replace stack. We'll push any other characters that
585 * might be replaced at the start of the next line (due to autoindent
586 * etc) a bit later.
587 */
588 replace_push(NUL); /* Call twice because BS over NL expects it */
589 replace_push(NUL);
590 p = saved_line + curwin->w_cursor.col;
591 while (*p != NUL)
Bram Moolenaar2c994e82008-01-02 16:49:36 +0000592 {
593#ifdef FEAT_MBYTE
594 if (has_mbyte)
595 p += replace_push_mb(p);
596 else
597#endif
598 replace_push(*p++);
599 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000600 saved_line[curwin->w_cursor.col] = NUL;
601 }
602#endif
603
604 if ((State & INSERT)
605#ifdef FEAT_VREPLACE
606 && !(State & VREPLACE_FLAG)
607#endif
608 )
609 {
610 p_extra = saved_line + curwin->w_cursor.col;
611#ifdef FEAT_SMARTINDENT
612 if (do_si) /* need first char after new line break */
613 {
614 p = skipwhite(p_extra);
615 first_char = *p;
616 }
617#endif
618#ifdef FEAT_COMMENTS
619 extra_len = (int)STRLEN(p_extra);
620#endif
621 saved_char = *p_extra;
622 *p_extra = NUL;
623 }
624
625 u_clearline(); /* cannot do "U" command when adding lines */
626#ifdef FEAT_SMARTINDENT
627 did_si = FALSE;
628#endif
629 ai_col = 0;
630
631 /*
632 * If we just did an auto-indent, then we didn't type anything on
633 * the prior line, and it should be truncated. Do this even if 'ai' is not
634 * set because automatically inserting a comment leader also sets did_ai.
635 */
636 if (dir == FORWARD && did_ai)
637 trunc_line = TRUE;
638
639 /*
640 * If 'autoindent' and/or 'smartindent' is set, try to figure out what
641 * indent to use for the new line.
642 */
643 if (curbuf->b_p_ai
644#ifdef FEAT_SMARTINDENT
645 || do_si
646#endif
647 )
648 {
649 /*
650 * count white space on current line
651 */
652 newindent = get_indent_str(saved_line, (int)curbuf->b_p_ts);
653 if (newindent == 0)
654 newindent = old_indent; /* for ^^D command in insert mode */
655
656#ifdef FEAT_SMARTINDENT
657 /*
658 * Do smart indenting.
659 * In insert/replace mode (only when dir == FORWARD)
660 * we may move some text to the next line. If it starts with '{'
661 * don't add an indent. Fixes inserting a NL before '{' in line
662 * "if (condition) {"
663 */
664 if (!trunc_line && do_si && *saved_line != NUL
665 && (p_extra == NULL || first_char != '{'))
666 {
667 char_u *ptr;
668 char_u last_char;
669
670 old_cursor = curwin->w_cursor;
671 ptr = saved_line;
672# ifdef FEAT_COMMENTS
673 if (flags & OPENLINE_DO_COM)
674 lead_len = get_leader_len(ptr, NULL, FALSE);
675 else
676 lead_len = 0;
677# endif
678 if (dir == FORWARD)
679 {
680 /*
681 * Skip preprocessor directives, unless they are
682 * recognised as comments.
683 */
684 if (
685# ifdef FEAT_COMMENTS
686 lead_len == 0 &&
687# endif
688 ptr[0] == '#')
689 {
690 while (ptr[0] == '#' && curwin->w_cursor.lnum > 1)
691 ptr = ml_get(--curwin->w_cursor.lnum);
692 newindent = get_indent();
693 }
694# ifdef FEAT_COMMENTS
695 if (flags & OPENLINE_DO_COM)
696 lead_len = get_leader_len(ptr, NULL, FALSE);
697 else
698 lead_len = 0;
699 if (lead_len > 0)
700 {
701 /*
702 * This case gets the following right:
703 * \*
704 * * A comment (read '\' as '/').
705 * *\
706 * #define IN_THE_WAY
707 * This should line up here;
708 */
709 p = skipwhite(ptr);
710 if (p[0] == '/' && p[1] == '*')
711 p++;
712 if (p[0] == '*')
713 {
714 for (p++; *p; p++)
715 {
716 if (p[0] == '/' && p[-1] == '*')
717 {
718 /*
719 * End of C comment, indent should line up
720 * with the line containing the start of
721 * the comment
722 */
723 curwin->w_cursor.col = (colnr_T)(p - ptr);
724 if ((pos = findmatch(NULL, NUL)) != NULL)
725 {
726 curwin->w_cursor.lnum = pos->lnum;
727 newindent = get_indent();
728 }
729 }
730 }
731 }
732 }
733 else /* Not a comment line */
734# endif
735 {
736 /* Find last non-blank in line */
737 p = ptr + STRLEN(ptr) - 1;
738 while (p > ptr && vim_iswhite(*p))
739 --p;
740 last_char = *p;
741
742 /*
743 * find the character just before the '{' or ';'
744 */
745 if (last_char == '{' || last_char == ';')
746 {
747 if (p > ptr)
748 --p;
749 while (p > ptr && vim_iswhite(*p))
750 --p;
751 }
752 /*
753 * Try to catch lines that are split over multiple
754 * lines. eg:
755 * if (condition &&
756 * condition) {
757 * Should line up here!
758 * }
759 */
760 if (*p == ')')
761 {
762 curwin->w_cursor.col = (colnr_T)(p - ptr);
763 if ((pos = findmatch(NULL, '(')) != NULL)
764 {
765 curwin->w_cursor.lnum = pos->lnum;
766 newindent = get_indent();
767 ptr = ml_get_curline();
768 }
769 }
770 /*
771 * If last character is '{' do indent, without
772 * checking for "if" and the like.
773 */
774 if (last_char == '{')
775 {
776 did_si = TRUE; /* do indent */
777 no_si = TRUE; /* don't delete it when '{' typed */
778 }
779 /*
780 * Look for "if" and the like, use 'cinwords'.
781 * Don't do this if the previous line ended in ';' or
782 * '}'.
783 */
784 else if (last_char != ';' && last_char != '}'
785 && cin_is_cinword(ptr))
786 did_si = TRUE;
787 }
788 }
789 else /* dir == BACKWARD */
790 {
791 /*
792 * Skip preprocessor directives, unless they are
793 * recognised as comments.
794 */
795 if (
796# ifdef FEAT_COMMENTS
797 lead_len == 0 &&
798# endif
799 ptr[0] == '#')
800 {
801 int was_backslashed = FALSE;
802
803 while ((ptr[0] == '#' || was_backslashed) &&
804 curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
805 {
806 if (*ptr && ptr[STRLEN(ptr) - 1] == '\\')
807 was_backslashed = TRUE;
808 else
809 was_backslashed = FALSE;
810 ptr = ml_get(++curwin->w_cursor.lnum);
811 }
812 if (was_backslashed)
813 newindent = 0; /* Got to end of file */
814 else
815 newindent = get_indent();
816 }
817 p = skipwhite(ptr);
818 if (*p == '}') /* if line starts with '}': do indent */
819 did_si = TRUE;
820 else /* can delete indent when '{' typed */
821 can_si_back = TRUE;
822 }
823 curwin->w_cursor = old_cursor;
824 }
825 if (do_si)
826 can_si = TRUE;
827#endif /* FEAT_SMARTINDENT */
828
829 did_ai = TRUE;
830 }
831
832#ifdef FEAT_COMMENTS
833 /*
834 * Find out if the current line starts with a comment leader.
835 * This may then be inserted in front of the new line.
836 */
837 end_comment_pending = NUL;
838 if (flags & OPENLINE_DO_COM)
839 lead_len = get_leader_len(saved_line, &lead_flags, dir == BACKWARD);
840 else
841 lead_len = 0;
842 if (lead_len > 0)
843 {
844 char_u *lead_repl = NULL; /* replaces comment leader */
845 int lead_repl_len = 0; /* length of *lead_repl */
846 char_u lead_middle[COM_MAX_LEN]; /* middle-comment string */
847 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
848 char_u *comment_end = NULL; /* where lead_end has been found */
849 int extra_space = FALSE; /* append extra space */
850 int current_flag;
851 int require_blank = FALSE; /* requires blank after middle */
852 char_u *p2;
853
854 /*
855 * If the comment leader has the start, middle or end flag, it may not
856 * be used or may be replaced with the middle leader.
857 */
858 for (p = lead_flags; *p && *p != ':'; ++p)
859 {
860 if (*p == COM_BLANK)
861 {
862 require_blank = TRUE;
863 continue;
864 }
865 if (*p == COM_START || *p == COM_MIDDLE)
866 {
867 current_flag = *p;
868 if (*p == COM_START)
869 {
870 /*
871 * Doing "O" on a start of comment does not insert leader.
872 */
873 if (dir == BACKWARD)
874 {
875 lead_len = 0;
876 break;
877 }
878
879 /* find start of middle part */
880 (void)copy_option_part(&p, lead_middle, COM_MAX_LEN, ",");
881 require_blank = FALSE;
882 }
883
884 /*
885 * Isolate the strings of the middle and end leader.
886 */
887 while (*p && p[-1] != ':') /* find end of middle flags */
888 {
889 if (*p == COM_BLANK)
890 require_blank = TRUE;
891 ++p;
892 }
893 (void)copy_option_part(&p, lead_middle, COM_MAX_LEN, ",");
894
895 while (*p && p[-1] != ':') /* find end of end flags */
896 {
897 /* Check whether we allow automatic ending of comments */
898 if (*p == COM_AUTO_END)
899 end_comment_pending = -1; /* means we want to set it */
900 ++p;
901 }
902 n = copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
903
904 if (end_comment_pending == -1) /* we can set it now */
905 end_comment_pending = lead_end[n - 1];
906
907 /*
908 * If the end of the comment is in the same line, don't use
909 * the comment leader.
910 */
911 if (dir == FORWARD)
912 {
913 for (p = saved_line + lead_len; *p; ++p)
914 if (STRNCMP(p, lead_end, n) == 0)
915 {
916 comment_end = p;
917 lead_len = 0;
918 break;
919 }
920 }
921
922 /*
923 * Doing "o" on a start of comment inserts the middle leader.
924 */
925 if (lead_len > 0)
926 {
927 if (current_flag == COM_START)
928 {
929 lead_repl = lead_middle;
930 lead_repl_len = (int)STRLEN(lead_middle);
931 }
932
933 /*
934 * If we have hit RETURN immediately after the start
935 * comment leader, then put a space after the middle
936 * comment leader on the next line.
937 */
938 if (!vim_iswhite(saved_line[lead_len - 1])
939 && ((p_extra != NULL
940 && (int)curwin->w_cursor.col == lead_len)
941 || (p_extra == NULL
942 && saved_line[lead_len] == NUL)
943 || require_blank))
944 extra_space = TRUE;
945 }
946 break;
947 }
948 if (*p == COM_END)
949 {
950 /*
951 * Doing "o" on the end of a comment does not insert leader.
952 * Remember where the end is, might want to use it to find the
953 * start (for C-comments).
954 */
955 if (dir == FORWARD)
956 {
957 comment_end = skipwhite(saved_line);
958 lead_len = 0;
959 break;
960 }
961
962 /*
963 * Doing "O" on the end of a comment inserts the middle leader.
964 * Find the string for the middle leader, searching backwards.
965 */
966 while (p > curbuf->b_p_com && *p != ',')
967 --p;
968 for (lead_repl = p; lead_repl > curbuf->b_p_com
969 && lead_repl[-1] != ':'; --lead_repl)
970 ;
971 lead_repl_len = (int)(p - lead_repl);
972
973 /* We can probably always add an extra space when doing "O" on
974 * the comment-end */
975 extra_space = TRUE;
976
977 /* Check whether we allow automatic ending of comments */
978 for (p2 = p; *p2 && *p2 != ':'; p2++)
979 {
980 if (*p2 == COM_AUTO_END)
981 end_comment_pending = -1; /* means we want to set it */
982 }
983 if (end_comment_pending == -1)
984 {
985 /* Find last character in end-comment string */
986 while (*p2 && *p2 != ',')
987 p2++;
988 end_comment_pending = p2[-1];
989 }
990 break;
991 }
992 if (*p == COM_FIRST)
993 {
994 /*
995 * Comment leader for first line only: Don't repeat leader
996 * when using "O", blank out leader when using "o".
997 */
998 if (dir == BACKWARD)
999 lead_len = 0;
1000 else
1001 {
1002 lead_repl = (char_u *)"";
1003 lead_repl_len = 0;
1004 }
1005 break;
1006 }
1007 }
1008 if (lead_len)
1009 {
1010 /* allocate buffer (may concatenate p_exta later) */
1011 leader = alloc(lead_len + lead_repl_len + extra_space +
1012 extra_len + 1);
1013 allocated = leader; /* remember to free it later */
1014
1015 if (leader == NULL)
1016 lead_len = 0;
1017 else
1018 {
Bram Moolenaarce0842a2005-07-18 21:58:11 +00001019 vim_strncpy(leader, saved_line, lead_len);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001020
1021 /*
1022 * Replace leader with lead_repl, right or left adjusted
1023 */
1024 if (lead_repl != NULL)
1025 {
1026 int c = 0;
1027 int off = 0;
1028
Bram Moolenaard7d5b472009-11-11 16:30:08 +00001029 for (p = lead_flags; *p != NUL && *p != ':'; )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001030 {
1031 if (*p == COM_RIGHT || *p == COM_LEFT)
Bram Moolenaard7d5b472009-11-11 16:30:08 +00001032 c = *p++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001033 else if (VIM_ISDIGIT(*p) || *p == '-')
1034 off = getdigits(&p);
Bram Moolenaard7d5b472009-11-11 16:30:08 +00001035 else
1036 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001037 }
1038 if (c == COM_RIGHT) /* right adjusted leader */
1039 {
1040 /* find last non-white in the leader to line up with */
1041 for (p = leader + lead_len - 1; p > leader
1042 && vim_iswhite(*p); --p)
1043 ;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001044 ++p;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001045
1046#ifdef FEAT_MBYTE
1047 /* Compute the length of the replaced characters in
1048 * screen characters, not bytes. */
1049 {
1050 int repl_size = vim_strnsize(lead_repl,
1051 lead_repl_len);
1052 int old_size = 0;
1053 char_u *endp = p;
1054 int l;
1055
1056 while (old_size < repl_size && p > leader)
1057 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001058 mb_ptr_back(leader, p);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001059 old_size += ptr2cells(p);
1060 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001061 l = lead_repl_len - (int)(endp - p);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001062 if (l != 0)
1063 mch_memmove(endp + l, endp,
1064 (size_t)((leader + lead_len) - endp));
1065 lead_len += l;
1066 }
1067#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001068 if (p < leader + lead_repl_len)
1069 p = leader;
1070 else
1071 p -= lead_repl_len;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001072#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001073 mch_memmove(p, lead_repl, (size_t)lead_repl_len);
1074 if (p + lead_repl_len > leader + lead_len)
1075 p[lead_repl_len] = NUL;
1076
1077 /* blank-out any other chars from the old leader. */
1078 while (--p >= leader)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001079 {
1080#ifdef FEAT_MBYTE
1081 int l = mb_head_off(leader, p);
1082
1083 if (l > 1)
1084 {
1085 p -= l;
1086 if (ptr2cells(p) > 1)
1087 {
1088 p[1] = ' ';
1089 --l;
1090 }
1091 mch_memmove(p + 1, p + l + 1,
1092 (size_t)((leader + lead_len) - (p + l + 1)));
1093 lead_len -= l;
1094 *p = ' ';
1095 }
1096 else
1097#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001098 if (!vim_iswhite(*p))
1099 *p = ' ';
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001100 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001101 }
1102 else /* left adjusted leader */
1103 {
1104 p = skipwhite(leader);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001105#ifdef FEAT_MBYTE
1106 /* Compute the length of the replaced characters in
1107 * screen characters, not bytes. Move the part that is
1108 * not to be overwritten. */
1109 {
1110 int repl_size = vim_strnsize(lead_repl,
1111 lead_repl_len);
1112 int i;
1113 int l;
1114
1115 for (i = 0; p[i] != NUL && i < lead_len; i += l)
1116 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00001117 l = (*mb_ptr2len)(p + i);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001118 if (vim_strnsize(p, i + l) > repl_size)
1119 break;
1120 }
1121 if (i != lead_repl_len)
1122 {
1123 mch_memmove(p + lead_repl_len, p + i,
Bram Moolenaar2d7ff052009-11-17 15:08:26 +00001124 (size_t)(lead_len - i - (p - leader)));
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001125 lead_len += lead_repl_len - i;
1126 }
1127 }
1128#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001129 mch_memmove(p, lead_repl, (size_t)lead_repl_len);
1130
1131 /* Replace any remaining non-white chars in the old
1132 * leader by spaces. Keep Tabs, the indent must
1133 * remain the same. */
1134 for (p += lead_repl_len; p < leader + lead_len; ++p)
1135 if (!vim_iswhite(*p))
1136 {
1137 /* Don't put a space before a TAB. */
1138 if (p + 1 < leader + lead_len && p[1] == TAB)
1139 {
1140 --lead_len;
1141 mch_memmove(p, p + 1,
1142 (leader + lead_len) - p);
1143 }
1144 else
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001145 {
1146#ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00001147 int l = (*mb_ptr2len)(p);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001148
1149 if (l > 1)
1150 {
1151 if (ptr2cells(p) > 1)
1152 {
1153 /* Replace a double-wide char with
1154 * two spaces */
1155 --l;
1156 *p++ = ' ';
1157 }
1158 mch_memmove(p + 1, p + l,
1159 (leader + lead_len) - p);
1160 lead_len -= l - 1;
1161 }
1162#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001163 *p = ' ';
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001164 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001165 }
1166 *p = NUL;
1167 }
1168
1169 /* Recompute the indent, it may have changed. */
1170 if (curbuf->b_p_ai
1171#ifdef FEAT_SMARTINDENT
1172 || do_si
1173#endif
1174 )
1175 newindent = get_indent_str(leader, (int)curbuf->b_p_ts);
1176
1177 /* Add the indent offset */
1178 if (newindent + off < 0)
1179 {
1180 off = -newindent;
1181 newindent = 0;
1182 }
1183 else
1184 newindent += off;
1185
1186 /* Correct trailing spaces for the shift, so that
1187 * alignment remains equal. */
1188 while (off > 0 && lead_len > 0
1189 && leader[lead_len - 1] == ' ')
1190 {
1191 /* Don't do it when there is a tab before the space */
1192 if (vim_strchr(skipwhite(leader), '\t') != NULL)
1193 break;
1194 --lead_len;
1195 --off;
1196 }
1197
1198 /* If the leader ends in white space, don't add an
1199 * extra space */
1200 if (lead_len > 0 && vim_iswhite(leader[lead_len - 1]))
1201 extra_space = FALSE;
1202 leader[lead_len] = NUL;
1203 }
1204
1205 if (extra_space)
1206 {
1207 leader[lead_len++] = ' ';
1208 leader[lead_len] = NUL;
1209 }
1210
1211 newcol = lead_len;
1212
1213 /*
1214 * if a new indent will be set below, remove the indent that
1215 * is in the comment leader
1216 */
1217 if (newindent
1218#ifdef FEAT_SMARTINDENT
1219 || did_si
1220#endif
1221 )
1222 {
1223 while (lead_len && vim_iswhite(*leader))
1224 {
1225 --lead_len;
1226 --newcol;
1227 ++leader;
1228 }
1229 }
1230
1231 }
1232#ifdef FEAT_SMARTINDENT
1233 did_si = can_si = FALSE;
1234#endif
1235 }
1236 else if (comment_end != NULL)
1237 {
1238 /*
1239 * We have finished a comment, so we don't use the leader.
1240 * If this was a C-comment and 'ai' or 'si' is set do a normal
1241 * indent to align with the line containing the start of the
1242 * comment.
1243 */
1244 if (comment_end[0] == '*' && comment_end[1] == '/' &&
1245 (curbuf->b_p_ai
1246#ifdef FEAT_SMARTINDENT
1247 || do_si
1248#endif
1249 ))
1250 {
1251 old_cursor = curwin->w_cursor;
1252 curwin->w_cursor.col = (colnr_T)(comment_end - saved_line);
1253 if ((pos = findmatch(NULL, NUL)) != NULL)
1254 {
1255 curwin->w_cursor.lnum = pos->lnum;
1256 newindent = get_indent();
1257 }
1258 curwin->w_cursor = old_cursor;
1259 }
1260 }
1261 }
1262#endif
1263
1264 /* (State == INSERT || State == REPLACE), only when dir == FORWARD */
1265 if (p_extra != NULL)
1266 {
1267 *p_extra = saved_char; /* restore char that NUL replaced */
1268
1269 /*
1270 * When 'ai' set or "flags" has OPENLINE_DELSPACES, skip to the first
1271 * non-blank.
1272 *
1273 * When in REPLACE mode, put the deleted blanks on the replace stack,
1274 * preceded by a NUL, so they can be put back when a BS is entered.
1275 */
1276 if (REPLACE_NORMAL(State))
1277 replace_push(NUL); /* end of extra blanks */
1278 if (curbuf->b_p_ai || (flags & OPENLINE_DELSPACES))
1279 {
1280 while ((*p_extra == ' ' || *p_extra == '\t')
1281#ifdef FEAT_MBYTE
1282 && (!enc_utf8
1283 || !utf_iscomposing(utf_ptr2char(p_extra + 1)))
1284#endif
1285 )
1286 {
1287 if (REPLACE_NORMAL(State))
1288 replace_push(*p_extra);
1289 ++p_extra;
1290 ++less_cols_off;
1291 }
1292 }
1293 if (*p_extra != NUL)
1294 did_ai = FALSE; /* append some text, don't truncate now */
1295
1296 /* columns for marks adjusted for removed columns */
1297 less_cols = (int)(p_extra - saved_line);
1298 }
1299
1300 if (p_extra == NULL)
1301 p_extra = (char_u *)""; /* append empty line */
1302
1303#ifdef FEAT_COMMENTS
1304 /* concatenate leader and p_extra, if there is a leader */
1305 if (lead_len)
1306 {
1307 STRCAT(leader, p_extra);
1308 p_extra = leader;
1309 did_ai = TRUE; /* So truncating blanks works with comments */
1310 less_cols -= lead_len;
1311 }
1312 else
1313 end_comment_pending = NUL; /* turns out there was no leader */
1314#endif
1315
1316 old_cursor = curwin->w_cursor;
1317 if (dir == BACKWARD)
1318 --curwin->w_cursor.lnum;
1319#ifdef FEAT_VREPLACE
1320 if (!(State & VREPLACE_FLAG) || old_cursor.lnum >= orig_line_count)
1321#endif
1322 {
1323 if (ml_append(curwin->w_cursor.lnum, p_extra, (colnr_T)0, FALSE)
1324 == FAIL)
1325 goto theend;
1326 /* Postpone calling changed_lines(), because it would mess up folding
1327 * with markers. */
1328 mark_adjust(curwin->w_cursor.lnum + 1, (linenr_T)MAXLNUM, 1L, 0L);
1329 did_append = TRUE;
1330 }
1331#ifdef FEAT_VREPLACE
1332 else
1333 {
1334 /*
1335 * In VREPLACE mode we are starting to replace the next line.
1336 */
1337 curwin->w_cursor.lnum++;
1338 if (curwin->w_cursor.lnum >= Insstart.lnum + vr_lines_changed)
1339 {
1340 /* In case we NL to a new line, BS to the previous one, and NL
1341 * again, we don't want to save the new line for undo twice.
1342 */
1343 (void)u_save_cursor(); /* errors are ignored! */
1344 vr_lines_changed++;
1345 }
1346 ml_replace(curwin->w_cursor.lnum, p_extra, TRUE);
1347 changed_bytes(curwin->w_cursor.lnum, 0);
1348 curwin->w_cursor.lnum--;
1349 did_append = FALSE;
1350 }
1351#endif
1352
1353 if (newindent
1354#ifdef FEAT_SMARTINDENT
1355 || did_si
1356#endif
1357 )
1358 {
1359 ++curwin->w_cursor.lnum;
1360#ifdef FEAT_SMARTINDENT
1361 if (did_si)
1362 {
1363 if (p_sr)
1364 newindent -= newindent % (int)curbuf->b_p_sw;
1365 newindent += (int)curbuf->b_p_sw;
1366 }
1367#endif
Bram Moolenaar5002c292007-07-24 13:26:15 +00001368 /* Copy the indent */
1369 if (curbuf->b_p_ci)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001370 {
1371 (void)copy_indent(newindent, saved_line);
1372
1373 /*
1374 * Set the 'preserveindent' option so that any further screwing
1375 * with the line doesn't entirely destroy our efforts to preserve
1376 * it. It gets restored at the function end.
1377 */
1378 curbuf->b_p_pi = TRUE;
1379 }
1380 else
1381 (void)set_indent(newindent, SIN_INSERT);
1382 less_cols -= curwin->w_cursor.col;
1383
1384 ai_col = curwin->w_cursor.col;
1385
1386 /*
1387 * In REPLACE mode, for each character in the new indent, there must
1388 * be a NUL on the replace stack, for when it is deleted with BS
1389 */
1390 if (REPLACE_NORMAL(State))
1391 for (n = 0; n < (int)curwin->w_cursor.col; ++n)
1392 replace_push(NUL);
1393 newcol += curwin->w_cursor.col;
1394#ifdef FEAT_SMARTINDENT
1395 if (no_si)
1396 did_si = FALSE;
1397#endif
1398 }
1399
1400#ifdef FEAT_COMMENTS
1401 /*
1402 * In REPLACE mode, for each character in the extra leader, there must be
1403 * a NUL on the replace stack, for when it is deleted with BS.
1404 */
1405 if (REPLACE_NORMAL(State))
1406 while (lead_len-- > 0)
1407 replace_push(NUL);
1408#endif
1409
1410 curwin->w_cursor = old_cursor;
1411
1412 if (dir == FORWARD)
1413 {
1414 if (trunc_line || (State & INSERT))
1415 {
1416 /* truncate current line at cursor */
1417 saved_line[curwin->w_cursor.col] = NUL;
1418 /* Remove trailing white space, unless OPENLINE_KEEPTRAIL used. */
1419 if (trunc_line && !(flags & OPENLINE_KEEPTRAIL))
1420 truncate_spaces(saved_line);
1421 ml_replace(curwin->w_cursor.lnum, saved_line, FALSE);
1422 saved_line = NULL;
1423 if (did_append)
1424 {
1425 changed_lines(curwin->w_cursor.lnum, curwin->w_cursor.col,
1426 curwin->w_cursor.lnum + 1, 1L);
1427 did_append = FALSE;
1428
1429 /* Move marks after the line break to the new line. */
1430 if (flags & OPENLINE_MARKFIX)
1431 mark_col_adjust(curwin->w_cursor.lnum,
1432 curwin->w_cursor.col + less_cols_off,
1433 1L, (long)-less_cols);
1434 }
1435 else
1436 changed_bytes(curwin->w_cursor.lnum, curwin->w_cursor.col);
1437 }
1438
1439 /*
1440 * Put the cursor on the new line. Careful: the scrollup() above may
1441 * have moved w_cursor, we must use old_cursor.
1442 */
1443 curwin->w_cursor.lnum = old_cursor.lnum + 1;
1444 }
1445 if (did_append)
1446 changed_lines(curwin->w_cursor.lnum, 0, curwin->w_cursor.lnum, 1L);
1447
1448 curwin->w_cursor.col = newcol;
1449#ifdef FEAT_VIRTUALEDIT
1450 curwin->w_cursor.coladd = 0;
1451#endif
1452
1453#if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
1454 /*
1455 * In VREPLACE mode, we are handling the replace stack ourselves, so stop
1456 * fixthisline() from doing it (via change_indent()) by telling it we're in
1457 * normal INSERT mode.
1458 */
1459 if (State & VREPLACE_FLAG)
1460 {
1461 vreplace_mode = State; /* So we know to put things right later */
1462 State = INSERT;
1463 }
1464 else
1465 vreplace_mode = 0;
1466#endif
1467#ifdef FEAT_LISP
1468 /*
1469 * May do lisp indenting.
1470 */
1471 if (!p_paste
1472# ifdef FEAT_COMMENTS
1473 && leader == NULL
1474# endif
1475 && curbuf->b_p_lisp
1476 && curbuf->b_p_ai)
1477 {
1478 fixthisline(get_lisp_indent);
1479 p = ml_get_curline();
1480 ai_col = (colnr_T)(skipwhite(p) - p);
1481 }
1482#endif
1483#ifdef FEAT_CINDENT
1484 /*
1485 * May do indenting after opening a new line.
1486 */
1487 if (!p_paste
1488 && (curbuf->b_p_cin
1489# ifdef FEAT_EVAL
1490 || *curbuf->b_p_inde != NUL
1491# endif
1492 )
1493 && in_cinkeys(dir == FORWARD
1494 ? KEY_OPEN_FORW
1495 : KEY_OPEN_BACK, ' ', linewhite(curwin->w_cursor.lnum)))
1496 {
1497 do_c_expr_indent();
1498 p = ml_get_curline();
1499 ai_col = (colnr_T)(skipwhite(p) - p);
1500 }
1501#endif
1502#if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
1503 if (vreplace_mode != 0)
1504 State = vreplace_mode;
1505#endif
1506
1507#ifdef FEAT_VREPLACE
1508 /*
1509 * Finally, VREPLACE gets the stuff on the new line, then puts back the
1510 * original line, and inserts the new stuff char by char, pushing old stuff
1511 * onto the replace stack (via ins_char()).
1512 */
1513 if (State & VREPLACE_FLAG)
1514 {
1515 /* Put new line in p_extra */
1516 p_extra = vim_strsave(ml_get_curline());
1517 if (p_extra == NULL)
1518 goto theend;
1519
1520 /* Put back original line */
1521 ml_replace(curwin->w_cursor.lnum, next_line, FALSE);
1522
1523 /* Insert new stuff into line again */
1524 curwin->w_cursor.col = 0;
1525#ifdef FEAT_VIRTUALEDIT
1526 curwin->w_cursor.coladd = 0;
1527#endif
1528 ins_bytes(p_extra); /* will call changed_bytes() */
1529 vim_free(p_extra);
1530 next_line = NULL;
1531 }
1532#endif
1533
1534 retval = TRUE; /* success! */
1535theend:
1536 curbuf->b_p_pi = saved_pi;
1537 vim_free(saved_line);
1538 vim_free(next_line);
1539 vim_free(allocated);
1540 return retval;
1541}
1542
1543#if defined(FEAT_COMMENTS) || defined(PROTO)
1544/*
1545 * get_leader_len() returns the length of the prefix of the given string
1546 * which introduces a comment. If this string is not a comment then 0 is
1547 * returned.
1548 * When "flags" is not NULL, it is set to point to the flags of the recognized
1549 * comment leader.
1550 * "backward" must be true for the "O" command.
1551 */
1552 int
1553get_leader_len(line, flags, backward)
1554 char_u *line;
1555 char_u **flags;
1556 int backward;
1557{
1558 int i, j;
1559 int got_com = FALSE;
1560 int found_one;
1561 char_u part_buf[COM_MAX_LEN]; /* buffer for one option part */
1562 char_u *string; /* pointer to comment string */
1563 char_u *list;
Bram Moolenaara4271d52011-05-10 13:38:27 +02001564 int middle_match_len = 0;
1565 char_u *prev_list;
Bram Moolenaar05da4282011-05-10 14:44:11 +02001566 char_u *saved_flags = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001567
1568 i = 0;
1569 while (vim_iswhite(line[i])) /* leading white space is ignored */
1570 ++i;
1571
1572 /*
1573 * Repeat to match several nested comment strings.
1574 */
Bram Moolenaara4271d52011-05-10 13:38:27 +02001575 while (line[i] != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001576 {
1577 /*
1578 * scan through the 'comments' option for a match
1579 */
1580 found_one = FALSE;
1581 for (list = curbuf->b_p_com; *list; )
1582 {
Bram Moolenaara4271d52011-05-10 13:38:27 +02001583 /* Get one option part into part_buf[]. Advance "list" to next
1584 * one. Put "string" at start of string. */
1585 if (!got_com && flags != NULL)
1586 *flags = list; /* remember where flags started */
1587 prev_list = list;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001588 (void)copy_option_part(&list, part_buf, COM_MAX_LEN, ",");
1589 string = vim_strchr(part_buf, ':');
1590 if (string == NULL) /* missing ':', ignore this part */
1591 continue;
1592 *string++ = NUL; /* isolate flags from string */
1593
Bram Moolenaara4271d52011-05-10 13:38:27 +02001594 /* If we found a middle match previously, use that match when this
1595 * is not a middle or end. */
1596 if (middle_match_len != 0
1597 && vim_strchr(part_buf, COM_MIDDLE) == NULL
1598 && vim_strchr(part_buf, COM_END) == NULL)
1599 break;
1600
1601 /* When we already found a nested comment, only accept further
1602 * nested comments. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001603 if (got_com && vim_strchr(part_buf, COM_NEST) == NULL)
1604 continue;
1605
Bram Moolenaara4271d52011-05-10 13:38:27 +02001606 /* When 'O' flag present and using "O" command skip this one. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001607 if (backward && vim_strchr(part_buf, COM_NOBACK) != NULL)
1608 continue;
1609
Bram Moolenaara4271d52011-05-10 13:38:27 +02001610 /* Line contents and string must match.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001611 * When string starts with white space, must have some white space
1612 * (but the amount does not need to match, there might be a mix of
Bram Moolenaara4271d52011-05-10 13:38:27 +02001613 * TABs and spaces). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001614 if (vim_iswhite(string[0]))
1615 {
1616 if (i == 0 || !vim_iswhite(line[i - 1]))
Bram Moolenaara4271d52011-05-10 13:38:27 +02001617 continue; /* missing shite space */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001618 while (vim_iswhite(string[0]))
1619 ++string;
1620 }
1621 for (j = 0; string[j] != NUL && string[j] == line[i + j]; ++j)
1622 ;
1623 if (string[j] != NUL)
Bram Moolenaara4271d52011-05-10 13:38:27 +02001624 continue; /* string doesn't match */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001625
Bram Moolenaara4271d52011-05-10 13:38:27 +02001626 /* When 'b' flag used, there must be white space or an
1627 * end-of-line after the string in the line. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001628 if (vim_strchr(part_buf, COM_BLANK) != NULL
1629 && !vim_iswhite(line[i + j]) && line[i + j] != NUL)
1630 continue;
1631
Bram Moolenaara4271d52011-05-10 13:38:27 +02001632 /* We have found a match, stop searching unless this is a middle
1633 * comment. The middle comment can be a substring of the end
1634 * comment in which case it's better to return the length of the
1635 * end comment and its flags. Thus we keep searching with middle
1636 * and end matches and use an end match if it matches better. */
1637 if (vim_strchr(part_buf, COM_MIDDLE) != NULL)
1638 {
1639 if (middle_match_len == 0)
1640 {
1641 middle_match_len = j;
1642 saved_flags = prev_list;
1643 }
1644 continue;
1645 }
1646 if (middle_match_len != 0 && j > middle_match_len)
1647 /* Use this match instead of the middle match, since it's a
1648 * longer thus better match. */
1649 middle_match_len = 0;
1650
1651 if (middle_match_len == 0)
1652 i += j;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001653 found_one = TRUE;
1654 break;
1655 }
1656
Bram Moolenaara4271d52011-05-10 13:38:27 +02001657 if (middle_match_len != 0)
1658 {
1659 /* Use the previously found middle match after failing to find a
1660 * match with an end. */
1661 if (!got_com && flags != NULL)
1662 *flags = saved_flags;
1663 i += middle_match_len;
1664 found_one = TRUE;
1665 }
1666
1667 /* No match found, stop scanning. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001668 if (!found_one)
1669 break;
1670
Bram Moolenaara4271d52011-05-10 13:38:27 +02001671 /* Include any trailing white space. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001672 while (vim_iswhite(line[i]))
1673 ++i;
1674
Bram Moolenaara4271d52011-05-10 13:38:27 +02001675 /* If this comment doesn't nest, stop here. */
1676 got_com = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001677 if (vim_strchr(part_buf, COM_NEST) == NULL)
1678 break;
1679 }
Bram Moolenaara4271d52011-05-10 13:38:27 +02001680
Bram Moolenaar071d4272004-06-13 20:20:40 +00001681 return (got_com ? i : 0);
1682}
1683#endif
1684
1685/*
1686 * Return the number of window lines occupied by buffer line "lnum".
1687 */
1688 int
1689plines(lnum)
1690 linenr_T lnum;
1691{
1692 return plines_win(curwin, lnum, TRUE);
1693}
1694
1695 int
1696plines_win(wp, lnum, winheight)
1697 win_T *wp;
1698 linenr_T lnum;
1699 int winheight; /* when TRUE limit to window height */
1700{
1701#if defined(FEAT_DIFF) || defined(PROTO)
1702 /* Check for filler lines above this buffer line. When folded the result
1703 * is one line anyway. */
1704 return plines_win_nofill(wp, lnum, winheight) + diff_check_fill(wp, lnum);
1705}
1706
1707 int
1708plines_nofill(lnum)
1709 linenr_T lnum;
1710{
1711 return plines_win_nofill(curwin, lnum, TRUE);
1712}
1713
1714 int
1715plines_win_nofill(wp, lnum, winheight)
1716 win_T *wp;
1717 linenr_T lnum;
1718 int winheight; /* when TRUE limit to window height */
1719{
1720#endif
1721 int lines;
1722
1723 if (!wp->w_p_wrap)
1724 return 1;
1725
1726#ifdef FEAT_VERTSPLIT
1727 if (wp->w_width == 0)
1728 return 1;
1729#endif
1730
1731#ifdef FEAT_FOLDING
1732 /* A folded lines is handled just like an empty line. */
1733 /* NOTE: Caller must handle lines that are MAYBE folded. */
1734 if (lineFolded(wp, lnum) == TRUE)
1735 return 1;
1736#endif
1737
1738 lines = plines_win_nofold(wp, lnum);
1739 if (winheight > 0 && lines > wp->w_height)
1740 return (int)wp->w_height;
1741 return lines;
1742}
1743
1744/*
1745 * Return number of window lines physical line "lnum" will occupy in window
1746 * "wp". Does not care about folding, 'wrap' or 'diff'.
1747 */
1748 int
1749plines_win_nofold(wp, lnum)
1750 win_T *wp;
1751 linenr_T lnum;
1752{
1753 char_u *s;
1754 long col;
1755 int width;
1756
1757 s = ml_get_buf(wp->w_buffer, lnum, FALSE);
1758 if (*s == NUL) /* empty line */
1759 return 1;
1760 col = win_linetabsize(wp, s, (colnr_T)MAXCOL);
1761
1762 /*
1763 * If list mode is on, then the '$' at the end of the line may take up one
1764 * extra column.
1765 */
1766 if (wp->w_p_list && lcs_eol != NUL)
1767 col += 1;
1768
1769 /*
Bram Moolenaar64486672010-05-16 15:46:46 +02001770 * Add column offset for 'number', 'relativenumber' and 'foldcolumn'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001771 */
1772 width = W_WIDTH(wp) - win_col_off(wp);
1773 if (width <= 0)
1774 return 32000;
1775 if (col <= width)
1776 return 1;
1777 col -= width;
1778 width += win_col_off2(wp);
1779 return (col + (width - 1)) / width + 1;
1780}
1781
1782/*
1783 * Like plines_win(), but only reports the number of physical screen lines
1784 * used from the start of the line to the given column number.
1785 */
1786 int
1787plines_win_col(wp, lnum, column)
1788 win_T *wp;
1789 linenr_T lnum;
1790 long column;
1791{
1792 long col;
1793 char_u *s;
1794 int lines = 0;
1795 int width;
1796
1797#ifdef FEAT_DIFF
1798 /* Check for filler lines above this buffer line. When folded the result
1799 * is one line anyway. */
1800 lines = diff_check_fill(wp, lnum);
1801#endif
1802
1803 if (!wp->w_p_wrap)
1804 return lines + 1;
1805
1806#ifdef FEAT_VERTSPLIT
1807 if (wp->w_width == 0)
1808 return lines + 1;
1809#endif
1810
1811 s = ml_get_buf(wp->w_buffer, lnum, FALSE);
1812
1813 col = 0;
1814 while (*s != NUL && --column >= 0)
1815 {
1816 col += win_lbr_chartabsize(wp, s, (colnr_T)col, NULL);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001817 mb_ptr_adv(s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001818 }
1819
1820 /*
1821 * If *s is a TAB, and the TAB is not displayed as ^I, and we're not in
1822 * INSERT mode, then col must be adjusted so that it represents the last
1823 * screen position of the TAB. This only fixes an error when the TAB wraps
1824 * from one screen line to the next (when 'columns' is not a multiple of
1825 * 'ts') -- webb.
1826 */
1827 if (*s == TAB && (State & NORMAL) && (!wp->w_p_list || lcs_tab1))
1828 col += win_lbr_chartabsize(wp, s, (colnr_T)col, NULL) - 1;
1829
1830 /*
Bram Moolenaar64486672010-05-16 15:46:46 +02001831 * Add column offset for 'number', 'relativenumber', 'foldcolumn', etc.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001832 */
1833 width = W_WIDTH(wp) - win_col_off(wp);
Bram Moolenaar26470632006-10-24 19:12:40 +00001834 if (width <= 0)
1835 return 9999;
1836
1837 lines += 1;
1838 if (col > width)
1839 lines += (col - width) / (width + win_col_off2(wp)) + 1;
1840 return lines;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001841}
1842
1843 int
1844plines_m_win(wp, first, last)
1845 win_T *wp;
1846 linenr_T first, last;
1847{
1848 int count = 0;
1849
1850 while (first <= last)
1851 {
1852#ifdef FEAT_FOLDING
1853 int x;
1854
1855 /* Check if there are any really folded lines, but also included lines
1856 * that are maybe folded. */
1857 x = foldedCount(wp, first, NULL);
1858 if (x > 0)
1859 {
1860 ++count; /* count 1 for "+-- folded" line */
1861 first += x;
1862 }
1863 else
1864#endif
1865 {
1866#ifdef FEAT_DIFF
1867 if (first == wp->w_topline)
1868 count += plines_win_nofill(wp, first, TRUE) + wp->w_topfill;
1869 else
1870#endif
1871 count += plines_win(wp, first, TRUE);
1872 ++first;
1873 }
1874 }
1875 return (count);
1876}
1877
1878#if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) || defined(PROTO)
1879/*
1880 * Insert string "p" at the cursor position. Stops at a NUL byte.
1881 * Handles Replace mode and multi-byte characters.
1882 */
1883 void
1884ins_bytes(p)
1885 char_u *p;
1886{
1887 ins_bytes_len(p, (int)STRLEN(p));
1888}
1889#endif
1890
1891#if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) \
1892 || defined(FEAT_COMMENTS) || defined(FEAT_MBYTE) || defined(PROTO)
1893/*
1894 * Insert string "p" with length "len" at the cursor position.
1895 * Handles Replace mode and multi-byte characters.
1896 */
1897 void
1898ins_bytes_len(p, len)
1899 char_u *p;
1900 int len;
1901{
1902 int i;
1903# ifdef FEAT_MBYTE
1904 int n;
1905
Bram Moolenaar176dd1e2008-06-21 14:30:28 +00001906 if (has_mbyte)
1907 for (i = 0; i < len; i += n)
1908 {
1909 if (enc_utf8)
1910 /* avoid reading past p[len] */
1911 n = utfc_ptr2len_len(p + i, len - i);
1912 else
1913 n = (*mb_ptr2len)(p + i);
1914 ins_char_bytes(p + i, n);
1915 }
1916 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001917# endif
Bram Moolenaar176dd1e2008-06-21 14:30:28 +00001918 for (i = 0; i < len; ++i)
1919 ins_char(p[i]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001920}
1921#endif
1922
1923/*
1924 * Insert or replace a single character at the cursor position.
1925 * When in REPLACE or VREPLACE mode, replace any existing character.
1926 * Caller must have prepared for undo.
1927 * For multi-byte characters we get the whole character, the caller must
1928 * convert bytes to a character.
1929 */
1930 void
1931ins_char(c)
1932 int c;
1933{
1934#if defined(FEAT_MBYTE) || defined(PROTO)
1935 char_u buf[MB_MAXBYTES];
1936 int n;
1937
1938 n = (*mb_char2bytes)(c, buf);
1939
1940 /* When "c" is 0x100, 0x200, etc. we don't want to insert a NUL byte.
1941 * Happens for CTRL-Vu9900. */
1942 if (buf[0] == 0)
1943 buf[0] = '\n';
1944
1945 ins_char_bytes(buf, n);
1946}
1947
1948 void
1949ins_char_bytes(buf, charlen)
1950 char_u *buf;
1951 int charlen;
1952{
1953 int c = buf[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001954#endif
1955 int newlen; /* nr of bytes inserted */
1956 int oldlen; /* nr of bytes deleted (0 when not replacing) */
1957 char_u *p;
1958 char_u *newp;
1959 char_u *oldp;
1960 int linelen; /* length of old line including NUL */
1961 colnr_T col;
1962 linenr_T lnum = curwin->w_cursor.lnum;
1963 int i;
1964
1965#ifdef FEAT_VIRTUALEDIT
1966 /* Break tabs if needed. */
1967 if (virtual_active() && curwin->w_cursor.coladd > 0)
1968 coladvance_force(getviscol());
1969#endif
1970
1971 col = curwin->w_cursor.col;
1972 oldp = ml_get(lnum);
1973 linelen = (int)STRLEN(oldp) + 1;
1974
1975 /* The lengths default to the values for when not replacing. */
1976 oldlen = 0;
1977#ifdef FEAT_MBYTE
1978 newlen = charlen;
1979#else
1980 newlen = 1;
1981#endif
1982
1983 if (State & REPLACE_FLAG)
1984 {
1985#ifdef FEAT_VREPLACE
1986 if (State & VREPLACE_FLAG)
1987 {
1988 colnr_T new_vcol = 0; /* init for GCC */
1989 colnr_T vcol;
1990 int old_list;
1991#ifndef FEAT_MBYTE
1992 char_u buf[2];
1993#endif
1994
1995 /*
1996 * Disable 'list' temporarily, unless 'cpo' contains the 'L' flag.
1997 * Returns the old value of list, so when finished,
1998 * curwin->w_p_list should be set back to this.
1999 */
2000 old_list = curwin->w_p_list;
2001 if (old_list && vim_strchr(p_cpo, CPO_LISTWM) == NULL)
2002 curwin->w_p_list = FALSE;
2003
2004 /*
2005 * In virtual replace mode each character may replace one or more
2006 * characters (zero if it's a TAB). Count the number of bytes to
2007 * be deleted to make room for the new character, counting screen
2008 * cells. May result in adding spaces to fill a gap.
2009 */
2010 getvcol(curwin, &curwin->w_cursor, NULL, &vcol, NULL);
2011#ifndef FEAT_MBYTE
2012 buf[0] = c;
2013 buf[1] = NUL;
2014#endif
2015 new_vcol = vcol + chartabsize(buf, vcol);
2016 while (oldp[col + oldlen] != NUL && vcol < new_vcol)
2017 {
2018 vcol += chartabsize(oldp + col + oldlen, vcol);
2019 /* Don't need to remove a TAB that takes us to the right
2020 * position. */
2021 if (vcol > new_vcol && oldp[col + oldlen] == TAB)
2022 break;
2023#ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002024 oldlen += (*mb_ptr2len)(oldp + col + oldlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002025#else
2026 ++oldlen;
2027#endif
2028 /* Deleted a bit too much, insert spaces. */
2029 if (vcol > new_vcol)
2030 newlen += vcol - new_vcol;
2031 }
2032 curwin->w_p_list = old_list;
2033 }
2034 else
2035#endif
2036 if (oldp[col] != NUL)
2037 {
2038 /* normal replace */
2039#ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002040 oldlen = (*mb_ptr2len)(oldp + col);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002041#else
2042 oldlen = 1;
2043#endif
2044 }
2045
2046
2047 /* Push the replaced bytes onto the replace stack, so that they can be
2048 * put back when BS is used. The bytes of a multi-byte character are
2049 * done the other way around, so that the first byte is popped off
2050 * first (it tells the byte length of the character). */
2051 replace_push(NUL);
2052 for (i = 0; i < oldlen; ++i)
2053 {
2054#ifdef FEAT_MBYTE
Bram Moolenaar2c994e82008-01-02 16:49:36 +00002055 if (has_mbyte)
2056 i += replace_push_mb(oldp + col + i) - 1;
2057 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002058#endif
Bram Moolenaar2c994e82008-01-02 16:49:36 +00002059 replace_push(oldp[col + i]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002060 }
2061 }
2062
2063 newp = alloc_check((unsigned)(linelen + newlen - oldlen));
2064 if (newp == NULL)
2065 return;
2066
2067 /* Copy bytes before the cursor. */
2068 if (col > 0)
2069 mch_memmove(newp, oldp, (size_t)col);
2070
2071 /* Copy bytes after the changed character(s). */
2072 p = newp + col;
2073 mch_memmove(p + newlen, oldp + col + oldlen,
2074 (size_t)(linelen - col - oldlen));
2075
2076 /* Insert or overwrite the new character. */
2077#ifdef FEAT_MBYTE
2078 mch_memmove(p, buf, charlen);
2079 i = charlen;
2080#else
2081 *p = c;
2082 i = 1;
2083#endif
2084
2085 /* Fill with spaces when necessary. */
2086 while (i < newlen)
2087 p[i++] = ' ';
2088
2089 /* Replace the line in the buffer. */
2090 ml_replace(lnum, newp, FALSE);
2091
2092 /* mark the buffer as changed and prepare for displaying */
2093 changed_bytes(lnum, col);
2094
2095 /*
2096 * If we're in Insert or Replace mode and 'showmatch' is set, then briefly
2097 * show the match for right parens and braces.
2098 */
2099 if (p_sm && (State & INSERT)
2100 && msg_silent == 0
2101#ifdef FEAT_MBYTE
2102 && charlen == 1
2103#endif
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00002104#ifdef FEAT_INS_EXPAND
2105 && !ins_compl_active()
2106#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002107 )
2108 showmatch(c);
2109
2110#ifdef FEAT_RIGHTLEFT
2111 if (!p_ri || (State & REPLACE_FLAG))
2112#endif
2113 {
2114 /* Normal insert: move cursor right */
2115#ifdef FEAT_MBYTE
2116 curwin->w_cursor.col += charlen;
2117#else
2118 ++curwin->w_cursor.col;
2119#endif
2120 }
2121 /*
2122 * TODO: should try to update w_row here, to avoid recomputing it later.
2123 */
2124}
2125
2126/*
2127 * Insert a string at the cursor position.
2128 * Note: Does NOT handle Replace mode.
2129 * Caller must have prepared for undo.
2130 */
2131 void
2132ins_str(s)
2133 char_u *s;
2134{
2135 char_u *oldp, *newp;
2136 int newlen = (int)STRLEN(s);
2137 int oldlen;
2138 colnr_T col;
2139 linenr_T lnum = curwin->w_cursor.lnum;
2140
2141#ifdef FEAT_VIRTUALEDIT
2142 if (virtual_active() && curwin->w_cursor.coladd > 0)
2143 coladvance_force(getviscol());
2144#endif
2145
2146 col = curwin->w_cursor.col;
2147 oldp = ml_get(lnum);
2148 oldlen = (int)STRLEN(oldp);
2149
2150 newp = alloc_check((unsigned)(oldlen + newlen + 1));
2151 if (newp == NULL)
2152 return;
2153 if (col > 0)
2154 mch_memmove(newp, oldp, (size_t)col);
2155 mch_memmove(newp + col, s, (size_t)newlen);
2156 mch_memmove(newp + col + newlen, oldp + col, (size_t)(oldlen - col + 1));
2157 ml_replace(lnum, newp, FALSE);
2158 changed_bytes(lnum, col);
2159 curwin->w_cursor.col += newlen;
2160}
2161
2162/*
2163 * Delete one character under the cursor.
2164 * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
2165 * Caller must have prepared for undo.
2166 *
2167 * return FAIL for failure, OK otherwise
2168 */
2169 int
2170del_char(fixpos)
2171 int fixpos;
2172{
2173#ifdef FEAT_MBYTE
2174 if (has_mbyte)
2175 {
2176 /* Make sure the cursor is at the start of a character. */
2177 mb_adjust_cursor();
2178 if (*ml_get_cursor() == NUL)
2179 return FAIL;
2180 return del_chars(1L, fixpos);
2181 }
2182#endif
Bram Moolenaare3226be2005-12-18 22:10:00 +00002183 return del_bytes(1L, fixpos, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002184}
2185
2186#if defined(FEAT_MBYTE) || defined(PROTO)
2187/*
2188 * Like del_bytes(), but delete characters instead of bytes.
2189 */
2190 int
2191del_chars(count, fixpos)
2192 long count;
2193 int fixpos;
2194{
2195 long bytes = 0;
2196 long i;
2197 char_u *p;
2198 int l;
2199
2200 p = ml_get_cursor();
2201 for (i = 0; i < count && *p != NUL; ++i)
2202 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002203 l = (*mb_ptr2len)(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002204 bytes += l;
2205 p += l;
2206 }
Bram Moolenaare3226be2005-12-18 22:10:00 +00002207 return del_bytes(bytes, fixpos, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002208}
2209#endif
2210
2211/*
2212 * Delete "count" bytes under the cursor.
2213 * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
2214 * Caller must have prepared for undo.
2215 *
2216 * return FAIL for failure, OK otherwise
2217 */
2218 int
Bram Moolenaarca003e12006-03-17 23:19:38 +00002219del_bytes(count, fixpos_arg, use_delcombine)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002220 long count;
Bram Moolenaarca003e12006-03-17 23:19:38 +00002221 int fixpos_arg;
Bram Moolenaar78a15312009-05-15 19:33:18 +00002222 int use_delcombine UNUSED; /* 'delcombine' option applies */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002223{
2224 char_u *oldp, *newp;
2225 colnr_T oldlen;
2226 linenr_T lnum = curwin->w_cursor.lnum;
2227 colnr_T col = curwin->w_cursor.col;
2228 int was_alloced;
2229 long movelen;
Bram Moolenaarca003e12006-03-17 23:19:38 +00002230 int fixpos = fixpos_arg;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002231
2232 oldp = ml_get(lnum);
2233 oldlen = (int)STRLEN(oldp);
2234
2235 /*
2236 * Can't do anything when the cursor is on the NUL after the line.
2237 */
2238 if (col >= oldlen)
2239 return FAIL;
2240
2241#ifdef FEAT_MBYTE
2242 /* If 'delcombine' is set and deleting (less than) one character, only
2243 * delete the last combining character. */
Bram Moolenaare3226be2005-12-18 22:10:00 +00002244 if (p_deco && use_delcombine && enc_utf8
2245 && utfc_ptr2len(oldp + col) >= count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002246 {
Bram Moolenaar362e1a32006-03-06 23:29:24 +00002247 int cc[MAX_MCO];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002248 int n;
2249
Bram Moolenaar362e1a32006-03-06 23:29:24 +00002250 (void)utfc_ptr2char(oldp + col, cc);
2251 if (cc[0] != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002252 {
2253 /* Find the last composing char, there can be several. */
2254 n = col;
2255 do
2256 {
2257 col = n;
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002258 count = utf_ptr2len(oldp + n);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002259 n += count;
2260 } while (UTF_COMPOSINGLIKE(oldp + col, oldp + n));
2261 fixpos = 0;
2262 }
2263 }
2264#endif
2265
2266 /*
2267 * When count is too big, reduce it.
2268 */
2269 movelen = (long)oldlen - (long)col - count + 1; /* includes trailing NUL */
2270 if (movelen <= 1)
2271 {
2272 /*
2273 * If we just took off the last character of a non-blank line, and
Bram Moolenaarca003e12006-03-17 23:19:38 +00002274 * fixpos is TRUE, we don't want to end up positioned at the NUL,
2275 * unless "restart_edit" is set or 'virtualedit' contains "onemore".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002276 */
Bram Moolenaarca003e12006-03-17 23:19:38 +00002277 if (col > 0 && fixpos && restart_edit == 0
2278#ifdef FEAT_VIRTUALEDIT
2279 && (ve_flags & VE_ONEMORE) == 0
2280#endif
2281 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00002282 {
2283 --curwin->w_cursor.col;
2284#ifdef FEAT_VIRTUALEDIT
2285 curwin->w_cursor.coladd = 0;
2286#endif
2287#ifdef FEAT_MBYTE
2288 if (has_mbyte)
2289 curwin->w_cursor.col -=
2290 (*mb_head_off)(oldp, oldp + curwin->w_cursor.col);
2291#endif
2292 }
2293 count = oldlen - col;
2294 movelen = 1;
2295 }
2296
2297 /*
2298 * If the old line has been allocated the deletion can be done in the
2299 * existing line. Otherwise a new line has to be allocated
Bram Moolenaare21877a2008-02-13 09:58:14 +00002300 * Can't do this when using Netbeans, because we would need to invoke
2301 * netbeans_removed(), which deallocates the line. Let ml_replace() take
Bram Moolenaar1a509df2010-08-01 17:59:57 +02002302 * care of notifying Netbeans.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002303 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002304#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02002305 if (netbeans_active())
Bram Moolenaare21877a2008-02-13 09:58:14 +00002306 was_alloced = FALSE;
2307 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002308#endif
Bram Moolenaare21877a2008-02-13 09:58:14 +00002309 was_alloced = ml_line_alloced(); /* check if oldp was allocated */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002310 if (was_alloced)
2311 newp = oldp; /* use same allocated memory */
2312 else
2313 { /* need to allocate a new line */
2314 newp = alloc((unsigned)(oldlen + 1 - count));
2315 if (newp == NULL)
2316 return FAIL;
2317 mch_memmove(newp, oldp, (size_t)col);
2318 }
2319 mch_memmove(newp + col, oldp + col + count, (size_t)movelen);
2320 if (!was_alloced)
2321 ml_replace(lnum, newp, FALSE);
2322
2323 /* mark the buffer as changed and prepare for displaying */
2324 changed_bytes(lnum, curwin->w_cursor.col);
2325
2326 return OK;
2327}
2328
2329/*
2330 * Delete from cursor to end of line.
2331 * Caller must have prepared for undo.
2332 *
2333 * return FAIL for failure, OK otherwise
2334 */
2335 int
2336truncate_line(fixpos)
2337 int fixpos; /* if TRUE fix the cursor position when done */
2338{
2339 char_u *newp;
2340 linenr_T lnum = curwin->w_cursor.lnum;
2341 colnr_T col = curwin->w_cursor.col;
2342
2343 if (col == 0)
2344 newp = vim_strsave((char_u *)"");
2345 else
2346 newp = vim_strnsave(ml_get(lnum), col);
2347
2348 if (newp == NULL)
2349 return FAIL;
2350
2351 ml_replace(lnum, newp, FALSE);
2352
2353 /* mark the buffer as changed and prepare for displaying */
2354 changed_bytes(lnum, curwin->w_cursor.col);
2355
2356 /*
2357 * If "fixpos" is TRUE we don't want to end up positioned at the NUL.
2358 */
2359 if (fixpos && curwin->w_cursor.col > 0)
2360 --curwin->w_cursor.col;
2361
2362 return OK;
2363}
2364
2365/*
2366 * Delete "nlines" lines at the cursor.
2367 * Saves the lines for undo first if "undo" is TRUE.
2368 */
2369 void
2370del_lines(nlines, undo)
2371 long nlines; /* number of lines to delete */
2372 int undo; /* if TRUE, prepare for undo */
2373{
2374 long n;
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002375 linenr_T first = curwin->w_cursor.lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002376
2377 if (nlines <= 0)
2378 return;
2379
2380 /* save the deleted lines for undo */
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002381 if (undo && u_savedel(first, nlines) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002382 return;
2383
2384 for (n = 0; n < nlines; )
2385 {
2386 if (curbuf->b_ml.ml_flags & ML_EMPTY) /* nothing to delete */
2387 break;
2388
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002389 ml_delete(first, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002390 ++n;
2391
2392 /* If we delete the last line in the file, stop */
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002393 if (first > curbuf->b_ml.ml_line_count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002394 break;
2395 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002396
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002397 /* Correct the cursor position before calling deleted_lines_mark(), it may
2398 * trigger a callback to display the cursor. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002399 curwin->w_cursor.col = 0;
2400 check_cursor_lnum();
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002401
2402 /* adjust marks, mark the buffer as changed and prepare for displaying */
2403 deleted_lines_mark(first, n);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002404}
2405
2406 int
2407gchar_pos(pos)
2408 pos_T *pos;
2409{
2410 char_u *ptr = ml_get_pos(pos);
2411
2412#ifdef FEAT_MBYTE
2413 if (has_mbyte)
2414 return (*mb_ptr2char)(ptr);
2415#endif
2416 return (int)*ptr;
2417}
2418
2419 int
2420gchar_cursor()
2421{
2422#ifdef FEAT_MBYTE
2423 if (has_mbyte)
2424 return (*mb_ptr2char)(ml_get_cursor());
2425#endif
2426 return (int)*ml_get_cursor();
2427}
2428
2429/*
2430 * Write a character at the current cursor position.
2431 * It is directly written into the block.
2432 */
2433 void
2434pchar_cursor(c)
2435 int c;
2436{
2437 *(ml_get_buf(curbuf, curwin->w_cursor.lnum, TRUE)
2438 + curwin->w_cursor.col) = c;
2439}
2440
Bram Moolenaar071d4272004-06-13 20:20:40 +00002441/*
2442 * When extra == 0: Return TRUE if the cursor is before or on the first
2443 * non-blank in the line.
2444 * When extra == 1: Return TRUE if the cursor is before the first non-blank in
2445 * the line.
2446 */
2447 int
2448inindent(extra)
2449 int extra;
2450{
2451 char_u *ptr;
2452 colnr_T col;
2453
2454 for (col = 0, ptr = ml_get_curline(); vim_iswhite(*ptr); ++col)
2455 ++ptr;
2456 if (col >= curwin->w_cursor.col + extra)
2457 return TRUE;
2458 else
2459 return FALSE;
2460}
2461
2462/*
2463 * Skip to next part of an option argument: Skip space and comma.
2464 */
2465 char_u *
2466skip_to_option_part(p)
2467 char_u *p;
2468{
2469 if (*p == ',')
2470 ++p;
2471 while (*p == ' ')
2472 ++p;
2473 return p;
2474}
2475
2476/*
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002477 * Call this function when something in the current buffer is changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002478 *
2479 * Most often called through changed_bytes() and changed_lines(), which also
2480 * mark the area of the display to be redrawn.
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002481 *
2482 * Careful: may trigger autocommands that reload the buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002483 */
2484 void
2485changed()
2486{
2487#if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
2488 /* The text of the preediting area is inserted, but this doesn't
2489 * mean a change of the buffer yet. That is delayed until the
2490 * text is committed. (this means preedit becomes empty) */
2491 if (im_is_preediting() && !xim_changed_while_preediting)
2492 return;
2493 xim_changed_while_preediting = FALSE;
2494#endif
2495
2496 if (!curbuf->b_changed)
2497 {
2498 int save_msg_scroll = msg_scroll;
2499
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002500 /* Give a warning about changing a read-only file. This may also
2501 * check-out the file, thus change "curbuf"! */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002502 change_warning(0);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002503
Bram Moolenaar071d4272004-06-13 20:20:40 +00002504 /* Create a swap file if that is wanted.
2505 * Don't do this for "nofile" and "nowrite" buffer types. */
2506 if (curbuf->b_may_swap
2507#ifdef FEAT_QUICKFIX
2508 && !bt_dontwrite(curbuf)
2509#endif
2510 )
2511 {
2512 ml_open_file(curbuf);
2513
2514 /* The ml_open_file() can cause an ATTENTION message.
2515 * Wait two seconds, to make sure the user reads this unexpected
2516 * message. Since we could be anywhere, call wait_return() now,
2517 * and don't let the emsg() set msg_scroll. */
2518 if (need_wait_return && emsg_silent == 0)
2519 {
2520 out_flush();
2521 ui_delay(2000L, TRUE);
2522 wait_return(TRUE);
2523 msg_scroll = save_msg_scroll;
2524 }
2525 }
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02002526 changed_int();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002527 }
2528 ++curbuf->b_changedtick;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002529}
2530
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02002531/*
2532 * Internal part of changed(), no user interaction.
2533 */
2534 void
2535changed_int()
2536{
2537 curbuf->b_changed = TRUE;
2538 ml_setflags(curbuf);
2539#ifdef FEAT_WINDOWS
2540 check_status(curbuf);
2541 redraw_tabline = TRUE;
2542#endif
2543#ifdef FEAT_TITLE
2544 need_maketitle = TRUE; /* set window title later */
2545#endif
2546}
2547
Bram Moolenaardba8a912005-04-24 22:08:39 +00002548static void changedOneline __ARGS((buf_T *buf, linenr_T lnum));
2549static void changed_lines_buf __ARGS((buf_T *buf, linenr_T lnum, linenr_T lnume, long xtra));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002550static void changed_common __ARGS((linenr_T lnum, colnr_T col, linenr_T lnume, long xtra));
2551
2552/*
2553 * Changed bytes within a single line for the current buffer.
2554 * - marks the windows on this buffer to be redisplayed
2555 * - marks the buffer changed by calling changed()
2556 * - invalidates cached values
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002557 * Careful: may trigger autocommands that reload the buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002558 */
2559 void
2560changed_bytes(lnum, col)
2561 linenr_T lnum;
2562 colnr_T col;
2563{
Bram Moolenaardba8a912005-04-24 22:08:39 +00002564 changedOneline(curbuf, lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002565 changed_common(lnum, col, lnum + 1, 0L);
Bram Moolenaardba8a912005-04-24 22:08:39 +00002566
2567#ifdef FEAT_DIFF
2568 /* Diff highlighting in other diff windows may need to be updated too. */
2569 if (curwin->w_p_diff)
2570 {
2571 win_T *wp;
2572 linenr_T wlnum;
2573
2574 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2575 if (wp->w_p_diff && wp != curwin)
2576 {
2577 redraw_win_later(wp, VALID);
2578 wlnum = diff_lnum_win(lnum, wp);
2579 if (wlnum > 0)
2580 changedOneline(wp->w_buffer, wlnum);
2581 }
2582 }
2583#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002584}
2585
2586 static void
Bram Moolenaardba8a912005-04-24 22:08:39 +00002587changedOneline(buf, lnum)
2588 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002589 linenr_T lnum;
2590{
Bram Moolenaardba8a912005-04-24 22:08:39 +00002591 if (buf->b_mod_set)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002592 {
2593 /* find the maximum area that must be redisplayed */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002594 if (lnum < buf->b_mod_top)
2595 buf->b_mod_top = lnum;
2596 else if (lnum >= buf->b_mod_bot)
2597 buf->b_mod_bot = lnum + 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002598 }
2599 else
2600 {
2601 /* set the area that must be redisplayed to one line */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002602 buf->b_mod_set = TRUE;
2603 buf->b_mod_top = lnum;
2604 buf->b_mod_bot = lnum + 1;
2605 buf->b_mod_xlines = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002606 }
2607}
2608
2609/*
2610 * Appended "count" lines below line "lnum" in the current buffer.
2611 * Must be called AFTER the change and after mark_adjust().
2612 * Takes care of marking the buffer to be redrawn and sets the changed flag.
2613 */
2614 void
2615appended_lines(lnum, count)
2616 linenr_T lnum;
2617 long count;
2618{
2619 changed_lines(lnum + 1, 0, lnum + 1, count);
2620}
2621
2622/*
2623 * Like appended_lines(), but adjust marks first.
2624 */
2625 void
2626appended_lines_mark(lnum, count)
2627 linenr_T lnum;
2628 long count;
2629{
2630 mark_adjust(lnum + 1, (linenr_T)MAXLNUM, count, 0L);
2631 changed_lines(lnum + 1, 0, lnum + 1, count);
2632}
2633
2634/*
2635 * Deleted "count" lines at line "lnum" in the current buffer.
2636 * Must be called AFTER the change and after mark_adjust().
2637 * Takes care of marking the buffer to be redrawn and sets the changed flag.
2638 */
2639 void
2640deleted_lines(lnum, count)
2641 linenr_T lnum;
2642 long count;
2643{
2644 changed_lines(lnum, 0, lnum + count, -count);
2645}
2646
2647/*
2648 * Like deleted_lines(), but adjust marks first.
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002649 * Make sure the cursor is on a valid line before calling, a GUI callback may
2650 * be triggered to display the cursor.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002651 */
2652 void
2653deleted_lines_mark(lnum, count)
2654 linenr_T lnum;
2655 long count;
2656{
2657 mark_adjust(lnum, (linenr_T)(lnum + count - 1), (long)MAXLNUM, -count);
2658 changed_lines(lnum, 0, lnum + count, -count);
2659}
2660
2661/*
2662 * Changed lines for the current buffer.
2663 * Must be called AFTER the change and after mark_adjust().
2664 * - mark the buffer changed by calling changed()
2665 * - mark the windows on this buffer to be redisplayed
2666 * - invalidate cached values
2667 * "lnum" is the first line that needs displaying, "lnume" the first line
2668 * below the changed lines (BEFORE the change).
2669 * When only inserting lines, "lnum" and "lnume" are equal.
2670 * Takes care of calling changed() and updating b_mod_*.
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002671 * Careful: may trigger autocommands that reload the buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002672 */
2673 void
2674changed_lines(lnum, col, lnume, xtra)
2675 linenr_T lnum; /* first line with change */
2676 colnr_T col; /* column in first line with change */
2677 linenr_T lnume; /* line below last changed line */
2678 long xtra; /* number of extra lines (negative when deleting) */
2679{
Bram Moolenaardba8a912005-04-24 22:08:39 +00002680 changed_lines_buf(curbuf, lnum, lnume, xtra);
2681
2682#ifdef FEAT_DIFF
2683 if (xtra == 0 && curwin->w_p_diff)
2684 {
2685 /* When the number of lines doesn't change then mark_adjust() isn't
2686 * called and other diff buffers still need to be marked for
2687 * displaying. */
2688 win_T *wp;
2689 linenr_T wlnum;
2690
2691 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2692 if (wp->w_p_diff && wp != curwin)
2693 {
2694 redraw_win_later(wp, VALID);
2695 wlnum = diff_lnum_win(lnum, wp);
2696 if (wlnum > 0)
2697 changed_lines_buf(wp->w_buffer, wlnum,
2698 lnume - lnum + wlnum, 0L);
2699 }
2700 }
2701#endif
2702
2703 changed_common(lnum, col, lnume, xtra);
2704}
2705
2706 static void
2707changed_lines_buf(buf, lnum, lnume, xtra)
2708 buf_T *buf;
2709 linenr_T lnum; /* first line with change */
2710 linenr_T lnume; /* line below last changed line */
2711 long xtra; /* number of extra lines (negative when deleting) */
2712{
2713 if (buf->b_mod_set)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002714 {
2715 /* find the maximum area that must be redisplayed */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002716 if (lnum < buf->b_mod_top)
2717 buf->b_mod_top = lnum;
2718 if (lnum < buf->b_mod_bot)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002719 {
2720 /* adjust old bot position for xtra lines */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002721 buf->b_mod_bot += xtra;
2722 if (buf->b_mod_bot < lnum)
2723 buf->b_mod_bot = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002724 }
Bram Moolenaardba8a912005-04-24 22:08:39 +00002725 if (lnume + xtra > buf->b_mod_bot)
2726 buf->b_mod_bot = lnume + xtra;
2727 buf->b_mod_xlines += xtra;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002728 }
2729 else
2730 {
2731 /* set the area that must be redisplayed */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002732 buf->b_mod_set = TRUE;
2733 buf->b_mod_top = lnum;
2734 buf->b_mod_bot = lnume + xtra;
2735 buf->b_mod_xlines = xtra;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002736 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002737}
2738
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002739/*
2740 * Common code for when a change is was made.
2741 * See changed_lines() for the arguments.
2742 * Careful: may trigger autocommands that reload the buffer.
2743 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002744 static void
2745changed_common(lnum, col, lnume, xtra)
2746 linenr_T lnum;
2747 colnr_T col;
2748 linenr_T lnume;
2749 long xtra;
2750{
2751 win_T *wp;
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00002752#ifdef FEAT_WINDOWS
2753 tabpage_T *tp;
2754#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002755 int i;
2756#ifdef FEAT_JUMPLIST
2757 int cols;
2758 pos_T *p;
2759 int add;
2760#endif
2761
2762 /* mark the buffer as modified */
2763 changed();
2764
2765 /* set the '. mark */
2766 if (!cmdmod.keepjumps)
2767 {
2768 curbuf->b_last_change.lnum = lnum;
2769 curbuf->b_last_change.col = col;
2770
2771#ifdef FEAT_JUMPLIST
2772 /* Create a new entry if a new undo-able change was started or we
2773 * don't have an entry yet. */
2774 if (curbuf->b_new_change || curbuf->b_changelistlen == 0)
2775 {
2776 if (curbuf->b_changelistlen == 0)
2777 add = TRUE;
2778 else
2779 {
2780 /* Don't create a new entry when the line number is the same
2781 * as the last one and the column is not too far away. Avoids
2782 * creating many entries for typing "xxxxx". */
2783 p = &curbuf->b_changelist[curbuf->b_changelistlen - 1];
2784 if (p->lnum != lnum)
2785 add = TRUE;
2786 else
2787 {
2788 cols = comp_textwidth(FALSE);
2789 if (cols == 0)
2790 cols = 79;
2791 add = (p->col + cols < col || col + cols < p->col);
2792 }
2793 }
2794 if (add)
2795 {
2796 /* This is the first of a new sequence of undo-able changes
2797 * and it's at some distance of the last change. Use a new
2798 * position in the changelist. */
2799 curbuf->b_new_change = FALSE;
2800
2801 if (curbuf->b_changelistlen == JUMPLISTSIZE)
2802 {
2803 /* changelist is full: remove oldest entry */
2804 curbuf->b_changelistlen = JUMPLISTSIZE - 1;
2805 mch_memmove(curbuf->b_changelist, curbuf->b_changelist + 1,
2806 sizeof(pos_T) * (JUMPLISTSIZE - 1));
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00002807 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002808 {
2809 /* Correct position in changelist for other windows on
2810 * this buffer. */
2811 if (wp->w_buffer == curbuf && wp->w_changelistidx > 0)
2812 --wp->w_changelistidx;
2813 }
2814 }
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00002815 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002816 {
2817 /* For other windows, if the position in the changelist is
2818 * at the end it stays at the end. */
2819 if (wp->w_buffer == curbuf
2820 && wp->w_changelistidx == curbuf->b_changelistlen)
2821 ++wp->w_changelistidx;
2822 }
2823 ++curbuf->b_changelistlen;
2824 }
2825 }
2826 curbuf->b_changelist[curbuf->b_changelistlen - 1] =
2827 curbuf->b_last_change;
2828 /* The current window is always after the last change, so that "g,"
2829 * takes you back to it. */
2830 curwin->w_changelistidx = curbuf->b_changelistlen;
2831#endif
2832 }
2833
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00002834 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002835 {
2836 if (wp->w_buffer == curbuf)
2837 {
2838 /* Mark this window to be redrawn later. */
2839 if (wp->w_redr_type < VALID)
2840 wp->w_redr_type = VALID;
2841
2842 /* Check if a change in the buffer has invalidated the cached
2843 * values for the cursor. */
2844#ifdef FEAT_FOLDING
2845 /*
2846 * Update the folds for this window. Can't postpone this, because
2847 * a following operator might work on the whole fold: ">>dd".
2848 */
2849 foldUpdate(wp, lnum, lnume + xtra - 1);
2850
2851 /* The change may cause lines above or below the change to become
2852 * included in a fold. Set lnum/lnume to the first/last line that
2853 * might be displayed differently.
2854 * Set w_cline_folded here as an efficient way to update it when
2855 * inserting lines just above a closed fold. */
2856 i = hasFoldingWin(wp, lnum, &lnum, NULL, FALSE, NULL);
2857 if (wp->w_cursor.lnum == lnum)
2858 wp->w_cline_folded = i;
2859 i = hasFoldingWin(wp, lnume, NULL, &lnume, FALSE, NULL);
2860 if (wp->w_cursor.lnum == lnume)
2861 wp->w_cline_folded = i;
2862
2863 /* If the changed line is in a range of previously folded lines,
2864 * compare with the first line in that range. */
2865 if (wp->w_cursor.lnum <= lnum)
2866 {
2867 i = find_wl_entry(wp, lnum);
2868 if (i >= 0 && wp->w_cursor.lnum > wp->w_lines[i].wl_lnum)
2869 changed_line_abv_curs_win(wp);
2870 }
2871#endif
2872
2873 if (wp->w_cursor.lnum > lnum)
2874 changed_line_abv_curs_win(wp);
2875 else if (wp->w_cursor.lnum == lnum && wp->w_cursor.col >= col)
2876 changed_cline_bef_curs_win(wp);
2877 if (wp->w_botline >= lnum)
2878 {
2879 /* Assume that botline doesn't change (inserted lines make
2880 * other lines scroll down below botline). */
2881 approximate_botline_win(wp);
2882 }
2883
2884 /* Check if any w_lines[] entries have become invalid.
2885 * For entries below the change: Correct the lnums for
2886 * inserted/deleted lines. Makes it possible to stop displaying
2887 * after the change. */
2888 for (i = 0; i < wp->w_lines_valid; ++i)
2889 if (wp->w_lines[i].wl_valid)
2890 {
2891 if (wp->w_lines[i].wl_lnum >= lnum)
2892 {
2893 if (wp->w_lines[i].wl_lnum < lnume)
2894 {
2895 /* line included in change */
2896 wp->w_lines[i].wl_valid = FALSE;
2897 }
2898 else if (xtra != 0)
2899 {
2900 /* line below change */
2901 wp->w_lines[i].wl_lnum += xtra;
2902#ifdef FEAT_FOLDING
2903 wp->w_lines[i].wl_lastlnum += xtra;
2904#endif
2905 }
2906 }
2907#ifdef FEAT_FOLDING
2908 else if (wp->w_lines[i].wl_lastlnum >= lnum)
2909 {
2910 /* change somewhere inside this range of folded lines,
2911 * may need to be redrawn */
2912 wp->w_lines[i].wl_valid = FALSE;
2913 }
2914#endif
2915 }
Bram Moolenaar3234cc62009-11-03 17:47:12 +00002916
2917#ifdef FEAT_FOLDING
2918 /* Take care of side effects for setting w_topline when folds have
2919 * changed. Esp. when the buffer was changed in another window. */
2920 if (hasAnyFolding(wp))
2921 set_topline(wp, wp->w_topline);
2922#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002923 }
2924 }
2925
2926 /* Call update_screen() later, which checks out what needs to be redrawn,
2927 * since it notices b_mod_set and then uses b_mod_*. */
2928 if (must_redraw < VALID)
2929 must_redraw = VALID;
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002930
2931#ifdef FEAT_AUTOCMD
2932 /* when the cursor line is changed always trigger CursorMoved */
Bram Moolenaare163f1c2006-10-17 09:12:21 +00002933 if (lnum <= curwin->w_cursor.lnum
2934 && lnume + (xtra < 0 ? -xtra : xtra) > curwin->w_cursor.lnum)
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002935 last_cursormoved.lnum = 0;
2936#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002937}
2938
2939/*
2940 * unchanged() is called when the changed flag must be reset for buffer 'buf'
2941 */
2942 void
2943unchanged(buf, ff)
2944 buf_T *buf;
2945 int ff; /* also reset 'fileformat' */
2946{
Bram Moolenaar164c60f2011-01-22 00:11:50 +01002947 if (buf->b_changed || (ff && file_ff_differs(buf, FALSE)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002948 {
2949 buf->b_changed = 0;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002950 ml_setflags(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002951 if (ff)
2952 save_file_ff(buf);
2953#ifdef FEAT_WINDOWS
2954 check_status(buf);
Bram Moolenaar997fb4b2006-02-17 21:53:23 +00002955 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002956#endif
2957#ifdef FEAT_TITLE
2958 need_maketitle = TRUE; /* set window title later */
2959#endif
2960 }
2961 ++buf->b_changedtick;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002962#ifdef FEAT_NETBEANS_INTG
2963 netbeans_unmodified(buf);
2964#endif
2965}
2966
2967#if defined(FEAT_WINDOWS) || defined(PROTO)
2968/*
2969 * check_status: called when the status bars for the buffer 'buf'
2970 * need to be updated
2971 */
2972 void
2973check_status(buf)
2974 buf_T *buf;
2975{
2976 win_T *wp;
2977
2978 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2979 if (wp->w_buffer == buf && wp->w_status_height)
2980 {
2981 wp->w_redr_status = TRUE;
2982 if (must_redraw < VALID)
2983 must_redraw = VALID;
2984 }
2985}
2986#endif
2987
2988/*
2989 * If the file is readonly, give a warning message with the first change.
2990 * Don't do this for autocommands.
2991 * Don't use emsg(), because it flushes the macro buffer.
Bram Moolenaard5cdbeb2005-10-10 20:59:28 +00002992 * If we have undone all changes b_changed will be FALSE, but "b_did_warn"
Bram Moolenaar071d4272004-06-13 20:20:40 +00002993 * will be TRUE.
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002994 * Careful: may trigger autocommands that reload the buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002995 */
2996 void
2997change_warning(col)
2998 int col; /* column for message; non-zero when in insert
2999 mode and 'showmode' is on */
3000{
Bram Moolenaar496c5262009-03-18 14:42:00 +00003001 static char *w_readonly = N_("W10: Warning: Changing a readonly file");
3002
Bram Moolenaar071d4272004-06-13 20:20:40 +00003003 if (curbuf->b_did_warn == FALSE
3004 && curbufIsChanged() == 0
3005#ifdef FEAT_AUTOCMD
3006 && !autocmd_busy
3007#endif
3008 && curbuf->b_p_ro)
3009 {
3010#ifdef FEAT_AUTOCMD
Bram Moolenaar910f66f2006-04-05 20:41:53 +00003011 ++curbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003012 apply_autocmds(EVENT_FILECHANGEDRO, NULL, NULL, FALSE, curbuf);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00003013 --curbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003014 if (!curbuf->b_p_ro)
3015 return;
3016#endif
3017 /*
3018 * Do what msg() does, but with a column offset if the warning should
3019 * be after the mode message.
3020 */
3021 msg_start();
3022 if (msg_row == Rows - 1)
3023 msg_col = col;
Bram Moolenaar2df6dcc2004-07-12 15:53:54 +00003024 msg_source(hl_attr(HLF_W));
Bram Moolenaar496c5262009-03-18 14:42:00 +00003025 MSG_PUTS_ATTR(_(w_readonly), hl_attr(HLF_W) | MSG_HIST);
3026#ifdef FEAT_EVAL
3027 set_vim_var_string(VV_WARNINGMSG, (char_u *)_(w_readonly), -1);
3028#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003029 msg_clr_eos();
3030 (void)msg_end();
3031 if (msg_silent == 0 && !silent_mode)
3032 {
3033 out_flush();
3034 ui_delay(1000L, TRUE); /* give the user time to think about it */
3035 }
3036 curbuf->b_did_warn = TRUE;
3037 redraw_cmdline = FALSE; /* don't redraw and erase the message */
3038 if (msg_row < Rows - 1)
3039 showmode();
3040 }
3041}
3042
3043/*
3044 * Ask for a reply from the user, a 'y' or a 'n'.
3045 * No other characters are accepted, the message is repeated until a valid
3046 * reply is entered or CTRL-C is hit.
3047 * If direct is TRUE, don't use vgetc() but ui_inchar(), don't get characters
3048 * from any buffers but directly from the user.
3049 *
3050 * return the 'y' or 'n'
3051 */
3052 int
3053ask_yesno(str, direct)
3054 char_u *str;
3055 int direct;
3056{
3057 int r = ' ';
3058 int save_State = State;
3059
3060 if (exiting) /* put terminal in raw mode for this question */
3061 settmode(TMODE_RAW);
3062 ++no_wait_return;
3063#ifdef USE_ON_FLY_SCROLL
3064 dont_scroll = TRUE; /* disallow scrolling here */
3065#endif
3066 State = CONFIRM; /* mouse behaves like with :confirm */
3067#ifdef FEAT_MOUSE
3068 setmouse(); /* disables mouse for xterm */
3069#endif
3070 ++no_mapping;
3071 ++allow_keys; /* no mapping here, but recognize keys */
3072
3073 while (r != 'y' && r != 'n')
3074 {
3075 /* same highlighting as for wait_return */
3076 smsg_attr(hl_attr(HLF_R), (char_u *)"%s (y/n)?", str);
3077 if (direct)
3078 r = get_keystroke();
3079 else
Bram Moolenaar913626c2008-01-03 11:43:42 +00003080 r = plain_vgetc();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003081 if (r == Ctrl_C || r == ESC)
3082 r = 'n';
3083 msg_putchar(r); /* show what you typed */
3084 out_flush();
3085 }
3086 --no_wait_return;
3087 State = save_State;
3088#ifdef FEAT_MOUSE
3089 setmouse();
3090#endif
3091 --no_mapping;
3092 --allow_keys;
3093
3094 return r;
3095}
3096
3097/*
3098 * Get a key stroke directly from the user.
3099 * Ignores mouse clicks and scrollbar events, except a click for the left
3100 * button (used at the more prompt).
3101 * Doesn't use vgetc(), because it syncs undo and eats mapped characters.
3102 * Disadvantage: typeahead is ignored.
3103 * Translates the interrupt character for unix to ESC.
3104 */
3105 int
3106get_keystroke()
3107{
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003108 char_u *buf = NULL;
3109 int buflen = 150;
3110 int maxlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003111 int len = 0;
3112 int n;
3113 int save_mapped_ctrl_c = mapped_ctrl_c;
Bram Moolenaar4395a712006-09-05 18:57:57 +00003114 int waited = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003115
3116 mapped_ctrl_c = FALSE; /* mappings are not used here */
3117 for (;;)
3118 {
3119 cursor_on();
3120 out_flush();
3121
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003122 /* Leave some room for check_termcode() to insert a key code into (max
3123 * 5 chars plus NUL). And fix_input_buffer() can triple the number of
3124 * bytes. */
3125 maxlen = (buflen - 6 - len) / 3;
3126 if (buf == NULL)
3127 buf = alloc(buflen);
3128 else if (maxlen < 10)
3129 {
3130 /* Need some more space. This migth happen when receiving a long
3131 * escape sequence. */
3132 buflen += 100;
3133 buf = vim_realloc(buf, buflen);
3134 maxlen = (buflen - 6 - len) / 3;
3135 }
3136 if (buf == NULL)
3137 {
3138 do_outofmem_msg((long_u)buflen);
3139 return ESC; /* panic! */
3140 }
3141
Bram Moolenaar071d4272004-06-13 20:20:40 +00003142 /* First time: blocking wait. Second time: wait up to 100ms for a
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003143 * terminal code to complete. */
3144 n = ui_inchar(buf + len, maxlen, len == 0 ? -1L : 100L, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003145 if (n > 0)
3146 {
3147 /* Replace zero and CSI by a special key code. */
3148 n = fix_input_buffer(buf + len, n, FALSE);
3149 len += n;
Bram Moolenaar4395a712006-09-05 18:57:57 +00003150 waited = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003151 }
Bram Moolenaar4395a712006-09-05 18:57:57 +00003152 else if (len > 0)
3153 ++waited; /* keep track of the waiting time */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003154
Bram Moolenaar4395a712006-09-05 18:57:57 +00003155 /* Incomplete termcode and not timed out yet: get more characters */
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003156 if ((n = check_termcode(1, buf, buflen, &len)) < 0
Bram Moolenaar4395a712006-09-05 18:57:57 +00003157 && (!p_ttimeout || waited * 100L < (p_ttm < 0 ? p_tm : p_ttm)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003158 continue;
Bram Moolenaar4395a712006-09-05 18:57:57 +00003159
Bram Moolenaar946ffd42010-12-30 12:30:31 +01003160 if (n == KEYLEN_REMOVED) /* key code removed */
Bram Moolenaar6eb634e2011-03-03 15:04:08 +01003161 {
Bram Moolenaarfd30cd42011-03-22 13:07:26 +01003162 if (must_redraw != 0 && !need_wait_return && (State & CMDLINE) == 0)
Bram Moolenaar6eb634e2011-03-03 15:04:08 +01003163 {
3164 /* Redrawing was postponed, do it now. */
3165 update_screen(0);
3166 setcursor(); /* put cursor back where it belongs */
3167 }
Bram Moolenaar946ffd42010-12-30 12:30:31 +01003168 continue;
Bram Moolenaar6eb634e2011-03-03 15:04:08 +01003169 }
Bram Moolenaar946ffd42010-12-30 12:30:31 +01003170 if (n > 0) /* found a termcode: adjust length */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003171 len = n;
Bram Moolenaar946ffd42010-12-30 12:30:31 +01003172 if (len == 0) /* nothing typed yet */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003173 continue;
3174
3175 /* Handle modifier and/or special key code. */
3176 n = buf[0];
3177 if (n == K_SPECIAL)
3178 {
3179 n = TO_SPECIAL(buf[1], buf[2]);
3180 if (buf[1] == KS_MODIFIER
3181 || n == K_IGNORE
3182#ifdef FEAT_MOUSE
3183 || n == K_LEFTMOUSE_NM
3184 || n == K_LEFTDRAG
3185 || n == K_LEFTRELEASE
3186 || n == K_LEFTRELEASE_NM
3187 || n == K_MIDDLEMOUSE
3188 || n == K_MIDDLEDRAG
3189 || n == K_MIDDLERELEASE
3190 || n == K_RIGHTMOUSE
3191 || n == K_RIGHTDRAG
3192 || n == K_RIGHTRELEASE
3193 || n == K_MOUSEDOWN
3194 || n == K_MOUSEUP
Bram Moolenaar8d9b40e2010-07-25 15:49:07 +02003195 || n == K_MOUSELEFT
3196 || n == K_MOUSERIGHT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003197 || n == K_X1MOUSE
3198 || n == K_X1DRAG
3199 || n == K_X1RELEASE
3200 || n == K_X2MOUSE
3201 || n == K_X2DRAG
3202 || n == K_X2RELEASE
3203# ifdef FEAT_GUI
3204 || n == K_VER_SCROLLBAR
3205 || n == K_HOR_SCROLLBAR
3206# endif
3207#endif
3208 )
3209 {
3210 if (buf[1] == KS_MODIFIER)
3211 mod_mask = buf[2];
3212 len -= 3;
3213 if (len > 0)
3214 mch_memmove(buf, buf + 3, (size_t)len);
3215 continue;
3216 }
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00003217 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003218 }
3219#ifdef FEAT_MBYTE
3220 if (has_mbyte)
3221 {
3222 if (MB_BYTE2LEN(n) > len)
3223 continue; /* more bytes to get */
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003224 buf[len >= buflen ? buflen - 1 : len] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003225 n = (*mb_ptr2char)(buf);
3226 }
3227#endif
3228#ifdef UNIX
3229 if (n == intr_char)
3230 n = ESC;
3231#endif
3232 break;
3233 }
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003234 vim_free(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003235
3236 mapped_ctrl_c = save_mapped_ctrl_c;
3237 return n;
3238}
3239
3240/*
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003241 * Get a number from the user.
3242 * When "mouse_used" is not NULL allow using the mouse.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003243 */
3244 int
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003245get_number(colon, mouse_used)
3246 int colon; /* allow colon to abort */
3247 int *mouse_used;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003248{
3249 int n = 0;
3250 int c;
Bram Moolenaar3991dab2006-03-27 17:01:56 +00003251 int typed = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003252
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003253 if (mouse_used != NULL)
3254 *mouse_used = FALSE;
3255
Bram Moolenaar071d4272004-06-13 20:20:40 +00003256 /* When not printing messages, the user won't know what to type, return a
3257 * zero (as if CR was hit). */
3258 if (msg_silent != 0)
3259 return 0;
3260
3261#ifdef USE_ON_FLY_SCROLL
3262 dont_scroll = TRUE; /* disallow scrolling here */
3263#endif
3264 ++no_mapping;
3265 ++allow_keys; /* no mapping here, but recognize keys */
3266 for (;;)
3267 {
3268 windgoto(msg_row, msg_col);
3269 c = safe_vgetc();
3270 if (VIM_ISDIGIT(c))
3271 {
3272 n = n * 10 + c - '0';
3273 msg_putchar(c);
Bram Moolenaar3991dab2006-03-27 17:01:56 +00003274 ++typed;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003275 }
3276 else if (c == K_DEL || c == K_KDEL || c == K_BS || c == Ctrl_H)
3277 {
Bram Moolenaar3991dab2006-03-27 17:01:56 +00003278 if (typed > 0)
3279 {
3280 MSG_PUTS("\b \b");
3281 --typed;
3282 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003283 n /= 10;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003284 }
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003285#ifdef FEAT_MOUSE
3286 else if (mouse_used != NULL && c == K_LEFTMOUSE)
3287 {
3288 *mouse_used = TRUE;
3289 n = mouse_row + 1;
3290 break;
3291 }
3292#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003293 else if (n == 0 && c == ':' && colon)
3294 {
3295 stuffcharReadbuff(':');
3296 if (!exmode_active)
3297 cmdline_row = msg_row;
3298 skip_redraw = TRUE; /* skip redraw once */
3299 do_redraw = FALSE;
3300 break;
3301 }
3302 else if (c == CAR || c == NL || c == Ctrl_C || c == ESC)
3303 break;
3304 }
3305 --no_mapping;
3306 --allow_keys;
3307 return n;
3308}
3309
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003310/*
3311 * Ask the user to enter a number.
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003312 * When "mouse_used" is not NULL allow using the mouse and in that case return
3313 * the line number.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003314 */
3315 int
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003316prompt_for_number(mouse_used)
3317 int *mouse_used;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003318{
3319 int i;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003320 int save_cmdline_row;
3321 int save_State;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003322
3323 /* When using ":silent" assume that <CR> was entered. */
Bram Moolenaar42eeac32005-06-29 22:40:58 +00003324 if (mouse_used != NULL)
Bram Moolenaard812df62008-11-09 12:46:09 +00003325 MSG_PUTS(_("Type number and <Enter> or click with mouse (empty cancels): "));
Bram Moolenaar42eeac32005-06-29 22:40:58 +00003326 else
Bram Moolenaard812df62008-11-09 12:46:09 +00003327 MSG_PUTS(_("Type number and <Enter> (empty cancels): "));
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003328
Bram Moolenaar203335e2006-09-03 14:35:42 +00003329 /* Set the state such that text can be selected/copied/pasted and we still
3330 * get mouse events. */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003331 save_cmdline_row = cmdline_row;
Bram Moolenaar203335e2006-09-03 14:35:42 +00003332 cmdline_row = 0;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003333 save_State = State;
Bram Moolenaar203335e2006-09-03 14:35:42 +00003334 State = CMDLINE;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003335
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003336 i = get_number(TRUE, mouse_used);
3337 if (KeyTyped)
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003338 {
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003339 /* don't call wait_return() now */
3340 /* msg_putchar('\n'); */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003341 cmdline_row = msg_row - 1;
3342 need_wait_return = FALSE;
3343 msg_didany = FALSE;
Bram Moolenaarb2450162009-07-22 09:04:20 +00003344 msg_didout = FALSE;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003345 }
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003346 else
3347 cmdline_row = save_cmdline_row;
3348 State = save_State;
3349
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003350 return i;
3351}
3352
Bram Moolenaar071d4272004-06-13 20:20:40 +00003353 void
3354msgmore(n)
3355 long n;
3356{
3357 long pn;
3358
3359 if (global_busy /* no messages now, wait until global is finished */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003360 || !messaging()) /* 'lazyredraw' set, don't do messages now */
3361 return;
3362
Bram Moolenaar7df2d662005-01-25 22:18:08 +00003363 /* We don't want to overwrite another important message, but do overwrite
3364 * a previous "more lines" or "fewer lines" message, so that "5dd" and
3365 * then "put" reports the last action. */
3366 if (keep_msg != NULL && !keep_msg_more)
3367 return;
3368
Bram Moolenaar071d4272004-06-13 20:20:40 +00003369 if (n > 0)
3370 pn = n;
3371 else
3372 pn = -n;
3373
3374 if (pn > p_report)
3375 {
3376 if (pn == 1)
3377 {
3378 if (n > 0)
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003379 vim_strncpy(msg_buf, (char_u *)_("1 more line"),
3380 MSG_BUF_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003381 else
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003382 vim_strncpy(msg_buf, (char_u *)_("1 line less"),
3383 MSG_BUF_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003384 }
3385 else
3386 {
3387 if (n > 0)
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003388 vim_snprintf((char *)msg_buf, MSG_BUF_LEN,
3389 _("%ld more lines"), pn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003390 else
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003391 vim_snprintf((char *)msg_buf, MSG_BUF_LEN,
3392 _("%ld fewer lines"), pn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003393 }
3394 if (got_int)
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003395 vim_strcat(msg_buf, (char_u *)_(" (Interrupted)"), MSG_BUF_LEN);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003396 if (msg(msg_buf))
3397 {
Bram Moolenaar238a5642006-02-21 22:12:05 +00003398 set_keep_msg(msg_buf, 0);
Bram Moolenaar7df2d662005-01-25 22:18:08 +00003399 keep_msg_more = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003400 }
3401 }
3402}
3403
3404/*
3405 * flush map and typeahead buffers and give a warning for an error
3406 */
3407 void
3408beep_flush()
3409{
3410 if (emsg_silent == 0)
3411 {
3412 flush_buffers(FALSE);
3413 vim_beep();
3414 }
3415}
3416
3417/*
3418 * give a warning for an error
3419 */
3420 void
3421vim_beep()
3422{
3423 if (emsg_silent == 0)
3424 {
3425 if (p_vb
3426#ifdef FEAT_GUI
3427 /* While the GUI is starting up the termcap is set for the GUI
3428 * but the output still goes to a terminal. */
3429 && !(gui.in_use && gui.starting)
3430#endif
3431 )
3432 {
3433 out_str(T_VB);
3434 }
3435 else
3436 {
3437#ifdef MSDOS
3438 /*
3439 * The number of beeps outputted is reduced to avoid having to wait
3440 * for all the beeps to finish. This is only a problem on systems
3441 * where the beeps don't overlap.
3442 */
3443 if (beep_count == 0 || beep_count == 10)
3444 {
3445 out_char(BELL);
3446 beep_count = 1;
3447 }
3448 else
3449 ++beep_count;
3450#else
3451 out_char(BELL);
3452#endif
3453 }
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003454
3455 /* When 'verbose' is set and we are sourcing a script or executing a
3456 * function give the user a hint where the beep comes from. */
3457 if (vim_strchr(p_debug, 'e') != NULL)
3458 {
3459 msg_source(hl_attr(HLF_W));
3460 msg_attr((char_u *)_("Beep!"), hl_attr(HLF_W));
3461 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003462 }
3463}
3464
3465/*
3466 * To get the "real" home directory:
3467 * - get value of $HOME
3468 * For Unix:
3469 * - go to that directory
3470 * - do mch_dirname() to get the real name of that directory.
3471 * This also works with mounts and links.
3472 * Don't do this for MS-DOS, it will change the "current dir" for a drive.
3473 */
3474static char_u *homedir = NULL;
3475
3476 void
3477init_homedir()
3478{
3479 char_u *var;
3480
Bram Moolenaar05159a02005-02-26 23:04:13 +00003481 /* In case we are called a second time (when 'encoding' changes). */
3482 vim_free(homedir);
3483 homedir = NULL;
3484
Bram Moolenaar071d4272004-06-13 20:20:40 +00003485#ifdef VMS
3486 var = mch_getenv((char_u *)"SYS$LOGIN");
3487#else
3488 var = mch_getenv((char_u *)"HOME");
3489#endif
3490
3491 if (var != NULL && *var == NUL) /* empty is same as not set */
3492 var = NULL;
3493
3494#ifdef WIN3264
3495 /*
3496 * Weird but true: $HOME may contain an indirect reference to another
3497 * variable, esp. "%USERPROFILE%". Happens when $USERPROFILE isn't set
3498 * when $HOME is being set.
3499 */
3500 if (var != NULL && *var == '%')
3501 {
3502 char_u *p;
3503 char_u *exp;
3504
3505 p = vim_strchr(var + 1, '%');
3506 if (p != NULL)
3507 {
Bram Moolenaarce0842a2005-07-18 21:58:11 +00003508 vim_strncpy(NameBuff, var + 1, p - (var + 1));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003509 exp = mch_getenv(NameBuff);
3510 if (exp != NULL && *exp != NUL
3511 && STRLEN(exp) + STRLEN(p) < MAXPATHL)
3512 {
Bram Moolenaar555b2802005-05-19 21:08:39 +00003513 vim_snprintf((char *)NameBuff, MAXPATHL, "%s%s", exp, p + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003514 var = NameBuff;
3515 /* Also set $HOME, it's needed for _viminfo. */
3516 vim_setenv((char_u *)"HOME", NameBuff);
3517 }
3518 }
3519 }
3520
3521 /*
3522 * Typically, $HOME is not defined on Windows, unless the user has
3523 * specifically defined it for Vim's sake. However, on Windows NT
3524 * platforms, $HOMEDRIVE and $HOMEPATH are automatically defined for
3525 * each user. Try constructing $HOME from these.
3526 */
3527 if (var == NULL)
3528 {
3529 char_u *homedrive, *homepath;
3530
3531 homedrive = mch_getenv((char_u *)"HOMEDRIVE");
3532 homepath = mch_getenv((char_u *)"HOMEPATH");
Bram Moolenaar6f977012010-01-06 17:53:38 +01003533 if (homepath == NULL || *homepath == NUL)
3534 homepath = "\\";
3535 if (homedrive != NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00003536 && STRLEN(homedrive) + STRLEN(homepath) < MAXPATHL)
3537 {
3538 sprintf((char *)NameBuff, "%s%s", homedrive, homepath);
3539 if (NameBuff[0] != NUL)
3540 {
3541 var = NameBuff;
3542 /* Also set $HOME, it's needed for _viminfo. */
3543 vim_setenv((char_u *)"HOME", NameBuff);
3544 }
3545 }
3546 }
Bram Moolenaar05159a02005-02-26 23:04:13 +00003547
3548# if defined(FEAT_MBYTE)
3549 if (enc_utf8 && var != NULL)
3550 {
3551 int len;
Bram Moolenaarb453a532011-04-28 17:48:44 +02003552 char_u *pp = NULL;
Bram Moolenaar05159a02005-02-26 23:04:13 +00003553
3554 /* Convert from active codepage to UTF-8. Other conversions are
3555 * not done, because they would fail for non-ASCII characters. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003556 acp_to_enc(var, (int)STRLEN(var), &pp, &len);
Bram Moolenaar05159a02005-02-26 23:04:13 +00003557 if (pp != NULL)
3558 {
3559 homedir = pp;
3560 return;
3561 }
3562 }
3563# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003564#endif
3565
3566#if defined(OS2) || defined(MSDOS) || defined(MSWIN)
3567 /*
3568 * Default home dir is C:/
3569 * Best assumption we can make in such a situation.
3570 */
3571 if (var == NULL)
3572 var = "C:/";
3573#endif
3574 if (var != NULL)
3575 {
3576#ifdef UNIX
3577 /*
3578 * Change to the directory and get the actual path. This resolves
3579 * links. Don't do it when we can't return.
3580 */
3581 if (mch_dirname(NameBuff, MAXPATHL) == OK
3582 && mch_chdir((char *)NameBuff) == 0)
3583 {
3584 if (!mch_chdir((char *)var) && mch_dirname(IObuff, IOSIZE) == OK)
3585 var = IObuff;
3586 if (mch_chdir((char *)NameBuff) != 0)
3587 EMSG(_(e_prev_dir));
3588 }
3589#endif
3590 homedir = vim_strsave(var);
3591 }
3592}
3593
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003594#if defined(EXITFREE) || defined(PROTO)
3595 void
3596free_homedir()
3597{
3598 vim_free(homedir);
3599}
3600#endif
3601
Bram Moolenaar071d4272004-06-13 20:20:40 +00003602/*
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003603 * Call expand_env() and store the result in an allocated string.
3604 * This is not very memory efficient, this expects the result to be freed
3605 * again soon.
3606 */
3607 char_u *
3608expand_env_save(src)
3609 char_u *src;
3610{
3611 return expand_env_save_opt(src, FALSE);
3612}
3613
3614/*
3615 * Idem, but when "one" is TRUE handle the string as one file name, only
3616 * expand "~" at the start.
3617 */
3618 char_u *
3619expand_env_save_opt(src, one)
3620 char_u *src;
3621 int one;
3622{
3623 char_u *p;
3624
3625 p = alloc(MAXPATHL);
3626 if (p != NULL)
3627 expand_env_esc(src, p, MAXPATHL, FALSE, one, NULL);
3628 return p;
3629}
3630
3631/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003632 * Expand environment variable with path name.
3633 * "~/" is also expanded, using $HOME. For Unix "~user/" is expanded.
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003634 * Skips over "\ ", "\~" and "\$" (not for Win32 though).
Bram Moolenaar071d4272004-06-13 20:20:40 +00003635 * If anything fails no expansion is done and dst equals src.
3636 */
3637 void
3638expand_env(src, dst, dstlen)
3639 char_u *src; /* input string e.g. "$HOME/vim.hlp" */
3640 char_u *dst; /* where to put the result */
3641 int dstlen; /* maximum length of the result */
3642{
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003643 expand_env_esc(src, dst, dstlen, FALSE, FALSE, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003644}
3645
3646 void
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003647expand_env_esc(srcp, dst, dstlen, esc, one, startstr)
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003648 char_u *srcp; /* input string e.g. "$HOME/vim.hlp" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003649 char_u *dst; /* where to put the result */
3650 int dstlen; /* maximum length of the result */
3651 int esc; /* escape spaces in expanded variables */
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003652 int one; /* "srcp" is one file name */
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003653 char_u *startstr; /* start again after this (can be NULL) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003654{
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003655 char_u *src;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003656 char_u *tail;
3657 int c;
3658 char_u *var;
3659 int copy_char;
3660 int mustfree; /* var was allocated, need to free it later */
3661 int at_start = TRUE; /* at start of a name */
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003662 int startstr_len = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003663
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003664 if (startstr != NULL)
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003665 startstr_len = (int)STRLEN(startstr);
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003666
3667 src = skipwhite(srcp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003668 --dstlen; /* leave one char space for "\," */
3669 while (*src && dstlen > 0)
3670 {
3671 copy_char = TRUE;
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003672 if ((*src == '$'
3673#ifdef VMS
3674 && at_start
3675#endif
3676 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003677#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3678 || *src == '%'
3679#endif
3680 || (*src == '~' && at_start))
3681 {
3682 mustfree = FALSE;
3683
3684 /*
3685 * The variable name is copied into dst temporarily, because it may
3686 * be a string in read-only memory and a NUL needs to be appended.
3687 */
3688 if (*src != '~') /* environment var */
3689 {
3690 tail = src + 1;
3691 var = dst;
3692 c = dstlen - 1;
3693
3694#ifdef UNIX
3695 /* Unix has ${var-name} type environment vars */
3696 if (*tail == '{' && !vim_isIDc('{'))
3697 {
3698 tail++; /* ignore '{' */
3699 while (c-- > 0 && *tail && *tail != '}')
3700 *var++ = *tail++;
3701 }
3702 else
3703#endif
3704 {
3705 while (c-- > 0 && *tail != NUL && ((vim_isIDc(*tail))
3706#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3707 || (*src == '%' && *tail != '%')
3708#endif
3709 ))
3710 {
3711#ifdef OS2 /* env vars only in uppercase */
3712 *var++ = TOUPPER_LOC(*tail);
3713 tail++; /* toupper() may be a macro! */
3714#else
3715 *var++ = *tail++;
3716#endif
3717 }
3718 }
3719
3720#if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
3721# ifdef UNIX
3722 if (src[1] == '{' && *tail != '}')
3723# else
3724 if (*src == '%' && *tail != '%')
3725# endif
3726 var = NULL;
3727 else
3728 {
3729# ifdef UNIX
3730 if (src[1] == '{')
3731# else
3732 if (*src == '%')
3733#endif
3734 ++tail;
3735#endif
3736 *var = NUL;
3737 var = vim_getenv(dst, &mustfree);
3738#if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
3739 }
3740#endif
3741 }
3742 /* home directory */
3743 else if ( src[1] == NUL
3744 || vim_ispathsep(src[1])
3745 || vim_strchr((char_u *)" ,\t\n", src[1]) != NULL)
3746 {
3747 var = homedir;
3748 tail = src + 1;
3749 }
3750 else /* user directory */
3751 {
3752#if defined(UNIX) || (defined(VMS) && defined(USER_HOME))
3753 /*
3754 * Copy ~user to dst[], so we can put a NUL after it.
3755 */
3756 tail = src;
3757 var = dst;
3758 c = dstlen - 1;
3759 while ( c-- > 0
3760 && *tail
3761 && vim_isfilec(*tail)
3762 && !vim_ispathsep(*tail))
3763 *var++ = *tail++;
3764 *var = NUL;
3765# ifdef UNIX
3766 /*
3767 * If the system supports getpwnam(), use it.
3768 * Otherwise, or if getpwnam() fails, the shell is used to
3769 * expand ~user. This is slower and may fail if the shell
3770 * does not support ~user (old versions of /bin/sh).
3771 */
3772# if defined(HAVE_GETPWNAM) && defined(HAVE_PWD_H)
3773 {
3774 struct passwd *pw;
3775
Bram Moolenaara40ceaf2006-01-13 22:35:40 +00003776 /* Note: memory allocated by getpwnam() is never freed.
3777 * Calling endpwent() apparently doesn't help. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003778 pw = getpwnam((char *)dst + 1);
3779 if (pw != NULL)
3780 var = (char_u *)pw->pw_dir;
3781 else
3782 var = NULL;
3783 }
3784 if (var == NULL)
3785# endif
3786 {
3787 expand_T xpc;
3788
3789 ExpandInit(&xpc);
3790 xpc.xp_context = EXPAND_FILES;
3791 var = ExpandOne(&xpc, dst, NULL,
3792 WILD_ADD_SLASH|WILD_SILENT, WILD_EXPAND_FREE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003793 mustfree = TRUE;
3794 }
3795
3796# else /* !UNIX, thus VMS */
3797 /*
3798 * USER_HOME is a comma-separated list of
3799 * directories to search for the user account in.
3800 */
3801 {
3802 char_u test[MAXPATHL], paths[MAXPATHL];
3803 char_u *path, *next_path, *ptr;
3804 struct stat st;
3805
3806 STRCPY(paths, USER_HOME);
3807 next_path = paths;
3808 while (*next_path)
3809 {
3810 for (path = next_path; *next_path && *next_path != ',';
3811 next_path++);
3812 if (*next_path)
3813 *next_path++ = NUL;
3814 STRCPY(test, path);
3815 STRCAT(test, "/");
3816 STRCAT(test, dst + 1);
3817 if (mch_stat(test, &st) == 0)
3818 {
3819 var = alloc(STRLEN(test) + 1);
3820 STRCPY(var, test);
3821 mustfree = TRUE;
3822 break;
3823 }
3824 }
3825 }
3826# endif /* UNIX */
3827#else
3828 /* cannot expand user's home directory, so don't try */
3829 var = NULL;
3830 tail = (char_u *)""; /* for gcc */
3831#endif /* UNIX || VMS */
3832 }
3833
3834#ifdef BACKSLASH_IN_FILENAME
3835 /* If 'shellslash' is set change backslashes to forward slashes.
3836 * Can't use slash_adjust(), p_ssl may be set temporarily. */
3837 if (p_ssl && var != NULL && vim_strchr(var, '\\') != NULL)
3838 {
3839 char_u *p = vim_strsave(var);
3840
3841 if (p != NULL)
3842 {
3843 if (mustfree)
3844 vim_free(var);
3845 var = p;
3846 mustfree = TRUE;
3847 forward_slash(var);
3848 }
3849 }
3850#endif
3851
3852 /* If "var" contains white space, escape it with a backslash.
3853 * Required for ":e ~/tt" when $HOME includes a space. */
3854 if (esc && var != NULL && vim_strpbrk(var, (char_u *)" \t") != NULL)
3855 {
3856 char_u *p = vim_strsave_escaped(var, (char_u *)" \t");
3857
3858 if (p != NULL)
3859 {
3860 if (mustfree)
3861 vim_free(var);
3862 var = p;
3863 mustfree = TRUE;
3864 }
3865 }
3866
3867 if (var != NULL && *var != NUL
3868 && (STRLEN(var) + STRLEN(tail) + 1 < (unsigned)dstlen))
3869 {
3870 STRCPY(dst, var);
3871 dstlen -= (int)STRLEN(var);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003872 c = (int)STRLEN(var);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003873 /* if var[] ends in a path separator and tail[] starts
3874 * with it, skip a character */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003875 if (*var != NUL && after_pathsep(dst, dst + c)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003876#if defined(BACKSLASH_IN_FILENAME) || defined(AMIGA)
3877 && dst[-1] != ':'
3878#endif
3879 && vim_ispathsep(*tail))
3880 ++tail;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003881 dst += c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003882 src = tail;
3883 copy_char = FALSE;
3884 }
3885 if (mustfree)
3886 vim_free(var);
3887 }
3888
3889 if (copy_char) /* copy at least one char */
3890 {
3891 /*
Bram Moolenaar25394022007-05-10 19:06:20 +00003892 * Recognize the start of a new name, for '~'.
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003893 * Don't do this when "one" is TRUE, to avoid expanding "~" in
3894 * ":edit foo ~ foo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00003895 */
3896 at_start = FALSE;
3897 if (src[0] == '\\' && src[1] != NUL)
3898 {
3899 *dst++ = *src++;
3900 --dstlen;
3901 }
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003902 else if ((src[0] == ' ' || src[0] == ',') && !one)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003903 at_start = TRUE;
3904 *dst++ = *src++;
3905 --dstlen;
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003906
3907 if (startstr != NULL && src - startstr_len >= srcp
3908 && STRNCMP(src - startstr_len, startstr, startstr_len) == 0)
3909 at_start = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003910 }
3911 }
3912 *dst = NUL;
3913}
3914
3915/*
3916 * Vim's version of getenv().
3917 * Special handling of $HOME, $VIM and $VIMRUNTIME.
Bram Moolenaar2f6b0b82005-03-08 22:43:10 +00003918 * Also does ACP to 'enc' conversion for Win32.
Bram Moolenaarb453a532011-04-28 17:48:44 +02003919 * "mustfree" is set to TRUE when returned is allocated, it must be
3920 * initialized to FALSE by the caller.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003921 */
3922 char_u *
3923vim_getenv(name, mustfree)
3924 char_u *name;
Bram Moolenaarb453a532011-04-28 17:48:44 +02003925 int *mustfree;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003926{
3927 char_u *p;
3928 char_u *pend;
3929 int vimruntime;
3930
3931#if defined(OS2) || defined(MSDOS) || defined(MSWIN)
3932 /* use "C:/" when $HOME is not set */
3933 if (STRCMP(name, "HOME") == 0)
3934 return homedir;
3935#endif
3936
3937 p = mch_getenv(name);
3938 if (p != NULL && *p == NUL) /* empty is the same as not set */
3939 p = NULL;
3940
3941 if (p != NULL)
Bram Moolenaar05159a02005-02-26 23:04:13 +00003942 {
3943#if defined(FEAT_MBYTE) && defined(WIN3264)
3944 if (enc_utf8)
3945 {
3946 int len;
Bram Moolenaarb453a532011-04-28 17:48:44 +02003947 char_u *pp = NULL;
Bram Moolenaar05159a02005-02-26 23:04:13 +00003948
3949 /* Convert from active codepage to UTF-8. Other conversions are
3950 * not done, because they would fail for non-ASCII characters. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003951 acp_to_enc(p, (int)STRLEN(p), &pp, &len);
Bram Moolenaar05159a02005-02-26 23:04:13 +00003952 if (pp != NULL)
3953 {
3954 p = pp;
3955 *mustfree = TRUE;
3956 }
3957 }
3958#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003959 return p;
Bram Moolenaar05159a02005-02-26 23:04:13 +00003960 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003961
3962 vimruntime = (STRCMP(name, "VIMRUNTIME") == 0);
3963 if (!vimruntime && STRCMP(name, "VIM") != 0)
3964 return NULL;
3965
3966 /*
3967 * When expanding $VIMRUNTIME fails, try using $VIM/vim<version> or $VIM.
3968 * Don't do this when default_vimruntime_dir is non-empty.
3969 */
3970 if (vimruntime
3971#ifdef HAVE_PATHDEF
3972 && *default_vimruntime_dir == NUL
3973#endif
3974 )
3975 {
3976 p = mch_getenv((char_u *)"VIM");
3977 if (p != NULL && *p == NUL) /* empty is the same as not set */
3978 p = NULL;
3979 if (p != NULL)
3980 {
3981 p = vim_version_dir(p);
3982 if (p != NULL)
3983 *mustfree = TRUE;
3984 else
3985 p = mch_getenv((char_u *)"VIM");
Bram Moolenaar05159a02005-02-26 23:04:13 +00003986
3987#if defined(FEAT_MBYTE) && defined(WIN3264)
3988 if (enc_utf8)
3989 {
3990 int len;
Bram Moolenaarb453a532011-04-28 17:48:44 +02003991 char_u *pp = NULL;
Bram Moolenaar05159a02005-02-26 23:04:13 +00003992
3993 /* Convert from active codepage to UTF-8. Other conversions
3994 * are not done, because they would fail for non-ASCII
3995 * characters. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003996 acp_to_enc(p, (int)STRLEN(p), &pp, &len);
Bram Moolenaar05159a02005-02-26 23:04:13 +00003997 if (pp != NULL)
3998 {
Bram Moolenaarb453a532011-04-28 17:48:44 +02003999 if (*mustfree)
Bram Moolenaar05159a02005-02-26 23:04:13 +00004000 vim_free(p);
4001 p = pp;
4002 *mustfree = TRUE;
4003 }
4004 }
4005#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004006 }
4007 }
4008
4009 /*
4010 * When expanding $VIM or $VIMRUNTIME fails, try using:
4011 * - the directory name from 'helpfile' (unless it contains '$')
4012 * - the executable name from argv[0]
4013 */
4014 if (p == NULL)
4015 {
4016 if (p_hf != NULL && vim_strchr(p_hf, '$') == NULL)
4017 p = p_hf;
4018#ifdef USE_EXE_NAME
4019 /*
4020 * Use the name of the executable, obtained from argv[0].
4021 */
4022 else
4023 p = exe_name;
4024#endif
4025 if (p != NULL)
4026 {
4027 /* remove the file name */
4028 pend = gettail(p);
4029
4030 /* remove "doc/" from 'helpfile', if present */
4031 if (p == p_hf)
4032 pend = remove_tail(p, pend, (char_u *)"doc");
4033
4034#ifdef USE_EXE_NAME
4035# ifdef MACOS_X
Bram Moolenaar95e9b492006-03-15 23:04:43 +00004036 /* remove "MacOS" from exe_name and add "Resources/vim" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004037 if (p == exe_name)
4038 {
4039 char_u *pend1;
Bram Moolenaar95e9b492006-03-15 23:04:43 +00004040 char_u *pnew;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004041
Bram Moolenaar95e9b492006-03-15 23:04:43 +00004042 pend1 = remove_tail(p, pend, (char_u *)"MacOS");
4043 if (pend1 != pend)
4044 {
4045 pnew = alloc((unsigned)(pend1 - p) + 15);
4046 if (pnew != NULL)
4047 {
4048 STRNCPY(pnew, p, (pend1 - p));
4049 STRCPY(pnew + (pend1 - p), "Resources/vim");
4050 p = pnew;
4051 pend = p + STRLEN(p);
4052 }
4053 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004054 }
4055# endif
4056 /* remove "src/" from exe_name, if present */
4057 if (p == exe_name)
4058 pend = remove_tail(p, pend, (char_u *)"src");
4059#endif
4060
4061 /* for $VIM, remove "runtime/" or "vim54/", if present */
4062 if (!vimruntime)
4063 {
4064 pend = remove_tail(p, pend, (char_u *)RUNTIME_DIRNAME);
4065 pend = remove_tail(p, pend, (char_u *)VIM_VERSION_NODOT);
4066 }
4067
4068 /* remove trailing path separator */
4069#ifndef MACOS_CLASSIC
4070 /* With MacOS path (with colons) the final colon is required */
Bram Moolenaare21877a2008-02-13 09:58:14 +00004071 /* to avoid confusion between absolute and relative path */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004072 if (pend > p && after_pathsep(p, pend))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004073 --pend;
4074#endif
4075
Bram Moolenaar95e9b492006-03-15 23:04:43 +00004076#ifdef MACOS_X
4077 if (p == exe_name || p == p_hf)
4078#endif
4079 /* check that the result is a directory name */
4080 p = vim_strnsave(p, (int)(pend - p));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004081
4082 if (p != NULL && !mch_isdir(p))
4083 {
4084 vim_free(p);
4085 p = NULL;
4086 }
4087 else
4088 {
4089#ifdef USE_EXE_NAME
4090 /* may add "/vim54" or "/runtime" if it exists */
4091 if (vimruntime && (pend = vim_version_dir(p)) != NULL)
4092 {
4093 vim_free(p);
4094 p = pend;
4095 }
4096#endif
4097 *mustfree = TRUE;
4098 }
4099 }
4100 }
4101
4102#ifdef HAVE_PATHDEF
4103 /* When there is a pathdef.c file we can use default_vim_dir and
4104 * default_vimruntime_dir */
4105 if (p == NULL)
4106 {
4107 /* Only use default_vimruntime_dir when it is not empty */
4108 if (vimruntime && *default_vimruntime_dir != NUL)
4109 {
4110 p = default_vimruntime_dir;
4111 *mustfree = FALSE;
4112 }
4113 else if (*default_vim_dir != NUL)
4114 {
4115 if (vimruntime && (p = vim_version_dir(default_vim_dir)) != NULL)
4116 *mustfree = TRUE;
4117 else
4118 {
4119 p = default_vim_dir;
4120 *mustfree = FALSE;
4121 }
4122 }
4123 }
4124#endif
4125
4126 /*
4127 * Set the environment variable, so that the new value can be found fast
4128 * next time, and others can also use it (e.g. Perl).
4129 */
4130 if (p != NULL)
4131 {
4132 if (vimruntime)
4133 {
4134 vim_setenv((char_u *)"VIMRUNTIME", p);
4135 didset_vimruntime = TRUE;
4136#ifdef FEAT_GETTEXT
4137 {
Bram Moolenaard6754642005-01-17 22:18:45 +00004138 char_u *buf = concat_str(p, (char_u *)"/lang");
Bram Moolenaar071d4272004-06-13 20:20:40 +00004139
4140 if (buf != NULL)
4141 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004142 bindtextdomain(VIMPACKAGE, (char *)buf);
4143 vim_free(buf);
4144 }
4145 }
4146#endif
4147 }
4148 else
4149 {
4150 vim_setenv((char_u *)"VIM", p);
4151 didset_vim = TRUE;
4152 }
4153 }
4154 return p;
4155}
4156
4157/*
4158 * Check if the directory "vimdir/<version>" or "vimdir/runtime" exists.
4159 * Return NULL if not, return its name in allocated memory otherwise.
4160 */
4161 static char_u *
4162vim_version_dir(vimdir)
4163 char_u *vimdir;
4164{
4165 char_u *p;
4166
4167 if (vimdir == NULL || *vimdir == NUL)
4168 return NULL;
4169 p = concat_fnames(vimdir, (char_u *)VIM_VERSION_NODOT, TRUE);
4170 if (p != NULL && mch_isdir(p))
4171 return p;
4172 vim_free(p);
4173 p = concat_fnames(vimdir, (char_u *)RUNTIME_DIRNAME, TRUE);
4174 if (p != NULL && mch_isdir(p))
4175 return p;
4176 vim_free(p);
4177 return NULL;
4178}
4179
4180/*
4181 * If the string between "p" and "pend" ends in "name/", return "pend" minus
4182 * the length of "name/". Otherwise return "pend".
4183 */
4184 static char_u *
4185remove_tail(p, pend, name)
4186 char_u *p;
4187 char_u *pend;
4188 char_u *name;
4189{
4190 int len = (int)STRLEN(name) + 1;
4191 char_u *newend = pend - len;
4192
4193 if (newend >= p
4194 && fnamencmp(newend, name, len - 1) == 0
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004195 && (newend == p || after_pathsep(p, newend)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004196 return newend;
4197 return pend;
4198}
4199
Bram Moolenaar071d4272004-06-13 20:20:40 +00004200/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004201 * Our portable version of setenv.
4202 */
4203 void
4204vim_setenv(name, val)
4205 char_u *name;
4206 char_u *val;
4207{
4208#ifdef HAVE_SETENV
4209 mch_setenv((char *)name, (char *)val, 1);
4210#else
4211 char_u *envbuf;
4212
4213 /*
4214 * Putenv does not copy the string, it has to remain
4215 * valid. The allocated memory will never be freed.
4216 */
4217 envbuf = alloc((unsigned)(STRLEN(name) + STRLEN(val) + 2));
4218 if (envbuf != NULL)
4219 {
4220 sprintf((char *)envbuf, "%s=%s", name, val);
4221 putenv((char *)envbuf);
4222 }
4223#endif
4224}
4225
4226#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
4227/*
4228 * Function given to ExpandGeneric() to obtain an environment variable name.
4229 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004230 char_u *
4231get_env_name(xp, idx)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00004232 expand_T *xp UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004233 int idx;
4234{
4235# if defined(AMIGA) || defined(__MRC__) || defined(__SC__)
4236 /*
4237 * No environ[] on the Amiga and on the Mac (using MPW).
4238 */
4239 return NULL;
4240# else
4241# ifndef __WIN32__
4242 /* Borland C++ 5.2 has this in a header file. */
4243 extern char **environ;
4244# endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00004245# define ENVNAMELEN 100
4246 static char_u name[ENVNAMELEN];
Bram Moolenaar071d4272004-06-13 20:20:40 +00004247 char_u *str;
4248 int n;
4249
4250 str = (char_u *)environ[idx];
4251 if (str == NULL)
4252 return NULL;
4253
Bram Moolenaar21cf8232004-07-16 20:18:37 +00004254 for (n = 0; n < ENVNAMELEN - 1; ++n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004255 {
4256 if (str[n] == '=' || str[n] == NUL)
4257 break;
4258 name[n] = str[n];
4259 }
4260 name[n] = NUL;
4261 return name;
4262# endif
4263}
4264#endif
4265
4266/*
4267 * Replace home directory by "~" in each space or comma separated file name in
4268 * 'src'.
4269 * If anything fails (except when out of space) dst equals src.
4270 */
4271 void
4272home_replace(buf, src, dst, dstlen, one)
4273 buf_T *buf; /* when not NULL, check for help files */
4274 char_u *src; /* input file name */
4275 char_u *dst; /* where to put the result */
4276 int dstlen; /* maximum length of the result */
4277 int one; /* if TRUE, only replace one file name, include
4278 spaces and commas in the file name. */
4279{
4280 size_t dirlen = 0, envlen = 0;
4281 size_t len;
4282 char_u *homedir_env;
4283 char_u *p;
4284
4285 if (src == NULL)
4286 {
4287 *dst = NUL;
4288 return;
4289 }
4290
4291 /*
4292 * If the file is a help file, remove the path completely.
4293 */
4294 if (buf != NULL && buf->b_help)
4295 {
4296 STRCPY(dst, gettail(src));
4297 return;
4298 }
4299
4300 /*
4301 * We check both the value of the $HOME environment variable and the
4302 * "real" home directory.
4303 */
4304 if (homedir != NULL)
4305 dirlen = STRLEN(homedir);
4306
4307#ifdef VMS
4308 homedir_env = mch_getenv((char_u *)"SYS$LOGIN");
4309#else
4310 homedir_env = mch_getenv((char_u *)"HOME");
4311#endif
4312
4313 if (homedir_env != NULL && *homedir_env == NUL)
4314 homedir_env = NULL;
4315 if (homedir_env != NULL)
4316 envlen = STRLEN(homedir_env);
4317
4318 if (!one)
4319 src = skipwhite(src);
4320 while (*src && dstlen > 0)
4321 {
4322 /*
4323 * Here we are at the beginning of a file name.
4324 * First, check to see if the beginning of the file name matches
4325 * $HOME or the "real" home directory. Check that there is a '/'
4326 * after the match (so that if e.g. the file is "/home/pieter/bla",
4327 * and the home directory is "/home/piet", the file does not end up
4328 * as "~er/bla" (which would seem to indicate the file "bla" in user
4329 * er's home directory)).
4330 */
4331 p = homedir;
4332 len = dirlen;
4333 for (;;)
4334 {
4335 if ( len
4336 && fnamencmp(src, p, len) == 0
4337 && (vim_ispathsep(src[len])
4338 || (!one && (src[len] == ',' || src[len] == ' '))
4339 || src[len] == NUL))
4340 {
4341 src += len;
4342 if (--dstlen > 0)
4343 *dst++ = '~';
4344
4345 /*
4346 * If it's just the home directory, add "/".
4347 */
4348 if (!vim_ispathsep(src[0]) && --dstlen > 0)
4349 *dst++ = '/';
4350 break;
4351 }
4352 if (p == homedir_env)
4353 break;
4354 p = homedir_env;
4355 len = envlen;
4356 }
4357
4358 /* if (!one) skip to separator: space or comma */
4359 while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
4360 *dst++ = *src++;
4361 /* skip separator */
4362 while ((*src == ' ' || *src == ',') && --dstlen > 0)
4363 *dst++ = *src++;
4364 }
4365 /* if (dstlen == 0) out of space, what to do??? */
4366
4367 *dst = NUL;
4368}
4369
4370/*
4371 * Like home_replace, store the replaced string in allocated memory.
4372 * When something fails, NULL is returned.
4373 */
4374 char_u *
4375home_replace_save(buf, src)
4376 buf_T *buf; /* when not NULL, check for help files */
4377 char_u *src; /* input file name */
4378{
4379 char_u *dst;
4380 unsigned len;
4381
4382 len = 3; /* space for "~/" and trailing NUL */
4383 if (src != NULL) /* just in case */
4384 len += (unsigned)STRLEN(src);
4385 dst = alloc(len);
4386 if (dst != NULL)
4387 home_replace(buf, src, dst, len, TRUE);
4388 return dst;
4389}
4390
4391/*
4392 * Compare two file names and return:
4393 * FPC_SAME if they both exist and are the same file.
4394 * FPC_SAMEX if they both don't exist and have the same file name.
4395 * FPC_DIFF if they both exist and are different files.
4396 * FPC_NOTX if they both don't exist.
4397 * FPC_DIFFX if one of them doesn't exist.
4398 * For the first name environment variables are expanded
4399 */
4400 int
4401fullpathcmp(s1, s2, checkname)
4402 char_u *s1, *s2;
4403 int checkname; /* when both don't exist, check file names */
4404{
4405#ifdef UNIX
4406 char_u exp1[MAXPATHL];
4407 char_u full1[MAXPATHL];
4408 char_u full2[MAXPATHL];
4409 struct stat st1, st2;
4410 int r1, r2;
4411
4412 expand_env(s1, exp1, MAXPATHL);
4413 r1 = mch_stat((char *)exp1, &st1);
4414 r2 = mch_stat((char *)s2, &st2);
4415 if (r1 != 0 && r2 != 0)
4416 {
4417 /* if mch_stat() doesn't work, may compare the names */
4418 if (checkname)
4419 {
4420 if (fnamecmp(exp1, s2) == 0)
4421 return FPC_SAMEX;
4422 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4423 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4424 if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
4425 return FPC_SAMEX;
4426 }
4427 return FPC_NOTX;
4428 }
4429 if (r1 != 0 || r2 != 0)
4430 return FPC_DIFFX;
4431 if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
4432 return FPC_SAME;
4433 return FPC_DIFF;
4434#else
4435 char_u *exp1; /* expanded s1 */
4436 char_u *full1; /* full path of s1 */
4437 char_u *full2; /* full path of s2 */
4438 int retval = FPC_DIFF;
4439 int r1, r2;
4440
4441 /* allocate one buffer to store three paths (alloc()/free() is slow!) */
4442 if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
4443 {
4444 full1 = exp1 + MAXPATHL;
4445 full2 = full1 + MAXPATHL;
4446
4447 expand_env(s1, exp1, MAXPATHL);
4448 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4449 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4450
4451 /* If vim_FullName() fails, the file probably doesn't exist. */
4452 if (r1 != OK && r2 != OK)
4453 {
4454 if (checkname && fnamecmp(exp1, s2) == 0)
4455 retval = FPC_SAMEX;
4456 else
4457 retval = FPC_NOTX;
4458 }
4459 else if (r1 != OK || r2 != OK)
4460 retval = FPC_DIFFX;
4461 else if (fnamecmp(full1, full2))
4462 retval = FPC_DIFF;
4463 else
4464 retval = FPC_SAME;
4465 vim_free(exp1);
4466 }
4467 return retval;
4468#endif
4469}
4470
4471/*
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004472 * Get the tail of a path: the file name.
Bram Moolenaar31710262010-08-13 13:36:15 +02004473 * When the path ends in a path separator the tail is the NUL after it.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004474 * Fail safe: never returns NULL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004475 */
4476 char_u *
4477gettail(fname)
4478 char_u *fname;
4479{
4480 char_u *p1, *p2;
4481
4482 if (fname == NULL)
4483 return (char_u *)"";
4484 for (p1 = p2 = fname; *p2; ) /* find last part of path */
4485 {
4486 if (vim_ispathsep(*p2))
4487 p1 = p2 + 1;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004488 mb_ptr_adv(p2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004489 }
4490 return p1;
4491}
4492
Bram Moolenaar31710262010-08-13 13:36:15 +02004493#if defined(FEAT_SEARCHPATH)
4494static char_u *gettail_dir __ARGS((char_u *fname));
4495
4496/*
4497 * Return the end of the directory name, on the first path
4498 * separator:
4499 * "/path/file", "/path/dir/", "/path//dir", "/file"
4500 * ^ ^ ^ ^
4501 */
4502 static char_u *
4503gettail_dir(fname)
4504 char_u *fname;
4505{
4506 char_u *dir_end = fname;
4507 char_u *next_dir_end = fname;
4508 int look_for_sep = TRUE;
4509 char_u *p;
4510
4511 for (p = fname; *p != NUL; )
4512 {
4513 if (vim_ispathsep(*p))
4514 {
4515 if (look_for_sep)
4516 {
4517 next_dir_end = p;
4518 look_for_sep = FALSE;
4519 }
4520 }
4521 else
4522 {
4523 if (!look_for_sep)
4524 dir_end = next_dir_end;
4525 look_for_sep = TRUE;
4526 }
4527 mb_ptr_adv(p);
4528 }
4529 return dir_end;
4530}
4531#endif
4532
Bram Moolenaar071d4272004-06-13 20:20:40 +00004533/*
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004534 * Get pointer to tail of "fname", including path separators. Putting a NUL
4535 * here leaves the directory name. Takes care of "c:/" and "//".
4536 * Always returns a valid pointer.
4537 */
4538 char_u *
4539gettail_sep(fname)
4540 char_u *fname;
4541{
4542 char_u *p;
4543 char_u *t;
4544
4545 p = get_past_head(fname); /* don't remove the '/' from "c:/file" */
4546 t = gettail(fname);
4547 while (t > p && after_pathsep(fname, t))
4548 --t;
4549#ifdef VMS
4550 /* path separator is part of the path */
4551 ++t;
4552#endif
4553 return t;
4554}
4555
4556/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004557 * get the next path component (just after the next path separator).
4558 */
4559 char_u *
4560getnextcomp(fname)
4561 char_u *fname;
4562{
4563 while (*fname && !vim_ispathsep(*fname))
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004564 mb_ptr_adv(fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004565 if (*fname)
4566 ++fname;
4567 return fname;
4568}
4569
Bram Moolenaar071d4272004-06-13 20:20:40 +00004570/*
4571 * Get a pointer to one character past the head of a path name.
4572 * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
4573 * If there is no head, path is returned.
4574 */
4575 char_u *
4576get_past_head(path)
4577 char_u *path;
4578{
4579 char_u *retval;
4580
4581#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
4582 /* may skip "c:" */
4583 if (isalpha(path[0]) && path[1] == ':')
4584 retval = path + 2;
4585 else
4586 retval = path;
4587#else
4588# if defined(AMIGA)
4589 /* may skip "label:" */
4590 retval = vim_strchr(path, ':');
4591 if (retval == NULL)
4592 retval = path;
4593# else /* Unix */
4594 retval = path;
4595# endif
4596#endif
4597
4598 while (vim_ispathsep(*retval))
4599 ++retval;
4600
4601 return retval;
4602}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004603
4604/*
4605 * return TRUE if 'c' is a path separator.
4606 */
4607 int
4608vim_ispathsep(c)
4609 int c;
4610{
Bram Moolenaare60acc12011-05-10 16:41:25 +02004611#ifdef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00004612 return (c == '/'); /* UNIX has ':' inside file names */
Bram Moolenaare60acc12011-05-10 16:41:25 +02004613#else
4614# ifdef BACKSLASH_IN_FILENAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00004615 return (c == ':' || c == '/' || c == '\\');
Bram Moolenaare60acc12011-05-10 16:41:25 +02004616# else
4617# ifdef VMS
Bram Moolenaar071d4272004-06-13 20:20:40 +00004618 /* server"user passwd"::device:[full.path.name]fname.extension;version" */
4619 return (c == ':' || c == '[' || c == ']' || c == '/'
4620 || c == '<' || c == '>' || c == '"' );
Bram Moolenaare60acc12011-05-10 16:41:25 +02004621# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004622 return (c == ':' || c == '/');
Bram Moolenaare60acc12011-05-10 16:41:25 +02004623# endif /* VMS */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004624# endif
Bram Moolenaare60acc12011-05-10 16:41:25 +02004625#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004626}
4627
4628#if defined(FEAT_SEARCHPATH) || defined(PROTO)
4629/*
4630 * return TRUE if 'c' is a path list separator.
4631 */
4632 int
4633vim_ispathlistsep(c)
4634 int c;
4635{
4636#ifdef UNIX
4637 return (c == ':');
4638#else
Bram Moolenaar25394022007-05-10 19:06:20 +00004639 return (c == ';'); /* might not be right for every system... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004640#endif
4641}
4642#endif
4643
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004644#if defined(FEAT_GUI_TABLINE) || defined(FEAT_WINDOWS) \
4645 || defined(FEAT_EVAL) || defined(PROTO)
4646/*
4647 * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
4648 * It's done in-place.
4649 */
4650 void
4651shorten_dir(str)
4652 char_u *str;
4653{
4654 char_u *tail, *s, *d;
4655 int skip = FALSE;
4656
4657 tail = gettail(str);
4658 d = str;
4659 for (s = str; ; ++s)
4660 {
4661 if (s >= tail) /* copy the whole tail */
4662 {
4663 *d++ = *s;
4664 if (*s == NUL)
4665 break;
4666 }
4667 else if (vim_ispathsep(*s)) /* copy '/' and next char */
4668 {
4669 *d++ = *s;
4670 skip = FALSE;
4671 }
4672 else if (!skip)
4673 {
4674 *d++ = *s; /* copy next char */
4675 if (*s != '~' && *s != '.') /* and leading "~" and "." */
4676 skip = TRUE;
4677# ifdef FEAT_MBYTE
4678 if (has_mbyte)
4679 {
4680 int l = mb_ptr2len(s);
4681
4682 while (--l > 0)
Bram Moolenaarb6baca52006-08-15 20:24:14 +00004683 *d++ = *++s;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004684 }
4685# endif
4686 }
4687 }
4688}
4689#endif
4690
Bram Moolenaar900b4d72005-12-12 22:05:50 +00004691/*
4692 * Return TRUE if the directory of "fname" exists, FALSE otherwise.
4693 * Also returns TRUE if there is no directory name.
4694 * "fname" must be writable!.
4695 */
4696 int
4697dir_of_file_exists(fname)
4698 char_u *fname;
4699{
4700 char_u *p;
4701 int c;
4702 int retval;
4703
4704 p = gettail_sep(fname);
4705 if (p == fname)
4706 return TRUE;
4707 c = *p;
4708 *p = NUL;
4709 retval = mch_isdir(fname);
4710 *p = c;
4711 return retval;
4712}
4713
Bram Moolenaar071d4272004-06-13 20:20:40 +00004714#if (defined(CASE_INSENSITIVE_FILENAME) && defined(BACKSLASH_IN_FILENAME)) \
4715 || defined(PROTO)
4716/*
4717 * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally.
4718 */
4719 int
4720vim_fnamecmp(x, y)
4721 char_u *x, *y;
4722{
4723 return vim_fnamencmp(x, y, MAXPATHL);
4724}
4725
4726 int
4727vim_fnamencmp(x, y, len)
4728 char_u *x, *y;
4729 size_t len;
4730{
4731 while (len > 0 && *x && *y)
4732 {
4733 if (TOLOWER_LOC(*x) != TOLOWER_LOC(*y)
4734 && !(*x == '/' && *y == '\\')
4735 && !(*x == '\\' && *y == '/'))
4736 break;
4737 ++x;
4738 ++y;
4739 --len;
4740 }
4741 if (len == 0)
4742 return 0;
4743 return (*x - *y);
4744}
4745#endif
4746
4747/*
4748 * Concatenate file names fname1 and fname2 into allocated memory.
Bram Moolenaar25394022007-05-10 19:06:20 +00004749 * Only add a '/' or '\\' when 'sep' is TRUE and it is necessary.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004750 */
4751 char_u *
4752concat_fnames(fname1, fname2, sep)
4753 char_u *fname1;
4754 char_u *fname2;
4755 int sep;
4756{
4757 char_u *dest;
4758
4759 dest = alloc((unsigned)(STRLEN(fname1) + STRLEN(fname2) + 3));
4760 if (dest != NULL)
4761 {
4762 STRCPY(dest, fname1);
4763 if (sep)
4764 add_pathsep(dest);
4765 STRCAT(dest, fname2);
4766 }
4767 return dest;
4768}
4769
Bram Moolenaard6754642005-01-17 22:18:45 +00004770/*
4771 * Concatenate two strings and return the result in allocated memory.
4772 * Returns NULL when out of memory.
4773 */
4774 char_u *
4775concat_str(str1, str2)
4776 char_u *str1;
4777 char_u *str2;
4778{
4779 char_u *dest;
4780 size_t l = STRLEN(str1);
4781
4782 dest = alloc((unsigned)(l + STRLEN(str2) + 1L));
4783 if (dest != NULL)
4784 {
4785 STRCPY(dest, str1);
4786 STRCPY(dest + l, str2);
4787 }
4788 return dest;
4789}
Bram Moolenaard6754642005-01-17 22:18:45 +00004790
Bram Moolenaar071d4272004-06-13 20:20:40 +00004791/*
4792 * Add a path separator to a file name, unless it already ends in a path
4793 * separator.
4794 */
4795 void
4796add_pathsep(p)
4797 char_u *p;
4798{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004799 if (*p != NUL && !after_pathsep(p, p + STRLEN(p)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004800 STRCAT(p, PATHSEPSTR);
4801}
4802
4803/*
4804 * FullName_save - Make an allocated copy of a full file name.
4805 * Returns NULL when out of memory.
4806 */
4807 char_u *
4808FullName_save(fname, force)
4809 char_u *fname;
4810 int force; /* force expansion, even when it already looks
4811 like a full path name */
4812{
4813 char_u *buf;
4814 char_u *new_fname = NULL;
4815
4816 if (fname == NULL)
4817 return NULL;
4818
4819 buf = alloc((unsigned)MAXPATHL);
4820 if (buf != NULL)
4821 {
4822 if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
4823 new_fname = vim_strsave(buf);
4824 else
4825 new_fname = vim_strsave(fname);
4826 vim_free(buf);
4827 }
4828 return new_fname;
4829}
4830
4831#if defined(FEAT_CINDENT) || defined(FEAT_SYN_HL)
4832
4833static char_u *skip_string __ARGS((char_u *p));
4834
4835/*
4836 * Find the start of a comment, not knowing if we are in a comment right now.
4837 * Search starts at w_cursor.lnum and goes backwards.
4838 */
4839 pos_T *
4840find_start_comment(ind_maxcomment) /* XXX */
4841 int ind_maxcomment;
4842{
4843 pos_T *pos;
4844 char_u *line;
4845 char_u *p;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00004846 int cur_maxcomment = ind_maxcomment;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004847
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00004848 for (;;)
4849 {
4850 pos = findmatchlimit(NULL, '*', FM_BACKWARD, cur_maxcomment);
4851 if (pos == NULL)
4852 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004853
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00004854 /*
4855 * Check if the comment start we found is inside a string.
4856 * If it is then restrict the search to below this line and try again.
4857 */
4858 line = ml_get(pos->lnum);
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00004859 for (p = line; *p && (colnr_T)(p - line) < pos->col; ++p)
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00004860 p = skip_string(p);
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00004861 if ((colnr_T)(p - line) <= pos->col)
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00004862 break;
4863 cur_maxcomment = curwin->w_cursor.lnum - pos->lnum - 1;
4864 if (cur_maxcomment <= 0)
4865 {
4866 pos = NULL;
4867 break;
4868 }
4869 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004870 return pos;
4871}
4872
4873/*
4874 * Skip to the end of a "string" and a 'c' character.
4875 * If there is no string or character, return argument unmodified.
4876 */
4877 static char_u *
4878skip_string(p)
4879 char_u *p;
4880{
4881 int i;
4882
4883 /*
4884 * We loop, because strings may be concatenated: "date""time".
4885 */
4886 for ( ; ; ++p)
4887 {
4888 if (p[0] == '\'') /* 'c' or '\n' or '\000' */
4889 {
4890 if (!p[1]) /* ' at end of line */
4891 break;
4892 i = 2;
4893 if (p[1] == '\\') /* '\n' or '\000' */
4894 {
4895 ++i;
4896 while (vim_isdigit(p[i - 1])) /* '\000' */
4897 ++i;
4898 }
4899 if (p[i] == '\'') /* check for trailing ' */
4900 {
4901 p += i;
4902 continue;
4903 }
4904 }
4905 else if (p[0] == '"') /* start of string */
4906 {
4907 for (++p; p[0]; ++p)
4908 {
4909 if (p[0] == '\\' && p[1] != NUL)
4910 ++p;
4911 else if (p[0] == '"') /* end of string */
4912 break;
4913 }
4914 if (p[0] == '"')
4915 continue;
4916 }
4917 break; /* no string found */
4918 }
4919 if (!*p)
4920 --p; /* backup from NUL */
4921 return p;
4922}
4923#endif /* FEAT_CINDENT || FEAT_SYN_HL */
4924
4925#if defined(FEAT_CINDENT) || defined(PROTO)
4926
4927/*
4928 * Do C or expression indenting on the current line.
4929 */
4930 void
4931do_c_expr_indent()
4932{
4933# ifdef FEAT_EVAL
4934 if (*curbuf->b_p_inde != NUL)
4935 fixthisline(get_expr_indent);
4936 else
4937# endif
4938 fixthisline(get_c_indent);
4939}
4940
4941/*
4942 * Functions for C-indenting.
4943 * Most of this originally comes from Eric Fischer.
4944 */
4945/*
4946 * Below "XXX" means that this function may unlock the current line.
4947 */
4948
4949static char_u *cin_skipcomment __ARGS((char_u *));
4950static int cin_nocode __ARGS((char_u *));
4951static pos_T *find_line_comment __ARGS((void));
4952static int cin_islabel_skip __ARGS((char_u **));
4953static int cin_isdefault __ARGS((char_u *));
4954static char_u *after_label __ARGS((char_u *l));
4955static int get_indent_nolabel __ARGS((linenr_T lnum));
4956static int skip_label __ARGS((linenr_T, char_u **pp, int ind_maxcomment));
4957static int cin_first_id_amount __ARGS((void));
4958static int cin_get_equal_amount __ARGS((linenr_T lnum));
4959static int cin_ispreproc __ARGS((char_u *));
4960static int cin_ispreproc_cont __ARGS((char_u **pp, linenr_T *lnump));
4961static int cin_iscomment __ARGS((char_u *));
4962static int cin_islinecomment __ARGS((char_u *));
4963static int cin_isterminated __ARGS((char_u *, int, int));
4964static int cin_isinit __ARGS((void));
Bram Moolenaarc367faa2011-12-14 20:21:35 +01004965static int cin_isfuncdecl __ARGS((char_u **, linenr_T, linenr_T, int, int));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004966static int cin_isif __ARGS((char_u *));
4967static int cin_iselse __ARGS((char_u *));
4968static int cin_isdo __ARGS((char_u *));
4969static int cin_iswhileofdo __ARGS((char_u *, linenr_T, int));
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00004970static int cin_iswhileofdo_end __ARGS((int terminated, int ind_maxparen, int ind_maxcomment));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004971static int cin_isbreak __ARGS((char_u *));
Bram Moolenaare7c56862007-08-04 10:14:52 +00004972static int cin_is_cpp_baseclass __ARGS((colnr_T *col));
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00004973static int get_baseclass_amount __ARGS((int col, int ind_maxparen, int ind_maxcomment, int ind_cpp_baseclass));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004974static int cin_ends_in __ARGS((char_u *, char_u *, char_u *));
4975static int cin_skip2pos __ARGS((pos_T *trypos));
4976static pos_T *find_start_brace __ARGS((int));
4977static pos_T *find_match_paren __ARGS((int, int));
4978static int corr_ind_maxparen __ARGS((int ind_maxparen, pos_T *startpos));
4979static int find_last_paren __ARGS((char_u *l, int start, int end));
4980static int find_match __ARGS((int lookfor, linenr_T ourscope, int ind_maxparen, int ind_maxcomment));
Bram Moolenaared38b0a2011-05-25 15:16:18 +02004981static int cin_is_cpp_namespace __ARGS((char_u *));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004982
Bram Moolenaar39353fd2007-03-27 09:02:11 +00004983static int ind_hash_comment = 0; /* # starts a comment */
4984
Bram Moolenaar071d4272004-06-13 20:20:40 +00004985/*
4986 * Skip over white space and C comments within the line.
Bram Moolenaar39353fd2007-03-27 09:02:11 +00004987 * Also skip over Perl/shell comments if desired.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004988 */
4989 static char_u *
4990cin_skipcomment(s)
4991 char_u *s;
4992{
4993 while (*s)
4994 {
Bram Moolenaar39353fd2007-03-27 09:02:11 +00004995 char_u *prev_s = s;
4996
Bram Moolenaar071d4272004-06-13 20:20:40 +00004997 s = skipwhite(s);
Bram Moolenaar39353fd2007-03-27 09:02:11 +00004998
4999 /* Perl/shell # comment comment continues until eol. Require a space
5000 * before # to avoid recognizing $#array. */
5001 if (ind_hash_comment != 0 && s != prev_s && *s == '#')
5002 {
5003 s += STRLEN(s);
5004 break;
5005 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005006 if (*s != '/')
5007 break;
5008 ++s;
5009 if (*s == '/') /* slash-slash comment continues till eol */
5010 {
5011 s += STRLEN(s);
5012 break;
5013 }
5014 if (*s != '*')
5015 break;
5016 for (++s; *s; ++s) /* skip slash-star comment */
5017 if (s[0] == '*' && s[1] == '/')
5018 {
5019 s += 2;
5020 break;
5021 }
5022 }
5023 return s;
5024}
5025
5026/*
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005027 * Return TRUE if there is no code at *s. White space and comments are
Bram Moolenaar071d4272004-06-13 20:20:40 +00005028 * not considered code.
5029 */
5030 static int
5031cin_nocode(s)
5032 char_u *s;
5033{
5034 return *cin_skipcomment(s) == NUL;
5035}
5036
5037/*
5038 * Check previous lines for a "//" line comment, skipping over blank lines.
5039 */
5040 static pos_T *
5041find_line_comment() /* XXX */
5042{
5043 static pos_T pos;
5044 char_u *line;
5045 char_u *p;
5046
5047 pos = curwin->w_cursor;
5048 while (--pos.lnum > 0)
5049 {
5050 line = ml_get(pos.lnum);
5051 p = skipwhite(line);
5052 if (cin_islinecomment(p))
5053 {
5054 pos.col = (int)(p - line);
5055 return &pos;
5056 }
5057 if (*p != NUL)
5058 break;
5059 }
5060 return NULL;
5061}
5062
5063/*
5064 * Check if string matches "label:"; move to character after ':' if true.
5065 */
5066 static int
5067cin_islabel_skip(s)
5068 char_u **s;
5069{
5070 if (!vim_isIDc(**s)) /* need at least one ID character */
5071 return FALSE;
5072
5073 while (vim_isIDc(**s))
5074 (*s)++;
5075
5076 *s = cin_skipcomment(*s);
5077
5078 /* "::" is not a label, it's C++ */
5079 return (**s == ':' && *++*s != ':');
5080}
5081
5082/*
5083 * Recognize a label: "label:".
5084 * Note: curwin->w_cursor must be where we are looking for the label.
5085 */
5086 int
5087cin_islabel(ind_maxcomment) /* XXX */
5088 int ind_maxcomment;
5089{
5090 char_u *s;
5091
5092 s = cin_skipcomment(ml_get_curline());
5093
5094 /*
5095 * Exclude "default" from labels, since it should be indented
5096 * like a switch label. Same for C++ scope declarations.
5097 */
5098 if (cin_isdefault(s))
5099 return FALSE;
5100 if (cin_isscopedecl(s))
5101 return FALSE;
5102
5103 if (cin_islabel_skip(&s))
5104 {
5105 /*
5106 * Only accept a label if the previous line is terminated or is a case
5107 * label.
5108 */
5109 pos_T cursor_save;
5110 pos_T *trypos;
5111 char_u *line;
5112
5113 cursor_save = curwin->w_cursor;
5114 while (curwin->w_cursor.lnum > 1)
5115 {
5116 --curwin->w_cursor.lnum;
5117
5118 /*
5119 * If we're in a comment now, skip to the start of the comment.
5120 */
5121 curwin->w_cursor.col = 0;
5122 if ((trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
5123 curwin->w_cursor = *trypos;
5124
5125 line = ml_get_curline();
5126 if (cin_ispreproc(line)) /* ignore #defines, #if, etc. */
5127 continue;
5128 if (*(line = cin_skipcomment(line)) == NUL)
5129 continue;
5130
5131 curwin->w_cursor = cursor_save;
5132 if (cin_isterminated(line, TRUE, FALSE)
5133 || cin_isscopedecl(line)
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005134 || cin_iscase(line, TRUE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005135 || (cin_islabel_skip(&line) && cin_nocode(line)))
5136 return TRUE;
5137 return FALSE;
5138 }
5139 curwin->w_cursor = cursor_save;
5140 return TRUE; /* label at start of file??? */
5141 }
5142 return FALSE;
5143}
5144
5145/*
5146 * Recognize structure initialization and enumerations.
5147 * Q&D-Implementation:
5148 * check for "=" at end or "[typedef] enum" at beginning of line.
5149 */
5150 static int
5151cin_isinit(void)
5152{
5153 char_u *s;
5154
5155 s = cin_skipcomment(ml_get_curline());
5156
5157 if (STRNCMP(s, "typedef", 7) == 0 && !vim_isIDc(s[7]))
5158 s = cin_skipcomment(s + 7);
5159
Bram Moolenaara5285652011-12-14 20:05:21 +01005160 if (STRNCMP(s, "static", 6) == 0 && !vim_isIDc(s[6]))
5161 s = cin_skipcomment(s + 6);
5162
Bram Moolenaar071d4272004-06-13 20:20:40 +00005163 if (STRNCMP(s, "enum", 4) == 0 && !vim_isIDc(s[4]))
5164 return TRUE;
5165
5166 if (cin_ends_in(s, (char_u *)"=", (char_u *)"{"))
5167 return TRUE;
5168
5169 return FALSE;
5170}
5171
5172/*
5173 * Recognize a switch label: "case .*:" or "default:".
5174 */
5175 int
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005176cin_iscase(s, strict)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005177 char_u *s;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005178 int strict; /* Allow relaxed check of case statement for JS */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005179{
5180 s = cin_skipcomment(s);
5181 if (STRNCMP(s, "case", 4) == 0 && !vim_isIDc(s[4]))
5182 {
5183 for (s += 4; *s; ++s)
5184 {
5185 s = cin_skipcomment(s);
5186 if (*s == ':')
5187 {
5188 if (s[1] == ':') /* skip over "::" for C++ */
5189 ++s;
5190 else
5191 return TRUE;
5192 }
5193 if (*s == '\'' && s[1] && s[2] == '\'')
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005194 s += 2; /* skip over ':' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005195 else if (*s == '/' && (s[1] == '*' || s[1] == '/'))
5196 return FALSE; /* stop at comment */
5197 else if (*s == '"')
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005198 {
5199 /* JS etc. */
5200 if (strict)
5201 return FALSE; /* stop at string */
5202 else
5203 return TRUE;
5204 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005205 }
5206 return FALSE;
5207 }
5208
5209 if (cin_isdefault(s))
5210 return TRUE;
5211 return FALSE;
5212}
5213
5214/*
5215 * Recognize a "default" switch label.
5216 */
5217 static int
5218cin_isdefault(s)
5219 char_u *s;
5220{
5221 return (STRNCMP(s, "default", 7) == 0
5222 && *(s = cin_skipcomment(s + 7)) == ':'
5223 && s[1] != ':');
5224}
5225
5226/*
Bram Moolenaar1a509df2010-08-01 17:59:57 +02005227 * Recognize a "public/private/protected" scope declaration label.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005228 */
5229 int
5230cin_isscopedecl(s)
5231 char_u *s;
5232{
5233 int i;
5234
5235 s = cin_skipcomment(s);
5236 if (STRNCMP(s, "public", 6) == 0)
5237 i = 6;
5238 else if (STRNCMP(s, "protected", 9) == 0)
5239 i = 9;
5240 else if (STRNCMP(s, "private", 7) == 0)
5241 i = 7;
5242 else
5243 return FALSE;
5244 return (*(s = cin_skipcomment(s + i)) == ':' && s[1] != ':');
5245}
5246
Bram Moolenaared38b0a2011-05-25 15:16:18 +02005247/* Maximum number of lines to search back for a "namespace" line. */
5248#define FIND_NAMESPACE_LIM 20
5249
5250/*
5251 * Recognize a "namespace" scope declaration.
5252 */
5253 static int
5254cin_is_cpp_namespace(s)
5255 char_u *s;
5256{
5257 char_u *p;
5258 int has_name = FALSE;
5259
5260 s = cin_skipcomment(s);
5261 if (STRNCMP(s, "namespace", 9) == 0 && (s[9] == NUL || !vim_iswordc(s[9])))
5262 {
5263 p = cin_skipcomment(skipwhite(s + 9));
5264 while (*p != NUL)
5265 {
5266 if (vim_iswhite(*p))
5267 {
5268 has_name = TRUE; /* found end of a name */
5269 p = cin_skipcomment(skipwhite(p));
5270 }
5271 else if (*p == '{')
5272 {
5273 break;
5274 }
5275 else if (vim_iswordc(*p))
5276 {
5277 if (has_name)
5278 return FALSE; /* word character after skipping past name */
5279 ++p;
5280 }
5281 else
5282 {
5283 return FALSE;
5284 }
5285 }
5286 return TRUE;
5287 }
5288 return FALSE;
5289}
5290
Bram Moolenaar071d4272004-06-13 20:20:40 +00005291/*
5292 * Return a pointer to the first non-empty non-comment character after a ':'.
5293 * Return NULL if not found.
5294 * case 234: a = b;
5295 * ^
5296 */
5297 static char_u *
5298after_label(l)
5299 char_u *l;
5300{
5301 for ( ; *l; ++l)
5302 {
5303 if (*l == ':')
5304 {
5305 if (l[1] == ':') /* skip over "::" for C++ */
5306 ++l;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005307 else if (!cin_iscase(l + 1, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005308 break;
5309 }
5310 else if (*l == '\'' && l[1] && l[2] == '\'')
5311 l += 2; /* skip over 'x' */
5312 }
5313 if (*l == NUL)
5314 return NULL;
5315 l = cin_skipcomment(l + 1);
5316 if (*l == NUL)
5317 return NULL;
5318 return l;
5319}
5320
5321/*
5322 * Get indent of line "lnum", skipping a label.
5323 * Return 0 if there is nothing after the label.
5324 */
5325 static int
5326get_indent_nolabel(lnum) /* XXX */
5327 linenr_T lnum;
5328{
5329 char_u *l;
5330 pos_T fp;
5331 colnr_T col;
5332 char_u *p;
5333
5334 l = ml_get(lnum);
5335 p = after_label(l);
5336 if (p == NULL)
5337 return 0;
5338
5339 fp.col = (colnr_T)(p - l);
5340 fp.lnum = lnum;
5341 getvcol(curwin, &fp, &col, NULL, NULL);
5342 return (int)col;
5343}
5344
5345/*
5346 * Find indent for line "lnum", ignoring any case or jump label.
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005347 * Also return a pointer to the text (after the label) in "pp".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005348 * label: if (asdf && asdfasdf)
5349 * ^
5350 */
5351 static int
5352skip_label(lnum, pp, ind_maxcomment)
5353 linenr_T lnum;
5354 char_u **pp;
5355 int ind_maxcomment;
5356{
5357 char_u *l;
5358 int amount;
5359 pos_T cursor_save;
5360
5361 cursor_save = curwin->w_cursor;
5362 curwin->w_cursor.lnum = lnum;
5363 l = ml_get_curline();
5364 /* XXX */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005365 if (cin_iscase(l, FALSE) || cin_isscopedecl(l)
5366 || cin_islabel(ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005367 {
5368 amount = get_indent_nolabel(lnum);
5369 l = after_label(ml_get_curline());
5370 if (l == NULL) /* just in case */
5371 l = ml_get_curline();
5372 }
5373 else
5374 {
5375 amount = get_indent();
5376 l = ml_get_curline();
5377 }
5378 *pp = l;
5379
5380 curwin->w_cursor = cursor_save;
5381 return amount;
5382}
5383
5384/*
5385 * Return the indent of the first variable name after a type in a declaration.
5386 * int a, indent of "a"
5387 * static struct foo b, indent of "b"
5388 * enum bla c, indent of "c"
5389 * Returns zero when it doesn't look like a declaration.
5390 */
5391 static int
5392cin_first_id_amount()
5393{
5394 char_u *line, *p, *s;
5395 int len;
5396 pos_T fp;
5397 colnr_T col;
5398
5399 line = ml_get_curline();
5400 p = skipwhite(line);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005401 len = (int)(skiptowhite(p) - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005402 if (len == 6 && STRNCMP(p, "static", 6) == 0)
5403 {
5404 p = skipwhite(p + 6);
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00005405 len = (int)(skiptowhite(p) - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005406 }
5407 if (len == 6 && STRNCMP(p, "struct", 6) == 0)
5408 p = skipwhite(p + 6);
5409 else if (len == 4 && STRNCMP(p, "enum", 4) == 0)
5410 p = skipwhite(p + 4);
5411 else if ((len == 8 && STRNCMP(p, "unsigned", 8) == 0)
5412 || (len == 6 && STRNCMP(p, "signed", 6) == 0))
5413 {
5414 s = skipwhite(p + len);
5415 if ((STRNCMP(s, "int", 3) == 0 && vim_iswhite(s[3]))
5416 || (STRNCMP(s, "long", 4) == 0 && vim_iswhite(s[4]))
5417 || (STRNCMP(s, "short", 5) == 0 && vim_iswhite(s[5]))
5418 || (STRNCMP(s, "char", 4) == 0 && vim_iswhite(s[4])))
5419 p = s;
5420 }
5421 for (len = 0; vim_isIDc(p[len]); ++len)
5422 ;
5423 if (len == 0 || !vim_iswhite(p[len]) || cin_nocode(p))
5424 return 0;
5425
5426 p = skipwhite(p + len);
5427 fp.lnum = curwin->w_cursor.lnum;
5428 fp.col = (colnr_T)(p - line);
5429 getvcol(curwin, &fp, &col, NULL, NULL);
5430 return (int)col;
5431}
5432
5433/*
5434 * Return the indent of the first non-blank after an equal sign.
5435 * char *foo = "here";
5436 * Return zero if no (useful) equal sign found.
5437 * Return -1 if the line above "lnum" ends in a backslash.
5438 * foo = "asdf\
5439 * asdf\
5440 * here";
5441 */
5442 static int
5443cin_get_equal_amount(lnum)
5444 linenr_T lnum;
5445{
5446 char_u *line;
5447 char_u *s;
5448 colnr_T col;
5449 pos_T fp;
5450
5451 if (lnum > 1)
5452 {
5453 line = ml_get(lnum - 1);
5454 if (*line != NUL && line[STRLEN(line) - 1] == '\\')
5455 return -1;
5456 }
5457
5458 line = s = ml_get(lnum);
5459 while (*s != NUL && vim_strchr((char_u *)"=;{}\"'", *s) == NULL)
5460 {
5461 if (cin_iscomment(s)) /* ignore comments */
5462 s = cin_skipcomment(s);
5463 else
5464 ++s;
5465 }
5466 if (*s != '=')
5467 return 0;
5468
5469 s = skipwhite(s + 1);
5470 if (cin_nocode(s))
5471 return 0;
5472
5473 if (*s == '"') /* nice alignment for continued strings */
5474 ++s;
5475
5476 fp.lnum = lnum;
5477 fp.col = (colnr_T)(s - line);
5478 getvcol(curwin, &fp, &col, NULL, NULL);
5479 return (int)col;
5480}
5481
5482/*
5483 * Recognize a preprocessor statement: Any line that starts with '#'.
5484 */
5485 static int
5486cin_ispreproc(s)
5487 char_u *s;
5488{
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005489 if (*skipwhite(s) == '#')
Bram Moolenaar071d4272004-06-13 20:20:40 +00005490 return TRUE;
5491 return FALSE;
5492}
5493
5494/*
5495 * Return TRUE if line "*pp" at "*lnump" is a preprocessor statement or a
5496 * continuation line of a preprocessor statement. Decrease "*lnump" to the
5497 * start and return the line in "*pp".
5498 */
5499 static int
5500cin_ispreproc_cont(pp, lnump)
5501 char_u **pp;
5502 linenr_T *lnump;
5503{
5504 char_u *line = *pp;
5505 linenr_T lnum = *lnump;
5506 int retval = FALSE;
5507
Bram Moolenaard8e9bb22005-07-09 21:14:46 +00005508 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005509 {
5510 if (cin_ispreproc(line))
5511 {
5512 retval = TRUE;
5513 *lnump = lnum;
5514 break;
5515 }
5516 if (lnum == 1)
5517 break;
5518 line = ml_get(--lnum);
5519 if (*line == NUL || line[STRLEN(line) - 1] != '\\')
5520 break;
5521 }
5522
5523 if (lnum != *lnump)
5524 *pp = ml_get(*lnump);
5525 return retval;
5526}
5527
5528/*
5529 * Recognize the start of a C or C++ comment.
5530 */
5531 static int
5532cin_iscomment(p)
5533 char_u *p;
5534{
5535 return (p[0] == '/' && (p[1] == '*' || p[1] == '/'));
5536}
5537
5538/*
5539 * Recognize the start of a "//" comment.
5540 */
5541 static int
5542cin_islinecomment(p)
5543 char_u *p;
5544{
5545 return (p[0] == '/' && p[1] == '/');
5546}
5547
5548/*
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005549 * Recognize a line that starts with '{' or '}', or ends with ';', ',', '{' or
5550 * '}'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005551 * Don't consider "} else" a terminated line.
Bram Moolenaar496f9512011-05-19 16:35:09 +02005552 * If a line begins with an "else", only consider it terminated if no unmatched
5553 * opening braces follow (handle "else { foo();" correctly).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005554 * Return the character terminating the line (ending char's have precedence if
5555 * both apply in order to determine initializations).
5556 */
5557 static int
5558cin_isterminated(s, incl_open, incl_comma)
5559 char_u *s;
5560 int incl_open; /* include '{' at the end as terminator */
5561 int incl_comma; /* recognize a trailing comma */
5562{
Bram Moolenaar496f9512011-05-19 16:35:09 +02005563 char_u found_start = 0;
5564 unsigned n_open = 0;
5565 int is_else = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005566
5567 s = cin_skipcomment(s);
5568
5569 if (*s == '{' || (*s == '}' && !cin_iselse(s)))
5570 found_start = *s;
5571
Bram Moolenaar496f9512011-05-19 16:35:09 +02005572 if (!found_start)
5573 is_else = cin_iselse(s);
5574
Bram Moolenaar071d4272004-06-13 20:20:40 +00005575 while (*s)
5576 {
5577 /* skip over comments, "" strings and 'c'haracters */
5578 s = skip_string(cin_skipcomment(s));
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005579 if (*s == '}' && n_open > 0)
5580 --n_open;
Bram Moolenaar496f9512011-05-19 16:35:09 +02005581 if ((!is_else || n_open == 0)
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005582 && (*s == ';' || *s == '}' || (incl_comma && *s == ','))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005583 && cin_nocode(s + 1))
5584 return *s;
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005585 else if (*s == '{')
5586 {
5587 if (incl_open && cin_nocode(s + 1))
5588 return *s;
5589 else
5590 ++n_open;
5591 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005592
5593 if (*s)
5594 s++;
5595 }
5596 return found_start;
5597}
5598
5599/*
5600 * Recognize the basic picture of a function declaration -- it needs to
5601 * have an open paren somewhere and a close paren at the end of the line and
5602 * no semicolons anywhere.
5603 * When a line ends in a comma we continue looking in the next line.
5604 * "sp" points to a string with the line. When looking at other lines it must
5605 * be restored to the line. When it's NULL fetch lines here.
5606 * "lnum" is where we start looking.
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005607 * "min_lnum" is the line before which we will not be looking.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005608 */
5609 static int
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005610cin_isfuncdecl(sp, first_lnum, min_lnum, ind_maxparen, ind_maxcomment)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005611 char_u **sp;
5612 linenr_T first_lnum;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005613 linenr_T min_lnum;
5614 int ind_maxparen;
5615 int ind_maxcomment;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005616{
5617 char_u *s;
5618 linenr_T lnum = first_lnum;
5619 int retval = FALSE;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005620 pos_T *trypos;
5621 int just_started = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005622
5623 if (sp == NULL)
5624 s = ml_get(lnum);
5625 else
5626 s = *sp;
5627
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005628 if (find_last_paren(s, '(', ')')
5629 && (trypos = find_match_paren(ind_maxparen, ind_maxcomment)) != NULL)
5630 {
5631 lnum = trypos->lnum;
5632 if (lnum < min_lnum)
5633 return FALSE;
5634
5635 s = ml_get(lnum);
5636 }
5637
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005638 /* Ignore line starting with #. */
5639 if (cin_ispreproc(s))
5640 return FALSE;
5641
Bram Moolenaar071d4272004-06-13 20:20:40 +00005642 while (*s && *s != '(' && *s != ';' && *s != '\'' && *s != '"')
5643 {
5644 if (cin_iscomment(s)) /* ignore comments */
5645 s = cin_skipcomment(s);
5646 else
5647 ++s;
5648 }
5649 if (*s != '(')
5650 return FALSE; /* ';', ' or " before any () or no '(' */
5651
5652 while (*s && *s != ';' && *s != '\'' && *s != '"')
5653 {
5654 if (*s == ')' && cin_nocode(s + 1))
5655 {
5656 /* ')' at the end: may have found a match
5657 * Check for he previous line not to end in a backslash:
5658 * #if defined(x) && \
5659 * defined(y)
5660 */
5661 lnum = first_lnum - 1;
5662 s = ml_get(lnum);
5663 if (*s == NUL || s[STRLEN(s) - 1] != '\\')
5664 retval = TRUE;
5665 goto done;
5666 }
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005667 if ((*s == ',' && cin_nocode(s + 1)) || s[1] == NUL || cin_nocode(s))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005668 {
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005669 int comma = (*s == ',');
5670
5671 /* ',' at the end: continue looking in the next line.
5672 * At the end: check for ',' in the next line, for this style:
5673 * func(arg1
5674 * , arg2) */
5675 for (;;)
5676 {
5677 if (lnum >= curbuf->b_ml.ml_line_count)
5678 break;
5679 s = ml_get(++lnum);
5680 if (!cin_ispreproc(s))
5681 break;
5682 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005683 if (lnum >= curbuf->b_ml.ml_line_count)
5684 break;
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005685 /* Require a comma at end of the line or a comma or ')' at the
5686 * start of next line. */
5687 s = skipwhite(s);
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005688 if (!just_started && (!comma && *s != ',' && *s != ')'))
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005689 break;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005690 just_started = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005691 }
5692 else if (cin_iscomment(s)) /* ignore comments */
5693 s = cin_skipcomment(s);
5694 else
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005695 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005696 ++s;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005697 just_started = FALSE;
5698 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005699 }
5700
5701done:
5702 if (lnum != first_lnum && sp != NULL)
5703 *sp = ml_get(first_lnum);
5704
5705 return retval;
5706}
5707
5708 static int
5709cin_isif(p)
5710 char_u *p;
5711{
5712 return (STRNCMP(p, "if", 2) == 0 && !vim_isIDc(p[2]));
5713}
5714
5715 static int
5716cin_iselse(p)
5717 char_u *p;
5718{
5719 if (*p == '}') /* accept "} else" */
5720 p = cin_skipcomment(p + 1);
5721 return (STRNCMP(p, "else", 4) == 0 && !vim_isIDc(p[4]));
5722}
5723
5724 static int
5725cin_isdo(p)
5726 char_u *p;
5727{
5728 return (STRNCMP(p, "do", 2) == 0 && !vim_isIDc(p[2]));
5729}
5730
5731/*
5732 * Check if this is a "while" that should have a matching "do".
5733 * We only accept a "while (condition) ;", with only white space between the
5734 * ')' and ';'. The condition may be spread over several lines.
5735 */
5736 static int
5737cin_iswhileofdo(p, lnum, ind_maxparen) /* XXX */
5738 char_u *p;
5739 linenr_T lnum;
5740 int ind_maxparen;
5741{
5742 pos_T cursor_save;
5743 pos_T *trypos;
5744 int retval = FALSE;
5745
5746 p = cin_skipcomment(p);
5747 if (*p == '}') /* accept "} while (cond);" */
5748 p = cin_skipcomment(p + 1);
5749 if (STRNCMP(p, "while", 5) == 0 && !vim_isIDc(p[5]))
5750 {
5751 cursor_save = curwin->w_cursor;
5752 curwin->w_cursor.lnum = lnum;
5753 curwin->w_cursor.col = 0;
5754 p = ml_get_curline();
5755 while (*p && *p != 'w') /* skip any '}', until the 'w' of the "while" */
5756 {
5757 ++p;
5758 ++curwin->w_cursor.col;
5759 }
5760 if ((trypos = findmatchlimit(NULL, 0, 0, ind_maxparen)) != NULL
5761 && *cin_skipcomment(ml_get_pos(trypos) + 1) == ';')
5762 retval = TRUE;
5763 curwin->w_cursor = cursor_save;
5764 }
5765 return retval;
5766}
5767
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005768/*
5769 * Return TRUE if we are at the end of a do-while.
5770 * do
5771 * nothing;
5772 * while (foo
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00005773 * && bar); <-- here
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005774 * Adjust the cursor to the line with "while".
5775 */
5776 static int
5777cin_iswhileofdo_end(terminated, ind_maxparen, ind_maxcomment)
5778 int terminated;
5779 int ind_maxparen;
5780 int ind_maxcomment;
5781{
5782 char_u *line;
5783 char_u *p;
5784 char_u *s;
5785 pos_T *trypos;
5786 int i;
5787
5788 if (terminated != ';') /* there must be a ';' at the end */
5789 return FALSE;
5790
5791 p = line = ml_get_curline();
5792 while (*p != NUL)
5793 {
5794 p = cin_skipcomment(p);
5795 if (*p == ')')
5796 {
5797 s = skipwhite(p + 1);
5798 if (*s == ';' && cin_nocode(s + 1))
5799 {
5800 /* Found ");" at end of the line, now check there is "while"
5801 * before the matching '('. XXX */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005802 i = (int)(p - line);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005803 curwin->w_cursor.col = i;
5804 trypos = find_match_paren(ind_maxparen, ind_maxcomment);
5805 if (trypos != NULL)
5806 {
5807 s = cin_skipcomment(ml_get(trypos->lnum));
5808 if (*s == '}') /* accept "} while (cond);" */
5809 s = cin_skipcomment(s + 1);
5810 if (STRNCMP(s, "while", 5) == 0 && !vim_isIDc(s[5]))
5811 {
5812 curwin->w_cursor.lnum = trypos->lnum;
5813 return TRUE;
5814 }
5815 }
5816
5817 /* Searching may have made "line" invalid, get it again. */
5818 line = ml_get_curline();
5819 p = line + i;
5820 }
5821 }
5822 if (*p != NUL)
5823 ++p;
5824 }
5825 return FALSE;
5826}
5827
Bram Moolenaar071d4272004-06-13 20:20:40 +00005828 static int
5829cin_isbreak(p)
5830 char_u *p;
5831{
5832 return (STRNCMP(p, "break", 5) == 0 && !vim_isIDc(p[5]));
5833}
5834
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005835/*
5836 * Find the position of a C++ base-class declaration or
Bram Moolenaar071d4272004-06-13 20:20:40 +00005837 * constructor-initialization. eg:
5838 *
5839 * class MyClass :
5840 * baseClass <-- here
5841 * class MyClass : public baseClass,
5842 * anotherBaseClass <-- here (should probably lineup ??)
5843 * MyClass::MyClass(...) :
5844 * baseClass(...) <-- here (constructor-initialization)
Bram Moolenaar18144c82006-04-12 21:52:12 +00005845 *
5846 * This is a lot of guessing. Watch out for "cond ? func() : foo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005847 */
5848 static int
Bram Moolenaare7c56862007-08-04 10:14:52 +00005849cin_is_cpp_baseclass(col)
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005850 colnr_T *col; /* return: column to align with */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005851{
5852 char_u *s;
5853 int class_or_struct, lookfor_ctor_init, cpp_base_class;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005854 linenr_T lnum = curwin->w_cursor.lnum;
Bram Moolenaare7c56862007-08-04 10:14:52 +00005855 char_u *line = ml_get_curline();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005856
5857 *col = 0;
5858
Bram Moolenaar21cf8232004-07-16 20:18:37 +00005859 s = skipwhite(line);
5860 if (*s == '#') /* skip #define FOO x ? (x) : x */
5861 return FALSE;
5862 s = cin_skipcomment(s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005863 if (*s == NUL)
5864 return FALSE;
5865
5866 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
5867
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005868 /* Search for a line starting with '#', empty, ending in ';' or containing
5869 * '{' or '}' and start below it. This handles the following situations:
5870 * a = cond ?
5871 * func() :
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00005872 * asdf;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005873 * func::foo()
5874 * : something
5875 * {}
5876 * Foo::Foo (int one, int two)
5877 * : something(4),
5878 * somethingelse(3)
5879 * {}
5880 */
5881 while (lnum > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005882 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00005883 line = ml_get(lnum - 1);
5884 s = skipwhite(line);
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005885 if (*s == '#' || *s == NUL)
5886 break;
5887 while (*s != NUL)
5888 {
5889 s = cin_skipcomment(s);
5890 if (*s == '{' || *s == '}'
5891 || (*s == ';' && cin_nocode(s + 1)))
5892 break;
5893 if (*s != NUL)
5894 ++s;
5895 }
5896 if (*s != NUL)
5897 break;
5898 --lnum;
5899 }
5900
Bram Moolenaare7c56862007-08-04 10:14:52 +00005901 line = ml_get(lnum);
5902 s = cin_skipcomment(line);
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005903 for (;;)
5904 {
5905 if (*s == NUL)
5906 {
5907 if (lnum == curwin->w_cursor.lnum)
5908 break;
5909 /* Continue in the cursor line. */
Bram Moolenaare7c56862007-08-04 10:14:52 +00005910 line = ml_get(++lnum);
5911 s = cin_skipcomment(line);
5912 if (*s == NUL)
5913 continue;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005914 }
5915
Bram Moolenaaraede6ce2011-05-10 11:56:30 +02005916 if (s[0] == '"')
5917 s = skip_string(s) + 1;
5918 else if (s[0] == ':')
Bram Moolenaar071d4272004-06-13 20:20:40 +00005919 {
5920 if (s[1] == ':')
5921 {
5922 /* skip double colon. It can't be a constructor
5923 * initialization any more */
5924 lookfor_ctor_init = FALSE;
5925 s = cin_skipcomment(s + 2);
5926 }
5927 else if (lookfor_ctor_init || class_or_struct)
5928 {
5929 /* we have something found, that looks like the start of
Bram Moolenaare21877a2008-02-13 09:58:14 +00005930 * cpp-base-class-declaration or constructor-initialization */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005931 cpp_base_class = TRUE;
5932 lookfor_ctor_init = class_or_struct = FALSE;
5933 *col = 0;
5934 s = cin_skipcomment(s + 1);
5935 }
5936 else
5937 s = cin_skipcomment(s + 1);
5938 }
5939 else if ((STRNCMP(s, "class", 5) == 0 && !vim_isIDc(s[5]))
5940 || (STRNCMP(s, "struct", 6) == 0 && !vim_isIDc(s[6])))
5941 {
5942 class_or_struct = TRUE;
5943 lookfor_ctor_init = FALSE;
5944
5945 if (*s == 'c')
5946 s = cin_skipcomment(s + 5);
5947 else
5948 s = cin_skipcomment(s + 6);
5949 }
5950 else
5951 {
5952 if (s[0] == '{' || s[0] == '}' || s[0] == ';')
5953 {
5954 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
5955 }
5956 else if (s[0] == ')')
5957 {
5958 /* Constructor-initialization is assumed if we come across
5959 * something like "):" */
5960 class_or_struct = FALSE;
5961 lookfor_ctor_init = TRUE;
5962 }
Bram Moolenaar18144c82006-04-12 21:52:12 +00005963 else if (s[0] == '?')
5964 {
5965 /* Avoid seeing '() :' after '?' as constructor init. */
5966 return FALSE;
5967 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005968 else if (!vim_isIDc(s[0]))
5969 {
5970 /* if it is not an identifier, we are wrong */
5971 class_or_struct = FALSE;
5972 lookfor_ctor_init = FALSE;
5973 }
5974 else if (*col == 0)
5975 {
5976 /* it can't be a constructor-initialization any more */
5977 lookfor_ctor_init = FALSE;
5978
5979 /* the first statement starts here: lineup with this one... */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005980 if (cpp_base_class)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005981 *col = (colnr_T)(s - line);
5982 }
5983
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005984 /* When the line ends in a comma don't align with it. */
5985 if (lnum == curwin->w_cursor.lnum && *s == ',' && cin_nocode(s + 1))
5986 *col = 0;
5987
Bram Moolenaar071d4272004-06-13 20:20:40 +00005988 s = cin_skipcomment(s + 1);
5989 }
5990 }
5991
5992 return cpp_base_class;
5993}
5994
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005995 static int
5996get_baseclass_amount(col, ind_maxparen, ind_maxcomment, ind_cpp_baseclass)
5997 int col;
5998 int ind_maxparen;
5999 int ind_maxcomment;
6000 int ind_cpp_baseclass;
6001{
6002 int amount;
6003 colnr_T vcol;
6004 pos_T *trypos;
6005
6006 if (col == 0)
6007 {
6008 amount = get_indent();
6009 if (find_last_paren(ml_get_curline(), '(', ')')
6010 && (trypos = find_match_paren(ind_maxparen,
6011 ind_maxcomment)) != NULL)
6012 amount = get_indent_lnum(trypos->lnum); /* XXX */
6013 if (!cin_ends_in(ml_get_curline(), (char_u *)",", NULL))
6014 amount += ind_cpp_baseclass;
6015 }
6016 else
6017 {
6018 curwin->w_cursor.col = col;
6019 getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
6020 amount = (int)vcol;
6021 }
6022 if (amount < ind_cpp_baseclass)
6023 amount = ind_cpp_baseclass;
6024 return amount;
6025}
6026
Bram Moolenaar071d4272004-06-13 20:20:40 +00006027/*
6028 * Return TRUE if string "s" ends with the string "find", possibly followed by
6029 * white space and comments. Skip strings and comments.
6030 * Ignore "ignore" after "find" if it's not NULL.
6031 */
6032 static int
6033cin_ends_in(s, find, ignore)
6034 char_u *s;
6035 char_u *find;
6036 char_u *ignore;
6037{
6038 char_u *p = s;
6039 char_u *r;
6040 int len = (int)STRLEN(find);
6041
6042 while (*p != NUL)
6043 {
6044 p = cin_skipcomment(p);
6045 if (STRNCMP(p, find, len) == 0)
6046 {
6047 r = skipwhite(p + len);
6048 if (ignore != NULL && STRNCMP(r, ignore, STRLEN(ignore)) == 0)
6049 r = skipwhite(r + STRLEN(ignore));
6050 if (cin_nocode(r))
6051 return TRUE;
6052 }
6053 if (*p != NUL)
6054 ++p;
6055 }
6056 return FALSE;
6057}
6058
6059/*
6060 * Skip strings, chars and comments until at or past "trypos".
6061 * Return the column found.
6062 */
6063 static int
6064cin_skip2pos(trypos)
6065 pos_T *trypos;
6066{
6067 char_u *line;
6068 char_u *p;
6069
6070 p = line = ml_get(trypos->lnum);
6071 while (*p && (colnr_T)(p - line) < trypos->col)
6072 {
6073 if (cin_iscomment(p))
6074 p = cin_skipcomment(p);
6075 else
6076 {
6077 p = skip_string(p);
6078 ++p;
6079 }
6080 }
6081 return (int)(p - line);
6082}
6083
6084/*
6085 * Find the '{' at the start of the block we are in.
6086 * Return NULL if no match found.
6087 * Ignore a '{' that is in a comment, makes indenting the next three lines
6088 * work. */
6089/* foo() */
6090/* { */
6091/* } */
6092
6093 static pos_T *
6094find_start_brace(ind_maxcomment) /* XXX */
6095 int ind_maxcomment;
6096{
6097 pos_T cursor_save;
6098 pos_T *trypos;
6099 pos_T *pos;
6100 static pos_T pos_copy;
6101
6102 cursor_save = curwin->w_cursor;
6103 while ((trypos = findmatchlimit(NULL, '{', FM_BLOCKSTOP, 0)) != NULL)
6104 {
6105 pos_copy = *trypos; /* copy pos_T, next findmatch will change it */
6106 trypos = &pos_copy;
6107 curwin->w_cursor = *trypos;
6108 pos = NULL;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006109 /* ignore the { if it's in a // or / * * / comment */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006110 if ((colnr_T)cin_skip2pos(trypos) == trypos->col
6111 && (pos = find_start_comment(ind_maxcomment)) == NULL) /* XXX */
6112 break;
6113 if (pos != NULL)
6114 curwin->w_cursor.lnum = pos->lnum;
6115 }
6116 curwin->w_cursor = cursor_save;
6117 return trypos;
6118}
6119
6120/*
6121 * Find the matching '(', failing if it is in a comment.
6122 * Return NULL of no match found.
6123 */
6124 static pos_T *
6125find_match_paren(ind_maxparen, ind_maxcomment) /* XXX */
6126 int ind_maxparen;
6127 int ind_maxcomment;
6128{
6129 pos_T cursor_save;
6130 pos_T *trypos;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006131 static pos_T pos_copy;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006132
6133 cursor_save = curwin->w_cursor;
6134 if ((trypos = findmatchlimit(NULL, '(', 0, ind_maxparen)) != NULL)
6135 {
6136 /* check if the ( is in a // comment */
6137 if ((colnr_T)cin_skip2pos(trypos) > trypos->col)
6138 trypos = NULL;
6139 else
6140 {
6141 pos_copy = *trypos; /* copy trypos, findmatch will change it */
6142 trypos = &pos_copy;
6143 curwin->w_cursor = *trypos;
6144 if (find_start_comment(ind_maxcomment) != NULL) /* XXX */
6145 trypos = NULL;
6146 }
6147 }
6148 curwin->w_cursor = cursor_save;
6149 return trypos;
6150}
6151
6152/*
6153 * Return ind_maxparen corrected for the difference in line number between the
6154 * cursor position and "startpos". This makes sure that searching for a
6155 * matching paren above the cursor line doesn't find a match because of
6156 * looking a few lines further.
6157 */
6158 static int
6159corr_ind_maxparen(ind_maxparen, startpos)
6160 int ind_maxparen;
6161 pos_T *startpos;
6162{
6163 long n = (long)startpos->lnum - (long)curwin->w_cursor.lnum;
6164
6165 if (n > 0 && n < ind_maxparen / 2)
6166 return ind_maxparen - (int)n;
6167 return ind_maxparen;
6168}
6169
6170/*
6171 * Set w_cursor.col to the column number of the last unmatched ')' or '{' in
Bram Moolenaar6d8f9c62011-11-30 13:03:28 +01006172 * line "l". "l" must point to the start of the line.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006173 */
6174 static int
6175find_last_paren(l, start, end)
6176 char_u *l;
6177 int start, end;
6178{
6179 int i;
6180 int retval = FALSE;
6181 int open_count = 0;
6182
6183 curwin->w_cursor.col = 0; /* default is start of line */
6184
Bram Moolenaar6d8f9c62011-11-30 13:03:28 +01006185 for (i = 0; l[i] != NUL; i++)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006186 {
6187 i = (int)(cin_skipcomment(l + i) - l); /* ignore parens in comments */
6188 i = (int)(skip_string(l + i) - l); /* ignore parens in quotes */
6189 if (l[i] == start)
6190 ++open_count;
6191 else if (l[i] == end)
6192 {
6193 if (open_count > 0)
6194 --open_count;
6195 else
6196 {
6197 curwin->w_cursor.col = i;
6198 retval = TRUE;
6199 }
6200 }
6201 }
6202 return retval;
6203}
6204
6205 int
6206get_c_indent()
6207{
6208 /*
6209 * spaces from a block's opening brace the prevailing indent for that
6210 * block should be
6211 */
6212 int ind_level = curbuf->b_p_sw;
6213
6214 /*
6215 * spaces from the edge of the line an open brace that's at the end of a
6216 * line is imagined to be.
6217 */
6218 int ind_open_imag = 0;
6219
6220 /*
Bram Moolenaar1a509df2010-08-01 17:59:57 +02006221 * spaces from the prevailing indent for a line that is not preceded by
Bram Moolenaar071d4272004-06-13 20:20:40 +00006222 * an opening brace.
6223 */
6224 int ind_no_brace = 0;
6225
6226 /*
6227 * column where the first { of a function should be located }
6228 */
6229 int ind_first_open = 0;
6230
6231 /*
6232 * spaces from the prevailing indent a leftmost open brace should be
6233 * located
6234 */
6235 int ind_open_extra = 0;
6236
6237 /*
6238 * spaces from the matching open brace (real location for one at the left
6239 * edge; imaginary location from one that ends a line) the matching close
6240 * brace should be located
6241 */
6242 int ind_close_extra = 0;
6243
6244 /*
6245 * spaces from the edge of the line an open brace sitting in the leftmost
6246 * column is imagined to be
6247 */
6248 int ind_open_left_imag = 0;
6249
6250 /*
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006251 * Spaces jump labels should be shifted to the left if N is non-negative,
6252 * otherwise the jump label will be put to column 1.
6253 */
6254 int ind_jump_label = -1;
6255
6256 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006257 * spaces from the switch() indent a "case xx" label should be located
6258 */
6259 int ind_case = curbuf->b_p_sw;
6260
6261 /*
6262 * spaces from the "case xx:" code after a switch() should be located
6263 */
6264 int ind_case_code = curbuf->b_p_sw;
6265
6266 /*
6267 * lineup break at end of case in switch() with case label
6268 */
6269 int ind_case_break = 0;
6270
6271 /*
6272 * spaces from the class declaration indent a scope declaration label
6273 * should be located
6274 */
6275 int ind_scopedecl = curbuf->b_p_sw;
6276
6277 /*
6278 * spaces from the scope declaration label code should be located
6279 */
6280 int ind_scopedecl_code = curbuf->b_p_sw;
6281
6282 /*
6283 * amount K&R-style parameters should be indented
6284 */
6285 int ind_param = curbuf->b_p_sw;
6286
6287 /*
6288 * amount a function type spec should be indented
6289 */
6290 int ind_func_type = curbuf->b_p_sw;
6291
6292 /*
6293 * amount a cpp base class declaration or constructor initialization
6294 * should be indented
6295 */
6296 int ind_cpp_baseclass = curbuf->b_p_sw;
6297
6298 /*
6299 * additional spaces beyond the prevailing indent a continuation line
6300 * should be located
6301 */
6302 int ind_continuation = curbuf->b_p_sw;
6303
6304 /*
6305 * spaces from the indent of the line with an unclosed parentheses
6306 */
6307 int ind_unclosed = curbuf->b_p_sw * 2;
6308
6309 /*
6310 * spaces from the indent of the line with an unclosed parentheses, which
6311 * itself is also unclosed
6312 */
6313 int ind_unclosed2 = curbuf->b_p_sw;
6314
6315 /*
6316 * suppress ignoring spaces from the indent of a line starting with an
6317 * unclosed parentheses.
6318 */
6319 int ind_unclosed_noignore = 0;
6320
6321 /*
6322 * If the opening paren is the last nonwhite character on the line, and
6323 * ind_unclosed_wrapped is nonzero, use this indent relative to the outer
6324 * context (for very long lines).
6325 */
6326 int ind_unclosed_wrapped = 0;
6327
6328 /*
6329 * suppress ignoring white space when lining up with the character after
6330 * an unclosed parentheses.
6331 */
6332 int ind_unclosed_whiteok = 0;
6333
6334 /*
6335 * indent a closing parentheses under the line start of the matching
6336 * opening parentheses.
6337 */
6338 int ind_matching_paren = 0;
6339
6340 /*
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006341 * indent a closing parentheses under the previous line.
6342 */
6343 int ind_paren_prev = 0;
6344
6345 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006346 * Extra indent for comments.
6347 */
6348 int ind_comment = 0;
6349
6350 /*
6351 * spaces from the comment opener when there is nothing after it.
6352 */
6353 int ind_in_comment = 3;
6354
6355 /*
6356 * boolean: if non-zero, use ind_in_comment even if there is something
6357 * after the comment opener.
6358 */
6359 int ind_in_comment2 = 0;
6360
6361 /*
6362 * max lines to search for an open paren
6363 */
6364 int ind_maxparen = 20;
6365
6366 /*
6367 * max lines to search for an open comment
6368 */
6369 int ind_maxcomment = 70;
6370
6371 /*
6372 * handle braces for java code
6373 */
6374 int ind_java = 0;
6375
6376 /*
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006377 * not to confuse JS object properties with labels
6378 */
6379 int ind_js = 0;
6380
6381 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006382 * handle blocked cases correctly
6383 */
6384 int ind_keep_case_label = 0;
6385
Bram Moolenaared38b0a2011-05-25 15:16:18 +02006386 /*
6387 * handle C++ namespace
6388 */
6389 int ind_cpp_namespace = 0;
6390
Bram Moolenaar071d4272004-06-13 20:20:40 +00006391 pos_T cur_curpos;
6392 int amount;
6393 int scope_amount;
Bram Moolenaarb21e5842006-04-16 18:30:08 +00006394 int cur_amount = MAXCOL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006395 colnr_T col;
6396 char_u *theline;
6397 char_u *linecopy;
6398 pos_T *trypos;
6399 pos_T *tryposBrace = NULL;
6400 pos_T our_paren_pos;
6401 char_u *start;
6402 int start_brace;
Bram Moolenaare21877a2008-02-13 09:58:14 +00006403#define BRACE_IN_COL0 1 /* '{' is in column 0 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006404#define BRACE_AT_START 2 /* '{' is at start of line */
6405#define BRACE_AT_END 3 /* '{' is at end of line */
6406 linenr_T ourscope;
6407 char_u *l;
6408 char_u *look;
6409 char_u terminated;
6410 int lookfor;
6411#define LOOKFOR_INITIAL 0
6412#define LOOKFOR_IF 1
6413#define LOOKFOR_DO 2
6414#define LOOKFOR_CASE 3
6415#define LOOKFOR_ANY 4
6416#define LOOKFOR_TERM 5
6417#define LOOKFOR_UNTERM 6
6418#define LOOKFOR_SCOPEDECL 7
6419#define LOOKFOR_NOBREAK 8
6420#define LOOKFOR_CPP_BASECLASS 9
6421#define LOOKFOR_ENUM_OR_INIT 10
6422
6423 int whilelevel;
6424 linenr_T lnum;
6425 char_u *options;
6426 int fraction = 0; /* init for GCC */
6427 int divider;
6428 int n;
6429 int iscase;
6430 int lookfor_break;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02006431 int lookfor_cpp_namespace = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006432 int cont_amount = 0; /* amount for continuation line */
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006433 int original_line_islabel;
Bram Moolenaare79d1532011-10-04 18:03:47 +02006434 int added_to_amount = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006435
6436 for (options = curbuf->b_p_cino; *options; )
6437 {
6438 l = options++;
6439 if (*options == '-')
6440 ++options;
6441 n = getdigits(&options);
6442 divider = 0;
6443 if (*options == '.') /* ".5s" means a fraction */
6444 {
6445 fraction = atol((char *)++options);
6446 while (VIM_ISDIGIT(*options))
6447 {
6448 ++options;
6449 if (divider)
6450 divider *= 10;
6451 else
6452 divider = 10;
6453 }
6454 }
6455 if (*options == 's') /* "2s" means two times 'shiftwidth' */
6456 {
6457 if (n == 0 && fraction == 0)
6458 n = curbuf->b_p_sw; /* just "s" is one 'shiftwidth' */
6459 else
6460 {
6461 n *= curbuf->b_p_sw;
6462 if (divider)
6463 n += (curbuf->b_p_sw * fraction + divider / 2) / divider;
6464 }
6465 ++options;
6466 }
6467 if (l[1] == '-')
6468 n = -n;
6469 /* When adding an entry here, also update the default 'cinoptions' in
Bram Moolenaar39353fd2007-03-27 09:02:11 +00006470 * doc/indent.txt, and add explanation for it! */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006471 switch (*l)
6472 {
6473 case '>': ind_level = n; break;
6474 case 'e': ind_open_imag = n; break;
6475 case 'n': ind_no_brace = n; break;
6476 case 'f': ind_first_open = n; break;
6477 case '{': ind_open_extra = n; break;
6478 case '}': ind_close_extra = n; break;
6479 case '^': ind_open_left_imag = n; break;
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006480 case 'L': ind_jump_label = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006481 case ':': ind_case = n; break;
6482 case '=': ind_case_code = n; break;
6483 case 'b': ind_case_break = n; break;
6484 case 'p': ind_param = n; break;
6485 case 't': ind_func_type = n; break;
6486 case '/': ind_comment = n; break;
6487 case 'c': ind_in_comment = n; break;
6488 case 'C': ind_in_comment2 = n; break;
6489 case 'i': ind_cpp_baseclass = n; break;
6490 case '+': ind_continuation = n; break;
6491 case '(': ind_unclosed = n; break;
6492 case 'u': ind_unclosed2 = n; break;
6493 case 'U': ind_unclosed_noignore = n; break;
6494 case 'W': ind_unclosed_wrapped = n; break;
6495 case 'w': ind_unclosed_whiteok = n; break;
6496 case 'm': ind_matching_paren = n; break;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006497 case 'M': ind_paren_prev = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006498 case ')': ind_maxparen = n; break;
6499 case '*': ind_maxcomment = n; break;
6500 case 'g': ind_scopedecl = n; break;
6501 case 'h': ind_scopedecl_code = n; break;
6502 case 'j': ind_java = n; break;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006503 case 'J': ind_js = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006504 case 'l': ind_keep_case_label = n; break;
Bram Moolenaar39353fd2007-03-27 09:02:11 +00006505 case '#': ind_hash_comment = n; break;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02006506 case 'N': ind_cpp_namespace = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006507 }
Bram Moolenaardfdf3c42010-03-23 18:22:46 +01006508 if (*options == ',')
6509 ++options;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006510 }
6511
6512 /* remember where the cursor was when we started */
6513 cur_curpos = curwin->w_cursor;
6514
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006515 /* if we are at line 1 0 is fine, right? */
6516 if (cur_curpos.lnum == 1)
6517 return 0;
6518
Bram Moolenaar071d4272004-06-13 20:20:40 +00006519 /* Get a copy of the current contents of the line.
6520 * This is required, because only the most recent line obtained with
6521 * ml_get is valid! */
6522 linecopy = vim_strsave(ml_get(cur_curpos.lnum));
6523 if (linecopy == NULL)
6524 return 0;
6525
6526 /*
6527 * In insert mode and the cursor is on a ')' truncate the line at the
6528 * cursor position. We don't want to line up with the matching '(' when
6529 * inserting new stuff.
6530 * For unknown reasons the cursor might be past the end of the line, thus
6531 * check for that.
6532 */
6533 if ((State & INSERT)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006534 && curwin->w_cursor.col < (colnr_T)STRLEN(linecopy)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006535 && linecopy[curwin->w_cursor.col] == ')')
6536 linecopy[curwin->w_cursor.col] = NUL;
6537
6538 theline = skipwhite(linecopy);
6539
6540 /* move the cursor to the start of the line */
6541
6542 curwin->w_cursor.col = 0;
6543
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006544 original_line_islabel = cin_islabel(ind_maxcomment); /* XXX */
6545
Bram Moolenaar071d4272004-06-13 20:20:40 +00006546 /*
6547 * #defines and so on always go at the left when included in 'cinkeys'.
6548 */
6549 if (*theline == '#' && (*linecopy == '#' || in_cinkeys('#', ' ', TRUE)))
6550 {
6551 amount = 0;
6552 }
6553
6554 /*
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006555 * Is it a non-case label? Then that goes at the left margin too unless:
6556 * - JS flag is set.
6557 * - 'L' item has a positive value.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006558 */
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006559 else if (original_line_islabel && !ind_js && ind_jump_label < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006560 {
6561 amount = 0;
6562 }
6563
6564 /*
6565 * If we're inside a "//" comment and there is a "//" comment in a
6566 * previous line, lineup with that one.
6567 */
6568 else if (cin_islinecomment(theline)
6569 && (trypos = find_line_comment()) != NULL) /* XXX */
6570 {
6571 /* find how indented the line beginning the comment is */
6572 getvcol(curwin, trypos, &col, NULL, NULL);
6573 amount = col;
6574 }
6575
6576 /*
6577 * If we're inside a comment and not looking at the start of the
6578 * comment, try using the 'comments' option.
6579 */
6580 else if (!cin_iscomment(theline)
6581 && (trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
6582 {
6583 int lead_start_len = 2;
6584 int lead_middle_len = 1;
6585 char_u lead_start[COM_MAX_LEN]; /* start-comment string */
6586 char_u lead_middle[COM_MAX_LEN]; /* middle-comment string */
6587 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
6588 char_u *p;
6589 int start_align = 0;
6590 int start_off = 0;
6591 int done = FALSE;
6592
6593 /* find how indented the line beginning the comment is */
6594 getvcol(curwin, trypos, &col, NULL, NULL);
6595 amount = col;
Bram Moolenaar4aa97422011-04-11 14:27:38 +02006596 *lead_start = NUL;
6597 *lead_middle = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006598
6599 p = curbuf->b_p_com;
6600 while (*p != NUL)
6601 {
6602 int align = 0;
6603 int off = 0;
6604 int what = 0;
6605
6606 while (*p != NUL && *p != ':')
6607 {
6608 if (*p == COM_START || *p == COM_END || *p == COM_MIDDLE)
6609 what = *p++;
6610 else if (*p == COM_LEFT || *p == COM_RIGHT)
6611 align = *p++;
6612 else if (VIM_ISDIGIT(*p) || *p == '-')
6613 off = getdigits(&p);
6614 else
6615 ++p;
6616 }
6617
6618 if (*p == ':')
6619 ++p;
6620 (void)copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
6621 if (what == COM_START)
6622 {
6623 STRCPY(lead_start, lead_end);
6624 lead_start_len = (int)STRLEN(lead_start);
6625 start_off = off;
6626 start_align = align;
6627 }
6628 else if (what == COM_MIDDLE)
6629 {
6630 STRCPY(lead_middle, lead_end);
6631 lead_middle_len = (int)STRLEN(lead_middle);
6632 }
6633 else if (what == COM_END)
6634 {
6635 /* If our line starts with the middle comment string, line it
6636 * up with the comment opener per the 'comments' option. */
6637 if (STRNCMP(theline, lead_middle, lead_middle_len) == 0
6638 && STRNCMP(theline, lead_end, STRLEN(lead_end)) != 0)
6639 {
6640 done = TRUE;
6641 if (curwin->w_cursor.lnum > 1)
6642 {
6643 /* If the start comment string matches in the previous
Bram Moolenaare21877a2008-02-13 09:58:14 +00006644 * line, use the indent of that line plus offset. If
Bram Moolenaar071d4272004-06-13 20:20:40 +00006645 * the middle comment string matches in the previous
6646 * line, use the indent of that line. XXX */
6647 look = skipwhite(ml_get(curwin->w_cursor.lnum - 1));
6648 if (STRNCMP(look, lead_start, lead_start_len) == 0)
6649 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6650 else if (STRNCMP(look, lead_middle,
6651 lead_middle_len) == 0)
6652 {
6653 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6654 break;
6655 }
6656 /* If the start comment string doesn't match with the
6657 * start of the comment, skip this entry. XXX */
6658 else if (STRNCMP(ml_get(trypos->lnum) + trypos->col,
6659 lead_start, lead_start_len) != 0)
6660 continue;
6661 }
6662 if (start_off != 0)
6663 amount += start_off;
6664 else if (start_align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006665 amount += vim_strsize(lead_start)
6666 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006667 break;
6668 }
6669
6670 /* If our line starts with the end comment string, line it up
6671 * with the middle comment */
6672 if (STRNCMP(theline, lead_middle, lead_middle_len) != 0
6673 && STRNCMP(theline, lead_end, STRLEN(lead_end)) == 0)
6674 {
6675 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6676 /* XXX */
6677 if (off != 0)
6678 amount += off;
6679 else if (align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006680 amount += vim_strsize(lead_start)
6681 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006682 done = TRUE;
6683 break;
6684 }
6685 }
6686 }
6687
6688 /* If our line starts with an asterisk, line up with the
6689 * asterisk in the comment opener; otherwise, line up
6690 * with the first character of the comment text.
6691 */
6692 if (done)
6693 ;
6694 else if (theline[0] == '*')
6695 amount += 1;
6696 else
6697 {
6698 /*
6699 * If we are more than one line away from the comment opener, take
6700 * the indent of the previous non-empty line. If 'cino' has "CO"
6701 * and we are just below the comment opener and there are any
6702 * white characters after it line up with the text after it;
6703 * otherwise, add the amount specified by "c" in 'cino'
6704 */
6705 amount = -1;
6706 for (lnum = cur_curpos.lnum - 1; lnum > trypos->lnum; --lnum)
6707 {
6708 if (linewhite(lnum)) /* skip blank lines */
6709 continue;
6710 amount = get_indent_lnum(lnum); /* XXX */
6711 break;
6712 }
6713 if (amount == -1) /* use the comment opener */
6714 {
6715 if (!ind_in_comment2)
6716 {
6717 start = ml_get(trypos->lnum);
6718 look = start + trypos->col + 2; /* skip / and * */
6719 if (*look != NUL) /* if something after it */
6720 trypos->col = (colnr_T)(skipwhite(look) - start);
6721 }
6722 getvcol(curwin, trypos, &col, NULL, NULL);
6723 amount = col;
6724 if (ind_in_comment2 || *look == NUL)
6725 amount += ind_in_comment;
6726 }
6727 }
6728 }
6729
6730 /*
6731 * Are we inside parentheses or braces?
6732 */ /* XXX */
6733 else if (((trypos = find_match_paren(ind_maxparen, ind_maxcomment)) != NULL
6734 && ind_java == 0)
6735 || (tryposBrace = find_start_brace(ind_maxcomment)) != NULL
6736 || trypos != NULL)
6737 {
6738 if (trypos != NULL && tryposBrace != NULL)
6739 {
6740 /* Both an unmatched '(' and '{' is found. Use the one which is
6741 * closer to the current cursor position, set the other to NULL. */
6742 if (trypos->lnum != tryposBrace->lnum
6743 ? trypos->lnum < tryposBrace->lnum
6744 : trypos->col < tryposBrace->col)
6745 trypos = NULL;
6746 else
6747 tryposBrace = NULL;
6748 }
6749
6750 if (trypos != NULL)
6751 {
6752 /*
6753 * If the matching paren is more than one line away, use the indent of
6754 * a previous non-empty line that matches the same paren.
6755 */
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006756 if (theline[0] == ')' && ind_paren_prev)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006757 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006758 /* Line up with the start of the matching paren line. */
6759 amount = get_indent_lnum(curwin->w_cursor.lnum - 1); /* XXX */
6760 }
6761 else
6762 {
6763 amount = -1;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006764 our_paren_pos = *trypos;
6765 for (lnum = cur_curpos.lnum - 1; lnum > our_paren_pos.lnum; --lnum)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006766 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006767 l = skipwhite(ml_get(lnum));
6768 if (cin_nocode(l)) /* skip comment lines */
6769 continue;
6770 if (cin_ispreproc_cont(&l, &lnum))
6771 continue; /* ignore #define, #if, etc. */
6772 curwin->w_cursor.lnum = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006773
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006774 /* Skip a comment. XXX */
6775 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
6776 {
6777 lnum = trypos->lnum + 1;
6778 continue;
6779 }
6780
6781 /* XXX */
6782 if ((trypos = find_match_paren(
6783 corr_ind_maxparen(ind_maxparen, &cur_curpos),
Bram Moolenaar071d4272004-06-13 20:20:40 +00006784 ind_maxcomment)) != NULL
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006785 && trypos->lnum == our_paren_pos.lnum
6786 && trypos->col == our_paren_pos.col)
6787 {
6788 amount = get_indent_lnum(lnum); /* XXX */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006789
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006790 if (theline[0] == ')')
6791 {
6792 if (our_paren_pos.lnum != lnum
6793 && cur_amount > amount)
6794 cur_amount = amount;
6795 amount = -1;
6796 }
6797 break;
6798 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006799 }
6800 }
6801
6802 /*
6803 * Line up with line where the matching paren is. XXX
6804 * If the line starts with a '(' or the indent for unclosed
6805 * parentheses is zero, line up with the unclosed parentheses.
6806 */
6807 if (amount == -1)
6808 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006809 int ignore_paren_col = 0;
6810
Bram Moolenaar071d4272004-06-13 20:20:40 +00006811 amount = skip_label(our_paren_pos.lnum, &look, ind_maxcomment);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006812 look = skipwhite(look);
6813 if (*look == '(')
6814 {
6815 linenr_T save_lnum = curwin->w_cursor.lnum;
6816 char_u *line;
6817 int look_col;
6818
6819 /* Ignore a '(' in front of the line that has a match before
6820 * our matching '('. */
6821 curwin->w_cursor.lnum = our_paren_pos.lnum;
6822 line = ml_get_curline();
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006823 look_col = (int)(look - line);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006824 curwin->w_cursor.col = look_col + 1;
6825 if ((trypos = findmatchlimit(NULL, ')', 0, ind_maxparen))
6826 != NULL
6827 && trypos->lnum == our_paren_pos.lnum
6828 && trypos->col < our_paren_pos.col)
6829 ignore_paren_col = trypos->col + 1;
6830
6831 curwin->w_cursor.lnum = save_lnum;
6832 look = ml_get(our_paren_pos.lnum) + look_col;
6833 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006834 if (theline[0] == ')' || ind_unclosed == 0
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006835 || (!ind_unclosed_noignore && *look == '('
6836 && ignore_paren_col == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006837 {
6838 /*
6839 * If we're looking at a close paren, line up right there;
6840 * otherwise, line up with the next (non-white) character.
6841 * When ind_unclosed_wrapped is set and the matching paren is
6842 * the last nonwhite character of the line, use either the
6843 * indent of the current line or the indentation of the next
6844 * outer paren and add ind_unclosed_wrapped (for very long
6845 * lines).
6846 */
6847 if (theline[0] != ')')
6848 {
6849 cur_amount = MAXCOL;
6850 l = ml_get(our_paren_pos.lnum);
6851 if (ind_unclosed_wrapped
6852 && cin_ends_in(l, (char_u *)"(", NULL))
6853 {
6854 /* look for opening unmatched paren, indent one level
6855 * for each additional level */
6856 n = 1;
6857 for (col = 0; col < our_paren_pos.col; ++col)
6858 {
6859 switch (l[col])
6860 {
6861 case '(':
6862 case '{': ++n;
6863 break;
6864
6865 case ')':
6866 case '}': if (n > 1)
6867 --n;
6868 break;
6869 }
6870 }
6871
6872 our_paren_pos.col = 0;
6873 amount += n * ind_unclosed_wrapped;
6874 }
6875 else if (ind_unclosed_whiteok)
6876 our_paren_pos.col++;
6877 else
6878 {
6879 col = our_paren_pos.col + 1;
6880 while (vim_iswhite(l[col]))
6881 col++;
6882 if (l[col] != NUL) /* In case of trailing space */
6883 our_paren_pos.col = col;
6884 else
6885 our_paren_pos.col++;
6886 }
6887 }
6888
6889 /*
6890 * Find how indented the paren is, or the character after it
6891 * if we did the above "if".
6892 */
6893 if (our_paren_pos.col > 0)
6894 {
6895 getvcol(curwin, &our_paren_pos, &col, NULL, NULL);
6896 if (cur_amount > (int)col)
6897 cur_amount = col;
6898 }
6899 }
6900
6901 if (theline[0] == ')' && ind_matching_paren)
6902 {
6903 /* Line up with the start of the matching paren line. */
6904 }
6905 else if (ind_unclosed == 0 || (!ind_unclosed_noignore
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006906 && *look == '(' && ignore_paren_col == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006907 {
6908 if (cur_amount != MAXCOL)
6909 amount = cur_amount;
6910 }
6911 else
6912 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006913 /* Add ind_unclosed2 for each '(' before our matching one, but
6914 * ignore (void) before the line (ignore_paren_col). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006915 col = our_paren_pos.col;
Bram Moolenaarb21e5842006-04-16 18:30:08 +00006916 while ((int)our_paren_pos.col > ignore_paren_col)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006917 {
6918 --our_paren_pos.col;
6919 switch (*ml_get_pos(&our_paren_pos))
6920 {
6921 case '(': amount += ind_unclosed2;
6922 col = our_paren_pos.col;
6923 break;
6924 case ')': amount -= ind_unclosed2;
6925 col = MAXCOL;
6926 break;
6927 }
6928 }
6929
6930 /* Use ind_unclosed once, when the first '(' is not inside
6931 * braces */
6932 if (col == MAXCOL)
6933 amount += ind_unclosed;
6934 else
6935 {
6936 curwin->w_cursor.lnum = our_paren_pos.lnum;
6937 curwin->w_cursor.col = col;
Bram Moolenaar367bec82011-04-11 14:26:19 +02006938 if (find_match_paren(ind_maxparen, ind_maxcomment) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006939 amount += ind_unclosed2;
6940 else
6941 amount += ind_unclosed;
6942 }
6943 /*
6944 * For a line starting with ')' use the minimum of the two
6945 * positions, to avoid giving it more indent than the previous
6946 * lines:
6947 * func_long_name( if (x
6948 * arg && yy
6949 * ) ^ not here ) ^ not here
6950 */
6951 if (cur_amount < amount)
6952 amount = cur_amount;
6953 }
6954 }
6955
6956 /* add extra indent for a comment */
6957 if (cin_iscomment(theline))
6958 amount += ind_comment;
6959 }
6960
6961 /*
6962 * Are we at least inside braces, then?
6963 */
6964 else
6965 {
6966 trypos = tryposBrace;
6967
6968 ourscope = trypos->lnum;
6969 start = ml_get(ourscope);
6970
6971 /*
6972 * Now figure out how indented the line is in general.
6973 * If the brace was at the start of the line, we use that;
6974 * otherwise, check out the indentation of the line as
6975 * a whole and then add the "imaginary indent" to that.
6976 */
6977 look = skipwhite(start);
6978 if (*look == '{')
6979 {
6980 getvcol(curwin, trypos, &col, NULL, NULL);
6981 amount = col;
6982 if (*start == '{')
6983 start_brace = BRACE_IN_COL0;
6984 else
6985 start_brace = BRACE_AT_START;
6986 }
6987 else
6988 {
6989 /*
6990 * that opening brace might have been on a continuation
6991 * line. if so, find the start of the line.
6992 */
6993 curwin->w_cursor.lnum = ourscope;
6994
6995 /*
6996 * position the cursor over the rightmost paren, so that
6997 * matching it will take us back to the start of the line.
6998 */
6999 lnum = ourscope;
7000 if (find_last_paren(start, '(', ')')
7001 && (trypos = find_match_paren(ind_maxparen,
7002 ind_maxcomment)) != NULL)
7003 lnum = trypos->lnum;
7004
7005 /*
7006 * It could have been something like
7007 * case 1: if (asdf &&
7008 * ldfd) {
7009 * }
7010 */
Bram Moolenaar6ec154b2011-06-12 21:51:08 +02007011 if (ind_js || (ind_keep_case_label
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007012 && cin_iscase(skipwhite(ml_get_curline()), FALSE)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007013 amount = get_indent();
7014 else
7015 amount = skip_label(lnum, &l, ind_maxcomment);
7016
7017 start_brace = BRACE_AT_END;
7018 }
7019
7020 /*
7021 * if we're looking at a closing brace, that's where
7022 * we want to be. otherwise, add the amount of room
7023 * that an indent is supposed to be.
7024 */
7025 if (theline[0] == '}')
7026 {
7027 /*
7028 * they may want closing braces to line up with something
7029 * other than the open brace. indulge them, if so.
7030 */
7031 amount += ind_close_extra;
7032 }
7033 else
7034 {
7035 /*
7036 * If we're looking at an "else", try to find an "if"
7037 * to match it with.
7038 * If we're looking at a "while", try to find a "do"
7039 * to match it with.
7040 */
7041 lookfor = LOOKFOR_INITIAL;
7042 if (cin_iselse(theline))
7043 lookfor = LOOKFOR_IF;
7044 else if (cin_iswhileofdo(theline, cur_curpos.lnum, ind_maxparen))
7045 /* XXX */
7046 lookfor = LOOKFOR_DO;
7047 if (lookfor != LOOKFOR_INITIAL)
7048 {
7049 curwin->w_cursor.lnum = cur_curpos.lnum;
7050 if (find_match(lookfor, ourscope, ind_maxparen,
7051 ind_maxcomment) == OK)
7052 {
7053 amount = get_indent(); /* XXX */
7054 goto theend;
7055 }
7056 }
7057
7058 /*
7059 * We get here if we are not on an "while-of-do" or "else" (or
7060 * failed to find a matching "if").
7061 * Search backwards for something to line up with.
7062 * First set amount for when we don't find anything.
7063 */
7064
7065 /*
7066 * if the '{' is _really_ at the left margin, use the imaginary
7067 * location of a left-margin brace. Otherwise, correct the
7068 * location for ind_open_extra.
7069 */
7070
7071 if (start_brace == BRACE_IN_COL0) /* '{' is in column 0 */
7072 {
7073 amount = ind_open_left_imag;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007074 lookfor_cpp_namespace = TRUE;
7075 }
7076 else if (start_brace == BRACE_AT_START &&
7077 lookfor_cpp_namespace) /* '{' is at start */
7078 {
7079
7080 lookfor_cpp_namespace = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007081 }
7082 else
7083 {
7084 if (start_brace == BRACE_AT_END) /* '{' is at end of line */
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007085 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007086 amount += ind_open_imag;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007087
7088 l = skipwhite(ml_get_curline());
7089 if (cin_is_cpp_namespace(l))
7090 amount += ind_cpp_namespace;
7091 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007092 else
7093 {
7094 /* Compensate for adding ind_open_extra later. */
7095 amount -= ind_open_extra;
7096 if (amount < 0)
7097 amount = 0;
7098 }
7099 }
7100
7101 lookfor_break = FALSE;
7102
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007103 if (cin_iscase(theline, FALSE)) /* it's a switch() label */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007104 {
7105 lookfor = LOOKFOR_CASE; /* find a previous switch() label */
7106 amount += ind_case;
7107 }
7108 else if (cin_isscopedecl(theline)) /* private:, ... */
7109 {
7110 lookfor = LOOKFOR_SCOPEDECL; /* class decl is this block */
7111 amount += ind_scopedecl;
7112 }
7113 else
7114 {
7115 if (ind_case_break && cin_isbreak(theline)) /* break; ... */
7116 lookfor_break = TRUE;
7117
7118 lookfor = LOOKFOR_INITIAL;
7119 amount += ind_level; /* ind_level from start of block */
7120 }
7121 scope_amount = amount;
7122 whilelevel = 0;
7123
7124 /*
7125 * Search backwards. If we find something we recognize, line up
7126 * with that.
7127 *
7128 * if we're looking at an open brace, indent
7129 * the usual amount relative to the conditional
7130 * that opens the block.
7131 */
7132 curwin->w_cursor = cur_curpos;
7133 for (;;)
7134 {
7135 curwin->w_cursor.lnum--;
7136 curwin->w_cursor.col = 0;
7137
7138 /*
7139 * If we went all the way back to the start of our scope, line
7140 * up with it.
7141 */
7142 if (curwin->w_cursor.lnum <= ourscope)
7143 {
7144 /* we reached end of scope:
7145 * if looking for a enum or structure initialization
7146 * go further back:
7147 * if it is an initializer (enum xxx or xxx =), then
7148 * don't add ind_continuation, otherwise it is a variable
7149 * declaration:
7150 * int x,
7151 * here; <-- add ind_continuation
7152 */
7153 if (lookfor == LOOKFOR_ENUM_OR_INIT)
7154 {
7155 if (curwin->w_cursor.lnum == 0
7156 || curwin->w_cursor.lnum
7157 < ourscope - ind_maxparen)
7158 {
7159 /* nothing found (abuse ind_maxparen as limit)
7160 * assume terminated line (i.e. a variable
7161 * initialization) */
7162 if (cont_amount > 0)
7163 amount = cont_amount;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007164 else if (!ind_js)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007165 amount += ind_continuation;
7166 break;
7167 }
7168
7169 l = ml_get_curline();
7170
7171 /*
7172 * If we're in a comment now, skip to the start of the
7173 * comment.
7174 */
7175 trypos = find_start_comment(ind_maxcomment);
7176 if (trypos != NULL)
7177 {
7178 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007179 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007180 continue;
7181 }
7182
7183 /*
7184 * Skip preprocessor directives and blank lines.
7185 */
7186 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7187 continue;
7188
7189 if (cin_nocode(l))
7190 continue;
7191
7192 terminated = cin_isterminated(l, FALSE, TRUE);
7193
7194 /*
7195 * If we are at top level and the line looks like a
7196 * function declaration, we are done
7197 * (it's a variable declaration).
7198 */
7199 if (start_brace != BRACE_IN_COL0
Bram Moolenaarc367faa2011-12-14 20:21:35 +01007200 || !cin_isfuncdecl(&l, curwin->w_cursor.lnum,
7201 0, ind_maxparen, ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007202 {
7203 /* if the line is terminated with another ','
7204 * it is a continued variable initialization.
7205 * don't add extra indent.
7206 * TODO: does not work, if a function
7207 * declaration is split over multiple lines:
7208 * cin_isfuncdecl returns FALSE then.
7209 */
7210 if (terminated == ',')
7211 break;
7212
7213 /* if it es a enum declaration or an assignment,
7214 * we are done.
7215 */
7216 if (terminated != ';' && cin_isinit())
7217 break;
7218
7219 /* nothing useful found */
7220 if (terminated == 0 || terminated == '{')
7221 continue;
7222 }
7223
7224 if (terminated != ';')
7225 {
7226 /* Skip parens and braces. Position the cursor
7227 * over the rightmost paren, so that matching it
7228 * will take us back to the start of the line.
7229 */ /* XXX */
7230 trypos = NULL;
7231 if (find_last_paren(l, '(', ')'))
7232 trypos = find_match_paren(ind_maxparen,
7233 ind_maxcomment);
7234
7235 if (trypos == NULL && find_last_paren(l, '{', '}'))
7236 trypos = find_start_brace(ind_maxcomment);
7237
7238 if (trypos != NULL)
7239 {
7240 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007241 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007242 continue;
7243 }
7244 }
7245
7246 /* it's a variable declaration, add indentation
7247 * like in
7248 * int a,
7249 * b;
7250 */
7251 if (cont_amount > 0)
7252 amount = cont_amount;
7253 else
7254 amount += ind_continuation;
7255 }
7256 else if (lookfor == LOOKFOR_UNTERM)
7257 {
7258 if (cont_amount > 0)
7259 amount = cont_amount;
7260 else
7261 amount += ind_continuation;
7262 }
Bram Moolenaare79d1532011-10-04 18:03:47 +02007263 else
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007264 {
Bram Moolenaare79d1532011-10-04 18:03:47 +02007265 if (lookfor != LOOKFOR_TERM
Bram Moolenaar071d4272004-06-13 20:20:40 +00007266 && lookfor != LOOKFOR_CPP_BASECLASS)
Bram Moolenaare79d1532011-10-04 18:03:47 +02007267 {
7268 amount = scope_amount;
7269 if (theline[0] == '{')
7270 {
7271 amount += ind_open_extra;
7272 added_to_amount = ind_open_extra;
7273 }
7274 }
7275
7276 if (lookfor_cpp_namespace)
7277 {
7278 /*
7279 * Looking for C++ namespace, need to look further
7280 * back.
7281 */
7282 if (curwin->w_cursor.lnum == ourscope)
7283 continue;
7284
7285 if (curwin->w_cursor.lnum == 0
7286 || curwin->w_cursor.lnum
7287 < ourscope - FIND_NAMESPACE_LIM)
7288 break;
7289
7290 l = ml_get_curline();
7291
7292 /* If we're in a comment now, skip to the start of
7293 * the comment. */
7294 trypos = find_start_comment(ind_maxcomment);
7295 if (trypos != NULL)
7296 {
7297 curwin->w_cursor.lnum = trypos->lnum + 1;
7298 curwin->w_cursor.col = 0;
7299 continue;
7300 }
7301
7302 /* Skip preprocessor directives and blank lines. */
7303 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7304 continue;
7305
7306 /* Finally the actual check for "namespace". */
7307 if (cin_is_cpp_namespace(l))
7308 {
7309 amount += ind_cpp_namespace - added_to_amount;
7310 break;
7311 }
7312
7313 if (cin_nocode(l))
7314 continue;
7315 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007316 }
7317 break;
7318 }
7319
7320 /*
7321 * If we're in a comment now, skip to the start of the comment.
7322 */ /* XXX */
7323 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
7324 {
7325 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007326 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007327 continue;
7328 }
7329
7330 l = ml_get_curline();
7331
7332 /*
7333 * If this is a switch() label, may line up relative to that.
Bram Moolenaar18144c82006-04-12 21:52:12 +00007334 * If this is a C++ scope declaration, do the same.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007335 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007336 iscase = cin_iscase(l, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007337 if (iscase || cin_isscopedecl(l))
7338 {
7339 /* we are only looking for cpp base class
7340 * declaration/initialization any longer */
7341 if (lookfor == LOOKFOR_CPP_BASECLASS)
7342 break;
7343
7344 /* When looking for a "do" we are not interested in
7345 * labels. */
7346 if (whilelevel > 0)
7347 continue;
7348
7349 /*
7350 * case xx:
7351 * c = 99 + <- this indent plus continuation
7352 *-> here;
7353 */
7354 if (lookfor == LOOKFOR_UNTERM
7355 || lookfor == LOOKFOR_ENUM_OR_INIT)
7356 {
7357 if (cont_amount > 0)
7358 amount = cont_amount;
7359 else
7360 amount += ind_continuation;
7361 break;
7362 }
7363
7364 /*
7365 * case xx: <- line up with this case
7366 * x = 333;
7367 * case yy:
7368 */
7369 if ( (iscase && lookfor == LOOKFOR_CASE)
7370 || (iscase && lookfor_break)
7371 || (!iscase && lookfor == LOOKFOR_SCOPEDECL))
7372 {
7373 /*
7374 * Check that this case label is not for another
7375 * switch()
7376 */ /* XXX */
7377 if ((trypos = find_start_brace(ind_maxcomment)) ==
7378 NULL || trypos->lnum == ourscope)
7379 {
7380 amount = get_indent(); /* XXX */
7381 break;
7382 }
7383 continue;
7384 }
7385
7386 n = get_indent_nolabel(curwin->w_cursor.lnum); /* XXX */
7387
7388 /*
7389 * case xx: if (cond) <- line up with this if
7390 * y = y + 1;
7391 * -> s = 99;
7392 *
7393 * case xx:
7394 * if (cond) <- line up with this line
7395 * y = y + 1;
7396 * -> s = 99;
7397 */
7398 if (lookfor == LOOKFOR_TERM)
7399 {
7400 if (n)
7401 amount = n;
7402
7403 if (!lookfor_break)
7404 break;
7405 }
7406
7407 /*
7408 * case xx: x = x + 1; <- line up with this x
7409 * -> y = y + 1;
7410 *
7411 * case xx: if (cond) <- line up with this if
7412 * -> y = y + 1;
7413 */
7414 if (n)
7415 {
7416 amount = n;
7417 l = after_label(ml_get_curline());
7418 if (l != NULL && cin_is_cinword(l))
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007419 {
7420 if (theline[0] == '{')
7421 amount += ind_open_extra;
7422 else
7423 amount += ind_level + ind_no_brace;
7424 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007425 break;
7426 }
7427
7428 /*
7429 * Try to get the indent of a statement before the switch
7430 * label. If nothing is found, line up relative to the
7431 * switch label.
7432 * break; <- may line up with this line
7433 * case xx:
7434 * -> y = 1;
7435 */
7436 scope_amount = get_indent() + (iscase /* XXX */
7437 ? ind_case_code : ind_scopedecl_code);
7438 lookfor = ind_case_break ? LOOKFOR_NOBREAK : LOOKFOR_ANY;
7439 continue;
7440 }
7441
7442 /*
7443 * Looking for a switch() label or C++ scope declaration,
7444 * ignore other lines, skip {}-blocks.
7445 */
7446 if (lookfor == LOOKFOR_CASE || lookfor == LOOKFOR_SCOPEDECL)
7447 {
7448 if (find_last_paren(l, '{', '}') && (trypos =
7449 find_start_brace(ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007450 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007451 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007452 curwin->w_cursor.col = 0;
7453 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007454 continue;
7455 }
7456
7457 /*
7458 * Ignore jump labels with nothing after them.
7459 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007460 if (!ind_js && cin_islabel(ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007461 {
7462 l = after_label(ml_get_curline());
7463 if (l == NULL || cin_nocode(l))
7464 continue;
7465 }
7466
7467 /*
7468 * Ignore #defines, #if, etc.
7469 * Ignore comment and empty lines.
7470 * (need to get the line again, cin_islabel() may have
7471 * unlocked it)
7472 */
7473 l = ml_get_curline();
7474 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum)
7475 || cin_nocode(l))
7476 continue;
7477
7478 /*
7479 * Are we at the start of a cpp base class declaration or
7480 * constructor initialization?
7481 */ /* XXX */
Bram Moolenaar18144c82006-04-12 21:52:12 +00007482 n = FALSE;
7483 if (lookfor != LOOKFOR_TERM && ind_cpp_baseclass > 0)
7484 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00007485 n = cin_is_cpp_baseclass(&col);
Bram Moolenaar18144c82006-04-12 21:52:12 +00007486 l = ml_get_curline();
7487 }
7488 if (n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007489 {
7490 if (lookfor == LOOKFOR_UNTERM)
7491 {
7492 if (cont_amount > 0)
7493 amount = cont_amount;
7494 else
7495 amount += ind_continuation;
7496 }
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007497 else if (theline[0] == '{')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007498 {
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007499 /* Need to find start of the declaration. */
7500 lookfor = LOOKFOR_UNTERM;
7501 ind_continuation = 0;
7502 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007503 }
7504 else
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007505 /* XXX */
7506 amount = get_baseclass_amount(col, ind_maxparen,
7507 ind_maxcomment, ind_cpp_baseclass);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007508 break;
7509 }
7510 else if (lookfor == LOOKFOR_CPP_BASECLASS)
7511 {
7512 /* only look, whether there is a cpp base class
Bram Moolenaar18144c82006-04-12 21:52:12 +00007513 * declaration or initialization before the opening brace.
7514 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007515 if (cin_isterminated(l, TRUE, FALSE))
7516 break;
7517 else
7518 continue;
7519 }
7520
7521 /*
7522 * What happens next depends on the line being terminated.
7523 * If terminated with a ',' only consider it terminating if
Bram Moolenaar25394022007-05-10 19:06:20 +00007524 * there is another unterminated statement behind, eg:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007525 * 123,
7526 * sizeof
7527 * here
7528 * Otherwise check whether it is a enumeration or structure
7529 * initialisation (not indented) or a variable declaration
7530 * (indented).
7531 */
7532 terminated = cin_isterminated(l, FALSE, TRUE);
7533
7534 if (terminated == 0 || (lookfor != LOOKFOR_UNTERM
7535 && terminated == ','))
7536 {
7537 /*
7538 * if we're in the middle of a paren thing,
7539 * go back to the line that starts it so
7540 * we can get the right prevailing indent
7541 * if ( foo &&
7542 * bar )
7543 */
7544 /*
7545 * position the cursor over the rightmost paren, so that
7546 * matching it will take us back to the start of the line.
7547 */
7548 (void)find_last_paren(l, '(', ')');
7549 trypos = find_match_paren(
7550 corr_ind_maxparen(ind_maxparen, &cur_curpos),
7551 ind_maxcomment);
7552
7553 /*
7554 * If we are looking for ',', we also look for matching
7555 * braces.
7556 */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007557 if (trypos == NULL && terminated == ','
7558 && find_last_paren(l, '{', '}'))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007559 trypos = find_start_brace(ind_maxcomment);
7560
7561 if (trypos != NULL)
7562 {
7563 /*
7564 * Check if we are on a case label now. This is
7565 * handled above.
7566 * case xx: if ( asdf &&
7567 * asdf)
7568 */
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007569 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007570 l = ml_get_curline();
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007571 if (cin_iscase(l, FALSE) || cin_isscopedecl(l))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007572 {
7573 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007574 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007575 continue;
7576 }
7577 }
7578
7579 /*
7580 * Skip over continuation lines to find the one to get the
7581 * indent from
7582 * char *usethis = "bla\
7583 * bla",
7584 * here;
7585 */
7586 if (terminated == ',')
7587 {
7588 while (curwin->w_cursor.lnum > 1)
7589 {
7590 l = ml_get(curwin->w_cursor.lnum - 1);
7591 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
7592 break;
7593 --curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007594 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007595 }
7596 }
7597
7598 /*
7599 * Get indent and pointer to text for current line,
7600 * ignoring any jump label. XXX
7601 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007602 if (!ind_js)
7603 cur_amount = skip_label(curwin->w_cursor.lnum,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007604 &l, ind_maxcomment);
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007605 else
7606 cur_amount = get_indent();
Bram Moolenaar071d4272004-06-13 20:20:40 +00007607 /*
7608 * If this is just above the line we are indenting, and it
7609 * starts with a '{', line it up with this line.
7610 * while (not)
7611 * -> {
7612 * }
7613 */
7614 if (terminated != ',' && lookfor != LOOKFOR_TERM
7615 && theline[0] == '{')
7616 {
7617 amount = cur_amount;
7618 /*
7619 * Only add ind_open_extra when the current line
7620 * doesn't start with a '{', which must have a match
7621 * in the same line (scope is the same). Probably:
7622 * { 1, 2 },
7623 * -> { 3, 4 }
7624 */
7625 if (*skipwhite(l) != '{')
7626 amount += ind_open_extra;
7627
7628 if (ind_cpp_baseclass)
7629 {
7630 /* have to look back, whether it is a cpp base
7631 * class declaration or initialization */
7632 lookfor = LOOKFOR_CPP_BASECLASS;
7633 continue;
7634 }
7635 break;
7636 }
7637
7638 /*
7639 * Check if we are after an "if", "while", etc.
7640 * Also allow " } else".
7641 */
7642 if (cin_is_cinword(l) || cin_iselse(skipwhite(l)))
7643 {
7644 /*
7645 * Found an unterminated line after an if (), line up
7646 * with the last one.
7647 * if (cond)
7648 * 100 +
7649 * -> here;
7650 */
7651 if (lookfor == LOOKFOR_UNTERM
7652 || lookfor == LOOKFOR_ENUM_OR_INIT)
7653 {
7654 if (cont_amount > 0)
7655 amount = cont_amount;
7656 else
7657 amount += ind_continuation;
7658 break;
7659 }
7660
7661 /*
7662 * If this is just above the line we are indenting, we
7663 * are finished.
7664 * while (not)
7665 * -> here;
7666 * Otherwise this indent can be used when the line
7667 * before this is terminated.
7668 * yyy;
7669 * if (stat)
7670 * while (not)
7671 * xxx;
7672 * -> here;
7673 */
7674 amount = cur_amount;
7675 if (theline[0] == '{')
7676 amount += ind_open_extra;
7677 if (lookfor != LOOKFOR_TERM)
7678 {
7679 amount += ind_level + ind_no_brace;
7680 break;
7681 }
7682
7683 /*
7684 * Special trick: when expecting the while () after a
7685 * do, line up with the while()
7686 * do
7687 * x = 1;
7688 * -> here
7689 */
7690 l = skipwhite(ml_get_curline());
7691 if (cin_isdo(l))
7692 {
7693 if (whilelevel == 0)
7694 break;
7695 --whilelevel;
7696 }
7697
7698 /*
7699 * When searching for a terminated line, don't use the
Bram Moolenaar334adf02011-05-25 13:34:04 +02007700 * one between the "if" and the matching "else".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007701 * Need to use the scope of this "else". XXX
7702 * If whilelevel != 0 continue looking for a "do {".
7703 */
Bram Moolenaar334adf02011-05-25 13:34:04 +02007704 if (cin_iselse(l) && whilelevel == 0)
7705 {
7706 /* If we're looking at "} else", let's make sure we
7707 * find the opening brace of the enclosing scope,
7708 * not the one from "if () {". */
7709 if (*l == '}')
7710 curwin->w_cursor.col =
Bram Moolenaar9b83c2f2011-05-25 17:29:44 +02007711 (colnr_T)(l - ml_get_curline()) + 1;
Bram Moolenaar334adf02011-05-25 13:34:04 +02007712
7713 if ((trypos = find_start_brace(ind_maxcomment))
7714 == NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007715 || find_match(LOOKFOR_IF, trypos->lnum,
Bram Moolenaar334adf02011-05-25 13:34:04 +02007716 ind_maxparen, ind_maxcomment) == FAIL)
7717 break;
7718 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007719 }
7720
7721 /*
7722 * If we're below an unterminated line that is not an
7723 * "if" or something, we may line up with this line or
Bram Moolenaar25394022007-05-10 19:06:20 +00007724 * add something for a continuation line, depending on
Bram Moolenaar071d4272004-06-13 20:20:40 +00007725 * the line before this one.
7726 */
7727 else
7728 {
7729 /*
7730 * Found two unterminated lines on a row, line up with
7731 * the last one.
7732 * c = 99 +
7733 * 100 +
7734 * -> here;
7735 */
7736 if (lookfor == LOOKFOR_UNTERM)
7737 {
7738 /* When line ends in a comma add extra indent */
7739 if (terminated == ',')
7740 amount += ind_continuation;
7741 break;
7742 }
7743
7744 if (lookfor == LOOKFOR_ENUM_OR_INIT)
7745 {
7746 /* Found two lines ending in ',', lineup with the
7747 * lowest one, but check for cpp base class
7748 * declaration/initialization, if it is an
7749 * opening brace or we are looking just for
7750 * enumerations/initializations. */
7751 if (terminated == ',')
7752 {
7753 if (ind_cpp_baseclass == 0)
7754 break;
7755
7756 lookfor = LOOKFOR_CPP_BASECLASS;
7757 continue;
7758 }
7759
7760 /* Ignore unterminated lines in between, but
7761 * reduce indent. */
7762 if (amount > cur_amount)
7763 amount = cur_amount;
7764 }
7765 else
7766 {
7767 /*
7768 * Found first unterminated line on a row, may
7769 * line up with this line, remember its indent
7770 * 100 +
7771 * -> here;
7772 */
7773 amount = cur_amount;
7774
7775 /*
7776 * If previous line ends in ',', check whether we
7777 * are in an initialization or enum
7778 * struct xxx =
7779 * {
7780 * sizeof a,
7781 * 124 };
7782 * or a normal possible continuation line.
7783 * but only, of no other statement has been found
7784 * yet.
7785 */
7786 if (lookfor == LOOKFOR_INITIAL && terminated == ',')
7787 {
7788 lookfor = LOOKFOR_ENUM_OR_INIT;
7789 cont_amount = cin_first_id_amount();
7790 }
7791 else
7792 {
7793 if (lookfor == LOOKFOR_INITIAL
7794 && *l != NUL
7795 && l[STRLEN(l) - 1] == '\\')
7796 /* XXX */
7797 cont_amount = cin_get_equal_amount(
7798 curwin->w_cursor.lnum);
7799 if (lookfor != LOOKFOR_TERM)
7800 lookfor = LOOKFOR_UNTERM;
7801 }
7802 }
7803 }
7804 }
7805
7806 /*
7807 * Check if we are after a while (cond);
7808 * If so: Ignore until the matching "do".
7809 */
7810 /* XXX */
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007811 else if (cin_iswhileofdo_end(terminated, ind_maxparen,
7812 ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007813 {
7814 /*
7815 * Found an unterminated line after a while ();, line up
7816 * with the last one.
7817 * while (cond);
7818 * 100 + <- line up with this one
7819 * -> here;
7820 */
7821 if (lookfor == LOOKFOR_UNTERM
7822 || lookfor == LOOKFOR_ENUM_OR_INIT)
7823 {
7824 if (cont_amount > 0)
7825 amount = cont_amount;
7826 else
7827 amount += ind_continuation;
7828 break;
7829 }
7830
7831 if (whilelevel == 0)
7832 {
7833 lookfor = LOOKFOR_TERM;
7834 amount = get_indent(); /* XXX */
7835 if (theline[0] == '{')
7836 amount += ind_open_extra;
7837 }
7838 ++whilelevel;
7839 }
7840
7841 /*
7842 * We are after a "normal" statement.
7843 * If we had another statement we can stop now and use the
7844 * indent of that other statement.
7845 * Otherwise the indent of the current statement may be used,
7846 * search backwards for the next "normal" statement.
7847 */
7848 else
7849 {
7850 /*
7851 * Skip single break line, if before a switch label. It
7852 * may be lined up with the case label.
7853 */
7854 if (lookfor == LOOKFOR_NOBREAK
7855 && cin_isbreak(skipwhite(ml_get_curline())))
7856 {
7857 lookfor = LOOKFOR_ANY;
7858 continue;
7859 }
7860
7861 /*
7862 * Handle "do {" line.
7863 */
7864 if (whilelevel > 0)
7865 {
7866 l = cin_skipcomment(ml_get_curline());
7867 if (cin_isdo(l))
7868 {
7869 amount = get_indent(); /* XXX */
7870 --whilelevel;
7871 continue;
7872 }
7873 }
7874
7875 /*
7876 * Found a terminated line above an unterminated line. Add
7877 * the amount for a continuation line.
7878 * x = 1;
7879 * y = foo +
7880 * -> here;
7881 * or
7882 * int x = 1;
7883 * int foo,
7884 * -> here;
7885 */
7886 if (lookfor == LOOKFOR_UNTERM
7887 || lookfor == LOOKFOR_ENUM_OR_INIT)
7888 {
7889 if (cont_amount > 0)
7890 amount = cont_amount;
7891 else
7892 amount += ind_continuation;
7893 break;
7894 }
7895
7896 /*
7897 * Found a terminated line above a terminated line or "if"
7898 * etc. line. Use the amount of the line below us.
7899 * x = 1; x = 1;
7900 * if (asdf) y = 2;
7901 * while (asdf) ->here;
7902 * here;
7903 * ->foo;
7904 */
7905 if (lookfor == LOOKFOR_TERM)
7906 {
7907 if (!lookfor_break && whilelevel == 0)
7908 break;
7909 }
7910
7911 /*
7912 * First line above the one we're indenting is terminated.
7913 * To know what needs to be done look further backward for
7914 * a terminated line.
7915 */
7916 else
7917 {
7918 /*
7919 * position the cursor over the rightmost paren, so
7920 * that matching it will take us back to the start of
7921 * the line. Helps for:
7922 * func(asdr,
7923 * asdfasdf);
7924 * here;
7925 */
7926term_again:
7927 l = ml_get_curline();
7928 if (find_last_paren(l, '(', ')')
7929 && (trypos = find_match_paren(ind_maxparen,
7930 ind_maxcomment)) != NULL)
7931 {
7932 /*
7933 * Check if we are on a case label now. This is
7934 * handled above.
7935 * case xx: if ( asdf &&
7936 * asdf)
7937 */
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007938 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007939 l = ml_get_curline();
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007940 if (cin_iscase(l, FALSE) || cin_isscopedecl(l))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007941 {
7942 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007943 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007944 continue;
7945 }
7946 }
7947
7948 /* When aligning with the case statement, don't align
7949 * with a statement after it.
7950 * case 1: { <-- don't use this { position
7951 * stat;
7952 * }
7953 * case 2:
7954 * stat;
7955 * }
7956 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007957 iscase = (ind_keep_case_label && cin_iscase(l, FALSE));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007958
7959 /*
7960 * Get indent and pointer to text for current line,
7961 * ignoring any jump label.
7962 */
7963 amount = skip_label(curwin->w_cursor.lnum,
7964 &l, ind_maxcomment);
7965
7966 if (theline[0] == '{')
7967 amount += ind_open_extra;
7968 /* See remark above: "Only add ind_open_extra.." */
Bram Moolenaar18144c82006-04-12 21:52:12 +00007969 l = skipwhite(l);
7970 if (*l == '{')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007971 amount -= ind_open_extra;
7972 lookfor = iscase ? LOOKFOR_ANY : LOOKFOR_TERM;
7973
7974 /*
Bram Moolenaar18144c82006-04-12 21:52:12 +00007975 * When a terminated line starts with "else" skip to
7976 * the matching "if":
7977 * else 3;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00007978 * indent this;
Bram Moolenaar18144c82006-04-12 21:52:12 +00007979 * Need to use the scope of this "else". XXX
7980 * If whilelevel != 0 continue looking for a "do {".
7981 */
7982 if (lookfor == LOOKFOR_TERM
7983 && *l != '}'
7984 && cin_iselse(l)
7985 && whilelevel == 0)
7986 {
7987 if ((trypos = find_start_brace(ind_maxcomment))
7988 == NULL
7989 || find_match(LOOKFOR_IF, trypos->lnum,
7990 ind_maxparen, ind_maxcomment) == FAIL)
7991 break;
7992 continue;
7993 }
7994
7995 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007996 * If we're at the end of a block, skip to the start of
7997 * that block.
7998 */
Bram Moolenaar6d8f9c62011-11-30 13:03:28 +01007999 l = ml_get_curline();
Bram Moolenaar50f42ca2011-07-15 14:12:30 +02008000 if (find_last_paren(l, '{', '}')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008001 && (trypos = find_start_brace(ind_maxcomment))
8002 != NULL) /* XXX */
8003 {
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008004 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008005 /* if not "else {" check for terminated again */
8006 /* but skip block for "} else {" */
8007 l = cin_skipcomment(ml_get_curline());
8008 if (*l == '}' || !cin_iselse(l))
8009 goto term_again;
8010 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008011 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008012 }
8013 }
8014 }
8015 }
8016 }
8017 }
8018
8019 /* add extra indent for a comment */
8020 if (cin_iscomment(theline))
8021 amount += ind_comment;
Bram Moolenaar02c707a2010-07-17 17:12:06 +02008022
8023 /* subtract extra left-shift for jump labels */
8024 if (ind_jump_label > 0 && original_line_islabel)
8025 amount -= ind_jump_label;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008026 }
8027
8028 /*
8029 * ok -- we're not inside any sort of structure at all!
8030 *
8031 * this means we're at the top level, and everything should
8032 * basically just match where the previous line is, except
8033 * for the lines immediately following a function declaration,
8034 * which are K&R-style parameters and need to be indented.
8035 */
8036 else
8037 {
8038 /*
8039 * if our line starts with an open brace, forget about any
8040 * prevailing indent and make sure it looks like the start
8041 * of a function
8042 */
8043
8044 if (theline[0] == '{')
8045 {
8046 amount = ind_first_open;
8047 }
8048
8049 /*
8050 * If the NEXT line is a function declaration, the current
8051 * line needs to be indented as a function type spec.
Bram Moolenaar1a89bbe2010-03-02 12:38:22 +01008052 * Don't do this if the current line looks like a comment or if the
8053 * current line is terminated, ie. ends in ';', or if the current line
8054 * contains { or }: "void f() {\n if (1)"
Bram Moolenaar071d4272004-06-13 20:20:40 +00008055 */
8056 else if (cur_curpos.lnum < curbuf->b_ml.ml_line_count
8057 && !cin_nocode(theline)
Bram Moolenaar1a89bbe2010-03-02 12:38:22 +01008058 && vim_strchr(theline, '{') == NULL
8059 && vim_strchr(theline, '}') == NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00008060 && !cin_ends_in(theline, (char_u *)":", NULL)
8061 && !cin_ends_in(theline, (char_u *)",", NULL)
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008062 && cin_isfuncdecl(NULL, cur_curpos.lnum + 1,
8063 cur_curpos.lnum + 1,
8064 ind_maxparen, ind_maxcomment)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008065 && !cin_isterminated(theline, FALSE, TRUE))
8066 {
8067 amount = ind_func_type;
8068 }
8069 else
8070 {
8071 amount = 0;
8072 curwin->w_cursor = cur_curpos;
8073
8074 /* search backwards until we find something we recognize */
8075
8076 while (curwin->w_cursor.lnum > 1)
8077 {
8078 curwin->w_cursor.lnum--;
8079 curwin->w_cursor.col = 0;
8080
8081 l = ml_get_curline();
8082
8083 /*
8084 * If we're in a comment now, skip to the start of the comment.
8085 */ /* XXX */
8086 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
8087 {
8088 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008089 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008090 continue;
8091 }
8092
8093 /*
Bram Moolenaar18144c82006-04-12 21:52:12 +00008094 * Are we at the start of a cpp base class declaration or
8095 * constructor initialization?
Bram Moolenaar071d4272004-06-13 20:20:40 +00008096 */ /* XXX */
Bram Moolenaar18144c82006-04-12 21:52:12 +00008097 n = FALSE;
8098 if (ind_cpp_baseclass != 0 && theline[0] != '{')
8099 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00008100 n = cin_is_cpp_baseclass(&col);
Bram Moolenaar18144c82006-04-12 21:52:12 +00008101 l = ml_get_curline();
8102 }
8103 if (n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008104 {
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00008105 /* XXX */
8106 amount = get_baseclass_amount(col, ind_maxparen,
8107 ind_maxcomment, ind_cpp_baseclass);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008108 break;
8109 }
8110
8111 /*
8112 * Skip preprocessor directives and blank lines.
8113 */
8114 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
8115 continue;
8116
8117 if (cin_nocode(l))
8118 continue;
8119
8120 /*
8121 * If the previous line ends in ',', use one level of
8122 * indentation:
8123 * int foo,
8124 * bar;
8125 * do this before checking for '}' in case of eg.
8126 * enum foobar
8127 * {
8128 * ...
8129 * } foo,
8130 * bar;
8131 */
8132 n = 0;
8133 if (cin_ends_in(l, (char_u *)",", NULL)
8134 || (*l != NUL && (n = l[STRLEN(l) - 1]) == '\\'))
8135 {
8136 /* take us back to opening paren */
8137 if (find_last_paren(l, '(', ')')
8138 && (trypos = find_match_paren(ind_maxparen,
8139 ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008140 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008141
8142 /* For a line ending in ',' that is a continuation line go
8143 * back to the first line with a backslash:
8144 * char *foo = "bla\
8145 * bla",
8146 * here;
8147 */
8148 while (n == 0 && curwin->w_cursor.lnum > 1)
8149 {
8150 l = ml_get(curwin->w_cursor.lnum - 1);
8151 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
8152 break;
8153 --curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008154 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008155 }
8156
8157 amount = get_indent(); /* XXX */
8158
8159 if (amount == 0)
8160 amount = cin_first_id_amount();
8161 if (amount == 0)
8162 amount = ind_continuation;
8163 break;
8164 }
8165
8166 /*
8167 * If the line looks like a function declaration, and we're
8168 * not in a comment, put it the left margin.
8169 */
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008170 if (cin_isfuncdecl(NULL, cur_curpos.lnum, 0,
8171 ind_maxparen, ind_maxcomment)) /* XXX */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008172 break;
8173 l = ml_get_curline();
8174
8175 /*
8176 * Finding the closing '}' of a previous function. Put
8177 * current line at the left margin. For when 'cino' has "fs".
8178 */
8179 if (*skipwhite(l) == '}')
8180 break;
8181
8182 /* (matching {)
8183 * If the previous line ends on '};' (maybe followed by
8184 * comments) align at column 0. For example:
8185 * char *string_array[] = { "foo",
8186 * / * x * / "b};ar" }; / * foobar * /
8187 */
8188 if (cin_ends_in(l, (char_u *)"};", NULL))
8189 break;
8190
8191 /*
Bram Moolenaar3388bb42011-11-30 17:20:23 +01008192 * Find a line only has a semicolon that belongs to a previous
8193 * line ending in '}', e.g. before an #endif. Don't increase
8194 * indent then.
8195 */
8196 if (*(look = skipwhite(l)) == ';' && cin_nocode(look + 1))
8197 {
8198 pos_T curpos_save = curwin->w_cursor;
8199
8200 while (curwin->w_cursor.lnum > 1)
8201 {
8202 look = ml_get(--curwin->w_cursor.lnum);
8203 if (!(cin_nocode(look) || cin_ispreproc_cont(
8204 &look, &curwin->w_cursor.lnum)))
8205 break;
8206 }
8207 if (curwin->w_cursor.lnum > 0
8208 && cin_ends_in(look, (char_u *)"}", NULL))
8209 break;
8210
8211 curwin->w_cursor = curpos_save;
8212 }
8213
8214 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008215 * If the PREVIOUS line is a function declaration, the current
8216 * line (and the ones that follow) needs to be indented as
8217 * parameters.
8218 */
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008219 if (cin_isfuncdecl(&l, curwin->w_cursor.lnum, 0,
8220 ind_maxparen, ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008221 {
8222 amount = ind_param;
8223 break;
8224 }
8225
8226 /*
8227 * If the previous line ends in ';' and the line before the
8228 * previous line ends in ',' or '\', ident to column zero:
8229 * int foo,
8230 * bar;
8231 * indent_to_0 here;
8232 */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00008233 if (cin_ends_in(l, (char_u *)";", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008234 {
8235 l = ml_get(curwin->w_cursor.lnum - 1);
8236 if (cin_ends_in(l, (char_u *)",", NULL)
8237 || (*l != NUL && l[STRLEN(l) - 1] == '\\'))
8238 break;
8239 l = ml_get_curline();
8240 }
8241
8242 /*
8243 * Doesn't look like anything interesting -- so just
8244 * use the indent of this line.
8245 *
8246 * Position the cursor over the rightmost paren, so that
8247 * matching it will take us back to the start of the line.
8248 */
8249 find_last_paren(l, '(', ')');
8250
8251 if ((trypos = find_match_paren(ind_maxparen,
8252 ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008253 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008254 amount = get_indent(); /* XXX */
8255 break;
8256 }
8257
8258 /* add extra indent for a comment */
8259 if (cin_iscomment(theline))
8260 amount += ind_comment;
8261
8262 /* add extra indent if the previous line ended in a backslash:
8263 * "asdfasdf\
8264 * here";
8265 * char *foo = "asdf\
8266 * here";
8267 */
8268 if (cur_curpos.lnum > 1)
8269 {
8270 l = ml_get(cur_curpos.lnum - 1);
8271 if (*l != NUL && l[STRLEN(l) - 1] == '\\')
8272 {
8273 cur_amount = cin_get_equal_amount(cur_curpos.lnum - 1);
8274 if (cur_amount > 0)
8275 amount = cur_amount;
8276 else if (cur_amount == 0)
8277 amount += ind_continuation;
8278 }
8279 }
8280 }
8281 }
8282
8283theend:
8284 /* put the cursor back where it belongs */
8285 curwin->w_cursor = cur_curpos;
8286
8287 vim_free(linecopy);
8288
8289 if (amount < 0)
8290 return 0;
8291 return amount;
8292}
8293
8294 static int
8295find_match(lookfor, ourscope, ind_maxparen, ind_maxcomment)
8296 int lookfor;
8297 linenr_T ourscope;
8298 int ind_maxparen;
8299 int ind_maxcomment;
8300{
8301 char_u *look;
8302 pos_T *theirscope;
8303 char_u *mightbeif;
8304 int elselevel;
8305 int whilelevel;
8306
8307 if (lookfor == LOOKFOR_IF)
8308 {
8309 elselevel = 1;
8310 whilelevel = 0;
8311 }
8312 else
8313 {
8314 elselevel = 0;
8315 whilelevel = 1;
8316 }
8317
8318 curwin->w_cursor.col = 0;
8319
8320 while (curwin->w_cursor.lnum > ourscope + 1)
8321 {
8322 curwin->w_cursor.lnum--;
8323 curwin->w_cursor.col = 0;
8324
8325 look = cin_skipcomment(ml_get_curline());
8326 if (cin_iselse(look)
8327 || cin_isif(look)
8328 || cin_isdo(look) /* XXX */
8329 || cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
8330 {
8331 /*
8332 * if we've gone outside the braces entirely,
8333 * we must be out of scope...
8334 */
8335 theirscope = find_start_brace(ind_maxcomment); /* XXX */
8336 if (theirscope == NULL)
8337 break;
8338
8339 /*
8340 * and if the brace enclosing this is further
8341 * back than the one enclosing the else, we're
8342 * out of luck too.
8343 */
8344 if (theirscope->lnum < ourscope)
8345 break;
8346
8347 /*
8348 * and if they're enclosed in a *deeper* brace,
8349 * then we can ignore it because it's in a
8350 * different scope...
8351 */
8352 if (theirscope->lnum > ourscope)
8353 continue;
8354
8355 /*
8356 * if it was an "else" (that's not an "else if")
8357 * then we need to go back to another if, so
8358 * increment elselevel
8359 */
8360 look = cin_skipcomment(ml_get_curline());
8361 if (cin_iselse(look))
8362 {
8363 mightbeif = cin_skipcomment(look + 4);
8364 if (!cin_isif(mightbeif))
8365 ++elselevel;
8366 continue;
8367 }
8368
8369 /*
8370 * if it was a "while" then we need to go back to
8371 * another "do", so increment whilelevel. XXX
8372 */
8373 if (cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
8374 {
8375 ++whilelevel;
8376 continue;
8377 }
8378
8379 /* If it's an "if" decrement elselevel */
8380 look = cin_skipcomment(ml_get_curline());
8381 if (cin_isif(look))
8382 {
8383 elselevel--;
8384 /*
8385 * When looking for an "if" ignore "while"s that
8386 * get in the way.
8387 */
8388 if (elselevel == 0 && lookfor == LOOKFOR_IF)
8389 whilelevel = 0;
8390 }
8391
8392 /* If it's a "do" decrement whilelevel */
8393 if (cin_isdo(look))
8394 whilelevel--;
8395
8396 /*
8397 * if we've used up all the elses, then
8398 * this must be the if that we want!
8399 * match the indent level of that if.
8400 */
8401 if (elselevel <= 0 && whilelevel <= 0)
8402 {
8403 return OK;
8404 }
8405 }
8406 }
8407 return FAIL;
8408}
8409
8410# if defined(FEAT_EVAL) || defined(PROTO)
8411/*
8412 * Get indent level from 'indentexpr'.
8413 */
8414 int
8415get_expr_indent()
8416{
8417 int indent;
8418 pos_T pos;
8419 int save_State;
Bram Moolenaard1f56e62006-02-22 21:25:37 +00008420 int use_sandbox = was_set_insecurely((char_u *)"indentexpr",
8421 OPT_LOCAL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008422
8423 pos = curwin->w_cursor;
8424 set_vim_var_nr(VV_LNUM, curwin->w_cursor.lnum);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00008425 if (use_sandbox)
8426 ++sandbox;
8427 ++textlock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008428 indent = eval_to_number(curbuf->b_p_inde);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00008429 if (use_sandbox)
8430 --sandbox;
8431 --textlock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008432
8433 /* Restore the cursor position so that 'indentexpr' doesn't need to.
8434 * Pretend to be in Insert mode, allow cursor past end of line for "o"
8435 * command. */
8436 save_State = State;
8437 State = INSERT;
8438 curwin->w_cursor = pos;
8439 check_cursor();
8440 State = save_State;
8441
8442 /* If there is an error, just keep the current indent. */
8443 if (indent < 0)
8444 indent = get_indent();
8445
8446 return indent;
8447}
8448# endif
8449
8450#endif /* FEAT_CINDENT */
8451
8452#if defined(FEAT_LISP) || defined(PROTO)
8453
8454static int lisp_match __ARGS((char_u *p));
8455
8456 static int
8457lisp_match(p)
8458 char_u *p;
8459{
8460 char_u buf[LSIZE];
8461 int len;
8462 char_u *word = p_lispwords;
8463
8464 while (*word != NUL)
8465 {
8466 (void)copy_option_part(&word, buf, LSIZE, ",");
8467 len = (int)STRLEN(buf);
8468 if (STRNCMP(buf, p, len) == 0 && p[len] == ' ')
8469 return TRUE;
8470 }
8471 return FALSE;
8472}
8473
8474/*
8475 * When 'p' is present in 'cpoptions, a Vi compatible method is used.
8476 * The incompatible newer method is quite a bit better at indenting
8477 * code in lisp-like languages than the traditional one; it's still
8478 * mostly heuristics however -- Dirk van Deun, dirk@rave.org
8479 *
8480 * TODO:
8481 * Findmatch() should be adapted for lisp, also to make showmatch
8482 * work correctly: now (v5.3) it seems all C/C++ oriented:
8483 * - it does not recognize the #\( and #\) notations as character literals
8484 * - it doesn't know about comments starting with a semicolon
8485 * - it incorrectly interprets '(' as a character literal
8486 * All this messes up get_lisp_indent in some rare cases.
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008487 * Update from Sergey Khorev:
8488 * I tried to fix the first two issues.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008489 */
8490 int
8491get_lisp_indent()
8492{
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008493 pos_T *pos, realpos, paren;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008494 int amount;
8495 char_u *that;
8496 colnr_T col;
8497 colnr_T firsttry;
8498 int parencount, quotecount;
8499 int vi_lisp;
8500
8501 /* Set vi_lisp to use the vi-compatible method */
8502 vi_lisp = (vim_strchr(p_cpo, CPO_LISP) != NULL);
8503
8504 realpos = curwin->w_cursor;
8505 curwin->w_cursor.col = 0;
8506
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008507 if ((pos = findmatch(NULL, '(')) == NULL)
8508 pos = findmatch(NULL, '[');
8509 else
8510 {
8511 paren = *pos;
8512 pos = findmatch(NULL, '[');
8513 if (pos == NULL || ltp(pos, &paren))
8514 pos = &paren;
8515 }
8516 if (pos != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008517 {
8518 /* Extra trick: Take the indent of the first previous non-white
8519 * line that is at the same () level. */
8520 amount = -1;
8521 parencount = 0;
8522
8523 while (--curwin->w_cursor.lnum >= pos->lnum)
8524 {
8525 if (linewhite(curwin->w_cursor.lnum))
8526 continue;
8527 for (that = ml_get_curline(); *that != NUL; ++that)
8528 {
8529 if (*that == ';')
8530 {
8531 while (*(that + 1) != NUL)
8532 ++that;
8533 continue;
8534 }
8535 if (*that == '\\')
8536 {
8537 if (*(that + 1) != NUL)
8538 ++that;
8539 continue;
8540 }
8541 if (*that == '"' && *(that + 1) != NUL)
8542 {
Bram Moolenaar15ff6c12006-09-15 18:18:09 +00008543 while (*++that && *that != '"')
8544 {
8545 /* skipping escaped characters in the string */
8546 if (*that == '\\')
8547 {
8548 if (*++that == NUL)
8549 break;
8550 if (that[1] == NUL)
8551 {
8552 ++that;
8553 break;
8554 }
8555 }
8556 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008557 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008558 if (*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008559 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008560 else if (*that == ')' || *that == ']')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008561 --parencount;
8562 }
8563 if (parencount == 0)
8564 {
8565 amount = get_indent();
8566 break;
8567 }
8568 }
8569
8570 if (amount == -1)
8571 {
8572 curwin->w_cursor.lnum = pos->lnum;
8573 curwin->w_cursor.col = pos->col;
8574 col = pos->col;
8575
8576 that = ml_get_curline();
8577
8578 if (vi_lisp && get_indent() == 0)
8579 amount = 2;
8580 else
8581 {
8582 amount = 0;
8583 while (*that && col)
8584 {
8585 amount += lbr_chartabsize_adv(&that, (colnr_T)amount);
8586 col--;
8587 }
8588
8589 /*
8590 * Some keywords require "body" indenting rules (the
8591 * non-standard-lisp ones are Scheme special forms):
8592 *
8593 * (let ((a 1)) instead (let ((a 1))
8594 * (...)) of (...))
8595 */
8596
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008597 if (!vi_lisp && (*that == '(' || *that == '[')
8598 && lisp_match(that + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008599 amount += 2;
8600 else
8601 {
8602 that++;
8603 amount++;
8604 firsttry = amount;
8605
8606 while (vim_iswhite(*that))
8607 {
8608 amount += lbr_chartabsize(that, (colnr_T)amount);
8609 ++that;
8610 }
8611
8612 if (*that && *that != ';') /* not a comment line */
8613 {
Bram Moolenaare21877a2008-02-13 09:58:14 +00008614 /* test *that != '(' to accommodate first let/do
Bram Moolenaar071d4272004-06-13 20:20:40 +00008615 * argument if it is more than one line */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008616 if (!vi_lisp && *that != '(' && *that != '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008617 firsttry++;
8618
8619 parencount = 0;
8620 quotecount = 0;
8621
8622 if (vi_lisp
8623 || (*that != '"'
8624 && *that != '\''
8625 && *that != '#'
8626 && (*that < '0' || *that > '9')))
8627 {
8628 while (*that
8629 && (!vim_iswhite(*that)
8630 || quotecount
8631 || parencount)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008632 && (!((*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008633 && !quotecount
8634 && !parencount
8635 && vi_lisp)))
8636 {
8637 if (*that == '"')
8638 quotecount = !quotecount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008639 if ((*that == '(' || *that == '[')
8640 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008641 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008642 if ((*that == ')' || *that == ']')
8643 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008644 --parencount;
8645 if (*that == '\\' && *(that+1) != NUL)
8646 amount += lbr_chartabsize_adv(&that,
8647 (colnr_T)amount);
8648 amount += lbr_chartabsize_adv(&that,
8649 (colnr_T)amount);
8650 }
8651 }
8652 while (vim_iswhite(*that))
8653 {
8654 amount += lbr_chartabsize(that, (colnr_T)amount);
8655 that++;
8656 }
8657 if (!*that || *that == ';')
8658 amount = firsttry;
8659 }
8660 }
8661 }
8662 }
8663 }
8664 else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008665 amount = 0; /* no matching '(' or '[' found, use zero indent */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008666
8667 curwin->w_cursor = realpos;
8668
8669 return amount;
8670}
8671#endif /* FEAT_LISP */
8672
8673 void
8674prepare_to_exit()
8675{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00008676#if defined(SIGHUP) && defined(SIG_IGN)
8677 /* Ignore SIGHUP, because a dropped connection causes a read error, which
8678 * makes Vim exit and then handling SIGHUP causes various reentrance
8679 * problems. */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00008680 signal(SIGHUP, SIG_IGN);
8681#endif
8682
Bram Moolenaar071d4272004-06-13 20:20:40 +00008683#ifdef FEAT_GUI
8684 if (gui.in_use)
8685 {
8686 gui.dying = TRUE;
8687 out_trash(); /* trash any pending output */
8688 }
8689 else
8690#endif
8691 {
8692 windgoto((int)Rows - 1, 0);
8693
8694 /*
8695 * Switch terminal mode back now, so messages end up on the "normal"
8696 * screen (if there are two screens).
8697 */
8698 settmode(TMODE_COOK);
8699#ifdef WIN3264
8700 if (can_end_termcap_mode(FALSE) == TRUE)
8701#endif
8702 stoptermcap();
8703 out_flush();
8704 }
8705}
8706
8707/*
8708 * Preserve files and exit.
8709 * When called IObuff must contain a message.
8710 */
8711 void
8712preserve_exit()
8713{
8714 buf_T *buf;
8715
8716 prepare_to_exit();
8717
Bram Moolenaar4770d092006-01-12 23:22:24 +00008718 /* Setting this will prevent free() calls. That avoids calling free()
8719 * recursively when free() was invoked with a bad pointer. */
8720 really_exiting = TRUE;
8721
Bram Moolenaar071d4272004-06-13 20:20:40 +00008722 out_str(IObuff);
8723 screen_start(); /* don't know where cursor is now */
8724 out_flush();
8725
8726 ml_close_notmod(); /* close all not-modified buffers */
8727
8728 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8729 {
8730 if (buf->b_ml.ml_mfp != NULL && buf->b_ml.ml_mfp->mf_fname != NULL)
8731 {
8732 OUT_STR(_("Vim: preserving files...\n"));
8733 screen_start(); /* don't know where cursor is now */
8734 out_flush();
8735 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
8736 break;
8737 }
8738 }
8739
8740 ml_close_all(FALSE); /* close all memfiles, without deleting */
8741
8742 OUT_STR(_("Vim: Finished.\n"));
8743
8744 getout(1);
8745}
8746
8747/*
8748 * return TRUE if "fname" exists.
8749 */
8750 int
8751vim_fexists(fname)
8752 char_u *fname;
8753{
8754 struct stat st;
8755
8756 if (mch_stat((char *)fname, &st))
8757 return FALSE;
8758 return TRUE;
8759}
8760
8761/*
8762 * Check for CTRL-C pressed, but only once in a while.
8763 * Should be used instead of ui_breakcheck() for functions that check for
8764 * each line in the file. Calling ui_breakcheck() each time takes too much
8765 * time, because it can be a system call.
8766 */
8767
8768#ifndef BREAKCHECK_SKIP
8769# ifdef FEAT_GUI /* assume the GUI only runs on fast computers */
8770# define BREAKCHECK_SKIP 200
8771# else
8772# define BREAKCHECK_SKIP 32
8773# endif
8774#endif
8775
8776static int breakcheck_count = 0;
8777
8778 void
8779line_breakcheck()
8780{
8781 if (++breakcheck_count >= BREAKCHECK_SKIP)
8782 {
8783 breakcheck_count = 0;
8784 ui_breakcheck();
8785 }
8786}
8787
8788/*
8789 * Like line_breakcheck() but check 10 times less often.
8790 */
8791 void
8792fast_breakcheck()
8793{
8794 if (++breakcheck_count >= BREAKCHECK_SKIP * 10)
8795 {
8796 breakcheck_count = 0;
8797 ui_breakcheck();
8798 }
8799}
8800
8801/*
Bram Moolenaard7834d32009-12-02 16:14:36 +00008802 * Invoke expand_wildcards() for one pattern.
8803 * Expand items like "%:h" before the expansion.
8804 * Returns OK or FAIL.
8805 */
8806 int
8807expand_wildcards_eval(pat, num_file, file, flags)
8808 char_u **pat; /* pointer to input pattern */
8809 int *num_file; /* resulting number of files */
8810 char_u ***file; /* array of resulting files */
8811 int flags; /* EW_DIR, etc. */
8812{
8813 int ret = FAIL;
8814 char_u *eval_pat = NULL;
8815 char_u *exp_pat = *pat;
8816 char_u *ignored_msg;
8817 int usedlen;
8818
8819 if (*exp_pat == '%' || *exp_pat == '#' || *exp_pat == '<')
8820 {
8821 ++emsg_off;
8822 eval_pat = eval_vars(exp_pat, exp_pat, &usedlen,
8823 NULL, &ignored_msg, NULL);
8824 --emsg_off;
8825 if (eval_pat != NULL)
8826 exp_pat = concat_str(eval_pat, exp_pat + usedlen);
8827 }
8828
8829 if (exp_pat != NULL)
8830 ret = expand_wildcards(1, &exp_pat, num_file, file, flags);
8831
8832 if (eval_pat != NULL)
8833 {
8834 vim_free(exp_pat);
8835 vim_free(eval_pat);
8836 }
8837
8838 return ret;
8839}
8840
8841/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008842 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching
8843 * 'wildignore'.
Bram Moolenaar9e193ac2010-07-19 23:11:27 +02008844 * Returns OK or FAIL. When FAIL then "num_file" won't be set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008845 */
8846 int
8847expand_wildcards(num_pat, pat, num_file, file, flags)
8848 int num_pat; /* number of input patterns */
8849 char_u **pat; /* array of input patterns */
8850 int *num_file; /* resulting number of files */
8851 char_u ***file; /* array of resulting files */
8852 int flags; /* EW_DIR, etc. */
8853{
8854 int retval;
8855 int i, j;
8856 char_u *p;
8857 int non_suf_match; /* number without matching suffix */
8858
8859 retval = gen_expand_wildcards(num_pat, pat, num_file, file, flags);
8860
8861 /* When keeping all matches, return here */
Bram Moolenaar9e193ac2010-07-19 23:11:27 +02008862 if ((flags & EW_KEEPALL) || retval == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008863 return retval;
8864
8865#ifdef FEAT_WILDIGN
8866 /*
8867 * Remove names that match 'wildignore'.
8868 */
8869 if (*p_wig)
8870 {
8871 char_u *ffname;
8872
8873 /* check all files in (*file)[] */
8874 for (i = 0; i < *num_file; ++i)
8875 {
8876 ffname = FullName_save((*file)[i], FALSE);
8877 if (ffname == NULL) /* out of memory */
8878 break;
8879# ifdef VMS
8880 vms_remove_version(ffname);
8881# endif
8882 if (match_file_list(p_wig, (*file)[i], ffname))
8883 {
8884 /* remove this matching file from the list */
8885 vim_free((*file)[i]);
8886 for (j = i; j + 1 < *num_file; ++j)
8887 (*file)[j] = (*file)[j + 1];
8888 --*num_file;
8889 --i;
8890 }
8891 vim_free(ffname);
8892 }
8893 }
8894#endif
8895
8896 /*
8897 * Move the names where 'suffixes' match to the end.
8898 */
8899 if (*num_file > 1)
8900 {
8901 non_suf_match = 0;
8902 for (i = 0; i < *num_file; ++i)
8903 {
8904 if (!match_suffix((*file)[i]))
8905 {
8906 /*
8907 * Move the name without matching suffix to the front
8908 * of the list.
8909 */
8910 p = (*file)[i];
8911 for (j = i; j > non_suf_match; --j)
8912 (*file)[j] = (*file)[j - 1];
8913 (*file)[non_suf_match++] = p;
8914 }
8915 }
8916 }
8917
8918 return retval;
8919}
8920
8921/*
8922 * Return TRUE if "fname" matches with an entry in 'suffixes'.
8923 */
8924 int
8925match_suffix(fname)
8926 char_u *fname;
8927{
8928 int fnamelen, setsuflen;
8929 char_u *setsuf;
8930#define MAXSUFLEN 30 /* maximum length of a file suffix */
8931 char_u suf_buf[MAXSUFLEN];
8932
8933 fnamelen = (int)STRLEN(fname);
8934 setsuflen = 0;
8935 for (setsuf = p_su; *setsuf; )
8936 {
8937 setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
Bram Moolenaar055a2ba2009-07-14 19:40:21 +00008938 if (setsuflen == 0)
8939 {
8940 char_u *tail = gettail(fname);
8941
8942 /* empty entry: match name without a '.' */
8943 if (vim_strchr(tail, '.') == NULL)
8944 {
8945 setsuflen = 1;
8946 break;
8947 }
8948 }
8949 else
8950 {
8951 if (fnamelen >= setsuflen
8952 && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
8953 (size_t)setsuflen) == 0)
8954 break;
8955 setsuflen = 0;
8956 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008957 }
8958 return (setsuflen != 0);
8959}
8960
8961#if !defined(NO_EXPANDPATH) || defined(PROTO)
8962
8963# ifdef VIM_BACKTICK
8964static int vim_backtick __ARGS((char_u *p));
8965static int expand_backtick __ARGS((garray_T *gap, char_u *pat, int flags));
8966# endif
8967
8968# if defined(MSDOS) || defined(FEAT_GUI_W16) || defined(WIN3264)
8969/*
8970 * File name expansion code for MS-DOS, Win16 and Win32. It's here because
8971 * it's shared between these systems.
8972 */
8973# if defined(DJGPP) || defined(PROTO)
8974# define _cdecl /* DJGPP doesn't have this */
8975# else
8976# ifdef __BORLANDC__
8977# define _cdecl _RTLENTRYF
8978# endif
8979# endif
8980
8981/*
8982 * comparison function for qsort in dos_expandpath()
8983 */
8984 static int _cdecl
8985pstrcmp(const void *a, const void *b)
8986{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00008987 return (pathcmp(*(char **)a, *(char **)b, -1));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008988}
8989
8990# ifndef WIN3264
8991 static void
8992namelowcpy(
8993 char_u *d,
8994 char_u *s)
8995{
8996# ifdef DJGPP
8997 if (USE_LONG_FNAME) /* don't lower case on Windows 95/NT systems */
8998 while (*s)
8999 *d++ = *s++;
9000 else
9001# endif
9002 while (*s)
9003 *d++ = TOLOWER_LOC(*s++);
9004 *d = NUL;
9005}
9006# endif
9007
9008/*
Bram Moolenaar231334e2005-07-25 20:46:57 +00009009 * Recursively expand one path component into all matching files and/or
9010 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009011 * Return the number of matches found.
9012 * "path" has backslashes before chars that are not to be expanded, starting
9013 * at "path[wildoff]".
Bram Moolenaar231334e2005-07-25 20:46:57 +00009014 * Return the number of matches found.
9015 * NOTE: much of this is identical to unix_expandpath(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00009016 */
9017 static int
9018dos_expandpath(
9019 garray_T *gap,
9020 char_u *path,
9021 int wildoff,
Bram Moolenaar231334e2005-07-25 20:46:57 +00009022 int flags, /* EW_* flags */
Bram Moolenaar25394022007-05-10 19:06:20 +00009023 int didstar) /* expanded "**" once already */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009024{
Bram Moolenaar231334e2005-07-25 20:46:57 +00009025 char_u *buf;
9026 char_u *path_end;
9027 char_u *p, *s, *e;
9028 int start_len = gap->ga_len;
9029 char_u *pat;
9030 regmatch_T regmatch;
9031 int starts_with_dot;
9032 int matches;
9033 int len;
9034 int starstar = FALSE;
9035 static int stardepth = 0; /* depth for "**" expansion */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009036#ifdef WIN3264
9037 WIN32_FIND_DATA fb;
9038 HANDLE hFind = (HANDLE)0;
9039# ifdef FEAT_MBYTE
9040 WIN32_FIND_DATAW wfb;
9041 WCHAR *wn = NULL; /* UCS-2 name, NULL when not used. */
9042# endif
9043#else
9044 struct ffblk fb;
9045#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009046 char_u *matchname;
Bram Moolenaar231334e2005-07-25 20:46:57 +00009047 int ok;
9048
9049 /* Expanding "**" may take a long time, check for CTRL-C. */
9050 if (stardepth > 0)
9051 {
9052 ui_breakcheck();
9053 if (got_int)
9054 return 0;
9055 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009056
9057 /* make room for file name */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009058 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009059 if (buf == NULL)
9060 return 0;
9061
9062 /*
9063 * Find the first part in the path name that contains a wildcard or a ~1.
9064 * Copy it into buf, including the preceding characters.
9065 */
9066 p = buf;
9067 s = buf;
9068 e = NULL;
9069 path_end = path;
9070 while (*path_end != NUL)
9071 {
9072 /* May ignore a wildcard that has a backslash before it; it will
9073 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
9074 if (path_end >= path + wildoff && rem_backslash(path_end))
9075 *p++ = *path_end++;
9076 else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
9077 {
9078 if (e != NULL)
9079 break;
9080 s = p + 1;
9081 }
9082 else if (path_end >= path + wildoff
9083 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
9084 e = p;
9085#ifdef FEAT_MBYTE
9086 if (has_mbyte)
9087 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00009088 len = (*mb_ptr2len)(path_end);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009089 STRNCPY(p, path_end, len);
9090 p += len;
9091 path_end += len;
9092 }
9093 else
9094#endif
9095 *p++ = *path_end++;
9096 }
9097 e = p;
9098 *e = NUL;
9099
9100 /* now we have one wildcard component between s and e */
9101 /* Remove backslashes between "wildoff" and the start of the wildcard
9102 * component. */
9103 for (p = buf + wildoff; p < s; ++p)
9104 if (rem_backslash(p))
9105 {
Bram Moolenaar8c8de832008-06-24 22:58:06 +00009106 STRMOVE(p, p + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009107 --e;
9108 --s;
9109 }
9110
Bram Moolenaar231334e2005-07-25 20:46:57 +00009111 /* Check for "**" between "s" and "e". */
9112 for (p = s; p < e; ++p)
9113 if (p[0] == '*' && p[1] == '*')
9114 starstar = TRUE;
9115
Bram Moolenaar071d4272004-06-13 20:20:40 +00009116 starts_with_dot = (*s == '.');
9117 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
9118 if (pat == NULL)
9119 {
9120 vim_free(buf);
9121 return 0;
9122 }
9123
9124 /* compile the regexp into a program */
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009125 if (flags & (EW_NOERROR | EW_NOTWILD))
Bram Moolenaarb5609832011-07-20 15:04:58 +02009126 ++emsg_silent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009127 regmatch.rm_ic = TRUE; /* Always ignore case */
9128 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009129 if (flags & (EW_NOERROR | EW_NOTWILD))
Bram Moolenaarb5609832011-07-20 15:04:58 +02009130 --emsg_silent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009131 vim_free(pat);
9132
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009133 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009134 {
9135 vim_free(buf);
9136 return 0;
9137 }
9138
9139 /* remember the pattern or file name being looked for */
9140 matchname = vim_strsave(s);
9141
Bram Moolenaar231334e2005-07-25 20:46:57 +00009142 /* If "**" is by itself, this is the first time we encounter it and more
9143 * is following then find matches without any directory. */
9144 if (!didstar && stardepth < 100 && starstar && e - s == 2
9145 && *path_end == '/')
9146 {
9147 STRCPY(s, path_end + 1);
9148 ++stardepth;
9149 (void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
9150 --stardepth;
9151 }
9152
Bram Moolenaar071d4272004-06-13 20:20:40 +00009153 /* Scan all files in the directory with "dir/ *.*" */
9154 STRCPY(s, "*.*");
9155#ifdef WIN3264
9156# ifdef FEAT_MBYTE
9157 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
9158 {
9159 /* The active codepage differs from 'encoding'. Attempt using the
9160 * wide function. If it fails because it is not implemented fall back
9161 * to the non-wide version (for Windows 98) */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009162 wn = enc_to_utf16(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009163 if (wn != NULL)
9164 {
9165 hFind = FindFirstFileW(wn, &wfb);
9166 if (hFind == INVALID_HANDLE_VALUE
9167 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
9168 {
9169 vim_free(wn);
9170 wn = NULL;
9171 }
9172 }
9173 }
9174
9175 if (wn == NULL)
9176# endif
9177 hFind = FindFirstFile(buf, &fb);
9178 ok = (hFind != INVALID_HANDLE_VALUE);
9179#else
9180 /* If we are expanding wildcards we try both files and directories */
9181 ok = (findfirst((char *)buf, &fb,
9182 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
9183#endif
9184
9185 while (ok)
9186 {
9187#ifdef WIN3264
9188# ifdef FEAT_MBYTE
9189 if (wn != NULL)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009190 p = utf16_to_enc(wfb.cFileName, NULL); /* p is allocated here */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009191 else
9192# endif
9193 p = (char_u *)fb.cFileName;
9194#else
9195 p = (char_u *)fb.ff_name;
9196#endif
9197 /* Ignore entries starting with a dot, unless when asked for. Accept
9198 * all entries found with "matchname". */
9199 if ((p[0] != '.' || starts_with_dot)
9200 && (matchname == NULL
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009201 || (regmatch.regprog != NULL
9202 && vim_regexec(&regmatch, p, (colnr_T)0))
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009203 || ((flags & EW_NOTWILD)
9204 && fnamencmp(path + (s - buf), p, e - s) == 0)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009205 {
9206#ifdef WIN3264
9207 STRCPY(s, p);
9208#else
9209 namelowcpy(s, p);
9210#endif
9211 len = (int)STRLEN(buf);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009212
9213 if (starstar && stardepth < 100)
9214 {
9215 /* For "**" in the pattern first go deeper in the tree to
9216 * find matches. */
9217 STRCPY(buf + len, "/**");
9218 STRCPY(buf + len + 3, path_end);
9219 ++stardepth;
9220 (void)dos_expandpath(gap, buf, len + 1, flags, TRUE);
9221 --stardepth;
9222 }
9223
Bram Moolenaar071d4272004-06-13 20:20:40 +00009224 STRCPY(buf + len, path_end);
9225 if (mch_has_exp_wildcard(path_end))
9226 {
9227 /* need to expand another component of the path */
9228 /* remove backslashes for the remaining components only */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009229 (void)dos_expandpath(gap, buf, len + 1, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009230 }
9231 else
9232 {
9233 /* no more wildcards, check if there is a match */
9234 /* remove backslashes for the remaining components only */
9235 if (*path_end != 0)
9236 backslash_halve(buf + len + 1);
9237 if (mch_getperm(buf) >= 0) /* add existing file */
9238 addfile(gap, buf, flags);
9239 }
9240 }
9241
9242#ifdef WIN3264
9243# ifdef FEAT_MBYTE
9244 if (wn != NULL)
9245 {
9246 vim_free(p);
9247 ok = FindNextFileW(hFind, &wfb);
9248 }
9249 else
9250# endif
9251 ok = FindNextFile(hFind, &fb);
9252#else
9253 ok = (findnext(&fb) == 0);
9254#endif
9255
9256 /* If no more matches and no match was used, try expanding the name
9257 * itself. Finds the long name of a short filename. */
9258 if (!ok && matchname != NULL && gap->ga_len == start_len)
9259 {
9260 STRCPY(s, matchname);
9261#ifdef WIN3264
9262 FindClose(hFind);
9263# ifdef FEAT_MBYTE
9264 if (wn != NULL)
9265 {
9266 vim_free(wn);
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009267 wn = enc_to_utf16(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009268 if (wn != NULL)
9269 hFind = FindFirstFileW(wn, &wfb);
9270 }
9271 if (wn == NULL)
9272# endif
9273 hFind = FindFirstFile(buf, &fb);
9274 ok = (hFind != INVALID_HANDLE_VALUE);
9275#else
9276 ok = (findfirst((char *)buf, &fb,
9277 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
9278#endif
9279 vim_free(matchname);
9280 matchname = NULL;
9281 }
9282 }
9283
9284#ifdef WIN3264
9285 FindClose(hFind);
9286# ifdef FEAT_MBYTE
9287 vim_free(wn);
9288# endif
9289#endif
9290 vim_free(buf);
9291 vim_free(regmatch.regprog);
9292 vim_free(matchname);
9293
9294 matches = gap->ga_len - start_len;
9295 if (matches > 0)
9296 qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
9297 sizeof(char_u *), pstrcmp);
9298 return matches;
9299}
9300
9301 int
9302mch_expandpath(
9303 garray_T *gap,
9304 char_u *path,
9305 int flags) /* EW_* flags */
9306{
Bram Moolenaar231334e2005-07-25 20:46:57 +00009307 return dos_expandpath(gap, path, 0, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009308}
9309# endif /* MSDOS || FEAT_GUI_W16 || WIN3264 */
9310
Bram Moolenaar231334e2005-07-25 20:46:57 +00009311#if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
9312 || defined(PROTO)
9313/*
9314 * Unix style wildcard expansion code.
9315 * It's here because it's used both for Unix and Mac.
9316 */
9317static int pstrcmp __ARGS((const void *, const void *));
9318
9319 static int
9320pstrcmp(a, b)
9321 const void *a, *b;
9322{
9323 return (pathcmp(*(char **)a, *(char **)b, -1));
9324}
9325
9326/*
9327 * Recursively expand one path component into all matching files and/or
9328 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
9329 * "path" has backslashes before chars that are not to be expanded, starting
9330 * at "path + wildoff".
9331 * Return the number of matches found.
9332 * NOTE: much of this is identical to dos_expandpath(), keep in sync!
9333 */
9334 int
9335unix_expandpath(gap, path, wildoff, flags, didstar)
9336 garray_T *gap;
9337 char_u *path;
9338 int wildoff;
9339 int flags; /* EW_* flags */
9340 int didstar; /* expanded "**" once already */
9341{
9342 char_u *buf;
9343 char_u *path_end;
9344 char_u *p, *s, *e;
9345 int start_len = gap->ga_len;
9346 char_u *pat;
9347 regmatch_T regmatch;
9348 int starts_with_dot;
9349 int matches;
9350 int len;
9351 int starstar = FALSE;
9352 static int stardepth = 0; /* depth for "**" expansion */
9353
9354 DIR *dirp;
9355 struct dirent *dp;
9356
9357 /* Expanding "**" may take a long time, check for CTRL-C. */
9358 if (stardepth > 0)
9359 {
9360 ui_breakcheck();
9361 if (got_int)
9362 return 0;
9363 }
9364
9365 /* make room for file name */
9366 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
9367 if (buf == NULL)
9368 return 0;
9369
9370 /*
9371 * Find the first part in the path name that contains a wildcard.
9372 * Copy it into "buf", including the preceding characters.
9373 */
9374 p = buf;
9375 s = buf;
9376 e = NULL;
9377 path_end = path;
9378 while (*path_end != NUL)
9379 {
9380 /* May ignore a wildcard that has a backslash before it; it will
9381 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
9382 if (path_end >= path + wildoff && rem_backslash(path_end))
9383 *p++ = *path_end++;
9384 else if (*path_end == '/')
9385 {
9386 if (e != NULL)
9387 break;
9388 s = p + 1;
9389 }
9390 else if (path_end >= path + wildoff
9391 && vim_strchr((char_u *)"*?[{~$", *path_end) != NULL)
9392 e = p;
9393#ifdef FEAT_MBYTE
9394 if (has_mbyte)
9395 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00009396 len = (*mb_ptr2len)(path_end);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009397 STRNCPY(p, path_end, len);
9398 p += len;
9399 path_end += len;
9400 }
9401 else
9402#endif
9403 *p++ = *path_end++;
9404 }
9405 e = p;
9406 *e = NUL;
9407
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009408 /* Now we have one wildcard component between "s" and "e". */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009409 /* Remove backslashes between "wildoff" and the start of the wildcard
9410 * component. */
9411 for (p = buf + wildoff; p < s; ++p)
9412 if (rem_backslash(p))
9413 {
Bram Moolenaar8c8de832008-06-24 22:58:06 +00009414 STRMOVE(p, p + 1);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009415 --e;
9416 --s;
9417 }
9418
9419 /* Check for "**" between "s" and "e". */
9420 for (p = s; p < e; ++p)
9421 if (p[0] == '*' && p[1] == '*')
9422 starstar = TRUE;
9423
9424 /* convert the file pattern to a regexp pattern */
9425 starts_with_dot = (*s == '.');
9426 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
9427 if (pat == NULL)
9428 {
9429 vim_free(buf);
9430 return 0;
9431 }
9432
9433 /* compile the regexp into a program */
Bram Moolenaarcc016f52005-12-10 20:23:46 +00009434#ifdef CASE_INSENSITIVE_FILENAME
Bram Moolenaar231334e2005-07-25 20:46:57 +00009435 regmatch.rm_ic = TRUE; /* Behave like Terminal.app */
9436#else
Bram Moolenaar94950a92010-12-02 16:01:29 +01009437 if (flags & EW_ICASE)
9438 regmatch.rm_ic = TRUE; /* 'wildignorecase' set */
9439 else
9440 regmatch.rm_ic = FALSE; /* Don't ignore case */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009441#endif
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009442 if (flags & (EW_NOERROR | EW_NOTWILD))
9443 ++emsg_silent;
Bram Moolenaar231334e2005-07-25 20:46:57 +00009444 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009445 if (flags & (EW_NOERROR | EW_NOTWILD))
9446 --emsg_silent;
Bram Moolenaar231334e2005-07-25 20:46:57 +00009447 vim_free(pat);
9448
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009449 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
Bram Moolenaar231334e2005-07-25 20:46:57 +00009450 {
9451 vim_free(buf);
9452 return 0;
9453 }
9454
9455 /* If "**" is by itself, this is the first time we encounter it and more
9456 * is following then find matches without any directory. */
9457 if (!didstar && stardepth < 100 && starstar && e - s == 2
9458 && *path_end == '/')
9459 {
9460 STRCPY(s, path_end + 1);
9461 ++stardepth;
9462 (void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
9463 --stardepth;
9464 }
9465
9466 /* open the directory for scanning */
9467 *s = NUL;
9468 dirp = opendir(*buf == NUL ? "." : (char *)buf);
9469
9470 /* Find all matching entries */
9471 if (dirp != NULL)
9472 {
9473 for (;;)
9474 {
9475 dp = readdir(dirp);
9476 if (dp == NULL)
9477 break;
9478 if ((dp->d_name[0] != '.' || starts_with_dot)
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009479 && ((regmatch.regprog != NULL && vim_regexec(&regmatch,
9480 (char_u *)dp->d_name, (colnr_T)0))
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009481 || ((flags & EW_NOTWILD)
9482 && fnamencmp(path + (s - buf), dp->d_name, e - s) == 0)))
Bram Moolenaar231334e2005-07-25 20:46:57 +00009483 {
9484 STRCPY(s, dp->d_name);
9485 len = STRLEN(buf);
9486
9487 if (starstar && stardepth < 100)
9488 {
9489 /* For "**" in the pattern first go deeper in the tree to
9490 * find matches. */
9491 STRCPY(buf + len, "/**");
9492 STRCPY(buf + len + 3, path_end);
9493 ++stardepth;
9494 (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
9495 --stardepth;
9496 }
9497
9498 STRCPY(buf + len, path_end);
9499 if (mch_has_exp_wildcard(path_end)) /* handle more wildcards */
9500 {
9501 /* need to expand another component of the path */
9502 /* remove backslashes for the remaining components only */
9503 (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
9504 }
9505 else
9506 {
9507 /* no more wildcards, check if there is a match */
9508 /* remove backslashes for the remaining components only */
9509 if (*path_end != NUL)
9510 backslash_halve(buf + len + 1);
9511 if (mch_getperm(buf) >= 0) /* add existing file */
9512 {
Bram Moolenaar95e9b492006-03-15 23:04:43 +00009513#ifdef MACOS_CONVERT
Bram Moolenaar231334e2005-07-25 20:46:57 +00009514 size_t precomp_len = STRLEN(buf)+1;
9515 char_u *precomp_buf =
9516 mac_precompose_path(buf, precomp_len, &precomp_len);
Bram Moolenaar95e9b492006-03-15 23:04:43 +00009517
Bram Moolenaar231334e2005-07-25 20:46:57 +00009518 if (precomp_buf)
9519 {
9520 mch_memmove(buf, precomp_buf, precomp_len);
9521 vim_free(precomp_buf);
9522 }
9523#endif
9524 addfile(gap, buf, flags);
9525 }
9526 }
9527 }
9528 }
9529
9530 closedir(dirp);
9531 }
9532
9533 vim_free(buf);
9534 vim_free(regmatch.regprog);
9535
9536 matches = gap->ga_len - start_len;
9537 if (matches > 0)
9538 qsort(((char_u **)gap->ga_data) + start_len, matches,
9539 sizeof(char_u *), pstrcmp);
9540 return matches;
9541}
9542#endif
9543
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009544#if defined(FEAT_SEARCHPATH)
9545static int find_previous_pathsep __ARGS((char_u *path, char_u **psep));
9546static int is_unique __ARGS((char_u *maybe_unique, garray_T *gap, int i));
Bram Moolenaar162bd912010-07-28 22:29:10 +02009547static void expand_path_option __ARGS((char_u *curdir, garray_T *gap));
9548static char_u *get_path_cutoff __ARGS((char_u *fname, garray_T *gap));
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009549static void uniquefy_paths __ARGS((garray_T *gap, char_u *pattern));
9550static int expand_in_path __ARGS((garray_T *gap, char_u *pattern, int flags));
9551
9552/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009553 * Moves "*psep" back to the previous path separator in "path".
9554 * Returns FAIL is "*psep" ends up at the beginning of "path".
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009555 */
9556 static int
9557find_previous_pathsep(path, psep)
9558 char_u *path;
9559 char_u **psep;
9560{
9561 /* skip the current separator */
9562 if (*psep > path && vim_ispathsep(**psep))
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009563 --*psep;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009564
9565 /* find the previous separator */
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009566 while (*psep > path)
9567 {
9568 if (vim_ispathsep(**psep))
9569 return OK;
9570 mb_ptr_back(path, *psep);
9571 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009572
9573 return FAIL;
9574}
9575
9576/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009577 * Returns TRUE if "maybe_unique" is unique wrt other_paths in "gap".
9578 * "maybe_unique" is the end portion of "((char_u **)gap->ga_data)[i]".
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009579 */
9580 static int
9581is_unique(maybe_unique, gap, i)
9582 char_u *maybe_unique;
9583 garray_T *gap;
9584 int i;
9585{
9586 int j;
9587 int candidate_len;
9588 int other_path_len;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009589 char_u **other_paths = (char_u **)gap->ga_data;
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009590 char_u *rival;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009591
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009592 for (j = 0; j < gap->ga_len; j++)
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009593 {
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009594 if (j == i)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009595 continue; /* don't compare it with itself */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009596
Bram Moolenaar624c7aa2010-07-16 20:38:52 +02009597 candidate_len = (int)STRLEN(maybe_unique);
9598 other_path_len = (int)STRLEN(other_paths[j]);
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009599 if (other_path_len < candidate_len)
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009600 continue; /* it's different when it's shorter */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009601
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009602 rival = other_paths[j] + other_path_len - candidate_len;
Bram Moolenaarda9836c2010-08-16 21:53:27 +02009603 if (fnamecmp(maybe_unique, rival) == 0
9604 && (rival == other_paths[j] || vim_ispathsep(*(rival - 1))))
Bram Moolenaar162bd912010-07-28 22:29:10 +02009605 return FALSE; /* match */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009606 }
9607
Bram Moolenaar162bd912010-07-28 22:29:10 +02009608 return TRUE; /* no match found */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009609}
9610
9611/*
Bram Moolenaar1a509df2010-08-01 17:59:57 +02009612 * Split the 'path' option into an array of strings in garray_T. Relative
Bram Moolenaar162bd912010-07-28 22:29:10 +02009613 * paths are expanded to their equivalent fullpath. This includes the "."
9614 * (relative to current buffer directory) and empty path (relative to current
9615 * directory) notations.
9616 *
9617 * TODO: handle upward search (;) and path limiter (**N) notations by
9618 * expanding each into their equivalent path(s).
9619 */
9620 static void
9621expand_path_option(curdir, gap)
9622 char_u *curdir;
9623 garray_T *gap;
9624{
9625 char_u *path_option = *curbuf->b_p_path == NUL
9626 ? p_path : curbuf->b_p_path;
9627 char_u *buf;
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009628 char_u *p;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009629 int len;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009630
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +02009631 if ((buf = alloc((int)MAXPATHL)) == NULL)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009632 return;
9633
9634 while (*path_option != NUL)
9635 {
9636 copy_option_part(&path_option, buf, MAXPATHL, " ,");
9637
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009638 if (buf[0] == '.' && (buf[1] == NUL || vim_ispathsep(buf[1])))
Bram Moolenaar162bd912010-07-28 22:29:10 +02009639 {
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009640 /* Relative to current buffer:
9641 * "/path/file" + "." -> "/path/"
9642 * "/path/file" + "./subdir" -> "/path/subdir" */
Bram Moolenaar162bd912010-07-28 22:29:10 +02009643 if (curbuf->b_ffname == NULL)
9644 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009645 p = gettail(curbuf->b_ffname);
9646 len = (int)(p - curbuf->b_ffname);
9647 if (len + (int)STRLEN(buf) >= MAXPATHL)
9648 continue;
9649 if (buf[1] == NUL)
9650 buf[len] = NUL;
9651 else
9652 STRMOVE(buf + len, buf + 2);
9653 mch_memmove(buf, curbuf->b_ffname, len);
9654 simplify_filename(buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009655 }
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009656 else if (buf[0] == NUL)
9657 /* relative to current directory */
Bram Moolenaar162bd912010-07-28 22:29:10 +02009658 STRCPY(buf, curdir);
Bram Moolenaar84f888a2010-08-05 21:40:16 +02009659 else if (path_with_url(buf))
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009660 /* URL can't be used here */
Bram Moolenaar84f888a2010-08-05 21:40:16 +02009661 continue;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009662 else if (!mch_isFullName(buf))
9663 {
9664 /* Expand relative path to their full path equivalent */
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009665 len = (int)STRLEN(curdir);
9666 if (len + (int)STRLEN(buf) + 3 > MAXPATHL)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009667 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009668 STRMOVE(buf + len + 1, buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009669 STRCPY(buf, curdir);
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009670 buf[len] = PATHSEP;
Bram Moolenaar57adda12010-08-03 22:11:29 +02009671 simplify_filename(buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009672 }
9673
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009674 if (ga_grow(gap, 1) == FAIL)
9675 break;
9676 p = vim_strsave(buf);
9677 if (p == NULL)
9678 break;
9679 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009680 }
9681
9682 vim_free(buf);
9683}
9684
9685/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009686 * Returns a pointer to the file or directory name in "fname" that matches the
9687 * longest path in "ga"p, or NULL if there is no match. For example:
Bram Moolenaar162bd912010-07-28 22:29:10 +02009688 *
9689 * path: /foo/bar/baz
9690 * fname: /foo/bar/baz/quux.txt
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009691 * returns: ^this
Bram Moolenaar162bd912010-07-28 22:29:10 +02009692 */
9693 static char_u *
9694get_path_cutoff(fname, gap)
9695 char_u *fname;
9696 garray_T *gap;
9697{
9698 int i;
9699 int maxlen = 0;
9700 char_u **path_part = (char_u **)gap->ga_data;
9701 char_u *cutoff = NULL;
9702
9703 for (i = 0; i < gap->ga_len; i++)
9704 {
9705 int j = 0;
9706
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009707 while ((fname[j] == path_part[i][j]
Bram Moolenaar2d7c47d2010-08-10 19:50:26 +02009708# if defined(MSWIN) || defined(MSDOS)
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009709 || (vim_ispathsep(fname[j]) && vim_ispathsep(path_part[i][j]))
9710#endif
9711 ) && fname[j] != NUL && path_part[i][j] != NUL)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009712 j++;
9713 if (j > maxlen)
9714 {
9715 maxlen = j;
9716 cutoff = &fname[j];
9717 }
9718 }
9719
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009720 /* skip to the file or directory name */
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009721 if (cutoff != NULL)
Bram Moolenaar31710262010-08-13 13:36:15 +02009722 while (vim_ispathsep(*cutoff))
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009723 mb_ptr_adv(cutoff);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009724
9725 return cutoff;
9726}
9727
9728/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009729 * Sorts, removes duplicates and modifies all the fullpath names in "gap" so
9730 * that they are unique with respect to each other while conserving the part
9731 * that matches the pattern. Beware, this is at least O(n^2) wrt "gap->ga_len".
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009732 */
9733 static void
9734uniquefy_paths(gap, pattern)
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +02009735 garray_T *gap;
9736 char_u *pattern;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009737{
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +02009738 int i;
9739 int len;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009740 char_u **fnames = (char_u **)gap->ga_data;
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009741 int sort_again = FALSE;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009742 char_u *pat;
9743 char_u *file_pattern;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009744 char_u *curdir;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009745 regmatch_T regmatch;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009746 garray_T path_ga;
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009747 char_u **in_curdir = NULL;
9748 char_u *short_name;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009749
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +02009750 remove_duplicates(gap);
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009751 ga_init2(&path_ga, (int)sizeof(char_u *), 1);
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009752
9753 /*
9754 * We need to prepend a '*' at the beginning of file_pattern so that the
9755 * regex matches anywhere in the path. FIXME: is this valid for all
Bram Moolenaarb31e4382010-07-24 16:01:56 +02009756 * possible patterns?
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009757 */
Bram Moolenaar624c7aa2010-07-16 20:38:52 +02009758 len = (int)STRLEN(pattern);
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009759 file_pattern = alloc(len + 2);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009760 if (file_pattern == NULL)
9761 return;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009762 file_pattern[0] = '*';
Bram Moolenaar162bd912010-07-28 22:29:10 +02009763 file_pattern[1] = NUL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009764 STRCAT(file_pattern, pattern);
9765 pat = file_pat_to_reg_pat(file_pattern, NULL, NULL, TRUE);
9766 vim_free(file_pattern);
Bram Moolenaarb31e4382010-07-24 16:01:56 +02009767 if (pat == NULL)
9768 return;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009769
Bram Moolenaarb31e4382010-07-24 16:01:56 +02009770 regmatch.rm_ic = TRUE; /* always ignore case */
9771 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
9772 vim_free(pat);
9773 if (regmatch.regprog == NULL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009774 return;
9775
Bram Moolenaar162bd912010-07-28 22:29:10 +02009776 if ((curdir = alloc((int)(MAXPATHL))) == NULL)
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009777 goto theend;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009778 mch_dirname(curdir, MAXPATHL);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009779 expand_path_option(curdir, &path_ga);
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009780
9781 in_curdir = (char_u **)alloc_clear(gap->ga_len * sizeof(char_u *));
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009782 if (in_curdir == NULL)
9783 goto theend;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009784
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009785 for (i = 0; i < gap->ga_len && !got_int; i++)
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009786 {
Bram Moolenaar162bd912010-07-28 22:29:10 +02009787 char_u *path = fnames[i];
9788 int is_in_curdir;
Bram Moolenaar31710262010-08-13 13:36:15 +02009789 char_u *dir_end = gettail_dir(path);
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009790 char_u *pathsep_p;
9791 char_u *path_cutoff;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009792
Bram Moolenaar624c7aa2010-07-16 20:38:52 +02009793 len = (int)STRLEN(path);
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009794 is_in_curdir = fnamencmp(curdir, path, dir_end - path) == 0
Bram Moolenaar162bd912010-07-28 22:29:10 +02009795 && curdir[dir_end - path] == NUL;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009796 if (is_in_curdir)
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009797 in_curdir[i] = vim_strsave(path);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009798
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009799 /* Shorten the filename while maintaining its uniqueness */
9800 path_cutoff = get_path_cutoff(path, &path_ga);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009801
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009802 /* we start at the end of the path */
9803 pathsep_p = path + len - 1;
9804
9805 while (find_previous_pathsep(path, &pathsep_p))
9806 if (vim_regexec(&regmatch, pathsep_p + 1, (colnr_T)0)
9807 && is_unique(pathsep_p + 1, gap, i)
9808 && path_cutoff != NULL && pathsep_p + 1 >= path_cutoff)
9809 {
9810 sort_again = TRUE;
9811 mch_memmove(path, pathsep_p + 1, STRLEN(pathsep_p));
9812 break;
9813 }
Bram Moolenaar9bc040c2010-08-11 22:05:57 +02009814
9815 if (mch_isFullName(path))
9816 {
9817 /*
9818 * Last resort: shorten relative to curdir if possible.
9819 * 'possible' means:
9820 * 1. It is under the current directory.
9821 * 2. The result is actually shorter than the original.
9822 *
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009823 * Before curdir After
9824 * /foo/bar/file.txt /foo/bar ./file.txt
9825 * c:\foo\bar\file.txt c:\foo\bar .\file.txt
9826 * /file.txt / /file.txt
9827 * c:\file.txt c:\ .\file.txt
Bram Moolenaar9bc040c2010-08-11 22:05:57 +02009828 */
9829 short_name = shorten_fname(path, curdir);
Bram Moolenaar31710262010-08-13 13:36:15 +02009830 if (short_name != NULL && short_name > path + 1
9831#if defined(MSWIN) || defined(MSDOS)
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009832 /* On windows,
Bram Moolenaar31710262010-08-13 13:36:15 +02009833 * shorten_fname("c:\a\a.txt", "c:\a\b")
Bram Moolenaar31710262010-08-13 13:36:15 +02009834 * returns "\a\a.txt", which is not really the short
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009835 * name, hence: */
Bram Moolenaar31710262010-08-13 13:36:15 +02009836 && !vim_ispathsep(*short_name)
9837#endif
9838 )
Bram Moolenaar9bc040c2010-08-11 22:05:57 +02009839 {
9840 STRCPY(path, ".");
9841 add_pathsep(path);
Bram Moolenaarcda000e2010-08-14 13:34:39 +02009842 STRMOVE(path + STRLEN(path), short_name);
Bram Moolenaar9bc040c2010-08-11 22:05:57 +02009843 }
9844 }
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009845 ui_breakcheck();
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009846 }
9847
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009848 /* Shorten filenames in /in/current/directory/{filename} */
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009849 for (i = 0; i < gap->ga_len && !got_int; i++)
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009850 {
9851 char_u *rel_path;
9852 char_u *path = in_curdir[i];
9853
9854 if (path == NULL)
9855 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009856
9857 /* If the {filename} is not unique, change it to ./{filename}.
9858 * Else reduce it to {filename} */
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009859 short_name = shorten_fname(path, curdir);
9860 if (short_name == NULL)
9861 short_name = path;
9862 if (is_unique(short_name, gap, i))
9863 {
9864 STRCPY(fnames[i], short_name);
9865 continue;
9866 }
9867
9868 rel_path = alloc((int)(STRLEN(short_name) + STRLEN(PATHSEPSTR) + 2));
9869 if (rel_path == NULL)
9870 goto theend;
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009871 STRCPY(rel_path, ".");
9872 add_pathsep(rel_path);
9873 STRCAT(rel_path, short_name);
9874
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009875 vim_free(fnames[i]);
9876 fnames[i] = rel_path;
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009877 sort_again = TRUE;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009878 ui_breakcheck();
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009879 }
9880
Bram Moolenaar162bd912010-07-28 22:29:10 +02009881theend:
9882 vim_free(curdir);
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009883 if (in_curdir != NULL)
9884 {
9885 for (i = 0; i < gap->ga_len; i++)
9886 vim_free(in_curdir[i]);
9887 vim_free(in_curdir);
9888 }
Bram Moolenaar162bd912010-07-28 22:29:10 +02009889 ga_clear_strings(&path_ga);
Bram Moolenaarb31e4382010-07-24 16:01:56 +02009890 vim_free(regmatch.regprog);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009891
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009892 if (sort_again)
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +02009893 remove_duplicates(gap);
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009894}
9895
9896/*
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +02009897 * Calls globpath() with 'path' values for the given pattern and stores the
9898 * result in "gap".
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009899 * Returns the total number of matches.
9900 */
9901 static int
9902expand_in_path(gap, pattern, flags)
9903 garray_T *gap;
9904 char_u *pattern;
9905 int flags; /* EW_* flags */
9906{
Bram Moolenaar162bd912010-07-28 22:29:10 +02009907 char_u *curdir;
9908 garray_T path_ga;
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009909 char_u *files = NULL;
9910 char_u *s; /* start */
9911 char_u *e; /* end */
9912 char_u *paths = NULL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009913
Bram Moolenaar7f0f6212010-08-03 22:21:00 +02009914 if ((curdir = alloc((unsigned)MAXPATHL)) == NULL)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009915 return 0;
9916 mch_dirname(curdir, MAXPATHL);
9917
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009918 ga_init2(&path_ga, (int)sizeof(char_u *), 1);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009919 expand_path_option(curdir, &path_ga);
9920 vim_free(curdir);
Bram Moolenaar006d2b02010-08-04 12:39:44 +02009921 if (path_ga.ga_len == 0)
9922 return 0;
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +02009923
9924 paths = ga_concat_strings(&path_ga);
9925 ga_clear_strings(&path_ga);
9926 if (paths == NULL)
Bram Moolenaar7f0f6212010-08-03 22:21:00 +02009927 return 0;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009928
Bram Moolenaar94950a92010-12-02 16:01:29 +01009929 files = globpath(paths, pattern, (flags & EW_ICASE) ? WILD_ICASE : 0);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009930 vim_free(paths);
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009931 if (files == NULL)
9932 return 0;
9933
9934 /* Copy each path in files into gap */
9935 s = e = files;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009936 while (*s != NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009937 {
Bram Moolenaar162bd912010-07-28 22:29:10 +02009938 while (*e != '\n' && *e != NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009939 e++;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009940 if (*e == NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009941 {
9942 addfile(gap, s, flags);
9943 break;
9944 }
9945 else
9946 {
9947 /* *e is '\n' */
Bram Moolenaar162bd912010-07-28 22:29:10 +02009948 *e = NUL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009949 addfile(gap, s, flags);
9950 e++;
9951 s = e;
9952 }
9953 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009954 vim_free(files);
9955
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009956 return gap->ga_len;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009957}
9958#endif
9959
Bram Moolenaar1587a1e2010-07-29 20:59:59 +02009960#if defined(FEAT_SEARCHPATH) || defined(FEAT_CMDL_COMPL) || defined(PROTO)
9961/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009962 * Sort "gap" and remove duplicate entries. "gap" is expected to contain a
9963 * list of file names in allocated memory.
Bram Moolenaar1587a1e2010-07-29 20:59:59 +02009964 */
9965 void
9966remove_duplicates(gap)
9967 garray_T *gap;
9968{
9969 int i;
9970 int j;
9971 char_u **fnames = (char_u **)gap->ga_data;
9972
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009973 sort_strings(fnames, gap->ga_len);
Bram Moolenaar1587a1e2010-07-29 20:59:59 +02009974 for (i = gap->ga_len - 1; i > 0; --i)
9975 if (fnamecmp(fnames[i - 1], fnames[i]) == 0)
9976 {
9977 vim_free(fnames[i]);
9978 for (j = i + 1; j < gap->ga_len; ++j)
9979 fnames[j - 1] = fnames[j];
9980 --gap->ga_len;
9981 }
9982}
9983#endif
9984
Bram Moolenaar071d4272004-06-13 20:20:40 +00009985/*
9986 * Generic wildcard expansion code.
9987 *
9988 * Characters in "pat" that should not be expanded must be preceded with a
9989 * backslash. E.g., "/path\ with\ spaces/my\*star*"
9990 *
9991 * Return FAIL when no single file was found. In this case "num_file" is not
9992 * set, and "file" may contain an error message.
9993 * Return OK when some files found. "num_file" is set to the number of
9994 * matches, "file" to the array of matches. Call FreeWild() later.
9995 */
9996 int
9997gen_expand_wildcards(num_pat, pat, num_file, file, flags)
9998 int num_pat; /* number of input patterns */
9999 char_u **pat; /* array of input patterns */
10000 int *num_file; /* resulting number of files */
10001 char_u ***file; /* array of resulting files */
10002 int flags; /* EW_* flags */
10003{
10004 int i;
10005 garray_T ga;
10006 char_u *p;
10007 static int recursive = FALSE;
10008 int add_pat;
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010009#if defined(FEAT_SEARCHPATH)
10010 int did_expand_in_path = FALSE;
10011#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000010012
10013 /*
10014 * expand_env() is called to expand things like "~user". If this fails,
10015 * it calls ExpandOne(), which brings us back here. In this case, always
10016 * call the machine specific expansion function, if possible. Otherwise,
10017 * return FAIL.
10018 */
10019 if (recursive)
10020#ifdef SPECIAL_WILDCHAR
10021 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
10022#else
10023 return FAIL;
10024#endif
10025
10026#ifdef SPECIAL_WILDCHAR
10027 /*
10028 * If there are any special wildcard characters which we cannot handle
10029 * here, call machine specific function for all the expansion. This
10030 * avoids starting the shell for each argument separately.
10031 * For `=expr` do use the internal function.
10032 */
10033 for (i = 0; i < num_pat; i++)
10034 {
10035 if (vim_strpbrk(pat[i], (char_u *)SPECIAL_WILDCHAR) != NULL
10036# ifdef VIM_BACKTICK
10037 && !(vim_backtick(pat[i]) && pat[i][1] == '=')
10038# endif
10039 )
10040 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
10041 }
10042#endif
10043
10044 recursive = TRUE;
10045
10046 /*
10047 * The matching file names are stored in a growarray. Init it empty.
10048 */
10049 ga_init2(&ga, (int)sizeof(char_u *), 30);
10050
10051 for (i = 0; i < num_pat; ++i)
10052 {
10053 add_pat = -1;
10054 p = pat[i];
10055
10056#ifdef VIM_BACKTICK
10057 if (vim_backtick(p))
10058 add_pat = expand_backtick(&ga, p, flags);
10059 else
10060#endif
10061 {
10062 /*
10063 * First expand environment variables, "~/" and "~user/".
10064 */
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010065 if (vim_strchr(p, '$') != NULL || *p == '~')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010066 {
Bram Moolenaar9f0545d2007-09-26 20:36:32 +000010067 p = expand_env_save_opt(p, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010068 if (p == NULL)
10069 p = pat[i];
10070#ifdef UNIX
10071 /*
10072 * On Unix, if expand_env() can't expand an environment
10073 * variable, use the shell to do that. Discard previously
10074 * found file names and start all over again.
10075 */
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010076 else if (vim_strchr(p, '$') != NULL || *p == '~')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010077 {
10078 vim_free(p);
Bram Moolenaar782027e2009-06-24 14:25:49 +000010079 ga_clear_strings(&ga);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010080 i = mch_expand_wildcards(num_pat, pat, num_file, file,
10081 flags);
10082 recursive = FALSE;
10083 return i;
10084 }
10085#endif
10086 }
10087
10088 /*
10089 * If there are wildcards: Expand file names and add each match to
10090 * the list. If there is no match, and EW_NOTFOUND is given, add
10091 * the pattern.
10092 * If there are no wildcards: Add the file name if it exists or
10093 * when EW_NOTFOUND is given.
10094 */
10095 if (mch_has_exp_wildcard(p))
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010096 {
10097#if defined(FEAT_SEARCHPATH)
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010098 if ((flags & EW_PATH)
10099 && !mch_isFullName(p)
10100 && !(p[0] == '.'
10101 && (vim_ispathsep(p[1])
10102 || (p[1] == '.' && vim_ispathsep(p[2]))))
10103 )
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010104 {
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010105 /* :find completion where 'path' is used.
10106 * Recursiveness is OK here. */
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010107 recursive = FALSE;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010108 add_pat = expand_in_path(&ga, p, flags);
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010109 recursive = TRUE;
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010110 did_expand_in_path = TRUE;
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010111 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010112 else
10113#endif
10114 add_pat = mch_expandpath(&ga, p, flags);
10115 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010116 }
10117
10118 if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
10119 {
10120 char_u *t = backslash_halve_save(p);
10121
10122#if defined(MACOS_CLASSIC)
10123 slash_to_colon(t);
10124#endif
10125 /* When EW_NOTFOUND is used, always add files and dirs. Makes
10126 * "vim c:/" work. */
10127 if (flags & EW_NOTFOUND)
10128 addfile(&ga, t, flags | EW_DIR | EW_FILE);
10129 else if (mch_getperm(t) >= 0)
10130 addfile(&ga, t, flags);
10131 vim_free(t);
10132 }
10133
Bram Moolenaarb28ebbc2010-07-14 16:59:57 +020010134#if defined(FEAT_SEARCHPATH)
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010135 if (did_expand_in_path && ga.ga_len > 0 && (flags & EW_PATH))
Bram Moolenaarb28ebbc2010-07-14 16:59:57 +020010136 uniquefy_paths(&ga, p);
10137#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000010138 if (p != pat[i])
10139 vim_free(p);
10140 }
10141
10142 *num_file = ga.ga_len;
10143 *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data : (char_u **)"";
10144
10145 recursive = FALSE;
10146
10147 return (ga.ga_data != NULL) ? OK : FAIL;
10148}
10149
10150# ifdef VIM_BACKTICK
10151
10152/*
10153 * Return TRUE if we can expand this backtick thing here.
10154 */
10155 static int
10156vim_backtick(p)
10157 char_u *p;
10158{
10159 return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
10160}
10161
10162/*
10163 * Expand an item in `backticks` by executing it as a command.
10164 * Currently only works when pat[] starts and ends with a `.
10165 * Returns number of file names found.
10166 */
10167 static int
10168expand_backtick(gap, pat, flags)
10169 garray_T *gap;
10170 char_u *pat;
10171 int flags; /* EW_* flags */
10172{
10173 char_u *p;
10174 char_u *cmd;
10175 char_u *buffer;
10176 int cnt = 0;
10177 int i;
10178
10179 /* Create the command: lop off the backticks. */
10180 cmd = vim_strnsave(pat + 1, (int)STRLEN(pat) - 2);
10181 if (cmd == NULL)
10182 return 0;
10183
10184#ifdef FEAT_EVAL
10185 if (*cmd == '=') /* `={expr}`: Expand expression */
Bram Moolenaar362e1a32006-03-06 23:29:24 +000010186 buffer = eval_to_string(cmd + 1, &p, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010187 else
10188#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010189 buffer = get_cmd_output(cmd, NULL,
10190 (flags & EW_SILENT) ? SHELL_SILENT : 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010191 vim_free(cmd);
10192 if (buffer == NULL)
10193 return 0;
10194
10195 cmd = buffer;
10196 while (*cmd != NUL)
10197 {
10198 cmd = skipwhite(cmd); /* skip over white space */
10199 p = cmd;
10200 while (*p != NUL && *p != '\r' && *p != '\n') /* skip over entry */
10201 ++p;
10202 /* add an entry if it is not empty */
10203 if (p > cmd)
10204 {
10205 i = *p;
10206 *p = NUL;
10207 addfile(gap, cmd, flags);
10208 *p = i;
10209 ++cnt;
10210 }
10211 cmd = p;
10212 while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
10213 ++cmd;
10214 }
10215
10216 vim_free(buffer);
10217 return cnt;
10218}
10219# endif /* VIM_BACKTICK */
10220
10221/*
10222 * Add a file to a file list. Accepted flags:
10223 * EW_DIR add directories
10224 * EW_FILE add files
Bram Moolenaar1f35bf92006-03-07 22:38:47 +000010225 * EW_EXEC add executable files
Bram Moolenaar071d4272004-06-13 20:20:40 +000010226 * EW_NOTFOUND add even when it doesn't exist
10227 * EW_ADDSLASH add slash after directory name
10228 */
10229 void
10230addfile(gap, f, flags)
10231 garray_T *gap;
10232 char_u *f; /* filename */
10233 int flags;
10234{
10235 char_u *p;
10236 int isdir;
10237
10238 /* if the file/dir doesn't exist, may not add it */
10239 if (!(flags & EW_NOTFOUND) && mch_getperm(f) < 0)
10240 return;
10241
10242#ifdef FNAME_ILLEGAL
10243 /* if the file/dir contains illegal characters, don't add it */
10244 if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
10245 return;
10246#endif
10247
10248 isdir = mch_isdir(f);
10249 if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
10250 return;
10251
Bram Moolenaar1f35bf92006-03-07 22:38:47 +000010252 /* If the file isn't executable, may not add it. Do accept directories. */
10253 if (!isdir && (flags & EW_EXEC) && !mch_can_exe(f))
10254 return;
10255
Bram Moolenaar071d4272004-06-13 20:20:40 +000010256 /* Make room for another item in the file list. */
10257 if (ga_grow(gap, 1) == FAIL)
10258 return;
10259
10260 p = alloc((unsigned)(STRLEN(f) + 1 + isdir));
10261 if (p == NULL)
10262 return;
10263
10264 STRCPY(p, f);
10265#ifdef BACKSLASH_IN_FILENAME
10266 slash_adjust(p);
10267#endif
10268 /*
10269 * Append a slash or backslash after directory names if none is present.
10270 */
10271#ifndef DONT_ADD_PATHSEP_TO_DIR
10272 if (isdir && (flags & EW_ADDSLASH))
10273 add_pathsep(p);
10274#endif
10275 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010276}
10277#endif /* !NO_EXPANDPATH */
10278
10279#if defined(VIM_BACKTICK) || defined(FEAT_EVAL) || defined(PROTO)
10280
10281#ifndef SEEK_SET
10282# define SEEK_SET 0
10283#endif
10284#ifndef SEEK_END
10285# define SEEK_END 2
10286#endif
10287
10288/*
10289 * Get the stdout of an external command.
10290 * Returns an allocated string, or NULL for error.
10291 */
10292 char_u *
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010293get_cmd_output(cmd, infile, flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010294 char_u *cmd;
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010295 char_u *infile; /* optional input file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010296 int flags; /* can be SHELL_SILENT */
10297{
10298 char_u *tempname;
10299 char_u *command;
10300 char_u *buffer = NULL;
10301 int len;
10302 int i = 0;
10303 FILE *fd;
10304
10305 if (check_restricted() || check_secure())
10306 return NULL;
10307
10308 /* get a name for the temp file */
10309 if ((tempname = vim_tempname('o')) == NULL)
10310 {
10311 EMSG(_(e_notmp));
10312 return NULL;
10313 }
10314
10315 /* Add the redirection stuff */
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010316 command = make_filter_cmd(cmd, infile, tempname);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010317 if (command == NULL)
10318 goto done;
10319
10320 /*
10321 * Call the shell to execute the command (errors are ignored).
10322 * Don't check timestamps here.
10323 */
10324 ++no_check_timestamps;
10325 call_shell(command, SHELL_DOOUT | SHELL_EXPAND | flags);
10326 --no_check_timestamps;
10327
10328 vim_free(command);
10329
10330 /*
10331 * read the names from the file into memory
10332 */
10333# ifdef VMS
Bram Moolenaar25394022007-05-10 19:06:20 +000010334 /* created temporary file is not always readable as binary */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010335 fd = mch_fopen((char *)tempname, "r");
10336# else
10337 fd = mch_fopen((char *)tempname, READBIN);
10338# endif
10339
10340 if (fd == NULL)
10341 {
10342 EMSG2(_(e_notopen), tempname);
10343 goto done;
10344 }
10345
10346 fseek(fd, 0L, SEEK_END);
10347 len = ftell(fd); /* get size of temp file */
10348 fseek(fd, 0L, SEEK_SET);
10349
10350 buffer = alloc(len + 1);
10351 if (buffer != NULL)
10352 i = (int)fread((char *)buffer, (size_t)1, (size_t)len, fd);
10353 fclose(fd);
10354 mch_remove(tempname);
10355 if (buffer == NULL)
10356 goto done;
10357#ifdef VMS
10358 len = i; /* VMS doesn't give us what we asked for... */
10359#endif
10360 if (i != len)
10361 {
10362 EMSG2(_(e_notread), tempname);
10363 vim_free(buffer);
10364 buffer = NULL;
10365 }
10366 else
Bram Moolenaar162bd912010-07-28 22:29:10 +020010367 buffer[len] = NUL; /* make sure the buffer is terminated */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010368
10369done:
10370 vim_free(tempname);
10371 return buffer;
10372}
10373#endif
10374
10375/*
10376 * Free the list of files returned by expand_wildcards() or other expansion
10377 * functions.
10378 */
10379 void
10380FreeWild(count, files)
10381 int count;
10382 char_u **files;
10383{
Bram Moolenaarfc1421e2006-04-20 22:17:20 +000010384 if (count <= 0 || files == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010385 return;
10386#if defined(__EMX__) && defined(__ALWAYS_HAS_TRAILING_NULL_POINTER) /* XXX */
10387 /*
10388 * Is this still OK for when other functions than expand_wildcards() have
10389 * been used???
10390 */
10391 _fnexplodefree((char **)files);
10392#else
10393 while (count--)
10394 vim_free(files[count]);
10395 vim_free(files);
10396#endif
10397}
10398
10399/*
Bram Moolenaara9dc3752010-07-11 20:46:53 +020010400 * Return TRUE when need to go to Insert mode because of 'insertmode'.
Bram Moolenaar071d4272004-06-13 20:20:40 +000010401 * Don't do this when still processing a command or a mapping.
10402 * Don't do this when inside a ":normal" command.
10403 */
10404 int
10405goto_im()
10406{
10407 return (p_im && stuff_empty() && typebuf_typed());
10408}