blob: 34359a0b0d5505defd55e0d823c1b5ed4799bdea [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;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004136 }
4137 else
4138 {
4139 vim_setenv((char_u *)"VIM", p);
4140 didset_vim = TRUE;
4141 }
4142 }
4143 return p;
4144}
4145
4146/*
4147 * Check if the directory "vimdir/<version>" or "vimdir/runtime" exists.
4148 * Return NULL if not, return its name in allocated memory otherwise.
4149 */
4150 static char_u *
4151vim_version_dir(vimdir)
4152 char_u *vimdir;
4153{
4154 char_u *p;
4155
4156 if (vimdir == NULL || *vimdir == NUL)
4157 return NULL;
4158 p = concat_fnames(vimdir, (char_u *)VIM_VERSION_NODOT, TRUE);
4159 if (p != NULL && mch_isdir(p))
4160 return p;
4161 vim_free(p);
4162 p = concat_fnames(vimdir, (char_u *)RUNTIME_DIRNAME, TRUE);
4163 if (p != NULL && mch_isdir(p))
4164 return p;
4165 vim_free(p);
4166 return NULL;
4167}
4168
4169/*
4170 * If the string between "p" and "pend" ends in "name/", return "pend" minus
4171 * the length of "name/". Otherwise return "pend".
4172 */
4173 static char_u *
4174remove_tail(p, pend, name)
4175 char_u *p;
4176 char_u *pend;
4177 char_u *name;
4178{
4179 int len = (int)STRLEN(name) + 1;
4180 char_u *newend = pend - len;
4181
4182 if (newend >= p
4183 && fnamencmp(newend, name, len - 1) == 0
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004184 && (newend == p || after_pathsep(p, newend)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004185 return newend;
4186 return pend;
4187}
4188
Bram Moolenaar071d4272004-06-13 20:20:40 +00004189/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004190 * Our portable version of setenv.
4191 */
4192 void
4193vim_setenv(name, val)
4194 char_u *name;
4195 char_u *val;
4196{
4197#ifdef HAVE_SETENV
4198 mch_setenv((char *)name, (char *)val, 1);
4199#else
4200 char_u *envbuf;
4201
4202 /*
4203 * Putenv does not copy the string, it has to remain
4204 * valid. The allocated memory will never be freed.
4205 */
4206 envbuf = alloc((unsigned)(STRLEN(name) + STRLEN(val) + 2));
4207 if (envbuf != NULL)
4208 {
4209 sprintf((char *)envbuf, "%s=%s", name, val);
4210 putenv((char *)envbuf);
4211 }
4212#endif
Bram Moolenaar011a34d2012-02-29 13:49:09 +01004213#ifdef FEAT_GETTEXT
4214 /*
4215 * When setting $VIMRUNTIME adjust the directory to find message
4216 * translations to $VIMRUNTIME/lang.
4217 */
4218 if (*val != NUL && STRICMP(name, "VIMRUNTIME") == 0)
4219 {
4220 char_u *buf = concat_str(val, (char_u *)"/lang");
4221
4222 if (buf != NULL)
4223 {
4224 bindtextdomain(VIMPACKAGE, (char *)buf);
4225 vim_free(buf);
4226 }
4227 }
4228#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004229}
4230
4231#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
4232/*
4233 * Function given to ExpandGeneric() to obtain an environment variable name.
4234 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004235 char_u *
4236get_env_name(xp, idx)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00004237 expand_T *xp UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004238 int idx;
4239{
4240# if defined(AMIGA) || defined(__MRC__) || defined(__SC__)
4241 /*
4242 * No environ[] on the Amiga and on the Mac (using MPW).
4243 */
4244 return NULL;
4245# else
4246# ifndef __WIN32__
4247 /* Borland C++ 5.2 has this in a header file. */
4248 extern char **environ;
4249# endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00004250# define ENVNAMELEN 100
4251 static char_u name[ENVNAMELEN];
Bram Moolenaar071d4272004-06-13 20:20:40 +00004252 char_u *str;
4253 int n;
4254
4255 str = (char_u *)environ[idx];
4256 if (str == NULL)
4257 return NULL;
4258
Bram Moolenaar21cf8232004-07-16 20:18:37 +00004259 for (n = 0; n < ENVNAMELEN - 1; ++n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004260 {
4261 if (str[n] == '=' || str[n] == NUL)
4262 break;
4263 name[n] = str[n];
4264 }
4265 name[n] = NUL;
4266 return name;
4267# endif
4268}
4269#endif
4270
4271/*
4272 * Replace home directory by "~" in each space or comma separated file name in
4273 * 'src'.
4274 * If anything fails (except when out of space) dst equals src.
4275 */
4276 void
4277home_replace(buf, src, dst, dstlen, one)
4278 buf_T *buf; /* when not NULL, check for help files */
4279 char_u *src; /* input file name */
4280 char_u *dst; /* where to put the result */
4281 int dstlen; /* maximum length of the result */
4282 int one; /* if TRUE, only replace one file name, include
4283 spaces and commas in the file name. */
4284{
4285 size_t dirlen = 0, envlen = 0;
4286 size_t len;
4287 char_u *homedir_env;
4288 char_u *p;
4289
4290 if (src == NULL)
4291 {
4292 *dst = NUL;
4293 return;
4294 }
4295
4296 /*
4297 * If the file is a help file, remove the path completely.
4298 */
4299 if (buf != NULL && buf->b_help)
4300 {
4301 STRCPY(dst, gettail(src));
4302 return;
4303 }
4304
4305 /*
4306 * We check both the value of the $HOME environment variable and the
4307 * "real" home directory.
4308 */
4309 if (homedir != NULL)
4310 dirlen = STRLEN(homedir);
4311
4312#ifdef VMS
4313 homedir_env = mch_getenv((char_u *)"SYS$LOGIN");
4314#else
4315 homedir_env = mch_getenv((char_u *)"HOME");
4316#endif
4317
4318 if (homedir_env != NULL && *homedir_env == NUL)
4319 homedir_env = NULL;
4320 if (homedir_env != NULL)
4321 envlen = STRLEN(homedir_env);
4322
4323 if (!one)
4324 src = skipwhite(src);
4325 while (*src && dstlen > 0)
4326 {
4327 /*
4328 * Here we are at the beginning of a file name.
4329 * First, check to see if the beginning of the file name matches
4330 * $HOME or the "real" home directory. Check that there is a '/'
4331 * after the match (so that if e.g. the file is "/home/pieter/bla",
4332 * and the home directory is "/home/piet", the file does not end up
4333 * as "~er/bla" (which would seem to indicate the file "bla" in user
4334 * er's home directory)).
4335 */
4336 p = homedir;
4337 len = dirlen;
4338 for (;;)
4339 {
4340 if ( len
4341 && fnamencmp(src, p, len) == 0
4342 && (vim_ispathsep(src[len])
4343 || (!one && (src[len] == ',' || src[len] == ' '))
4344 || src[len] == NUL))
4345 {
4346 src += len;
4347 if (--dstlen > 0)
4348 *dst++ = '~';
4349
4350 /*
4351 * If it's just the home directory, add "/".
4352 */
4353 if (!vim_ispathsep(src[0]) && --dstlen > 0)
4354 *dst++ = '/';
4355 break;
4356 }
4357 if (p == homedir_env)
4358 break;
4359 p = homedir_env;
4360 len = envlen;
4361 }
4362
4363 /* if (!one) skip to separator: space or comma */
4364 while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
4365 *dst++ = *src++;
4366 /* skip separator */
4367 while ((*src == ' ' || *src == ',') && --dstlen > 0)
4368 *dst++ = *src++;
4369 }
4370 /* if (dstlen == 0) out of space, what to do??? */
4371
4372 *dst = NUL;
4373}
4374
4375/*
4376 * Like home_replace, store the replaced string in allocated memory.
4377 * When something fails, NULL is returned.
4378 */
4379 char_u *
4380home_replace_save(buf, src)
4381 buf_T *buf; /* when not NULL, check for help files */
4382 char_u *src; /* input file name */
4383{
4384 char_u *dst;
4385 unsigned len;
4386
4387 len = 3; /* space for "~/" and trailing NUL */
4388 if (src != NULL) /* just in case */
4389 len += (unsigned)STRLEN(src);
4390 dst = alloc(len);
4391 if (dst != NULL)
4392 home_replace(buf, src, dst, len, TRUE);
4393 return dst;
4394}
4395
4396/*
4397 * Compare two file names and return:
4398 * FPC_SAME if they both exist and are the same file.
4399 * FPC_SAMEX if they both don't exist and have the same file name.
4400 * FPC_DIFF if they both exist and are different files.
4401 * FPC_NOTX if they both don't exist.
4402 * FPC_DIFFX if one of them doesn't exist.
4403 * For the first name environment variables are expanded
4404 */
4405 int
4406fullpathcmp(s1, s2, checkname)
4407 char_u *s1, *s2;
4408 int checkname; /* when both don't exist, check file names */
4409{
4410#ifdef UNIX
4411 char_u exp1[MAXPATHL];
4412 char_u full1[MAXPATHL];
4413 char_u full2[MAXPATHL];
4414 struct stat st1, st2;
4415 int r1, r2;
4416
4417 expand_env(s1, exp1, MAXPATHL);
4418 r1 = mch_stat((char *)exp1, &st1);
4419 r2 = mch_stat((char *)s2, &st2);
4420 if (r1 != 0 && r2 != 0)
4421 {
4422 /* if mch_stat() doesn't work, may compare the names */
4423 if (checkname)
4424 {
4425 if (fnamecmp(exp1, s2) == 0)
4426 return FPC_SAMEX;
4427 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4428 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4429 if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
4430 return FPC_SAMEX;
4431 }
4432 return FPC_NOTX;
4433 }
4434 if (r1 != 0 || r2 != 0)
4435 return FPC_DIFFX;
4436 if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
4437 return FPC_SAME;
4438 return FPC_DIFF;
4439#else
4440 char_u *exp1; /* expanded s1 */
4441 char_u *full1; /* full path of s1 */
4442 char_u *full2; /* full path of s2 */
4443 int retval = FPC_DIFF;
4444 int r1, r2;
4445
4446 /* allocate one buffer to store three paths (alloc()/free() is slow!) */
4447 if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
4448 {
4449 full1 = exp1 + MAXPATHL;
4450 full2 = full1 + MAXPATHL;
4451
4452 expand_env(s1, exp1, MAXPATHL);
4453 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4454 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4455
4456 /* If vim_FullName() fails, the file probably doesn't exist. */
4457 if (r1 != OK && r2 != OK)
4458 {
4459 if (checkname && fnamecmp(exp1, s2) == 0)
4460 retval = FPC_SAMEX;
4461 else
4462 retval = FPC_NOTX;
4463 }
4464 else if (r1 != OK || r2 != OK)
4465 retval = FPC_DIFFX;
4466 else if (fnamecmp(full1, full2))
4467 retval = FPC_DIFF;
4468 else
4469 retval = FPC_SAME;
4470 vim_free(exp1);
4471 }
4472 return retval;
4473#endif
4474}
4475
4476/*
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004477 * Get the tail of a path: the file name.
Bram Moolenaar31710262010-08-13 13:36:15 +02004478 * When the path ends in a path separator the tail is the NUL after it.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004479 * Fail safe: never returns NULL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004480 */
4481 char_u *
4482gettail(fname)
4483 char_u *fname;
4484{
4485 char_u *p1, *p2;
4486
4487 if (fname == NULL)
4488 return (char_u *)"";
4489 for (p1 = p2 = fname; *p2; ) /* find last part of path */
4490 {
4491 if (vim_ispathsep(*p2))
4492 p1 = p2 + 1;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004493 mb_ptr_adv(p2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004494 }
4495 return p1;
4496}
4497
Bram Moolenaar31710262010-08-13 13:36:15 +02004498#if defined(FEAT_SEARCHPATH)
4499static char_u *gettail_dir __ARGS((char_u *fname));
4500
4501/*
4502 * Return the end of the directory name, on the first path
4503 * separator:
4504 * "/path/file", "/path/dir/", "/path//dir", "/file"
4505 * ^ ^ ^ ^
4506 */
4507 static char_u *
4508gettail_dir(fname)
4509 char_u *fname;
4510{
4511 char_u *dir_end = fname;
4512 char_u *next_dir_end = fname;
4513 int look_for_sep = TRUE;
4514 char_u *p;
4515
4516 for (p = fname; *p != NUL; )
4517 {
4518 if (vim_ispathsep(*p))
4519 {
4520 if (look_for_sep)
4521 {
4522 next_dir_end = p;
4523 look_for_sep = FALSE;
4524 }
4525 }
4526 else
4527 {
4528 if (!look_for_sep)
4529 dir_end = next_dir_end;
4530 look_for_sep = TRUE;
4531 }
4532 mb_ptr_adv(p);
4533 }
4534 return dir_end;
4535}
4536#endif
4537
Bram Moolenaar071d4272004-06-13 20:20:40 +00004538/*
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004539 * Get pointer to tail of "fname", including path separators. Putting a NUL
4540 * here leaves the directory name. Takes care of "c:/" and "//".
4541 * Always returns a valid pointer.
4542 */
4543 char_u *
4544gettail_sep(fname)
4545 char_u *fname;
4546{
4547 char_u *p;
4548 char_u *t;
4549
4550 p = get_past_head(fname); /* don't remove the '/' from "c:/file" */
4551 t = gettail(fname);
4552 while (t > p && after_pathsep(fname, t))
4553 --t;
4554#ifdef VMS
4555 /* path separator is part of the path */
4556 ++t;
4557#endif
4558 return t;
4559}
4560
4561/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004562 * get the next path component (just after the next path separator).
4563 */
4564 char_u *
4565getnextcomp(fname)
4566 char_u *fname;
4567{
4568 while (*fname && !vim_ispathsep(*fname))
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004569 mb_ptr_adv(fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004570 if (*fname)
4571 ++fname;
4572 return fname;
4573}
4574
Bram Moolenaar071d4272004-06-13 20:20:40 +00004575/*
4576 * Get a pointer to one character past the head of a path name.
4577 * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
4578 * If there is no head, path is returned.
4579 */
4580 char_u *
4581get_past_head(path)
4582 char_u *path;
4583{
4584 char_u *retval;
4585
4586#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
4587 /* may skip "c:" */
4588 if (isalpha(path[0]) && path[1] == ':')
4589 retval = path + 2;
4590 else
4591 retval = path;
4592#else
4593# if defined(AMIGA)
4594 /* may skip "label:" */
4595 retval = vim_strchr(path, ':');
4596 if (retval == NULL)
4597 retval = path;
4598# else /* Unix */
4599 retval = path;
4600# endif
4601#endif
4602
4603 while (vim_ispathsep(*retval))
4604 ++retval;
4605
4606 return retval;
4607}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004608
4609/*
4610 * return TRUE if 'c' is a path separator.
4611 */
4612 int
4613vim_ispathsep(c)
4614 int c;
4615{
Bram Moolenaare60acc12011-05-10 16:41:25 +02004616#ifdef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00004617 return (c == '/'); /* UNIX has ':' inside file names */
Bram Moolenaare60acc12011-05-10 16:41:25 +02004618#else
4619# ifdef BACKSLASH_IN_FILENAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00004620 return (c == ':' || c == '/' || c == '\\');
Bram Moolenaare60acc12011-05-10 16:41:25 +02004621# else
4622# ifdef VMS
Bram Moolenaar071d4272004-06-13 20:20:40 +00004623 /* server"user passwd"::device:[full.path.name]fname.extension;version" */
4624 return (c == ':' || c == '[' || c == ']' || c == '/'
4625 || c == '<' || c == '>' || c == '"' );
Bram Moolenaare60acc12011-05-10 16:41:25 +02004626# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004627 return (c == ':' || c == '/');
Bram Moolenaare60acc12011-05-10 16:41:25 +02004628# endif /* VMS */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004629# endif
Bram Moolenaare60acc12011-05-10 16:41:25 +02004630#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004631}
4632
4633#if defined(FEAT_SEARCHPATH) || defined(PROTO)
4634/*
4635 * return TRUE if 'c' is a path list separator.
4636 */
4637 int
4638vim_ispathlistsep(c)
4639 int c;
4640{
4641#ifdef UNIX
4642 return (c == ':');
4643#else
Bram Moolenaar25394022007-05-10 19:06:20 +00004644 return (c == ';'); /* might not be right for every system... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004645#endif
4646}
4647#endif
4648
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004649#if defined(FEAT_GUI_TABLINE) || defined(FEAT_WINDOWS) \
4650 || defined(FEAT_EVAL) || defined(PROTO)
4651/*
4652 * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
4653 * It's done in-place.
4654 */
4655 void
4656shorten_dir(str)
4657 char_u *str;
4658{
4659 char_u *tail, *s, *d;
4660 int skip = FALSE;
4661
4662 tail = gettail(str);
4663 d = str;
4664 for (s = str; ; ++s)
4665 {
4666 if (s >= tail) /* copy the whole tail */
4667 {
4668 *d++ = *s;
4669 if (*s == NUL)
4670 break;
4671 }
4672 else if (vim_ispathsep(*s)) /* copy '/' and next char */
4673 {
4674 *d++ = *s;
4675 skip = FALSE;
4676 }
4677 else if (!skip)
4678 {
4679 *d++ = *s; /* copy next char */
4680 if (*s != '~' && *s != '.') /* and leading "~" and "." */
4681 skip = TRUE;
4682# ifdef FEAT_MBYTE
4683 if (has_mbyte)
4684 {
4685 int l = mb_ptr2len(s);
4686
4687 while (--l > 0)
Bram Moolenaarb6baca52006-08-15 20:24:14 +00004688 *d++ = *++s;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004689 }
4690# endif
4691 }
4692 }
4693}
4694#endif
4695
Bram Moolenaar900b4d72005-12-12 22:05:50 +00004696/*
4697 * Return TRUE if the directory of "fname" exists, FALSE otherwise.
4698 * Also returns TRUE if there is no directory name.
4699 * "fname" must be writable!.
4700 */
4701 int
4702dir_of_file_exists(fname)
4703 char_u *fname;
4704{
4705 char_u *p;
4706 int c;
4707 int retval;
4708
4709 p = gettail_sep(fname);
4710 if (p == fname)
4711 return TRUE;
4712 c = *p;
4713 *p = NUL;
4714 retval = mch_isdir(fname);
4715 *p = c;
4716 return retval;
4717}
4718
Bram Moolenaar071d4272004-06-13 20:20:40 +00004719#if (defined(CASE_INSENSITIVE_FILENAME) && defined(BACKSLASH_IN_FILENAME)) \
4720 || defined(PROTO)
4721/*
4722 * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally.
4723 */
4724 int
4725vim_fnamecmp(x, y)
4726 char_u *x, *y;
4727{
4728 return vim_fnamencmp(x, y, MAXPATHL);
4729}
4730
4731 int
4732vim_fnamencmp(x, y, len)
4733 char_u *x, *y;
4734 size_t len;
4735{
4736 while (len > 0 && *x && *y)
4737 {
4738 if (TOLOWER_LOC(*x) != TOLOWER_LOC(*y)
4739 && !(*x == '/' && *y == '\\')
4740 && !(*x == '\\' && *y == '/'))
4741 break;
4742 ++x;
4743 ++y;
4744 --len;
4745 }
4746 if (len == 0)
4747 return 0;
4748 return (*x - *y);
4749}
4750#endif
4751
4752/*
4753 * Concatenate file names fname1 and fname2 into allocated memory.
Bram Moolenaar25394022007-05-10 19:06:20 +00004754 * Only add a '/' or '\\' when 'sep' is TRUE and it is necessary.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004755 */
4756 char_u *
4757concat_fnames(fname1, fname2, sep)
4758 char_u *fname1;
4759 char_u *fname2;
4760 int sep;
4761{
4762 char_u *dest;
4763
4764 dest = alloc((unsigned)(STRLEN(fname1) + STRLEN(fname2) + 3));
4765 if (dest != NULL)
4766 {
4767 STRCPY(dest, fname1);
4768 if (sep)
4769 add_pathsep(dest);
4770 STRCAT(dest, fname2);
4771 }
4772 return dest;
4773}
4774
Bram Moolenaard6754642005-01-17 22:18:45 +00004775/*
4776 * Concatenate two strings and return the result in allocated memory.
4777 * Returns NULL when out of memory.
4778 */
4779 char_u *
4780concat_str(str1, str2)
4781 char_u *str1;
4782 char_u *str2;
4783{
4784 char_u *dest;
4785 size_t l = STRLEN(str1);
4786
4787 dest = alloc((unsigned)(l + STRLEN(str2) + 1L));
4788 if (dest != NULL)
4789 {
4790 STRCPY(dest, str1);
4791 STRCPY(dest + l, str2);
4792 }
4793 return dest;
4794}
Bram Moolenaard6754642005-01-17 22:18:45 +00004795
Bram Moolenaar071d4272004-06-13 20:20:40 +00004796/*
4797 * Add a path separator to a file name, unless it already ends in a path
4798 * separator.
4799 */
4800 void
4801add_pathsep(p)
4802 char_u *p;
4803{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004804 if (*p != NUL && !after_pathsep(p, p + STRLEN(p)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004805 STRCAT(p, PATHSEPSTR);
4806}
4807
4808/*
4809 * FullName_save - Make an allocated copy of a full file name.
4810 * Returns NULL when out of memory.
4811 */
4812 char_u *
4813FullName_save(fname, force)
4814 char_u *fname;
4815 int force; /* force expansion, even when it already looks
4816 like a full path name */
4817{
4818 char_u *buf;
4819 char_u *new_fname = NULL;
4820
4821 if (fname == NULL)
4822 return NULL;
4823
4824 buf = alloc((unsigned)MAXPATHL);
4825 if (buf != NULL)
4826 {
4827 if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
4828 new_fname = vim_strsave(buf);
4829 else
4830 new_fname = vim_strsave(fname);
4831 vim_free(buf);
4832 }
4833 return new_fname;
4834}
4835
4836#if defined(FEAT_CINDENT) || defined(FEAT_SYN_HL)
4837
4838static char_u *skip_string __ARGS((char_u *p));
4839
4840/*
4841 * Find the start of a comment, not knowing if we are in a comment right now.
4842 * Search starts at w_cursor.lnum and goes backwards.
4843 */
4844 pos_T *
4845find_start_comment(ind_maxcomment) /* XXX */
4846 int ind_maxcomment;
4847{
4848 pos_T *pos;
4849 char_u *line;
4850 char_u *p;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00004851 int cur_maxcomment = ind_maxcomment;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004852
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00004853 for (;;)
4854 {
4855 pos = findmatchlimit(NULL, '*', FM_BACKWARD, cur_maxcomment);
4856 if (pos == NULL)
4857 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004858
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00004859 /*
4860 * Check if the comment start we found is inside a string.
4861 * If it is then restrict the search to below this line and try again.
4862 */
4863 line = ml_get(pos->lnum);
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00004864 for (p = line; *p && (colnr_T)(p - line) < pos->col; ++p)
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00004865 p = skip_string(p);
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00004866 if ((colnr_T)(p - line) <= pos->col)
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00004867 break;
4868 cur_maxcomment = curwin->w_cursor.lnum - pos->lnum - 1;
4869 if (cur_maxcomment <= 0)
4870 {
4871 pos = NULL;
4872 break;
4873 }
4874 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004875 return pos;
4876}
4877
4878/*
4879 * Skip to the end of a "string" and a 'c' character.
4880 * If there is no string or character, return argument unmodified.
4881 */
4882 static char_u *
4883skip_string(p)
4884 char_u *p;
4885{
4886 int i;
4887
4888 /*
4889 * We loop, because strings may be concatenated: "date""time".
4890 */
4891 for ( ; ; ++p)
4892 {
4893 if (p[0] == '\'') /* 'c' or '\n' or '\000' */
4894 {
4895 if (!p[1]) /* ' at end of line */
4896 break;
4897 i = 2;
4898 if (p[1] == '\\') /* '\n' or '\000' */
4899 {
4900 ++i;
4901 while (vim_isdigit(p[i - 1])) /* '\000' */
4902 ++i;
4903 }
4904 if (p[i] == '\'') /* check for trailing ' */
4905 {
4906 p += i;
4907 continue;
4908 }
4909 }
4910 else if (p[0] == '"') /* start of string */
4911 {
4912 for (++p; p[0]; ++p)
4913 {
4914 if (p[0] == '\\' && p[1] != NUL)
4915 ++p;
4916 else if (p[0] == '"') /* end of string */
4917 break;
4918 }
4919 if (p[0] == '"')
4920 continue;
4921 }
4922 break; /* no string found */
4923 }
4924 if (!*p)
4925 --p; /* backup from NUL */
4926 return p;
4927}
4928#endif /* FEAT_CINDENT || FEAT_SYN_HL */
4929
4930#if defined(FEAT_CINDENT) || defined(PROTO)
4931
4932/*
4933 * Do C or expression indenting on the current line.
4934 */
4935 void
4936do_c_expr_indent()
4937{
4938# ifdef FEAT_EVAL
4939 if (*curbuf->b_p_inde != NUL)
4940 fixthisline(get_expr_indent);
4941 else
4942# endif
4943 fixthisline(get_c_indent);
4944}
4945
4946/*
4947 * Functions for C-indenting.
4948 * Most of this originally comes from Eric Fischer.
4949 */
4950/*
4951 * Below "XXX" means that this function may unlock the current line.
4952 */
4953
4954static char_u *cin_skipcomment __ARGS((char_u *));
4955static int cin_nocode __ARGS((char_u *));
4956static pos_T *find_line_comment __ARGS((void));
4957static int cin_islabel_skip __ARGS((char_u **));
4958static int cin_isdefault __ARGS((char_u *));
4959static char_u *after_label __ARGS((char_u *l));
4960static int get_indent_nolabel __ARGS((linenr_T lnum));
4961static int skip_label __ARGS((linenr_T, char_u **pp, int ind_maxcomment));
4962static int cin_first_id_amount __ARGS((void));
4963static int cin_get_equal_amount __ARGS((linenr_T lnum));
4964static int cin_ispreproc __ARGS((char_u *));
4965static int cin_ispreproc_cont __ARGS((char_u **pp, linenr_T *lnump));
4966static int cin_iscomment __ARGS((char_u *));
4967static int cin_islinecomment __ARGS((char_u *));
4968static int cin_isterminated __ARGS((char_u *, int, int));
4969static int cin_isinit __ARGS((void));
Bram Moolenaarc367faa2011-12-14 20:21:35 +01004970static int cin_isfuncdecl __ARGS((char_u **, linenr_T, linenr_T, int, int));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004971static int cin_isif __ARGS((char_u *));
4972static int cin_iselse __ARGS((char_u *));
4973static int cin_isdo __ARGS((char_u *));
4974static int cin_iswhileofdo __ARGS((char_u *, linenr_T, int));
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00004975static int cin_iswhileofdo_end __ARGS((int terminated, int ind_maxparen, int ind_maxcomment));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004976static int cin_isbreak __ARGS((char_u *));
Bram Moolenaare7c56862007-08-04 10:14:52 +00004977static int cin_is_cpp_baseclass __ARGS((colnr_T *col));
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00004978static int get_baseclass_amount __ARGS((int col, int ind_maxparen, int ind_maxcomment, int ind_cpp_baseclass));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004979static int cin_ends_in __ARGS((char_u *, char_u *, char_u *));
4980static int cin_skip2pos __ARGS((pos_T *trypos));
4981static pos_T *find_start_brace __ARGS((int));
4982static pos_T *find_match_paren __ARGS((int, int));
4983static int corr_ind_maxparen __ARGS((int ind_maxparen, pos_T *startpos));
4984static int find_last_paren __ARGS((char_u *l, int start, int end));
4985static int find_match __ARGS((int lookfor, linenr_T ourscope, int ind_maxparen, int ind_maxcomment));
Bram Moolenaared38b0a2011-05-25 15:16:18 +02004986static int cin_is_cpp_namespace __ARGS((char_u *));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004987
Bram Moolenaar39353fd2007-03-27 09:02:11 +00004988static int ind_hash_comment = 0; /* # starts a comment */
4989
Bram Moolenaar071d4272004-06-13 20:20:40 +00004990/*
4991 * Skip over white space and C comments within the line.
Bram Moolenaar39353fd2007-03-27 09:02:11 +00004992 * Also skip over Perl/shell comments if desired.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004993 */
4994 static char_u *
4995cin_skipcomment(s)
4996 char_u *s;
4997{
4998 while (*s)
4999 {
Bram Moolenaar39353fd2007-03-27 09:02:11 +00005000 char_u *prev_s = s;
5001
Bram Moolenaar071d4272004-06-13 20:20:40 +00005002 s = skipwhite(s);
Bram Moolenaar39353fd2007-03-27 09:02:11 +00005003
5004 /* Perl/shell # comment comment continues until eol. Require a space
5005 * before # to avoid recognizing $#array. */
5006 if (ind_hash_comment != 0 && s != prev_s && *s == '#')
5007 {
5008 s += STRLEN(s);
5009 break;
5010 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005011 if (*s != '/')
5012 break;
5013 ++s;
5014 if (*s == '/') /* slash-slash comment continues till eol */
5015 {
5016 s += STRLEN(s);
5017 break;
5018 }
5019 if (*s != '*')
5020 break;
5021 for (++s; *s; ++s) /* skip slash-star comment */
5022 if (s[0] == '*' && s[1] == '/')
5023 {
5024 s += 2;
5025 break;
5026 }
5027 }
5028 return s;
5029}
5030
5031/*
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005032 * Return TRUE if there is no code at *s. White space and comments are
Bram Moolenaar071d4272004-06-13 20:20:40 +00005033 * not considered code.
5034 */
5035 static int
5036cin_nocode(s)
5037 char_u *s;
5038{
5039 return *cin_skipcomment(s) == NUL;
5040}
5041
5042/*
5043 * Check previous lines for a "//" line comment, skipping over blank lines.
5044 */
5045 static pos_T *
5046find_line_comment() /* XXX */
5047{
5048 static pos_T pos;
5049 char_u *line;
5050 char_u *p;
5051
5052 pos = curwin->w_cursor;
5053 while (--pos.lnum > 0)
5054 {
5055 line = ml_get(pos.lnum);
5056 p = skipwhite(line);
5057 if (cin_islinecomment(p))
5058 {
5059 pos.col = (int)(p - line);
5060 return &pos;
5061 }
5062 if (*p != NUL)
5063 break;
5064 }
5065 return NULL;
5066}
5067
5068/*
5069 * Check if string matches "label:"; move to character after ':' if true.
5070 */
5071 static int
5072cin_islabel_skip(s)
5073 char_u **s;
5074{
5075 if (!vim_isIDc(**s)) /* need at least one ID character */
5076 return FALSE;
5077
5078 while (vim_isIDc(**s))
5079 (*s)++;
5080
5081 *s = cin_skipcomment(*s);
5082
5083 /* "::" is not a label, it's C++ */
5084 return (**s == ':' && *++*s != ':');
5085}
5086
5087/*
5088 * Recognize a label: "label:".
5089 * Note: curwin->w_cursor must be where we are looking for the label.
5090 */
5091 int
5092cin_islabel(ind_maxcomment) /* XXX */
5093 int ind_maxcomment;
5094{
5095 char_u *s;
5096
5097 s = cin_skipcomment(ml_get_curline());
5098
5099 /*
5100 * Exclude "default" from labels, since it should be indented
5101 * like a switch label. Same for C++ scope declarations.
5102 */
5103 if (cin_isdefault(s))
5104 return FALSE;
5105 if (cin_isscopedecl(s))
5106 return FALSE;
5107
5108 if (cin_islabel_skip(&s))
5109 {
5110 /*
5111 * Only accept a label if the previous line is terminated or is a case
5112 * label.
5113 */
5114 pos_T cursor_save;
5115 pos_T *trypos;
5116 char_u *line;
5117
5118 cursor_save = curwin->w_cursor;
5119 while (curwin->w_cursor.lnum > 1)
5120 {
5121 --curwin->w_cursor.lnum;
5122
5123 /*
5124 * If we're in a comment now, skip to the start of the comment.
5125 */
5126 curwin->w_cursor.col = 0;
5127 if ((trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
5128 curwin->w_cursor = *trypos;
5129
5130 line = ml_get_curline();
5131 if (cin_ispreproc(line)) /* ignore #defines, #if, etc. */
5132 continue;
5133 if (*(line = cin_skipcomment(line)) == NUL)
5134 continue;
5135
5136 curwin->w_cursor = cursor_save;
5137 if (cin_isterminated(line, TRUE, FALSE)
5138 || cin_isscopedecl(line)
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005139 || cin_iscase(line, TRUE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005140 || (cin_islabel_skip(&line) && cin_nocode(line)))
5141 return TRUE;
5142 return FALSE;
5143 }
5144 curwin->w_cursor = cursor_save;
5145 return TRUE; /* label at start of file??? */
5146 }
5147 return FALSE;
5148}
5149
5150/*
5151 * Recognize structure initialization and enumerations.
5152 * Q&D-Implementation:
5153 * check for "=" at end or "[typedef] enum" at beginning of line.
5154 */
5155 static int
5156cin_isinit(void)
5157{
5158 char_u *s;
5159
5160 s = cin_skipcomment(ml_get_curline());
5161
5162 if (STRNCMP(s, "typedef", 7) == 0 && !vim_isIDc(s[7]))
5163 s = cin_skipcomment(s + 7);
5164
Bram Moolenaara5285652011-12-14 20:05:21 +01005165 if (STRNCMP(s, "static", 6) == 0 && !vim_isIDc(s[6]))
5166 s = cin_skipcomment(s + 6);
5167
Bram Moolenaar071d4272004-06-13 20:20:40 +00005168 if (STRNCMP(s, "enum", 4) == 0 && !vim_isIDc(s[4]))
5169 return TRUE;
5170
5171 if (cin_ends_in(s, (char_u *)"=", (char_u *)"{"))
5172 return TRUE;
5173
5174 return FALSE;
5175}
5176
5177/*
5178 * Recognize a switch label: "case .*:" or "default:".
5179 */
5180 int
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005181cin_iscase(s, strict)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005182 char_u *s;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005183 int strict; /* Allow relaxed check of case statement for JS */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005184{
5185 s = cin_skipcomment(s);
5186 if (STRNCMP(s, "case", 4) == 0 && !vim_isIDc(s[4]))
5187 {
5188 for (s += 4; *s; ++s)
5189 {
5190 s = cin_skipcomment(s);
5191 if (*s == ':')
5192 {
5193 if (s[1] == ':') /* skip over "::" for C++ */
5194 ++s;
5195 else
5196 return TRUE;
5197 }
5198 if (*s == '\'' && s[1] && s[2] == '\'')
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005199 s += 2; /* skip over ':' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005200 else if (*s == '/' && (s[1] == '*' || s[1] == '/'))
5201 return FALSE; /* stop at comment */
5202 else if (*s == '"')
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005203 {
5204 /* JS etc. */
5205 if (strict)
5206 return FALSE; /* stop at string */
5207 else
5208 return TRUE;
5209 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005210 }
5211 return FALSE;
5212 }
5213
5214 if (cin_isdefault(s))
5215 return TRUE;
5216 return FALSE;
5217}
5218
5219/*
5220 * Recognize a "default" switch label.
5221 */
5222 static int
5223cin_isdefault(s)
5224 char_u *s;
5225{
5226 return (STRNCMP(s, "default", 7) == 0
5227 && *(s = cin_skipcomment(s + 7)) == ':'
5228 && s[1] != ':');
5229}
5230
5231/*
Bram Moolenaar1a509df2010-08-01 17:59:57 +02005232 * Recognize a "public/private/protected" scope declaration label.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005233 */
5234 int
5235cin_isscopedecl(s)
5236 char_u *s;
5237{
5238 int i;
5239
5240 s = cin_skipcomment(s);
5241 if (STRNCMP(s, "public", 6) == 0)
5242 i = 6;
5243 else if (STRNCMP(s, "protected", 9) == 0)
5244 i = 9;
5245 else if (STRNCMP(s, "private", 7) == 0)
5246 i = 7;
5247 else
5248 return FALSE;
5249 return (*(s = cin_skipcomment(s + i)) == ':' && s[1] != ':');
5250}
5251
Bram Moolenaared38b0a2011-05-25 15:16:18 +02005252/* Maximum number of lines to search back for a "namespace" line. */
5253#define FIND_NAMESPACE_LIM 20
5254
5255/*
5256 * Recognize a "namespace" scope declaration.
5257 */
5258 static int
5259cin_is_cpp_namespace(s)
5260 char_u *s;
5261{
5262 char_u *p;
5263 int has_name = FALSE;
5264
5265 s = cin_skipcomment(s);
5266 if (STRNCMP(s, "namespace", 9) == 0 && (s[9] == NUL || !vim_iswordc(s[9])))
5267 {
5268 p = cin_skipcomment(skipwhite(s + 9));
5269 while (*p != NUL)
5270 {
5271 if (vim_iswhite(*p))
5272 {
5273 has_name = TRUE; /* found end of a name */
5274 p = cin_skipcomment(skipwhite(p));
5275 }
5276 else if (*p == '{')
5277 {
5278 break;
5279 }
5280 else if (vim_iswordc(*p))
5281 {
5282 if (has_name)
5283 return FALSE; /* word character after skipping past name */
5284 ++p;
5285 }
5286 else
5287 {
5288 return FALSE;
5289 }
5290 }
5291 return TRUE;
5292 }
5293 return FALSE;
5294}
5295
Bram Moolenaar071d4272004-06-13 20:20:40 +00005296/*
5297 * Return a pointer to the first non-empty non-comment character after a ':'.
5298 * Return NULL if not found.
5299 * case 234: a = b;
5300 * ^
5301 */
5302 static char_u *
5303after_label(l)
5304 char_u *l;
5305{
5306 for ( ; *l; ++l)
5307 {
5308 if (*l == ':')
5309 {
5310 if (l[1] == ':') /* skip over "::" for C++ */
5311 ++l;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005312 else if (!cin_iscase(l + 1, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005313 break;
5314 }
5315 else if (*l == '\'' && l[1] && l[2] == '\'')
5316 l += 2; /* skip over 'x' */
5317 }
5318 if (*l == NUL)
5319 return NULL;
5320 l = cin_skipcomment(l + 1);
5321 if (*l == NUL)
5322 return NULL;
5323 return l;
5324}
5325
5326/*
5327 * Get indent of line "lnum", skipping a label.
5328 * Return 0 if there is nothing after the label.
5329 */
5330 static int
5331get_indent_nolabel(lnum) /* XXX */
5332 linenr_T lnum;
5333{
5334 char_u *l;
5335 pos_T fp;
5336 colnr_T col;
5337 char_u *p;
5338
5339 l = ml_get(lnum);
5340 p = after_label(l);
5341 if (p == NULL)
5342 return 0;
5343
5344 fp.col = (colnr_T)(p - l);
5345 fp.lnum = lnum;
5346 getvcol(curwin, &fp, &col, NULL, NULL);
5347 return (int)col;
5348}
5349
5350/*
5351 * Find indent for line "lnum", ignoring any case or jump label.
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005352 * Also return a pointer to the text (after the label) in "pp".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005353 * label: if (asdf && asdfasdf)
5354 * ^
5355 */
5356 static int
5357skip_label(lnum, pp, ind_maxcomment)
5358 linenr_T lnum;
5359 char_u **pp;
5360 int ind_maxcomment;
5361{
5362 char_u *l;
5363 int amount;
5364 pos_T cursor_save;
5365
5366 cursor_save = curwin->w_cursor;
5367 curwin->w_cursor.lnum = lnum;
5368 l = ml_get_curline();
5369 /* XXX */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005370 if (cin_iscase(l, FALSE) || cin_isscopedecl(l)
5371 || cin_islabel(ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005372 {
5373 amount = get_indent_nolabel(lnum);
5374 l = after_label(ml_get_curline());
5375 if (l == NULL) /* just in case */
5376 l = ml_get_curline();
5377 }
5378 else
5379 {
5380 amount = get_indent();
5381 l = ml_get_curline();
5382 }
5383 *pp = l;
5384
5385 curwin->w_cursor = cursor_save;
5386 return amount;
5387}
5388
5389/*
5390 * Return the indent of the first variable name after a type in a declaration.
5391 * int a, indent of "a"
5392 * static struct foo b, indent of "b"
5393 * enum bla c, indent of "c"
5394 * Returns zero when it doesn't look like a declaration.
5395 */
5396 static int
5397cin_first_id_amount()
5398{
5399 char_u *line, *p, *s;
5400 int len;
5401 pos_T fp;
5402 colnr_T col;
5403
5404 line = ml_get_curline();
5405 p = skipwhite(line);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005406 len = (int)(skiptowhite(p) - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005407 if (len == 6 && STRNCMP(p, "static", 6) == 0)
5408 {
5409 p = skipwhite(p + 6);
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00005410 len = (int)(skiptowhite(p) - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005411 }
5412 if (len == 6 && STRNCMP(p, "struct", 6) == 0)
5413 p = skipwhite(p + 6);
5414 else if (len == 4 && STRNCMP(p, "enum", 4) == 0)
5415 p = skipwhite(p + 4);
5416 else if ((len == 8 && STRNCMP(p, "unsigned", 8) == 0)
5417 || (len == 6 && STRNCMP(p, "signed", 6) == 0))
5418 {
5419 s = skipwhite(p + len);
5420 if ((STRNCMP(s, "int", 3) == 0 && vim_iswhite(s[3]))
5421 || (STRNCMP(s, "long", 4) == 0 && vim_iswhite(s[4]))
5422 || (STRNCMP(s, "short", 5) == 0 && vim_iswhite(s[5]))
5423 || (STRNCMP(s, "char", 4) == 0 && vim_iswhite(s[4])))
5424 p = s;
5425 }
5426 for (len = 0; vim_isIDc(p[len]); ++len)
5427 ;
5428 if (len == 0 || !vim_iswhite(p[len]) || cin_nocode(p))
5429 return 0;
5430
5431 p = skipwhite(p + len);
5432 fp.lnum = curwin->w_cursor.lnum;
5433 fp.col = (colnr_T)(p - line);
5434 getvcol(curwin, &fp, &col, NULL, NULL);
5435 return (int)col;
5436}
5437
5438/*
5439 * Return the indent of the first non-blank after an equal sign.
5440 * char *foo = "here";
5441 * Return zero if no (useful) equal sign found.
5442 * Return -1 if the line above "lnum" ends in a backslash.
5443 * foo = "asdf\
5444 * asdf\
5445 * here";
5446 */
5447 static int
5448cin_get_equal_amount(lnum)
5449 linenr_T lnum;
5450{
5451 char_u *line;
5452 char_u *s;
5453 colnr_T col;
5454 pos_T fp;
5455
5456 if (lnum > 1)
5457 {
5458 line = ml_get(lnum - 1);
5459 if (*line != NUL && line[STRLEN(line) - 1] == '\\')
5460 return -1;
5461 }
5462
5463 line = s = ml_get(lnum);
5464 while (*s != NUL && vim_strchr((char_u *)"=;{}\"'", *s) == NULL)
5465 {
5466 if (cin_iscomment(s)) /* ignore comments */
5467 s = cin_skipcomment(s);
5468 else
5469 ++s;
5470 }
5471 if (*s != '=')
5472 return 0;
5473
5474 s = skipwhite(s + 1);
5475 if (cin_nocode(s))
5476 return 0;
5477
5478 if (*s == '"') /* nice alignment for continued strings */
5479 ++s;
5480
5481 fp.lnum = lnum;
5482 fp.col = (colnr_T)(s - line);
5483 getvcol(curwin, &fp, &col, NULL, NULL);
5484 return (int)col;
5485}
5486
5487/*
5488 * Recognize a preprocessor statement: Any line that starts with '#'.
5489 */
5490 static int
5491cin_ispreproc(s)
5492 char_u *s;
5493{
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005494 if (*skipwhite(s) == '#')
Bram Moolenaar071d4272004-06-13 20:20:40 +00005495 return TRUE;
5496 return FALSE;
5497}
5498
5499/*
5500 * Return TRUE if line "*pp" at "*lnump" is a preprocessor statement or a
5501 * continuation line of a preprocessor statement. Decrease "*lnump" to the
5502 * start and return the line in "*pp".
5503 */
5504 static int
5505cin_ispreproc_cont(pp, lnump)
5506 char_u **pp;
5507 linenr_T *lnump;
5508{
5509 char_u *line = *pp;
5510 linenr_T lnum = *lnump;
5511 int retval = FALSE;
5512
Bram Moolenaard8e9bb22005-07-09 21:14:46 +00005513 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005514 {
5515 if (cin_ispreproc(line))
5516 {
5517 retval = TRUE;
5518 *lnump = lnum;
5519 break;
5520 }
5521 if (lnum == 1)
5522 break;
5523 line = ml_get(--lnum);
5524 if (*line == NUL || line[STRLEN(line) - 1] != '\\')
5525 break;
5526 }
5527
5528 if (lnum != *lnump)
5529 *pp = ml_get(*lnump);
5530 return retval;
5531}
5532
5533/*
5534 * Recognize the start of a C or C++ comment.
5535 */
5536 static int
5537cin_iscomment(p)
5538 char_u *p;
5539{
5540 return (p[0] == '/' && (p[1] == '*' || p[1] == '/'));
5541}
5542
5543/*
5544 * Recognize the start of a "//" comment.
5545 */
5546 static int
5547cin_islinecomment(p)
5548 char_u *p;
5549{
5550 return (p[0] == '/' && p[1] == '/');
5551}
5552
5553/*
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005554 * Recognize a line that starts with '{' or '}', or ends with ';', ',', '{' or
5555 * '}'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005556 * Don't consider "} else" a terminated line.
Bram Moolenaar496f9512011-05-19 16:35:09 +02005557 * If a line begins with an "else", only consider it terminated if no unmatched
5558 * opening braces follow (handle "else { foo();" correctly).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005559 * Return the character terminating the line (ending char's have precedence if
5560 * both apply in order to determine initializations).
5561 */
5562 static int
5563cin_isterminated(s, incl_open, incl_comma)
5564 char_u *s;
5565 int incl_open; /* include '{' at the end as terminator */
5566 int incl_comma; /* recognize a trailing comma */
5567{
Bram Moolenaar496f9512011-05-19 16:35:09 +02005568 char_u found_start = 0;
5569 unsigned n_open = 0;
5570 int is_else = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005571
5572 s = cin_skipcomment(s);
5573
5574 if (*s == '{' || (*s == '}' && !cin_iselse(s)))
5575 found_start = *s;
5576
Bram Moolenaar496f9512011-05-19 16:35:09 +02005577 if (!found_start)
5578 is_else = cin_iselse(s);
5579
Bram Moolenaar071d4272004-06-13 20:20:40 +00005580 while (*s)
5581 {
5582 /* skip over comments, "" strings and 'c'haracters */
5583 s = skip_string(cin_skipcomment(s));
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005584 if (*s == '}' && n_open > 0)
5585 --n_open;
Bram Moolenaar496f9512011-05-19 16:35:09 +02005586 if ((!is_else || n_open == 0)
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005587 && (*s == ';' || *s == '}' || (incl_comma && *s == ','))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005588 && cin_nocode(s + 1))
5589 return *s;
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005590 else if (*s == '{')
5591 {
5592 if (incl_open && cin_nocode(s + 1))
5593 return *s;
5594 else
5595 ++n_open;
5596 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005597
5598 if (*s)
5599 s++;
5600 }
5601 return found_start;
5602}
5603
5604/*
5605 * Recognize the basic picture of a function declaration -- it needs to
5606 * have an open paren somewhere and a close paren at the end of the line and
5607 * no semicolons anywhere.
5608 * When a line ends in a comma we continue looking in the next line.
5609 * "sp" points to a string with the line. When looking at other lines it must
5610 * be restored to the line. When it's NULL fetch lines here.
5611 * "lnum" is where we start looking.
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005612 * "min_lnum" is the line before which we will not be looking.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005613 */
5614 static int
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005615cin_isfuncdecl(sp, first_lnum, min_lnum, ind_maxparen, ind_maxcomment)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005616 char_u **sp;
5617 linenr_T first_lnum;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005618 linenr_T min_lnum;
5619 int ind_maxparen;
5620 int ind_maxcomment;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005621{
5622 char_u *s;
5623 linenr_T lnum = first_lnum;
5624 int retval = FALSE;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005625 pos_T *trypos;
5626 int just_started = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005627
5628 if (sp == NULL)
5629 s = ml_get(lnum);
5630 else
5631 s = *sp;
5632
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005633 if (find_last_paren(s, '(', ')')
5634 && (trypos = find_match_paren(ind_maxparen, ind_maxcomment)) != NULL)
5635 {
5636 lnum = trypos->lnum;
5637 if (lnum < min_lnum)
5638 return FALSE;
5639
5640 s = ml_get(lnum);
5641 }
5642
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005643 /* Ignore line starting with #. */
5644 if (cin_ispreproc(s))
5645 return FALSE;
5646
Bram Moolenaar071d4272004-06-13 20:20:40 +00005647 while (*s && *s != '(' && *s != ';' && *s != '\'' && *s != '"')
5648 {
5649 if (cin_iscomment(s)) /* ignore comments */
5650 s = cin_skipcomment(s);
5651 else
5652 ++s;
5653 }
5654 if (*s != '(')
5655 return FALSE; /* ';', ' or " before any () or no '(' */
5656
5657 while (*s && *s != ';' && *s != '\'' && *s != '"')
5658 {
5659 if (*s == ')' && cin_nocode(s + 1))
5660 {
5661 /* ')' at the end: may have found a match
5662 * Check for he previous line not to end in a backslash:
5663 * #if defined(x) && \
5664 * defined(y)
5665 */
5666 lnum = first_lnum - 1;
5667 s = ml_get(lnum);
5668 if (*s == NUL || s[STRLEN(s) - 1] != '\\')
5669 retval = TRUE;
5670 goto done;
5671 }
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005672 if ((*s == ',' && cin_nocode(s + 1)) || s[1] == NUL || cin_nocode(s))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005673 {
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005674 int comma = (*s == ',');
5675
5676 /* ',' at the end: continue looking in the next line.
5677 * At the end: check for ',' in the next line, for this style:
5678 * func(arg1
5679 * , arg2) */
5680 for (;;)
5681 {
5682 if (lnum >= curbuf->b_ml.ml_line_count)
5683 break;
5684 s = ml_get(++lnum);
5685 if (!cin_ispreproc(s))
5686 break;
5687 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005688 if (lnum >= curbuf->b_ml.ml_line_count)
5689 break;
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005690 /* Require a comma at end of the line or a comma or ')' at the
5691 * start of next line. */
5692 s = skipwhite(s);
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005693 if (!just_started && (!comma && *s != ',' && *s != ')'))
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005694 break;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005695 just_started = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005696 }
5697 else if (cin_iscomment(s)) /* ignore comments */
5698 s = cin_skipcomment(s);
5699 else
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005700 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005701 ++s;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005702 just_started = FALSE;
5703 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005704 }
5705
5706done:
5707 if (lnum != first_lnum && sp != NULL)
5708 *sp = ml_get(first_lnum);
5709
5710 return retval;
5711}
5712
5713 static int
5714cin_isif(p)
5715 char_u *p;
5716{
5717 return (STRNCMP(p, "if", 2) == 0 && !vim_isIDc(p[2]));
5718}
5719
5720 static int
5721cin_iselse(p)
5722 char_u *p;
5723{
5724 if (*p == '}') /* accept "} else" */
5725 p = cin_skipcomment(p + 1);
5726 return (STRNCMP(p, "else", 4) == 0 && !vim_isIDc(p[4]));
5727}
5728
5729 static int
5730cin_isdo(p)
5731 char_u *p;
5732{
5733 return (STRNCMP(p, "do", 2) == 0 && !vim_isIDc(p[2]));
5734}
5735
5736/*
5737 * Check if this is a "while" that should have a matching "do".
5738 * We only accept a "while (condition) ;", with only white space between the
5739 * ')' and ';'. The condition may be spread over several lines.
5740 */
5741 static int
5742cin_iswhileofdo(p, lnum, ind_maxparen) /* XXX */
5743 char_u *p;
5744 linenr_T lnum;
5745 int ind_maxparen;
5746{
5747 pos_T cursor_save;
5748 pos_T *trypos;
5749 int retval = FALSE;
5750
5751 p = cin_skipcomment(p);
5752 if (*p == '}') /* accept "} while (cond);" */
5753 p = cin_skipcomment(p + 1);
5754 if (STRNCMP(p, "while", 5) == 0 && !vim_isIDc(p[5]))
5755 {
5756 cursor_save = curwin->w_cursor;
5757 curwin->w_cursor.lnum = lnum;
5758 curwin->w_cursor.col = 0;
5759 p = ml_get_curline();
5760 while (*p && *p != 'w') /* skip any '}', until the 'w' of the "while" */
5761 {
5762 ++p;
5763 ++curwin->w_cursor.col;
5764 }
5765 if ((trypos = findmatchlimit(NULL, 0, 0, ind_maxparen)) != NULL
5766 && *cin_skipcomment(ml_get_pos(trypos) + 1) == ';')
5767 retval = TRUE;
5768 curwin->w_cursor = cursor_save;
5769 }
5770 return retval;
5771}
5772
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005773/*
Bram Moolenaar3675fa02012-04-05 17:17:42 +02005774 * Check whether in "p" there is an "if", "for" or "while" before offset.
5775 * Return 0 if there is none.
5776 * Otherwise return !0 and update "*poffset" to point to the place where the
5777 * string was found.
5778 */
5779 static int
5780cin_is_if_for_while_before_offset(line, offset, poffset)
5781 char_u *line;
5782 size_t offset;
5783 int *poffset;
5784{
5785
5786 if (offset-- < 2)
5787 return 0;
5788 while (offset > 2 && vim_iswhite(line[offset]))
5789 --offset;
5790
5791 offset -= 1;
5792 if (!STRNCMP(line + offset, "if", 2))
5793 goto probablyFound;
5794
5795 if (offset >= 1)
5796 {
5797 offset -= 1;
5798 if (!STRNCMP(line + offset, "for", 3))
5799 goto probablyFound;
5800
5801 if (offset >= 2)
5802 {
5803 offset -= 2;
5804 if (!STRNCMP(line + offset, "while", 5))
5805 goto probablyFound;
5806 }
5807 }
5808
5809 return 0;
5810probablyFound:
5811 if (!offset || !vim_isIDc(line[offset - 1]))
5812 {
5813 *poffset = offset;
5814 return 1;
5815 }
5816 return 0;
5817}
5818
5819/*
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005820 * Return TRUE if we are at the end of a do-while.
5821 * do
5822 * nothing;
5823 * while (foo
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00005824 * && bar); <-- here
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005825 * Adjust the cursor to the line with "while".
5826 */
5827 static int
5828cin_iswhileofdo_end(terminated, ind_maxparen, ind_maxcomment)
5829 int terminated;
5830 int ind_maxparen;
5831 int ind_maxcomment;
5832{
5833 char_u *line;
5834 char_u *p;
5835 char_u *s;
5836 pos_T *trypos;
5837 int i;
5838
5839 if (terminated != ';') /* there must be a ';' at the end */
5840 return FALSE;
5841
5842 p = line = ml_get_curline();
5843 while (*p != NUL)
5844 {
5845 p = cin_skipcomment(p);
5846 if (*p == ')')
5847 {
5848 s = skipwhite(p + 1);
5849 if (*s == ';' && cin_nocode(s + 1))
5850 {
5851 /* Found ");" at end of the line, now check there is "while"
5852 * before the matching '('. XXX */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005853 i = (int)(p - line);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005854 curwin->w_cursor.col = i;
5855 trypos = find_match_paren(ind_maxparen, ind_maxcomment);
5856 if (trypos != NULL)
5857 {
5858 s = cin_skipcomment(ml_get(trypos->lnum));
5859 if (*s == '}') /* accept "} while (cond);" */
5860 s = cin_skipcomment(s + 1);
5861 if (STRNCMP(s, "while", 5) == 0 && !vim_isIDc(s[5]))
5862 {
5863 curwin->w_cursor.lnum = trypos->lnum;
5864 return TRUE;
5865 }
5866 }
5867
5868 /* Searching may have made "line" invalid, get it again. */
5869 line = ml_get_curline();
5870 p = line + i;
5871 }
5872 }
5873 if (*p != NUL)
5874 ++p;
5875 }
5876 return FALSE;
5877}
5878
Bram Moolenaar071d4272004-06-13 20:20:40 +00005879 static int
5880cin_isbreak(p)
5881 char_u *p;
5882{
5883 return (STRNCMP(p, "break", 5) == 0 && !vim_isIDc(p[5]));
5884}
5885
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005886/*
5887 * Find the position of a C++ base-class declaration or
Bram Moolenaar071d4272004-06-13 20:20:40 +00005888 * constructor-initialization. eg:
5889 *
5890 * class MyClass :
5891 * baseClass <-- here
5892 * class MyClass : public baseClass,
5893 * anotherBaseClass <-- here (should probably lineup ??)
5894 * MyClass::MyClass(...) :
5895 * baseClass(...) <-- here (constructor-initialization)
Bram Moolenaar18144c82006-04-12 21:52:12 +00005896 *
5897 * This is a lot of guessing. Watch out for "cond ? func() : foo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005898 */
5899 static int
Bram Moolenaare7c56862007-08-04 10:14:52 +00005900cin_is_cpp_baseclass(col)
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005901 colnr_T *col; /* return: column to align with */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005902{
5903 char_u *s;
5904 int class_or_struct, lookfor_ctor_init, cpp_base_class;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005905 linenr_T lnum = curwin->w_cursor.lnum;
Bram Moolenaare7c56862007-08-04 10:14:52 +00005906 char_u *line = ml_get_curline();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005907
5908 *col = 0;
5909
Bram Moolenaar21cf8232004-07-16 20:18:37 +00005910 s = skipwhite(line);
5911 if (*s == '#') /* skip #define FOO x ? (x) : x */
5912 return FALSE;
5913 s = cin_skipcomment(s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005914 if (*s == NUL)
5915 return FALSE;
5916
5917 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
5918
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005919 /* Search for a line starting with '#', empty, ending in ';' or containing
5920 * '{' or '}' and start below it. This handles the following situations:
5921 * a = cond ?
5922 * func() :
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00005923 * asdf;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005924 * func::foo()
5925 * : something
5926 * {}
5927 * Foo::Foo (int one, int two)
5928 * : something(4),
5929 * somethingelse(3)
5930 * {}
5931 */
5932 while (lnum > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005933 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00005934 line = ml_get(lnum - 1);
5935 s = skipwhite(line);
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005936 if (*s == '#' || *s == NUL)
5937 break;
5938 while (*s != NUL)
5939 {
5940 s = cin_skipcomment(s);
5941 if (*s == '{' || *s == '}'
5942 || (*s == ';' && cin_nocode(s + 1)))
5943 break;
5944 if (*s != NUL)
5945 ++s;
5946 }
5947 if (*s != NUL)
5948 break;
5949 --lnum;
5950 }
5951
Bram Moolenaare7c56862007-08-04 10:14:52 +00005952 line = ml_get(lnum);
5953 s = cin_skipcomment(line);
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005954 for (;;)
5955 {
5956 if (*s == NUL)
5957 {
5958 if (lnum == curwin->w_cursor.lnum)
5959 break;
5960 /* Continue in the cursor line. */
Bram Moolenaare7c56862007-08-04 10:14:52 +00005961 line = ml_get(++lnum);
5962 s = cin_skipcomment(line);
5963 if (*s == NUL)
5964 continue;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005965 }
5966
Bram Moolenaaraede6ce2011-05-10 11:56:30 +02005967 if (s[0] == '"')
5968 s = skip_string(s) + 1;
5969 else if (s[0] == ':')
Bram Moolenaar071d4272004-06-13 20:20:40 +00005970 {
5971 if (s[1] == ':')
5972 {
5973 /* skip double colon. It can't be a constructor
5974 * initialization any more */
5975 lookfor_ctor_init = FALSE;
5976 s = cin_skipcomment(s + 2);
5977 }
5978 else if (lookfor_ctor_init || class_or_struct)
5979 {
5980 /* we have something found, that looks like the start of
Bram Moolenaare21877a2008-02-13 09:58:14 +00005981 * cpp-base-class-declaration or constructor-initialization */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005982 cpp_base_class = TRUE;
5983 lookfor_ctor_init = class_or_struct = FALSE;
5984 *col = 0;
5985 s = cin_skipcomment(s + 1);
5986 }
5987 else
5988 s = cin_skipcomment(s + 1);
5989 }
5990 else if ((STRNCMP(s, "class", 5) == 0 && !vim_isIDc(s[5]))
5991 || (STRNCMP(s, "struct", 6) == 0 && !vim_isIDc(s[6])))
5992 {
5993 class_or_struct = TRUE;
5994 lookfor_ctor_init = FALSE;
5995
5996 if (*s == 'c')
5997 s = cin_skipcomment(s + 5);
5998 else
5999 s = cin_skipcomment(s + 6);
6000 }
6001 else
6002 {
6003 if (s[0] == '{' || s[0] == '}' || s[0] == ';')
6004 {
6005 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
6006 }
6007 else if (s[0] == ')')
6008 {
6009 /* Constructor-initialization is assumed if we come across
6010 * something like "):" */
6011 class_or_struct = FALSE;
6012 lookfor_ctor_init = TRUE;
6013 }
Bram Moolenaar18144c82006-04-12 21:52:12 +00006014 else if (s[0] == '?')
6015 {
6016 /* Avoid seeing '() :' after '?' as constructor init. */
6017 return FALSE;
6018 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006019 else if (!vim_isIDc(s[0]))
6020 {
6021 /* if it is not an identifier, we are wrong */
6022 class_or_struct = FALSE;
6023 lookfor_ctor_init = FALSE;
6024 }
6025 else if (*col == 0)
6026 {
6027 /* it can't be a constructor-initialization any more */
6028 lookfor_ctor_init = FALSE;
6029
6030 /* the first statement starts here: lineup with this one... */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006031 if (cpp_base_class)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006032 *col = (colnr_T)(s - line);
6033 }
6034
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006035 /* When the line ends in a comma don't align with it. */
6036 if (lnum == curwin->w_cursor.lnum && *s == ',' && cin_nocode(s + 1))
6037 *col = 0;
6038
Bram Moolenaar071d4272004-06-13 20:20:40 +00006039 s = cin_skipcomment(s + 1);
6040 }
6041 }
6042
6043 return cpp_base_class;
6044}
6045
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006046 static int
6047get_baseclass_amount(col, ind_maxparen, ind_maxcomment, ind_cpp_baseclass)
6048 int col;
6049 int ind_maxparen;
6050 int ind_maxcomment;
6051 int ind_cpp_baseclass;
6052{
6053 int amount;
6054 colnr_T vcol;
6055 pos_T *trypos;
6056
6057 if (col == 0)
6058 {
6059 amount = get_indent();
6060 if (find_last_paren(ml_get_curline(), '(', ')')
6061 && (trypos = find_match_paren(ind_maxparen,
6062 ind_maxcomment)) != NULL)
6063 amount = get_indent_lnum(trypos->lnum); /* XXX */
6064 if (!cin_ends_in(ml_get_curline(), (char_u *)",", NULL))
6065 amount += ind_cpp_baseclass;
6066 }
6067 else
6068 {
6069 curwin->w_cursor.col = col;
6070 getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
6071 amount = (int)vcol;
6072 }
6073 if (amount < ind_cpp_baseclass)
6074 amount = ind_cpp_baseclass;
6075 return amount;
6076}
6077
Bram Moolenaar071d4272004-06-13 20:20:40 +00006078/*
6079 * Return TRUE if string "s" ends with the string "find", possibly followed by
6080 * white space and comments. Skip strings and comments.
6081 * Ignore "ignore" after "find" if it's not NULL.
6082 */
6083 static int
6084cin_ends_in(s, find, ignore)
6085 char_u *s;
6086 char_u *find;
6087 char_u *ignore;
6088{
6089 char_u *p = s;
6090 char_u *r;
6091 int len = (int)STRLEN(find);
6092
6093 while (*p != NUL)
6094 {
6095 p = cin_skipcomment(p);
6096 if (STRNCMP(p, find, len) == 0)
6097 {
6098 r = skipwhite(p + len);
6099 if (ignore != NULL && STRNCMP(r, ignore, STRLEN(ignore)) == 0)
6100 r = skipwhite(r + STRLEN(ignore));
6101 if (cin_nocode(r))
6102 return TRUE;
6103 }
6104 if (*p != NUL)
6105 ++p;
6106 }
6107 return FALSE;
6108}
6109
6110/*
6111 * Skip strings, chars and comments until at or past "trypos".
6112 * Return the column found.
6113 */
6114 static int
6115cin_skip2pos(trypos)
6116 pos_T *trypos;
6117{
6118 char_u *line;
6119 char_u *p;
6120
6121 p = line = ml_get(trypos->lnum);
6122 while (*p && (colnr_T)(p - line) < trypos->col)
6123 {
6124 if (cin_iscomment(p))
6125 p = cin_skipcomment(p);
6126 else
6127 {
6128 p = skip_string(p);
6129 ++p;
6130 }
6131 }
6132 return (int)(p - line);
6133}
6134
6135/*
6136 * Find the '{' at the start of the block we are in.
6137 * Return NULL if no match found.
6138 * Ignore a '{' that is in a comment, makes indenting the next three lines
6139 * work. */
6140/* foo() */
6141/* { */
6142/* } */
6143
6144 static pos_T *
6145find_start_brace(ind_maxcomment) /* XXX */
6146 int ind_maxcomment;
6147{
6148 pos_T cursor_save;
6149 pos_T *trypos;
6150 pos_T *pos;
6151 static pos_T pos_copy;
6152
6153 cursor_save = curwin->w_cursor;
6154 while ((trypos = findmatchlimit(NULL, '{', FM_BLOCKSTOP, 0)) != NULL)
6155 {
6156 pos_copy = *trypos; /* copy pos_T, next findmatch will change it */
6157 trypos = &pos_copy;
6158 curwin->w_cursor = *trypos;
6159 pos = NULL;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006160 /* ignore the { if it's in a // or / * * / comment */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006161 if ((colnr_T)cin_skip2pos(trypos) == trypos->col
6162 && (pos = find_start_comment(ind_maxcomment)) == NULL) /* XXX */
6163 break;
6164 if (pos != NULL)
6165 curwin->w_cursor.lnum = pos->lnum;
6166 }
6167 curwin->w_cursor = cursor_save;
6168 return trypos;
6169}
6170
6171/*
6172 * Find the matching '(', failing if it is in a comment.
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006173 * Return NULL if no match found.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006174 */
6175 static pos_T *
6176find_match_paren(ind_maxparen, ind_maxcomment) /* XXX */
6177 int ind_maxparen;
6178 int ind_maxcomment;
6179{
6180 pos_T cursor_save;
6181 pos_T *trypos;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006182 static pos_T pos_copy;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006183
6184 cursor_save = curwin->w_cursor;
6185 if ((trypos = findmatchlimit(NULL, '(', 0, ind_maxparen)) != NULL)
6186 {
6187 /* check if the ( is in a // comment */
6188 if ((colnr_T)cin_skip2pos(trypos) > trypos->col)
6189 trypos = NULL;
6190 else
6191 {
6192 pos_copy = *trypos; /* copy trypos, findmatch will change it */
6193 trypos = &pos_copy;
6194 curwin->w_cursor = *trypos;
6195 if (find_start_comment(ind_maxcomment) != NULL) /* XXX */
6196 trypos = NULL;
6197 }
6198 }
6199 curwin->w_cursor = cursor_save;
6200 return trypos;
6201}
6202
6203/*
6204 * Return ind_maxparen corrected for the difference in line number between the
6205 * cursor position and "startpos". This makes sure that searching for a
6206 * matching paren above the cursor line doesn't find a match because of
6207 * looking a few lines further.
6208 */
6209 static int
6210corr_ind_maxparen(ind_maxparen, startpos)
6211 int ind_maxparen;
6212 pos_T *startpos;
6213{
6214 long n = (long)startpos->lnum - (long)curwin->w_cursor.lnum;
6215
6216 if (n > 0 && n < ind_maxparen / 2)
6217 return ind_maxparen - (int)n;
6218 return ind_maxparen;
6219}
6220
6221/*
6222 * Set w_cursor.col to the column number of the last unmatched ')' or '{' in
Bram Moolenaar6d8f9c62011-11-30 13:03:28 +01006223 * line "l". "l" must point to the start of the line.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006224 */
6225 static int
6226find_last_paren(l, start, end)
6227 char_u *l;
6228 int start, end;
6229{
6230 int i;
6231 int retval = FALSE;
6232 int open_count = 0;
6233
6234 curwin->w_cursor.col = 0; /* default is start of line */
6235
Bram Moolenaar6d8f9c62011-11-30 13:03:28 +01006236 for (i = 0; l[i] != NUL; i++)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006237 {
6238 i = (int)(cin_skipcomment(l + i) - l); /* ignore parens in comments */
6239 i = (int)(skip_string(l + i) - l); /* ignore parens in quotes */
6240 if (l[i] == start)
6241 ++open_count;
6242 else if (l[i] == end)
6243 {
6244 if (open_count > 0)
6245 --open_count;
6246 else
6247 {
6248 curwin->w_cursor.col = i;
6249 retval = TRUE;
6250 }
6251 }
6252 }
6253 return retval;
6254}
6255
6256 int
6257get_c_indent()
6258{
6259 /*
6260 * spaces from a block's opening brace the prevailing indent for that
6261 * block should be
6262 */
6263 int ind_level = curbuf->b_p_sw;
6264
6265 /*
6266 * spaces from the edge of the line an open brace that's at the end of a
6267 * line is imagined to be.
6268 */
6269 int ind_open_imag = 0;
6270
6271 /*
Bram Moolenaar1a509df2010-08-01 17:59:57 +02006272 * spaces from the prevailing indent for a line that is not preceded by
Bram Moolenaar071d4272004-06-13 20:20:40 +00006273 * an opening brace.
6274 */
6275 int ind_no_brace = 0;
6276
6277 /*
6278 * column where the first { of a function should be located }
6279 */
6280 int ind_first_open = 0;
6281
6282 /*
6283 * spaces from the prevailing indent a leftmost open brace should be
6284 * located
6285 */
6286 int ind_open_extra = 0;
6287
6288 /*
6289 * spaces from the matching open brace (real location for one at the left
6290 * edge; imaginary location from one that ends a line) the matching close
6291 * brace should be located
6292 */
6293 int ind_close_extra = 0;
6294
6295 /*
6296 * spaces from the edge of the line an open brace sitting in the leftmost
6297 * column is imagined to be
6298 */
6299 int ind_open_left_imag = 0;
6300
6301 /*
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006302 * Spaces jump labels should be shifted to the left if N is non-negative,
6303 * otherwise the jump label will be put to column 1.
6304 */
6305 int ind_jump_label = -1;
6306
6307 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006308 * spaces from the switch() indent a "case xx" label should be located
6309 */
6310 int ind_case = curbuf->b_p_sw;
6311
6312 /*
6313 * spaces from the "case xx:" code after a switch() should be located
6314 */
6315 int ind_case_code = curbuf->b_p_sw;
6316
6317 /*
6318 * lineup break at end of case in switch() with case label
6319 */
6320 int ind_case_break = 0;
6321
6322 /*
6323 * spaces from the class declaration indent a scope declaration label
6324 * should be located
6325 */
6326 int ind_scopedecl = curbuf->b_p_sw;
6327
6328 /*
6329 * spaces from the scope declaration label code should be located
6330 */
6331 int ind_scopedecl_code = curbuf->b_p_sw;
6332
6333 /*
6334 * amount K&R-style parameters should be indented
6335 */
6336 int ind_param = curbuf->b_p_sw;
6337
6338 /*
6339 * amount a function type spec should be indented
6340 */
6341 int ind_func_type = curbuf->b_p_sw;
6342
6343 /*
6344 * amount a cpp base class declaration or constructor initialization
6345 * should be indented
6346 */
6347 int ind_cpp_baseclass = curbuf->b_p_sw;
6348
6349 /*
6350 * additional spaces beyond the prevailing indent a continuation line
6351 * should be located
6352 */
6353 int ind_continuation = curbuf->b_p_sw;
6354
6355 /*
6356 * spaces from the indent of the line with an unclosed parentheses
6357 */
6358 int ind_unclosed = curbuf->b_p_sw * 2;
6359
6360 /*
6361 * spaces from the indent of the line with an unclosed parentheses, which
6362 * itself is also unclosed
6363 */
6364 int ind_unclosed2 = curbuf->b_p_sw;
6365
6366 /*
6367 * suppress ignoring spaces from the indent of a line starting with an
6368 * unclosed parentheses.
6369 */
6370 int ind_unclosed_noignore = 0;
6371
6372 /*
6373 * If the opening paren is the last nonwhite character on the line, and
6374 * ind_unclosed_wrapped is nonzero, use this indent relative to the outer
6375 * context (for very long lines).
6376 */
6377 int ind_unclosed_wrapped = 0;
6378
6379 /*
6380 * suppress ignoring white space when lining up with the character after
6381 * an unclosed parentheses.
6382 */
6383 int ind_unclosed_whiteok = 0;
6384
6385 /*
6386 * indent a closing parentheses under the line start of the matching
6387 * opening parentheses.
6388 */
6389 int ind_matching_paren = 0;
6390
6391 /*
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006392 * indent a closing parentheses under the previous line.
6393 */
6394 int ind_paren_prev = 0;
6395
6396 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006397 * Extra indent for comments.
6398 */
6399 int ind_comment = 0;
6400
6401 /*
6402 * spaces from the comment opener when there is nothing after it.
6403 */
6404 int ind_in_comment = 3;
6405
6406 /*
6407 * boolean: if non-zero, use ind_in_comment even if there is something
6408 * after the comment opener.
6409 */
6410 int ind_in_comment2 = 0;
6411
6412 /*
6413 * max lines to search for an open paren
6414 */
6415 int ind_maxparen = 20;
6416
6417 /*
6418 * max lines to search for an open comment
6419 */
6420 int ind_maxcomment = 70;
6421
6422 /*
6423 * handle braces for java code
6424 */
6425 int ind_java = 0;
6426
6427 /*
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006428 * not to confuse JS object properties with labels
6429 */
6430 int ind_js = 0;
6431
6432 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006433 * handle blocked cases correctly
6434 */
6435 int ind_keep_case_label = 0;
6436
Bram Moolenaared38b0a2011-05-25 15:16:18 +02006437 /*
6438 * handle C++ namespace
6439 */
6440 int ind_cpp_namespace = 0;
6441
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006442 /*
6443 * handle continuation lines containing conditions of if(), for() and
6444 * while()
6445 */
6446 int ind_if_for_while = 0;
6447
Bram Moolenaar071d4272004-06-13 20:20:40 +00006448 pos_T cur_curpos;
6449 int amount;
6450 int scope_amount;
Bram Moolenaarb21e5842006-04-16 18:30:08 +00006451 int cur_amount = MAXCOL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006452 colnr_T col;
6453 char_u *theline;
6454 char_u *linecopy;
6455 pos_T *trypos;
6456 pos_T *tryposBrace = NULL;
6457 pos_T our_paren_pos;
6458 char_u *start;
6459 int start_brace;
Bram Moolenaare21877a2008-02-13 09:58:14 +00006460#define BRACE_IN_COL0 1 /* '{' is in column 0 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006461#define BRACE_AT_START 2 /* '{' is at start of line */
6462#define BRACE_AT_END 3 /* '{' is at end of line */
6463 linenr_T ourscope;
6464 char_u *l;
6465 char_u *look;
6466 char_u terminated;
6467 int lookfor;
6468#define LOOKFOR_INITIAL 0
6469#define LOOKFOR_IF 1
6470#define LOOKFOR_DO 2
6471#define LOOKFOR_CASE 3
6472#define LOOKFOR_ANY 4
6473#define LOOKFOR_TERM 5
6474#define LOOKFOR_UNTERM 6
6475#define LOOKFOR_SCOPEDECL 7
6476#define LOOKFOR_NOBREAK 8
6477#define LOOKFOR_CPP_BASECLASS 9
6478#define LOOKFOR_ENUM_OR_INIT 10
6479
6480 int whilelevel;
6481 linenr_T lnum;
6482 char_u *options;
6483 int fraction = 0; /* init for GCC */
6484 int divider;
6485 int n;
6486 int iscase;
6487 int lookfor_break;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02006488 int lookfor_cpp_namespace = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006489 int cont_amount = 0; /* amount for continuation line */
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006490 int original_line_islabel;
Bram Moolenaare79d1532011-10-04 18:03:47 +02006491 int added_to_amount = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006492
6493 for (options = curbuf->b_p_cino; *options; )
6494 {
6495 l = options++;
6496 if (*options == '-')
6497 ++options;
6498 n = getdigits(&options);
6499 divider = 0;
6500 if (*options == '.') /* ".5s" means a fraction */
6501 {
6502 fraction = atol((char *)++options);
6503 while (VIM_ISDIGIT(*options))
6504 {
6505 ++options;
6506 if (divider)
6507 divider *= 10;
6508 else
6509 divider = 10;
6510 }
6511 }
6512 if (*options == 's') /* "2s" means two times 'shiftwidth' */
6513 {
6514 if (n == 0 && fraction == 0)
6515 n = curbuf->b_p_sw; /* just "s" is one 'shiftwidth' */
6516 else
6517 {
6518 n *= curbuf->b_p_sw;
6519 if (divider)
6520 n += (curbuf->b_p_sw * fraction + divider / 2) / divider;
6521 }
6522 ++options;
6523 }
6524 if (l[1] == '-')
6525 n = -n;
6526 /* When adding an entry here, also update the default 'cinoptions' in
Bram Moolenaar39353fd2007-03-27 09:02:11 +00006527 * doc/indent.txt, and add explanation for it! */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006528 switch (*l)
6529 {
6530 case '>': ind_level = n; break;
6531 case 'e': ind_open_imag = n; break;
6532 case 'n': ind_no_brace = n; break;
6533 case 'f': ind_first_open = n; break;
6534 case '{': ind_open_extra = n; break;
6535 case '}': ind_close_extra = n; break;
6536 case '^': ind_open_left_imag = n; break;
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006537 case 'L': ind_jump_label = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006538 case ':': ind_case = n; break;
6539 case '=': ind_case_code = n; break;
6540 case 'b': ind_case_break = n; break;
6541 case 'p': ind_param = n; break;
6542 case 't': ind_func_type = n; break;
6543 case '/': ind_comment = n; break;
6544 case 'c': ind_in_comment = n; break;
6545 case 'C': ind_in_comment2 = n; break;
6546 case 'i': ind_cpp_baseclass = n; break;
6547 case '+': ind_continuation = n; break;
6548 case '(': ind_unclosed = n; break;
6549 case 'u': ind_unclosed2 = n; break;
6550 case 'U': ind_unclosed_noignore = n; break;
6551 case 'W': ind_unclosed_wrapped = n; break;
6552 case 'w': ind_unclosed_whiteok = n; break;
6553 case 'm': ind_matching_paren = n; break;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006554 case 'M': ind_paren_prev = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006555 case ')': ind_maxparen = n; break;
6556 case '*': ind_maxcomment = n; break;
6557 case 'g': ind_scopedecl = n; break;
6558 case 'h': ind_scopedecl_code = n; break;
6559 case 'j': ind_java = n; break;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006560 case 'J': ind_js = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006561 case 'l': ind_keep_case_label = n; break;
Bram Moolenaar39353fd2007-03-27 09:02:11 +00006562 case '#': ind_hash_comment = n; break;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02006563 case 'N': ind_cpp_namespace = n; break;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006564 case 'k': ind_if_for_while = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006565 }
Bram Moolenaardfdf3c42010-03-23 18:22:46 +01006566 if (*options == ',')
6567 ++options;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006568 }
6569
6570 /* remember where the cursor was when we started */
6571 cur_curpos = curwin->w_cursor;
6572
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006573 /* if we are at line 1 0 is fine, right? */
6574 if (cur_curpos.lnum == 1)
6575 return 0;
6576
Bram Moolenaar071d4272004-06-13 20:20:40 +00006577 /* Get a copy of the current contents of the line.
6578 * This is required, because only the most recent line obtained with
6579 * ml_get is valid! */
6580 linecopy = vim_strsave(ml_get(cur_curpos.lnum));
6581 if (linecopy == NULL)
6582 return 0;
6583
6584 /*
6585 * In insert mode and the cursor is on a ')' truncate the line at the
6586 * cursor position. We don't want to line up with the matching '(' when
6587 * inserting new stuff.
6588 * For unknown reasons the cursor might be past the end of the line, thus
6589 * check for that.
6590 */
6591 if ((State & INSERT)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006592 && curwin->w_cursor.col < (colnr_T)STRLEN(linecopy)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006593 && linecopy[curwin->w_cursor.col] == ')')
6594 linecopy[curwin->w_cursor.col] = NUL;
6595
6596 theline = skipwhite(linecopy);
6597
6598 /* move the cursor to the start of the line */
6599
6600 curwin->w_cursor.col = 0;
6601
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006602 original_line_islabel = cin_islabel(ind_maxcomment); /* XXX */
6603
Bram Moolenaar071d4272004-06-13 20:20:40 +00006604 /*
6605 * #defines and so on always go at the left when included in 'cinkeys'.
6606 */
6607 if (*theline == '#' && (*linecopy == '#' || in_cinkeys('#', ' ', TRUE)))
6608 {
6609 amount = 0;
6610 }
6611
6612 /*
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006613 * Is it a non-case label? Then that goes at the left margin too unless:
6614 * - JS flag is set.
6615 * - 'L' item has a positive value.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006616 */
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006617 else if (original_line_islabel && !ind_js && ind_jump_label < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006618 {
6619 amount = 0;
6620 }
6621
6622 /*
6623 * If we're inside a "//" comment and there is a "//" comment in a
6624 * previous line, lineup with that one.
6625 */
6626 else if (cin_islinecomment(theline)
6627 && (trypos = find_line_comment()) != NULL) /* XXX */
6628 {
6629 /* find how indented the line beginning the comment is */
6630 getvcol(curwin, trypos, &col, NULL, NULL);
6631 amount = col;
6632 }
6633
6634 /*
6635 * If we're inside a comment and not looking at the start of the
6636 * comment, try using the 'comments' option.
6637 */
6638 else if (!cin_iscomment(theline)
6639 && (trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
6640 {
6641 int lead_start_len = 2;
6642 int lead_middle_len = 1;
6643 char_u lead_start[COM_MAX_LEN]; /* start-comment string */
6644 char_u lead_middle[COM_MAX_LEN]; /* middle-comment string */
6645 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
6646 char_u *p;
6647 int start_align = 0;
6648 int start_off = 0;
6649 int done = FALSE;
6650
6651 /* find how indented the line beginning the comment is */
6652 getvcol(curwin, trypos, &col, NULL, NULL);
6653 amount = col;
Bram Moolenaar4aa97422011-04-11 14:27:38 +02006654 *lead_start = NUL;
6655 *lead_middle = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006656
6657 p = curbuf->b_p_com;
6658 while (*p != NUL)
6659 {
6660 int align = 0;
6661 int off = 0;
6662 int what = 0;
6663
6664 while (*p != NUL && *p != ':')
6665 {
6666 if (*p == COM_START || *p == COM_END || *p == COM_MIDDLE)
6667 what = *p++;
6668 else if (*p == COM_LEFT || *p == COM_RIGHT)
6669 align = *p++;
6670 else if (VIM_ISDIGIT(*p) || *p == '-')
6671 off = getdigits(&p);
6672 else
6673 ++p;
6674 }
6675
6676 if (*p == ':')
6677 ++p;
6678 (void)copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
6679 if (what == COM_START)
6680 {
6681 STRCPY(lead_start, lead_end);
6682 lead_start_len = (int)STRLEN(lead_start);
6683 start_off = off;
6684 start_align = align;
6685 }
6686 else if (what == COM_MIDDLE)
6687 {
6688 STRCPY(lead_middle, lead_end);
6689 lead_middle_len = (int)STRLEN(lead_middle);
6690 }
6691 else if (what == COM_END)
6692 {
6693 /* If our line starts with the middle comment string, line it
6694 * up with the comment opener per the 'comments' option. */
6695 if (STRNCMP(theline, lead_middle, lead_middle_len) == 0
6696 && STRNCMP(theline, lead_end, STRLEN(lead_end)) != 0)
6697 {
6698 done = TRUE;
6699 if (curwin->w_cursor.lnum > 1)
6700 {
6701 /* If the start comment string matches in the previous
Bram Moolenaare21877a2008-02-13 09:58:14 +00006702 * line, use the indent of that line plus offset. If
Bram Moolenaar071d4272004-06-13 20:20:40 +00006703 * the middle comment string matches in the previous
6704 * line, use the indent of that line. XXX */
6705 look = skipwhite(ml_get(curwin->w_cursor.lnum - 1));
6706 if (STRNCMP(look, lead_start, lead_start_len) == 0)
6707 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6708 else if (STRNCMP(look, lead_middle,
6709 lead_middle_len) == 0)
6710 {
6711 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6712 break;
6713 }
6714 /* If the start comment string doesn't match with the
6715 * start of the comment, skip this entry. XXX */
6716 else if (STRNCMP(ml_get(trypos->lnum) + trypos->col,
6717 lead_start, lead_start_len) != 0)
6718 continue;
6719 }
6720 if (start_off != 0)
6721 amount += start_off;
6722 else if (start_align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006723 amount += vim_strsize(lead_start)
6724 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006725 break;
6726 }
6727
6728 /* If our line starts with the end comment string, line it up
6729 * with the middle comment */
6730 if (STRNCMP(theline, lead_middle, lead_middle_len) != 0
6731 && STRNCMP(theline, lead_end, STRLEN(lead_end)) == 0)
6732 {
6733 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6734 /* XXX */
6735 if (off != 0)
6736 amount += off;
6737 else if (align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006738 amount += vim_strsize(lead_start)
6739 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006740 done = TRUE;
6741 break;
6742 }
6743 }
6744 }
6745
6746 /* If our line starts with an asterisk, line up with the
6747 * asterisk in the comment opener; otherwise, line up
6748 * with the first character of the comment text.
6749 */
6750 if (done)
6751 ;
6752 else if (theline[0] == '*')
6753 amount += 1;
6754 else
6755 {
6756 /*
6757 * If we are more than one line away from the comment opener, take
6758 * the indent of the previous non-empty line. If 'cino' has "CO"
6759 * and we are just below the comment opener and there are any
6760 * white characters after it line up with the text after it;
6761 * otherwise, add the amount specified by "c" in 'cino'
6762 */
6763 amount = -1;
6764 for (lnum = cur_curpos.lnum - 1; lnum > trypos->lnum; --lnum)
6765 {
6766 if (linewhite(lnum)) /* skip blank lines */
6767 continue;
6768 amount = get_indent_lnum(lnum); /* XXX */
6769 break;
6770 }
6771 if (amount == -1) /* use the comment opener */
6772 {
6773 if (!ind_in_comment2)
6774 {
6775 start = ml_get(trypos->lnum);
6776 look = start + trypos->col + 2; /* skip / and * */
6777 if (*look != NUL) /* if something after it */
6778 trypos->col = (colnr_T)(skipwhite(look) - start);
6779 }
6780 getvcol(curwin, trypos, &col, NULL, NULL);
6781 amount = col;
6782 if (ind_in_comment2 || *look == NUL)
6783 amount += ind_in_comment;
6784 }
6785 }
6786 }
6787
6788 /*
6789 * Are we inside parentheses or braces?
6790 */ /* XXX */
6791 else if (((trypos = find_match_paren(ind_maxparen, ind_maxcomment)) != NULL
6792 && ind_java == 0)
6793 || (tryposBrace = find_start_brace(ind_maxcomment)) != NULL
6794 || trypos != NULL)
6795 {
6796 if (trypos != NULL && tryposBrace != NULL)
6797 {
6798 /* Both an unmatched '(' and '{' is found. Use the one which is
6799 * closer to the current cursor position, set the other to NULL. */
6800 if (trypos->lnum != tryposBrace->lnum
6801 ? trypos->lnum < tryposBrace->lnum
6802 : trypos->col < tryposBrace->col)
6803 trypos = NULL;
6804 else
6805 tryposBrace = NULL;
6806 }
6807
6808 if (trypos != NULL)
6809 {
6810 /*
6811 * If the matching paren is more than one line away, use the indent of
6812 * a previous non-empty line that matches the same paren.
6813 */
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006814 if (theline[0] == ')' && ind_paren_prev)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006815 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006816 /* Line up with the start of the matching paren line. */
6817 amount = get_indent_lnum(curwin->w_cursor.lnum - 1); /* XXX */
6818 }
6819 else
6820 {
6821 amount = -1;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006822 our_paren_pos = *trypos;
6823 for (lnum = cur_curpos.lnum - 1; lnum > our_paren_pos.lnum; --lnum)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006824 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006825 l = skipwhite(ml_get(lnum));
6826 if (cin_nocode(l)) /* skip comment lines */
6827 continue;
6828 if (cin_ispreproc_cont(&l, &lnum))
6829 continue; /* ignore #define, #if, etc. */
6830 curwin->w_cursor.lnum = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006831
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006832 /* Skip a comment. XXX */
6833 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
6834 {
6835 lnum = trypos->lnum + 1;
6836 continue;
6837 }
6838
6839 /* XXX */
6840 if ((trypos = find_match_paren(
6841 corr_ind_maxparen(ind_maxparen, &cur_curpos),
Bram Moolenaar071d4272004-06-13 20:20:40 +00006842 ind_maxcomment)) != NULL
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006843 && trypos->lnum == our_paren_pos.lnum
6844 && trypos->col == our_paren_pos.col)
6845 {
6846 amount = get_indent_lnum(lnum); /* XXX */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006847
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006848 if (theline[0] == ')')
6849 {
6850 if (our_paren_pos.lnum != lnum
6851 && cur_amount > amount)
6852 cur_amount = amount;
6853 amount = -1;
6854 }
6855 break;
6856 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006857 }
6858 }
6859
6860 /*
6861 * Line up with line where the matching paren is. XXX
6862 * If the line starts with a '(' or the indent for unclosed
6863 * parentheses is zero, line up with the unclosed parentheses.
6864 */
6865 if (amount == -1)
6866 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006867 int ignore_paren_col = 0;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006868 int is_if_for_while = 0;
6869
6870 if (ind_if_for_while)
6871 {
6872 /* Look for the outermost opening parenthesis on this line
6873 * and check whether it belongs to an "if", "for" or "while". */
6874
6875 pos_T cursor_save = curwin->w_cursor;
6876 pos_T outermost;
6877 char_u *line;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006878
6879 trypos = &our_paren_pos;
6880 do {
6881 outermost = *trypos;
6882 curwin->w_cursor.lnum = outermost.lnum;
6883 curwin->w_cursor.col = outermost.col;
6884
6885 trypos = find_match_paren(ind_maxparen, ind_maxcomment);
6886 } while (trypos && trypos->lnum == outermost.lnum);
6887
6888 curwin->w_cursor = cursor_save;
6889
6890 line = ml_get(outermost.lnum);
6891
6892 is_if_for_while =
6893 cin_is_if_for_while_before_offset(line, outermost.col,
6894 &outermost.col);
6895 }
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006896
Bram Moolenaar071d4272004-06-13 20:20:40 +00006897 amount = skip_label(our_paren_pos.lnum, &look, ind_maxcomment);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006898 look = skipwhite(look);
6899 if (*look == '(')
6900 {
6901 linenr_T save_lnum = curwin->w_cursor.lnum;
6902 char_u *line;
6903 int look_col;
6904
6905 /* Ignore a '(' in front of the line that has a match before
6906 * our matching '('. */
6907 curwin->w_cursor.lnum = our_paren_pos.lnum;
6908 line = ml_get_curline();
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006909 look_col = (int)(look - line);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006910 curwin->w_cursor.col = look_col + 1;
6911 if ((trypos = findmatchlimit(NULL, ')', 0, ind_maxparen))
6912 != NULL
6913 && trypos->lnum == our_paren_pos.lnum
6914 && trypos->col < our_paren_pos.col)
6915 ignore_paren_col = trypos->col + 1;
6916
6917 curwin->w_cursor.lnum = save_lnum;
6918 look = ml_get(our_paren_pos.lnum) + look_col;
6919 }
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006920 if (theline[0] == ')' || (ind_unclosed == 0 && is_if_for_while == 0)
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006921 || (!ind_unclosed_noignore && *look == '('
6922 && ignore_paren_col == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006923 {
6924 /*
6925 * If we're looking at a close paren, line up right there;
6926 * otherwise, line up with the next (non-white) character.
6927 * When ind_unclosed_wrapped is set and the matching paren is
6928 * the last nonwhite character of the line, use either the
6929 * indent of the current line or the indentation of the next
6930 * outer paren and add ind_unclosed_wrapped (for very long
6931 * lines).
6932 */
6933 if (theline[0] != ')')
6934 {
6935 cur_amount = MAXCOL;
6936 l = ml_get(our_paren_pos.lnum);
6937 if (ind_unclosed_wrapped
6938 && cin_ends_in(l, (char_u *)"(", NULL))
6939 {
6940 /* look for opening unmatched paren, indent one level
6941 * for each additional level */
6942 n = 1;
6943 for (col = 0; col < our_paren_pos.col; ++col)
6944 {
6945 switch (l[col])
6946 {
6947 case '(':
6948 case '{': ++n;
6949 break;
6950
6951 case ')':
6952 case '}': if (n > 1)
6953 --n;
6954 break;
6955 }
6956 }
6957
6958 our_paren_pos.col = 0;
6959 amount += n * ind_unclosed_wrapped;
6960 }
6961 else if (ind_unclosed_whiteok)
6962 our_paren_pos.col++;
6963 else
6964 {
6965 col = our_paren_pos.col + 1;
6966 while (vim_iswhite(l[col]))
6967 col++;
6968 if (l[col] != NUL) /* In case of trailing space */
6969 our_paren_pos.col = col;
6970 else
6971 our_paren_pos.col++;
6972 }
6973 }
6974
6975 /*
6976 * Find how indented the paren is, or the character after it
6977 * if we did the above "if".
6978 */
6979 if (our_paren_pos.col > 0)
6980 {
6981 getvcol(curwin, &our_paren_pos, &col, NULL, NULL);
6982 if (cur_amount > (int)col)
6983 cur_amount = col;
6984 }
6985 }
6986
6987 if (theline[0] == ')' && ind_matching_paren)
6988 {
6989 /* Line up with the start of the matching paren line. */
6990 }
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006991 else if ((ind_unclosed == 0 && is_if_for_while == 0)
6992 || (!ind_unclosed_noignore
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006993 && *look == '(' && ignore_paren_col == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006994 {
6995 if (cur_amount != MAXCOL)
6996 amount = cur_amount;
6997 }
6998 else
6999 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007000 /* Add ind_unclosed2 for each '(' before our matching one, but
7001 * ignore (void) before the line (ignore_paren_col). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007002 col = our_paren_pos.col;
Bram Moolenaarb21e5842006-04-16 18:30:08 +00007003 while ((int)our_paren_pos.col > ignore_paren_col)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007004 {
7005 --our_paren_pos.col;
7006 switch (*ml_get_pos(&our_paren_pos))
7007 {
7008 case '(': amount += ind_unclosed2;
7009 col = our_paren_pos.col;
7010 break;
7011 case ')': amount -= ind_unclosed2;
7012 col = MAXCOL;
7013 break;
7014 }
7015 }
7016
7017 /* Use ind_unclosed once, when the first '(' is not inside
7018 * braces */
7019 if (col == MAXCOL)
7020 amount += ind_unclosed;
7021 else
7022 {
7023 curwin->w_cursor.lnum = our_paren_pos.lnum;
7024 curwin->w_cursor.col = col;
Bram Moolenaar367bec82011-04-11 14:26:19 +02007025 if (find_match_paren(ind_maxparen, ind_maxcomment) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007026 amount += ind_unclosed2;
7027 else
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007028 {
7029 if (is_if_for_while)
7030 amount += ind_if_for_while;
7031 else
7032 amount += ind_unclosed;
7033 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007034 }
7035 /*
7036 * For a line starting with ')' use the minimum of the two
7037 * positions, to avoid giving it more indent than the previous
7038 * lines:
7039 * func_long_name( if (x
7040 * arg && yy
7041 * ) ^ not here ) ^ not here
7042 */
7043 if (cur_amount < amount)
7044 amount = cur_amount;
7045 }
7046 }
7047
7048 /* add extra indent for a comment */
7049 if (cin_iscomment(theline))
7050 amount += ind_comment;
7051 }
7052
7053 /*
7054 * Are we at least inside braces, then?
7055 */
7056 else
7057 {
7058 trypos = tryposBrace;
7059
7060 ourscope = trypos->lnum;
7061 start = ml_get(ourscope);
7062
7063 /*
7064 * Now figure out how indented the line is in general.
7065 * If the brace was at the start of the line, we use that;
7066 * otherwise, check out the indentation of the line as
7067 * a whole and then add the "imaginary indent" to that.
7068 */
7069 look = skipwhite(start);
7070 if (*look == '{')
7071 {
7072 getvcol(curwin, trypos, &col, NULL, NULL);
7073 amount = col;
7074 if (*start == '{')
7075 start_brace = BRACE_IN_COL0;
7076 else
7077 start_brace = BRACE_AT_START;
7078 }
7079 else
7080 {
7081 /*
7082 * that opening brace might have been on a continuation
7083 * line. if so, find the start of the line.
7084 */
7085 curwin->w_cursor.lnum = ourscope;
7086
7087 /*
7088 * position the cursor over the rightmost paren, so that
7089 * matching it will take us back to the start of the line.
7090 */
7091 lnum = ourscope;
7092 if (find_last_paren(start, '(', ')')
7093 && (trypos = find_match_paren(ind_maxparen,
7094 ind_maxcomment)) != NULL)
7095 lnum = trypos->lnum;
7096
7097 /*
7098 * It could have been something like
7099 * case 1: if (asdf &&
7100 * ldfd) {
7101 * }
7102 */
Bram Moolenaar6ec154b2011-06-12 21:51:08 +02007103 if (ind_js || (ind_keep_case_label
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007104 && cin_iscase(skipwhite(ml_get_curline()), FALSE)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007105 amount = get_indent();
7106 else
7107 amount = skip_label(lnum, &l, ind_maxcomment);
7108
7109 start_brace = BRACE_AT_END;
7110 }
7111
7112 /*
7113 * if we're looking at a closing brace, that's where
7114 * we want to be. otherwise, add the amount of room
7115 * that an indent is supposed to be.
7116 */
7117 if (theline[0] == '}')
7118 {
7119 /*
7120 * they may want closing braces to line up with something
7121 * other than the open brace. indulge them, if so.
7122 */
7123 amount += ind_close_extra;
7124 }
7125 else
7126 {
7127 /*
7128 * If we're looking at an "else", try to find an "if"
7129 * to match it with.
7130 * If we're looking at a "while", try to find a "do"
7131 * to match it with.
7132 */
7133 lookfor = LOOKFOR_INITIAL;
7134 if (cin_iselse(theline))
7135 lookfor = LOOKFOR_IF;
7136 else if (cin_iswhileofdo(theline, cur_curpos.lnum, ind_maxparen))
7137 /* XXX */
7138 lookfor = LOOKFOR_DO;
7139 if (lookfor != LOOKFOR_INITIAL)
7140 {
7141 curwin->w_cursor.lnum = cur_curpos.lnum;
7142 if (find_match(lookfor, ourscope, ind_maxparen,
7143 ind_maxcomment) == OK)
7144 {
7145 amount = get_indent(); /* XXX */
7146 goto theend;
7147 }
7148 }
7149
7150 /*
7151 * We get here if we are not on an "while-of-do" or "else" (or
7152 * failed to find a matching "if").
7153 * Search backwards for something to line up with.
7154 * First set amount for when we don't find anything.
7155 */
7156
7157 /*
7158 * if the '{' is _really_ at the left margin, use the imaginary
7159 * location of a left-margin brace. Otherwise, correct the
7160 * location for ind_open_extra.
7161 */
7162
7163 if (start_brace == BRACE_IN_COL0) /* '{' is in column 0 */
7164 {
7165 amount = ind_open_left_imag;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007166 lookfor_cpp_namespace = TRUE;
7167 }
7168 else if (start_brace == BRACE_AT_START &&
7169 lookfor_cpp_namespace) /* '{' is at start */
7170 {
7171
7172 lookfor_cpp_namespace = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007173 }
7174 else
7175 {
7176 if (start_brace == BRACE_AT_END) /* '{' is at end of line */
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007177 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007178 amount += ind_open_imag;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007179
7180 l = skipwhite(ml_get_curline());
7181 if (cin_is_cpp_namespace(l))
7182 amount += ind_cpp_namespace;
7183 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007184 else
7185 {
7186 /* Compensate for adding ind_open_extra later. */
7187 amount -= ind_open_extra;
7188 if (amount < 0)
7189 amount = 0;
7190 }
7191 }
7192
7193 lookfor_break = FALSE;
7194
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007195 if (cin_iscase(theline, FALSE)) /* it's a switch() label */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007196 {
7197 lookfor = LOOKFOR_CASE; /* find a previous switch() label */
7198 amount += ind_case;
7199 }
7200 else if (cin_isscopedecl(theline)) /* private:, ... */
7201 {
7202 lookfor = LOOKFOR_SCOPEDECL; /* class decl is this block */
7203 amount += ind_scopedecl;
7204 }
7205 else
7206 {
7207 if (ind_case_break && cin_isbreak(theline)) /* break; ... */
7208 lookfor_break = TRUE;
7209
7210 lookfor = LOOKFOR_INITIAL;
7211 amount += ind_level; /* ind_level from start of block */
7212 }
7213 scope_amount = amount;
7214 whilelevel = 0;
7215
7216 /*
7217 * Search backwards. If we find something we recognize, line up
7218 * with that.
7219 *
7220 * if we're looking at an open brace, indent
7221 * the usual amount relative to the conditional
7222 * that opens the block.
7223 */
7224 curwin->w_cursor = cur_curpos;
7225 for (;;)
7226 {
7227 curwin->w_cursor.lnum--;
7228 curwin->w_cursor.col = 0;
7229
7230 /*
7231 * If we went all the way back to the start of our scope, line
7232 * up with it.
7233 */
7234 if (curwin->w_cursor.lnum <= ourscope)
7235 {
7236 /* we reached end of scope:
7237 * if looking for a enum or structure initialization
7238 * go further back:
7239 * if it is an initializer (enum xxx or xxx =), then
7240 * don't add ind_continuation, otherwise it is a variable
7241 * declaration:
7242 * int x,
7243 * here; <-- add ind_continuation
7244 */
7245 if (lookfor == LOOKFOR_ENUM_OR_INIT)
7246 {
7247 if (curwin->w_cursor.lnum == 0
7248 || curwin->w_cursor.lnum
7249 < ourscope - ind_maxparen)
7250 {
7251 /* nothing found (abuse ind_maxparen as limit)
7252 * assume terminated line (i.e. a variable
7253 * initialization) */
7254 if (cont_amount > 0)
7255 amount = cont_amount;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007256 else if (!ind_js)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007257 amount += ind_continuation;
7258 break;
7259 }
7260
7261 l = ml_get_curline();
7262
7263 /*
7264 * If we're in a comment now, skip to the start of the
7265 * comment.
7266 */
7267 trypos = find_start_comment(ind_maxcomment);
7268 if (trypos != NULL)
7269 {
7270 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007271 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007272 continue;
7273 }
7274
7275 /*
7276 * Skip preprocessor directives and blank lines.
7277 */
7278 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7279 continue;
7280
7281 if (cin_nocode(l))
7282 continue;
7283
7284 terminated = cin_isterminated(l, FALSE, TRUE);
7285
7286 /*
7287 * If we are at top level and the line looks like a
7288 * function declaration, we are done
7289 * (it's a variable declaration).
7290 */
7291 if (start_brace != BRACE_IN_COL0
Bram Moolenaarc367faa2011-12-14 20:21:35 +01007292 || !cin_isfuncdecl(&l, curwin->w_cursor.lnum,
7293 0, ind_maxparen, ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007294 {
7295 /* if the line is terminated with another ','
7296 * it is a continued variable initialization.
7297 * don't add extra indent.
7298 * TODO: does not work, if a function
7299 * declaration is split over multiple lines:
7300 * cin_isfuncdecl returns FALSE then.
7301 */
7302 if (terminated == ',')
7303 break;
7304
7305 /* if it es a enum declaration or an assignment,
7306 * we are done.
7307 */
7308 if (terminated != ';' && cin_isinit())
7309 break;
7310
7311 /* nothing useful found */
7312 if (terminated == 0 || terminated == '{')
7313 continue;
7314 }
7315
7316 if (terminated != ';')
7317 {
7318 /* Skip parens and braces. Position the cursor
7319 * over the rightmost paren, so that matching it
7320 * will take us back to the start of the line.
7321 */ /* XXX */
7322 trypos = NULL;
7323 if (find_last_paren(l, '(', ')'))
7324 trypos = find_match_paren(ind_maxparen,
7325 ind_maxcomment);
7326
7327 if (trypos == NULL && find_last_paren(l, '{', '}'))
7328 trypos = find_start_brace(ind_maxcomment);
7329
7330 if (trypos != NULL)
7331 {
7332 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007333 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007334 continue;
7335 }
7336 }
7337
7338 /* it's a variable declaration, add indentation
7339 * like in
7340 * int a,
7341 * b;
7342 */
7343 if (cont_amount > 0)
7344 amount = cont_amount;
7345 else
7346 amount += ind_continuation;
7347 }
7348 else if (lookfor == LOOKFOR_UNTERM)
7349 {
7350 if (cont_amount > 0)
7351 amount = cont_amount;
7352 else
7353 amount += ind_continuation;
7354 }
Bram Moolenaare79d1532011-10-04 18:03:47 +02007355 else
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007356 {
Bram Moolenaare79d1532011-10-04 18:03:47 +02007357 if (lookfor != LOOKFOR_TERM
Bram Moolenaar071d4272004-06-13 20:20:40 +00007358 && lookfor != LOOKFOR_CPP_BASECLASS)
Bram Moolenaare79d1532011-10-04 18:03:47 +02007359 {
7360 amount = scope_amount;
7361 if (theline[0] == '{')
7362 {
7363 amount += ind_open_extra;
7364 added_to_amount = ind_open_extra;
7365 }
7366 }
7367
7368 if (lookfor_cpp_namespace)
7369 {
7370 /*
7371 * Looking for C++ namespace, need to look further
7372 * back.
7373 */
7374 if (curwin->w_cursor.lnum == ourscope)
7375 continue;
7376
7377 if (curwin->w_cursor.lnum == 0
7378 || curwin->w_cursor.lnum
7379 < ourscope - FIND_NAMESPACE_LIM)
7380 break;
7381
7382 l = ml_get_curline();
7383
7384 /* If we're in a comment now, skip to the start of
7385 * the comment. */
7386 trypos = find_start_comment(ind_maxcomment);
7387 if (trypos != NULL)
7388 {
7389 curwin->w_cursor.lnum = trypos->lnum + 1;
7390 curwin->w_cursor.col = 0;
7391 continue;
7392 }
7393
7394 /* Skip preprocessor directives and blank lines. */
7395 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7396 continue;
7397
7398 /* Finally the actual check for "namespace". */
7399 if (cin_is_cpp_namespace(l))
7400 {
7401 amount += ind_cpp_namespace - added_to_amount;
7402 break;
7403 }
7404
7405 if (cin_nocode(l))
7406 continue;
7407 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007408 }
7409 break;
7410 }
7411
7412 /*
7413 * If we're in a comment now, skip to the start of the comment.
7414 */ /* XXX */
7415 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
7416 {
7417 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007418 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007419 continue;
7420 }
7421
7422 l = ml_get_curline();
7423
7424 /*
7425 * If this is a switch() label, may line up relative to that.
Bram Moolenaar18144c82006-04-12 21:52:12 +00007426 * If this is a C++ scope declaration, do the same.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007427 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007428 iscase = cin_iscase(l, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007429 if (iscase || cin_isscopedecl(l))
7430 {
7431 /* we are only looking for cpp base class
7432 * declaration/initialization any longer */
7433 if (lookfor == LOOKFOR_CPP_BASECLASS)
7434 break;
7435
7436 /* When looking for a "do" we are not interested in
7437 * labels. */
7438 if (whilelevel > 0)
7439 continue;
7440
7441 /*
7442 * case xx:
7443 * c = 99 + <- this indent plus continuation
7444 *-> here;
7445 */
7446 if (lookfor == LOOKFOR_UNTERM
7447 || lookfor == LOOKFOR_ENUM_OR_INIT)
7448 {
7449 if (cont_amount > 0)
7450 amount = cont_amount;
7451 else
7452 amount += ind_continuation;
7453 break;
7454 }
7455
7456 /*
7457 * case xx: <- line up with this case
7458 * x = 333;
7459 * case yy:
7460 */
7461 if ( (iscase && lookfor == LOOKFOR_CASE)
7462 || (iscase && lookfor_break)
7463 || (!iscase && lookfor == LOOKFOR_SCOPEDECL))
7464 {
7465 /*
7466 * Check that this case label is not for another
7467 * switch()
7468 */ /* XXX */
7469 if ((trypos = find_start_brace(ind_maxcomment)) ==
7470 NULL || trypos->lnum == ourscope)
7471 {
7472 amount = get_indent(); /* XXX */
7473 break;
7474 }
7475 continue;
7476 }
7477
7478 n = get_indent_nolabel(curwin->w_cursor.lnum); /* XXX */
7479
7480 /*
7481 * case xx: if (cond) <- line up with this if
7482 * y = y + 1;
7483 * -> s = 99;
7484 *
7485 * case xx:
7486 * if (cond) <- line up with this line
7487 * y = y + 1;
7488 * -> s = 99;
7489 */
7490 if (lookfor == LOOKFOR_TERM)
7491 {
7492 if (n)
7493 amount = n;
7494
7495 if (!lookfor_break)
7496 break;
7497 }
7498
7499 /*
7500 * case xx: x = x + 1; <- line up with this x
7501 * -> y = y + 1;
7502 *
7503 * case xx: if (cond) <- line up with this if
7504 * -> y = y + 1;
7505 */
7506 if (n)
7507 {
7508 amount = n;
7509 l = after_label(ml_get_curline());
7510 if (l != NULL && cin_is_cinword(l))
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007511 {
7512 if (theline[0] == '{')
7513 amount += ind_open_extra;
7514 else
7515 amount += ind_level + ind_no_brace;
7516 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007517 break;
7518 }
7519
7520 /*
7521 * Try to get the indent of a statement before the switch
7522 * label. If nothing is found, line up relative to the
7523 * switch label.
7524 * break; <- may line up with this line
7525 * case xx:
7526 * -> y = 1;
7527 */
7528 scope_amount = get_indent() + (iscase /* XXX */
7529 ? ind_case_code : ind_scopedecl_code);
7530 lookfor = ind_case_break ? LOOKFOR_NOBREAK : LOOKFOR_ANY;
7531 continue;
7532 }
7533
7534 /*
7535 * Looking for a switch() label or C++ scope declaration,
7536 * ignore other lines, skip {}-blocks.
7537 */
7538 if (lookfor == LOOKFOR_CASE || lookfor == LOOKFOR_SCOPEDECL)
7539 {
7540 if (find_last_paren(l, '{', '}') && (trypos =
7541 find_start_brace(ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007542 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007543 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007544 curwin->w_cursor.col = 0;
7545 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007546 continue;
7547 }
7548
7549 /*
7550 * Ignore jump labels with nothing after them.
7551 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007552 if (!ind_js && cin_islabel(ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007553 {
7554 l = after_label(ml_get_curline());
7555 if (l == NULL || cin_nocode(l))
7556 continue;
7557 }
7558
7559 /*
7560 * Ignore #defines, #if, etc.
7561 * Ignore comment and empty lines.
7562 * (need to get the line again, cin_islabel() may have
7563 * unlocked it)
7564 */
7565 l = ml_get_curline();
7566 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum)
7567 || cin_nocode(l))
7568 continue;
7569
7570 /*
7571 * Are we at the start of a cpp base class declaration or
7572 * constructor initialization?
7573 */ /* XXX */
Bram Moolenaar18144c82006-04-12 21:52:12 +00007574 n = FALSE;
7575 if (lookfor != LOOKFOR_TERM && ind_cpp_baseclass > 0)
7576 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00007577 n = cin_is_cpp_baseclass(&col);
Bram Moolenaar18144c82006-04-12 21:52:12 +00007578 l = ml_get_curline();
7579 }
7580 if (n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007581 {
7582 if (lookfor == LOOKFOR_UNTERM)
7583 {
7584 if (cont_amount > 0)
7585 amount = cont_amount;
7586 else
7587 amount += ind_continuation;
7588 }
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007589 else if (theline[0] == '{')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007590 {
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007591 /* Need to find start of the declaration. */
7592 lookfor = LOOKFOR_UNTERM;
7593 ind_continuation = 0;
7594 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007595 }
7596 else
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007597 /* XXX */
7598 amount = get_baseclass_amount(col, ind_maxparen,
7599 ind_maxcomment, ind_cpp_baseclass);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007600 break;
7601 }
7602 else if (lookfor == LOOKFOR_CPP_BASECLASS)
7603 {
7604 /* only look, whether there is a cpp base class
Bram Moolenaar18144c82006-04-12 21:52:12 +00007605 * declaration or initialization before the opening brace.
7606 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007607 if (cin_isterminated(l, TRUE, FALSE))
7608 break;
7609 else
7610 continue;
7611 }
7612
7613 /*
7614 * What happens next depends on the line being terminated.
7615 * If terminated with a ',' only consider it terminating if
Bram Moolenaar25394022007-05-10 19:06:20 +00007616 * there is another unterminated statement behind, eg:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007617 * 123,
7618 * sizeof
7619 * here
7620 * Otherwise check whether it is a enumeration or structure
7621 * initialisation (not indented) or a variable declaration
7622 * (indented).
7623 */
7624 terminated = cin_isterminated(l, FALSE, TRUE);
7625
7626 if (terminated == 0 || (lookfor != LOOKFOR_UNTERM
7627 && terminated == ','))
7628 {
7629 /*
7630 * if we're in the middle of a paren thing,
7631 * go back to the line that starts it so
7632 * we can get the right prevailing indent
7633 * if ( foo &&
7634 * bar )
7635 */
7636 /*
7637 * position the cursor over the rightmost paren, so that
7638 * matching it will take us back to the start of the line.
7639 */
7640 (void)find_last_paren(l, '(', ')');
7641 trypos = find_match_paren(
7642 corr_ind_maxparen(ind_maxparen, &cur_curpos),
7643 ind_maxcomment);
7644
7645 /*
7646 * If we are looking for ',', we also look for matching
7647 * braces.
7648 */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007649 if (trypos == NULL && terminated == ','
7650 && find_last_paren(l, '{', '}'))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007651 trypos = find_start_brace(ind_maxcomment);
7652
7653 if (trypos != NULL)
7654 {
7655 /*
7656 * Check if we are on a case label now. This is
7657 * handled above.
7658 * case xx: if ( asdf &&
7659 * asdf)
7660 */
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007661 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007662 l = ml_get_curline();
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007663 if (cin_iscase(l, FALSE) || cin_isscopedecl(l))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007664 {
7665 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007666 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007667 continue;
7668 }
7669 }
7670
7671 /*
7672 * Skip over continuation lines to find the one to get the
7673 * indent from
7674 * char *usethis = "bla\
7675 * bla",
7676 * here;
7677 */
7678 if (terminated == ',')
7679 {
7680 while (curwin->w_cursor.lnum > 1)
7681 {
7682 l = ml_get(curwin->w_cursor.lnum - 1);
7683 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
7684 break;
7685 --curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007686 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007687 }
7688 }
7689
7690 /*
7691 * Get indent and pointer to text for current line,
7692 * ignoring any jump label. XXX
7693 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007694 if (!ind_js)
7695 cur_amount = skip_label(curwin->w_cursor.lnum,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007696 &l, ind_maxcomment);
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007697 else
7698 cur_amount = get_indent();
Bram Moolenaar071d4272004-06-13 20:20:40 +00007699 /*
7700 * If this is just above the line we are indenting, and it
7701 * starts with a '{', line it up with this line.
7702 * while (not)
7703 * -> {
7704 * }
7705 */
7706 if (terminated != ',' && lookfor != LOOKFOR_TERM
7707 && theline[0] == '{')
7708 {
7709 amount = cur_amount;
7710 /*
7711 * Only add ind_open_extra when the current line
7712 * doesn't start with a '{', which must have a match
7713 * in the same line (scope is the same). Probably:
7714 * { 1, 2 },
7715 * -> { 3, 4 }
7716 */
7717 if (*skipwhite(l) != '{')
7718 amount += ind_open_extra;
7719
7720 if (ind_cpp_baseclass)
7721 {
7722 /* have to look back, whether it is a cpp base
7723 * class declaration or initialization */
7724 lookfor = LOOKFOR_CPP_BASECLASS;
7725 continue;
7726 }
7727 break;
7728 }
7729
7730 /*
7731 * Check if we are after an "if", "while", etc.
7732 * Also allow " } else".
7733 */
7734 if (cin_is_cinword(l) || cin_iselse(skipwhite(l)))
7735 {
7736 /*
7737 * Found an unterminated line after an if (), line up
7738 * with the last one.
7739 * if (cond)
7740 * 100 +
7741 * -> here;
7742 */
7743 if (lookfor == LOOKFOR_UNTERM
7744 || lookfor == LOOKFOR_ENUM_OR_INIT)
7745 {
7746 if (cont_amount > 0)
7747 amount = cont_amount;
7748 else
7749 amount += ind_continuation;
7750 break;
7751 }
7752
7753 /*
7754 * If this is just above the line we are indenting, we
7755 * are finished.
7756 * while (not)
7757 * -> here;
7758 * Otherwise this indent can be used when the line
7759 * before this is terminated.
7760 * yyy;
7761 * if (stat)
7762 * while (not)
7763 * xxx;
7764 * -> here;
7765 */
7766 amount = cur_amount;
7767 if (theline[0] == '{')
7768 amount += ind_open_extra;
7769 if (lookfor != LOOKFOR_TERM)
7770 {
7771 amount += ind_level + ind_no_brace;
7772 break;
7773 }
7774
7775 /*
7776 * Special trick: when expecting the while () after a
7777 * do, line up with the while()
7778 * do
7779 * x = 1;
7780 * -> here
7781 */
7782 l = skipwhite(ml_get_curline());
7783 if (cin_isdo(l))
7784 {
7785 if (whilelevel == 0)
7786 break;
7787 --whilelevel;
7788 }
7789
7790 /*
7791 * When searching for a terminated line, don't use the
Bram Moolenaar334adf02011-05-25 13:34:04 +02007792 * one between the "if" and the matching "else".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007793 * Need to use the scope of this "else". XXX
7794 * If whilelevel != 0 continue looking for a "do {".
7795 */
Bram Moolenaar334adf02011-05-25 13:34:04 +02007796 if (cin_iselse(l) && whilelevel == 0)
7797 {
7798 /* If we're looking at "} else", let's make sure we
7799 * find the opening brace of the enclosing scope,
7800 * not the one from "if () {". */
7801 if (*l == '}')
7802 curwin->w_cursor.col =
Bram Moolenaar9b83c2f2011-05-25 17:29:44 +02007803 (colnr_T)(l - ml_get_curline()) + 1;
Bram Moolenaar334adf02011-05-25 13:34:04 +02007804
7805 if ((trypos = find_start_brace(ind_maxcomment))
7806 == NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007807 || find_match(LOOKFOR_IF, trypos->lnum,
Bram Moolenaar334adf02011-05-25 13:34:04 +02007808 ind_maxparen, ind_maxcomment) == FAIL)
7809 break;
7810 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007811 }
7812
7813 /*
7814 * If we're below an unterminated line that is not an
7815 * "if" or something, we may line up with this line or
Bram Moolenaar25394022007-05-10 19:06:20 +00007816 * add something for a continuation line, depending on
Bram Moolenaar071d4272004-06-13 20:20:40 +00007817 * the line before this one.
7818 */
7819 else
7820 {
7821 /*
7822 * Found two unterminated lines on a row, line up with
7823 * the last one.
7824 * c = 99 +
7825 * 100 +
7826 * -> here;
7827 */
7828 if (lookfor == LOOKFOR_UNTERM)
7829 {
7830 /* When line ends in a comma add extra indent */
7831 if (terminated == ',')
7832 amount += ind_continuation;
7833 break;
7834 }
7835
7836 if (lookfor == LOOKFOR_ENUM_OR_INIT)
7837 {
7838 /* Found two lines ending in ',', lineup with the
7839 * lowest one, but check for cpp base class
7840 * declaration/initialization, if it is an
7841 * opening brace or we are looking just for
7842 * enumerations/initializations. */
7843 if (terminated == ',')
7844 {
7845 if (ind_cpp_baseclass == 0)
7846 break;
7847
7848 lookfor = LOOKFOR_CPP_BASECLASS;
7849 continue;
7850 }
7851
7852 /* Ignore unterminated lines in between, but
7853 * reduce indent. */
7854 if (amount > cur_amount)
7855 amount = cur_amount;
7856 }
7857 else
7858 {
7859 /*
7860 * Found first unterminated line on a row, may
7861 * line up with this line, remember its indent
7862 * 100 +
7863 * -> here;
7864 */
7865 amount = cur_amount;
7866
7867 /*
7868 * If previous line ends in ',', check whether we
7869 * are in an initialization or enum
7870 * struct xxx =
7871 * {
7872 * sizeof a,
7873 * 124 };
7874 * or a normal possible continuation line.
7875 * but only, of no other statement has been found
7876 * yet.
7877 */
7878 if (lookfor == LOOKFOR_INITIAL && terminated == ',')
7879 {
7880 lookfor = LOOKFOR_ENUM_OR_INIT;
7881 cont_amount = cin_first_id_amount();
7882 }
7883 else
7884 {
7885 if (lookfor == LOOKFOR_INITIAL
7886 && *l != NUL
7887 && l[STRLEN(l) - 1] == '\\')
7888 /* XXX */
7889 cont_amount = cin_get_equal_amount(
7890 curwin->w_cursor.lnum);
7891 if (lookfor != LOOKFOR_TERM)
7892 lookfor = LOOKFOR_UNTERM;
7893 }
7894 }
7895 }
7896 }
7897
7898 /*
7899 * Check if we are after a while (cond);
7900 * If so: Ignore until the matching "do".
7901 */
7902 /* XXX */
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007903 else if (cin_iswhileofdo_end(terminated, ind_maxparen,
7904 ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007905 {
7906 /*
7907 * Found an unterminated line after a while ();, line up
7908 * with the last one.
7909 * while (cond);
7910 * 100 + <- line up with this one
7911 * -> here;
7912 */
7913 if (lookfor == LOOKFOR_UNTERM
7914 || lookfor == LOOKFOR_ENUM_OR_INIT)
7915 {
7916 if (cont_amount > 0)
7917 amount = cont_amount;
7918 else
7919 amount += ind_continuation;
7920 break;
7921 }
7922
7923 if (whilelevel == 0)
7924 {
7925 lookfor = LOOKFOR_TERM;
7926 amount = get_indent(); /* XXX */
7927 if (theline[0] == '{')
7928 amount += ind_open_extra;
7929 }
7930 ++whilelevel;
7931 }
7932
7933 /*
7934 * We are after a "normal" statement.
7935 * If we had another statement we can stop now and use the
7936 * indent of that other statement.
7937 * Otherwise the indent of the current statement may be used,
7938 * search backwards for the next "normal" statement.
7939 */
7940 else
7941 {
7942 /*
7943 * Skip single break line, if before a switch label. It
7944 * may be lined up with the case label.
7945 */
7946 if (lookfor == LOOKFOR_NOBREAK
7947 && cin_isbreak(skipwhite(ml_get_curline())))
7948 {
7949 lookfor = LOOKFOR_ANY;
7950 continue;
7951 }
7952
7953 /*
7954 * Handle "do {" line.
7955 */
7956 if (whilelevel > 0)
7957 {
7958 l = cin_skipcomment(ml_get_curline());
7959 if (cin_isdo(l))
7960 {
7961 amount = get_indent(); /* XXX */
7962 --whilelevel;
7963 continue;
7964 }
7965 }
7966
7967 /*
7968 * Found a terminated line above an unterminated line. Add
7969 * the amount for a continuation line.
7970 * x = 1;
7971 * y = foo +
7972 * -> here;
7973 * or
7974 * int x = 1;
7975 * int foo,
7976 * -> here;
7977 */
7978 if (lookfor == LOOKFOR_UNTERM
7979 || lookfor == LOOKFOR_ENUM_OR_INIT)
7980 {
7981 if (cont_amount > 0)
7982 amount = cont_amount;
7983 else
7984 amount += ind_continuation;
7985 break;
7986 }
7987
7988 /*
7989 * Found a terminated line above a terminated line or "if"
7990 * etc. line. Use the amount of the line below us.
7991 * x = 1; x = 1;
7992 * if (asdf) y = 2;
7993 * while (asdf) ->here;
7994 * here;
7995 * ->foo;
7996 */
7997 if (lookfor == LOOKFOR_TERM)
7998 {
7999 if (!lookfor_break && whilelevel == 0)
8000 break;
8001 }
8002
8003 /*
8004 * First line above the one we're indenting is terminated.
8005 * To know what needs to be done look further backward for
8006 * a terminated line.
8007 */
8008 else
8009 {
8010 /*
8011 * position the cursor over the rightmost paren, so
8012 * that matching it will take us back to the start of
8013 * the line. Helps for:
8014 * func(asdr,
8015 * asdfasdf);
8016 * here;
8017 */
8018term_again:
8019 l = ml_get_curline();
8020 if (find_last_paren(l, '(', ')')
8021 && (trypos = find_match_paren(ind_maxparen,
8022 ind_maxcomment)) != NULL)
8023 {
8024 /*
8025 * Check if we are on a case label now. This is
8026 * handled above.
8027 * case xx: if ( asdf &&
8028 * asdf)
8029 */
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008030 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008031 l = ml_get_curline();
Bram Moolenaar3acfc302010-07-11 17:23:02 +02008032 if (cin_iscase(l, FALSE) || cin_isscopedecl(l))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008033 {
8034 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008035 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008036 continue;
8037 }
8038 }
8039
8040 /* When aligning with the case statement, don't align
8041 * with a statement after it.
8042 * case 1: { <-- don't use this { position
8043 * stat;
8044 * }
8045 * case 2:
8046 * stat;
8047 * }
8048 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02008049 iscase = (ind_keep_case_label && cin_iscase(l, FALSE));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008050
8051 /*
8052 * Get indent and pointer to text for current line,
8053 * ignoring any jump label.
8054 */
8055 amount = skip_label(curwin->w_cursor.lnum,
8056 &l, ind_maxcomment);
8057
8058 if (theline[0] == '{')
8059 amount += ind_open_extra;
8060 /* See remark above: "Only add ind_open_extra.." */
Bram Moolenaar18144c82006-04-12 21:52:12 +00008061 l = skipwhite(l);
8062 if (*l == '{')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008063 amount -= ind_open_extra;
8064 lookfor = iscase ? LOOKFOR_ANY : LOOKFOR_TERM;
8065
8066 /*
Bram Moolenaar18144c82006-04-12 21:52:12 +00008067 * When a terminated line starts with "else" skip to
8068 * the matching "if":
8069 * else 3;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008070 * indent this;
Bram Moolenaar18144c82006-04-12 21:52:12 +00008071 * Need to use the scope of this "else". XXX
8072 * If whilelevel != 0 continue looking for a "do {".
8073 */
8074 if (lookfor == LOOKFOR_TERM
8075 && *l != '}'
8076 && cin_iselse(l)
8077 && whilelevel == 0)
8078 {
8079 if ((trypos = find_start_brace(ind_maxcomment))
8080 == NULL
8081 || find_match(LOOKFOR_IF, trypos->lnum,
8082 ind_maxparen, ind_maxcomment) == FAIL)
8083 break;
8084 continue;
8085 }
8086
8087 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008088 * If we're at the end of a block, skip to the start of
8089 * that block.
8090 */
Bram Moolenaar6d8f9c62011-11-30 13:03:28 +01008091 l = ml_get_curline();
Bram Moolenaar50f42ca2011-07-15 14:12:30 +02008092 if (find_last_paren(l, '{', '}')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008093 && (trypos = find_start_brace(ind_maxcomment))
8094 != NULL) /* XXX */
8095 {
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008096 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008097 /* if not "else {" check for terminated again */
8098 /* but skip block for "} else {" */
8099 l = cin_skipcomment(ml_get_curline());
8100 if (*l == '}' || !cin_iselse(l))
8101 goto term_again;
8102 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008103 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008104 }
8105 }
8106 }
8107 }
8108 }
8109 }
8110
8111 /* add extra indent for a comment */
8112 if (cin_iscomment(theline))
8113 amount += ind_comment;
Bram Moolenaar02c707a2010-07-17 17:12:06 +02008114
8115 /* subtract extra left-shift for jump labels */
8116 if (ind_jump_label > 0 && original_line_islabel)
8117 amount -= ind_jump_label;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008118 }
8119
8120 /*
8121 * ok -- we're not inside any sort of structure at all!
8122 *
8123 * this means we're at the top level, and everything should
8124 * basically just match where the previous line is, except
8125 * for the lines immediately following a function declaration,
8126 * which are K&R-style parameters and need to be indented.
8127 */
8128 else
8129 {
8130 /*
8131 * if our line starts with an open brace, forget about any
8132 * prevailing indent and make sure it looks like the start
8133 * of a function
8134 */
8135
8136 if (theline[0] == '{')
8137 {
8138 amount = ind_first_open;
8139 }
8140
8141 /*
8142 * If the NEXT line is a function declaration, the current
8143 * line needs to be indented as a function type spec.
Bram Moolenaar1a89bbe2010-03-02 12:38:22 +01008144 * Don't do this if the current line looks like a comment or if the
8145 * current line is terminated, ie. ends in ';', or if the current line
8146 * contains { or }: "void f() {\n if (1)"
Bram Moolenaar071d4272004-06-13 20:20:40 +00008147 */
8148 else if (cur_curpos.lnum < curbuf->b_ml.ml_line_count
8149 && !cin_nocode(theline)
Bram Moolenaar1a89bbe2010-03-02 12:38:22 +01008150 && vim_strchr(theline, '{') == NULL
8151 && vim_strchr(theline, '}') == NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00008152 && !cin_ends_in(theline, (char_u *)":", NULL)
8153 && !cin_ends_in(theline, (char_u *)",", NULL)
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008154 && cin_isfuncdecl(NULL, cur_curpos.lnum + 1,
8155 cur_curpos.lnum + 1,
8156 ind_maxparen, ind_maxcomment)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008157 && !cin_isterminated(theline, FALSE, TRUE))
8158 {
8159 amount = ind_func_type;
8160 }
8161 else
8162 {
8163 amount = 0;
8164 curwin->w_cursor = cur_curpos;
8165
8166 /* search backwards until we find something we recognize */
8167
8168 while (curwin->w_cursor.lnum > 1)
8169 {
8170 curwin->w_cursor.lnum--;
8171 curwin->w_cursor.col = 0;
8172
8173 l = ml_get_curline();
8174
8175 /*
8176 * If we're in a comment now, skip to the start of the comment.
8177 */ /* XXX */
8178 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
8179 {
8180 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008181 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008182 continue;
8183 }
8184
8185 /*
Bram Moolenaar18144c82006-04-12 21:52:12 +00008186 * Are we at the start of a cpp base class declaration or
8187 * constructor initialization?
Bram Moolenaar071d4272004-06-13 20:20:40 +00008188 */ /* XXX */
Bram Moolenaar18144c82006-04-12 21:52:12 +00008189 n = FALSE;
8190 if (ind_cpp_baseclass != 0 && theline[0] != '{')
8191 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00008192 n = cin_is_cpp_baseclass(&col);
Bram Moolenaar18144c82006-04-12 21:52:12 +00008193 l = ml_get_curline();
8194 }
8195 if (n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008196 {
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00008197 /* XXX */
8198 amount = get_baseclass_amount(col, ind_maxparen,
8199 ind_maxcomment, ind_cpp_baseclass);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008200 break;
8201 }
8202
8203 /*
8204 * Skip preprocessor directives and blank lines.
8205 */
8206 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
8207 continue;
8208
8209 if (cin_nocode(l))
8210 continue;
8211
8212 /*
8213 * If the previous line ends in ',', use one level of
8214 * indentation:
8215 * int foo,
8216 * bar;
8217 * do this before checking for '}' in case of eg.
8218 * enum foobar
8219 * {
8220 * ...
8221 * } foo,
8222 * bar;
8223 */
8224 n = 0;
8225 if (cin_ends_in(l, (char_u *)",", NULL)
8226 || (*l != NUL && (n = l[STRLEN(l) - 1]) == '\\'))
8227 {
8228 /* take us back to opening paren */
8229 if (find_last_paren(l, '(', ')')
8230 && (trypos = find_match_paren(ind_maxparen,
8231 ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008232 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008233
8234 /* For a line ending in ',' that is a continuation line go
8235 * back to the first line with a backslash:
8236 * char *foo = "bla\
8237 * bla",
8238 * here;
8239 */
8240 while (n == 0 && curwin->w_cursor.lnum > 1)
8241 {
8242 l = ml_get(curwin->w_cursor.lnum - 1);
8243 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
8244 break;
8245 --curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008246 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008247 }
8248
8249 amount = get_indent(); /* XXX */
8250
8251 if (amount == 0)
8252 amount = cin_first_id_amount();
8253 if (amount == 0)
8254 amount = ind_continuation;
8255 break;
8256 }
8257
8258 /*
8259 * If the line looks like a function declaration, and we're
8260 * not in a comment, put it the left margin.
8261 */
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008262 if (cin_isfuncdecl(NULL, cur_curpos.lnum, 0,
8263 ind_maxparen, ind_maxcomment)) /* XXX */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008264 break;
8265 l = ml_get_curline();
8266
8267 /*
8268 * Finding the closing '}' of a previous function. Put
8269 * current line at the left margin. For when 'cino' has "fs".
8270 */
8271 if (*skipwhite(l) == '}')
8272 break;
8273
8274 /* (matching {)
8275 * If the previous line ends on '};' (maybe followed by
8276 * comments) align at column 0. For example:
8277 * char *string_array[] = { "foo",
8278 * / * x * / "b};ar" }; / * foobar * /
8279 */
8280 if (cin_ends_in(l, (char_u *)"};", NULL))
8281 break;
8282
8283 /*
Bram Moolenaar3388bb42011-11-30 17:20:23 +01008284 * Find a line only has a semicolon that belongs to a previous
8285 * line ending in '}', e.g. before an #endif. Don't increase
8286 * indent then.
8287 */
8288 if (*(look = skipwhite(l)) == ';' && cin_nocode(look + 1))
8289 {
8290 pos_T curpos_save = curwin->w_cursor;
8291
8292 while (curwin->w_cursor.lnum > 1)
8293 {
8294 look = ml_get(--curwin->w_cursor.lnum);
8295 if (!(cin_nocode(look) || cin_ispreproc_cont(
8296 &look, &curwin->w_cursor.lnum)))
8297 break;
8298 }
8299 if (curwin->w_cursor.lnum > 0
8300 && cin_ends_in(look, (char_u *)"}", NULL))
8301 break;
8302
8303 curwin->w_cursor = curpos_save;
8304 }
8305
8306 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008307 * If the PREVIOUS line is a function declaration, the current
8308 * line (and the ones that follow) needs to be indented as
8309 * parameters.
8310 */
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008311 if (cin_isfuncdecl(&l, curwin->w_cursor.lnum, 0,
8312 ind_maxparen, ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008313 {
8314 amount = ind_param;
8315 break;
8316 }
8317
8318 /*
8319 * If the previous line ends in ';' and the line before the
8320 * previous line ends in ',' or '\', ident to column zero:
8321 * int foo,
8322 * bar;
8323 * indent_to_0 here;
8324 */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00008325 if (cin_ends_in(l, (char_u *)";", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008326 {
8327 l = ml_get(curwin->w_cursor.lnum - 1);
8328 if (cin_ends_in(l, (char_u *)",", NULL)
8329 || (*l != NUL && l[STRLEN(l) - 1] == '\\'))
8330 break;
8331 l = ml_get_curline();
8332 }
8333
8334 /*
8335 * Doesn't look like anything interesting -- so just
8336 * use the indent of this line.
8337 *
8338 * Position the cursor over the rightmost paren, so that
8339 * matching it will take us back to the start of the line.
8340 */
8341 find_last_paren(l, '(', ')');
8342
8343 if ((trypos = find_match_paren(ind_maxparen,
8344 ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008345 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008346 amount = get_indent(); /* XXX */
8347 break;
8348 }
8349
8350 /* add extra indent for a comment */
8351 if (cin_iscomment(theline))
8352 amount += ind_comment;
8353
8354 /* add extra indent if the previous line ended in a backslash:
8355 * "asdfasdf\
8356 * here";
8357 * char *foo = "asdf\
8358 * here";
8359 */
8360 if (cur_curpos.lnum > 1)
8361 {
8362 l = ml_get(cur_curpos.lnum - 1);
8363 if (*l != NUL && l[STRLEN(l) - 1] == '\\')
8364 {
8365 cur_amount = cin_get_equal_amount(cur_curpos.lnum - 1);
8366 if (cur_amount > 0)
8367 amount = cur_amount;
8368 else if (cur_amount == 0)
8369 amount += ind_continuation;
8370 }
8371 }
8372 }
8373 }
8374
8375theend:
8376 /* put the cursor back where it belongs */
8377 curwin->w_cursor = cur_curpos;
8378
8379 vim_free(linecopy);
8380
8381 if (amount < 0)
8382 return 0;
8383 return amount;
8384}
8385
8386 static int
8387find_match(lookfor, ourscope, ind_maxparen, ind_maxcomment)
8388 int lookfor;
8389 linenr_T ourscope;
8390 int ind_maxparen;
8391 int ind_maxcomment;
8392{
8393 char_u *look;
8394 pos_T *theirscope;
8395 char_u *mightbeif;
8396 int elselevel;
8397 int whilelevel;
8398
8399 if (lookfor == LOOKFOR_IF)
8400 {
8401 elselevel = 1;
8402 whilelevel = 0;
8403 }
8404 else
8405 {
8406 elselevel = 0;
8407 whilelevel = 1;
8408 }
8409
8410 curwin->w_cursor.col = 0;
8411
8412 while (curwin->w_cursor.lnum > ourscope + 1)
8413 {
8414 curwin->w_cursor.lnum--;
8415 curwin->w_cursor.col = 0;
8416
8417 look = cin_skipcomment(ml_get_curline());
8418 if (cin_iselse(look)
8419 || cin_isif(look)
8420 || cin_isdo(look) /* XXX */
8421 || cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
8422 {
8423 /*
8424 * if we've gone outside the braces entirely,
8425 * we must be out of scope...
8426 */
8427 theirscope = find_start_brace(ind_maxcomment); /* XXX */
8428 if (theirscope == NULL)
8429 break;
8430
8431 /*
8432 * and if the brace enclosing this is further
8433 * back than the one enclosing the else, we're
8434 * out of luck too.
8435 */
8436 if (theirscope->lnum < ourscope)
8437 break;
8438
8439 /*
8440 * and if they're enclosed in a *deeper* brace,
8441 * then we can ignore it because it's in a
8442 * different scope...
8443 */
8444 if (theirscope->lnum > ourscope)
8445 continue;
8446
8447 /*
8448 * if it was an "else" (that's not an "else if")
8449 * then we need to go back to another if, so
8450 * increment elselevel
8451 */
8452 look = cin_skipcomment(ml_get_curline());
8453 if (cin_iselse(look))
8454 {
8455 mightbeif = cin_skipcomment(look + 4);
8456 if (!cin_isif(mightbeif))
8457 ++elselevel;
8458 continue;
8459 }
8460
8461 /*
8462 * if it was a "while" then we need to go back to
8463 * another "do", so increment whilelevel. XXX
8464 */
8465 if (cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
8466 {
8467 ++whilelevel;
8468 continue;
8469 }
8470
8471 /* If it's an "if" decrement elselevel */
8472 look = cin_skipcomment(ml_get_curline());
8473 if (cin_isif(look))
8474 {
8475 elselevel--;
8476 /*
8477 * When looking for an "if" ignore "while"s that
8478 * get in the way.
8479 */
8480 if (elselevel == 0 && lookfor == LOOKFOR_IF)
8481 whilelevel = 0;
8482 }
8483
8484 /* If it's a "do" decrement whilelevel */
8485 if (cin_isdo(look))
8486 whilelevel--;
8487
8488 /*
8489 * if we've used up all the elses, then
8490 * this must be the if that we want!
8491 * match the indent level of that if.
8492 */
8493 if (elselevel <= 0 && whilelevel <= 0)
8494 {
8495 return OK;
8496 }
8497 }
8498 }
8499 return FAIL;
8500}
8501
8502# if defined(FEAT_EVAL) || defined(PROTO)
8503/*
8504 * Get indent level from 'indentexpr'.
8505 */
8506 int
8507get_expr_indent()
8508{
8509 int indent;
8510 pos_T pos;
8511 int save_State;
Bram Moolenaard1f56e62006-02-22 21:25:37 +00008512 int use_sandbox = was_set_insecurely((char_u *)"indentexpr",
8513 OPT_LOCAL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008514
8515 pos = curwin->w_cursor;
8516 set_vim_var_nr(VV_LNUM, curwin->w_cursor.lnum);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00008517 if (use_sandbox)
8518 ++sandbox;
8519 ++textlock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008520 indent = eval_to_number(curbuf->b_p_inde);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00008521 if (use_sandbox)
8522 --sandbox;
8523 --textlock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008524
8525 /* Restore the cursor position so that 'indentexpr' doesn't need to.
8526 * Pretend to be in Insert mode, allow cursor past end of line for "o"
8527 * command. */
8528 save_State = State;
8529 State = INSERT;
8530 curwin->w_cursor = pos;
8531 check_cursor();
8532 State = save_State;
8533
8534 /* If there is an error, just keep the current indent. */
8535 if (indent < 0)
8536 indent = get_indent();
8537
8538 return indent;
8539}
8540# endif
8541
8542#endif /* FEAT_CINDENT */
8543
8544#if defined(FEAT_LISP) || defined(PROTO)
8545
8546static int lisp_match __ARGS((char_u *p));
8547
8548 static int
8549lisp_match(p)
8550 char_u *p;
8551{
8552 char_u buf[LSIZE];
8553 int len;
8554 char_u *word = p_lispwords;
8555
8556 while (*word != NUL)
8557 {
8558 (void)copy_option_part(&word, buf, LSIZE, ",");
8559 len = (int)STRLEN(buf);
8560 if (STRNCMP(buf, p, len) == 0 && p[len] == ' ')
8561 return TRUE;
8562 }
8563 return FALSE;
8564}
8565
8566/*
8567 * When 'p' is present in 'cpoptions, a Vi compatible method is used.
8568 * The incompatible newer method is quite a bit better at indenting
8569 * code in lisp-like languages than the traditional one; it's still
8570 * mostly heuristics however -- Dirk van Deun, dirk@rave.org
8571 *
8572 * TODO:
8573 * Findmatch() should be adapted for lisp, also to make showmatch
8574 * work correctly: now (v5.3) it seems all C/C++ oriented:
8575 * - it does not recognize the #\( and #\) notations as character literals
8576 * - it doesn't know about comments starting with a semicolon
8577 * - it incorrectly interprets '(' as a character literal
8578 * All this messes up get_lisp_indent in some rare cases.
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008579 * Update from Sergey Khorev:
8580 * I tried to fix the first two issues.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008581 */
8582 int
8583get_lisp_indent()
8584{
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008585 pos_T *pos, realpos, paren;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008586 int amount;
8587 char_u *that;
8588 colnr_T col;
8589 colnr_T firsttry;
8590 int parencount, quotecount;
8591 int vi_lisp;
8592
8593 /* Set vi_lisp to use the vi-compatible method */
8594 vi_lisp = (vim_strchr(p_cpo, CPO_LISP) != NULL);
8595
8596 realpos = curwin->w_cursor;
8597 curwin->w_cursor.col = 0;
8598
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008599 if ((pos = findmatch(NULL, '(')) == NULL)
8600 pos = findmatch(NULL, '[');
8601 else
8602 {
8603 paren = *pos;
8604 pos = findmatch(NULL, '[');
8605 if (pos == NULL || ltp(pos, &paren))
8606 pos = &paren;
8607 }
8608 if (pos != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008609 {
8610 /* Extra trick: Take the indent of the first previous non-white
8611 * line that is at the same () level. */
8612 amount = -1;
8613 parencount = 0;
8614
8615 while (--curwin->w_cursor.lnum >= pos->lnum)
8616 {
8617 if (linewhite(curwin->w_cursor.lnum))
8618 continue;
8619 for (that = ml_get_curline(); *that != NUL; ++that)
8620 {
8621 if (*that == ';')
8622 {
8623 while (*(that + 1) != NUL)
8624 ++that;
8625 continue;
8626 }
8627 if (*that == '\\')
8628 {
8629 if (*(that + 1) != NUL)
8630 ++that;
8631 continue;
8632 }
8633 if (*that == '"' && *(that + 1) != NUL)
8634 {
Bram Moolenaar15ff6c12006-09-15 18:18:09 +00008635 while (*++that && *that != '"')
8636 {
8637 /* skipping escaped characters in the string */
8638 if (*that == '\\')
8639 {
8640 if (*++that == NUL)
8641 break;
8642 if (that[1] == NUL)
8643 {
8644 ++that;
8645 break;
8646 }
8647 }
8648 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008649 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008650 if (*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008651 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008652 else if (*that == ')' || *that == ']')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008653 --parencount;
8654 }
8655 if (parencount == 0)
8656 {
8657 amount = get_indent();
8658 break;
8659 }
8660 }
8661
8662 if (amount == -1)
8663 {
8664 curwin->w_cursor.lnum = pos->lnum;
8665 curwin->w_cursor.col = pos->col;
8666 col = pos->col;
8667
8668 that = ml_get_curline();
8669
8670 if (vi_lisp && get_indent() == 0)
8671 amount = 2;
8672 else
8673 {
8674 amount = 0;
8675 while (*that && col)
8676 {
8677 amount += lbr_chartabsize_adv(&that, (colnr_T)amount);
8678 col--;
8679 }
8680
8681 /*
8682 * Some keywords require "body" indenting rules (the
8683 * non-standard-lisp ones are Scheme special forms):
8684 *
8685 * (let ((a 1)) instead (let ((a 1))
8686 * (...)) of (...))
8687 */
8688
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008689 if (!vi_lisp && (*that == '(' || *that == '[')
8690 && lisp_match(that + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008691 amount += 2;
8692 else
8693 {
8694 that++;
8695 amount++;
8696 firsttry = amount;
8697
8698 while (vim_iswhite(*that))
8699 {
8700 amount += lbr_chartabsize(that, (colnr_T)amount);
8701 ++that;
8702 }
8703
8704 if (*that && *that != ';') /* not a comment line */
8705 {
Bram Moolenaare21877a2008-02-13 09:58:14 +00008706 /* test *that != '(' to accommodate first let/do
Bram Moolenaar071d4272004-06-13 20:20:40 +00008707 * argument if it is more than one line */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008708 if (!vi_lisp && *that != '(' && *that != '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008709 firsttry++;
8710
8711 parencount = 0;
8712 quotecount = 0;
8713
8714 if (vi_lisp
8715 || (*that != '"'
8716 && *that != '\''
8717 && *that != '#'
8718 && (*that < '0' || *that > '9')))
8719 {
8720 while (*that
8721 && (!vim_iswhite(*that)
8722 || quotecount
8723 || parencount)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008724 && (!((*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008725 && !quotecount
8726 && !parencount
8727 && vi_lisp)))
8728 {
8729 if (*that == '"')
8730 quotecount = !quotecount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008731 if ((*that == '(' || *that == '[')
8732 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008733 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008734 if ((*that == ')' || *that == ']')
8735 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008736 --parencount;
8737 if (*that == '\\' && *(that+1) != NUL)
8738 amount += lbr_chartabsize_adv(&that,
8739 (colnr_T)amount);
8740 amount += lbr_chartabsize_adv(&that,
8741 (colnr_T)amount);
8742 }
8743 }
8744 while (vim_iswhite(*that))
8745 {
8746 amount += lbr_chartabsize(that, (colnr_T)amount);
8747 that++;
8748 }
8749 if (!*that || *that == ';')
8750 amount = firsttry;
8751 }
8752 }
8753 }
8754 }
8755 }
8756 else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008757 amount = 0; /* no matching '(' or '[' found, use zero indent */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008758
8759 curwin->w_cursor = realpos;
8760
8761 return amount;
8762}
8763#endif /* FEAT_LISP */
8764
8765 void
8766prepare_to_exit()
8767{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00008768#if defined(SIGHUP) && defined(SIG_IGN)
8769 /* Ignore SIGHUP, because a dropped connection causes a read error, which
8770 * makes Vim exit and then handling SIGHUP causes various reentrance
8771 * problems. */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00008772 signal(SIGHUP, SIG_IGN);
8773#endif
8774
Bram Moolenaar071d4272004-06-13 20:20:40 +00008775#ifdef FEAT_GUI
8776 if (gui.in_use)
8777 {
8778 gui.dying = TRUE;
8779 out_trash(); /* trash any pending output */
8780 }
8781 else
8782#endif
8783 {
8784 windgoto((int)Rows - 1, 0);
8785
8786 /*
8787 * Switch terminal mode back now, so messages end up on the "normal"
8788 * screen (if there are two screens).
8789 */
8790 settmode(TMODE_COOK);
8791#ifdef WIN3264
8792 if (can_end_termcap_mode(FALSE) == TRUE)
8793#endif
8794 stoptermcap();
8795 out_flush();
8796 }
8797}
8798
8799/*
8800 * Preserve files and exit.
8801 * When called IObuff must contain a message.
8802 */
8803 void
8804preserve_exit()
8805{
8806 buf_T *buf;
8807
8808 prepare_to_exit();
8809
Bram Moolenaar4770d092006-01-12 23:22:24 +00008810 /* Setting this will prevent free() calls. That avoids calling free()
8811 * recursively when free() was invoked with a bad pointer. */
8812 really_exiting = TRUE;
8813
Bram Moolenaar071d4272004-06-13 20:20:40 +00008814 out_str(IObuff);
8815 screen_start(); /* don't know where cursor is now */
8816 out_flush();
8817
8818 ml_close_notmod(); /* close all not-modified buffers */
8819
8820 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8821 {
8822 if (buf->b_ml.ml_mfp != NULL && buf->b_ml.ml_mfp->mf_fname != NULL)
8823 {
8824 OUT_STR(_("Vim: preserving files...\n"));
8825 screen_start(); /* don't know where cursor is now */
8826 out_flush();
8827 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
8828 break;
8829 }
8830 }
8831
8832 ml_close_all(FALSE); /* close all memfiles, without deleting */
8833
8834 OUT_STR(_("Vim: Finished.\n"));
8835
8836 getout(1);
8837}
8838
8839/*
8840 * return TRUE if "fname" exists.
8841 */
8842 int
8843vim_fexists(fname)
8844 char_u *fname;
8845{
8846 struct stat st;
8847
8848 if (mch_stat((char *)fname, &st))
8849 return FALSE;
8850 return TRUE;
8851}
8852
8853/*
8854 * Check for CTRL-C pressed, but only once in a while.
8855 * Should be used instead of ui_breakcheck() for functions that check for
8856 * each line in the file. Calling ui_breakcheck() each time takes too much
8857 * time, because it can be a system call.
8858 */
8859
8860#ifndef BREAKCHECK_SKIP
8861# ifdef FEAT_GUI /* assume the GUI only runs on fast computers */
8862# define BREAKCHECK_SKIP 200
8863# else
8864# define BREAKCHECK_SKIP 32
8865# endif
8866#endif
8867
8868static int breakcheck_count = 0;
8869
8870 void
8871line_breakcheck()
8872{
8873 if (++breakcheck_count >= BREAKCHECK_SKIP)
8874 {
8875 breakcheck_count = 0;
8876 ui_breakcheck();
8877 }
8878}
8879
8880/*
8881 * Like line_breakcheck() but check 10 times less often.
8882 */
8883 void
8884fast_breakcheck()
8885{
8886 if (++breakcheck_count >= BREAKCHECK_SKIP * 10)
8887 {
8888 breakcheck_count = 0;
8889 ui_breakcheck();
8890 }
8891}
8892
8893/*
Bram Moolenaard7834d32009-12-02 16:14:36 +00008894 * Invoke expand_wildcards() for one pattern.
8895 * Expand items like "%:h" before the expansion.
8896 * Returns OK or FAIL.
8897 */
8898 int
8899expand_wildcards_eval(pat, num_file, file, flags)
8900 char_u **pat; /* pointer to input pattern */
8901 int *num_file; /* resulting number of files */
8902 char_u ***file; /* array of resulting files */
8903 int flags; /* EW_DIR, etc. */
8904{
8905 int ret = FAIL;
8906 char_u *eval_pat = NULL;
8907 char_u *exp_pat = *pat;
8908 char_u *ignored_msg;
8909 int usedlen;
8910
8911 if (*exp_pat == '%' || *exp_pat == '#' || *exp_pat == '<')
8912 {
8913 ++emsg_off;
8914 eval_pat = eval_vars(exp_pat, exp_pat, &usedlen,
8915 NULL, &ignored_msg, NULL);
8916 --emsg_off;
8917 if (eval_pat != NULL)
8918 exp_pat = concat_str(eval_pat, exp_pat + usedlen);
8919 }
8920
8921 if (exp_pat != NULL)
8922 ret = expand_wildcards(1, &exp_pat, num_file, file, flags);
8923
8924 if (eval_pat != NULL)
8925 {
8926 vim_free(exp_pat);
8927 vim_free(eval_pat);
8928 }
8929
8930 return ret;
8931}
8932
8933/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008934 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching
8935 * 'wildignore'.
Bram Moolenaar9e193ac2010-07-19 23:11:27 +02008936 * Returns OK or FAIL. When FAIL then "num_file" won't be set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008937 */
8938 int
8939expand_wildcards(num_pat, pat, num_file, file, flags)
8940 int num_pat; /* number of input patterns */
8941 char_u **pat; /* array of input patterns */
8942 int *num_file; /* resulting number of files */
8943 char_u ***file; /* array of resulting files */
8944 int flags; /* EW_DIR, etc. */
8945{
8946 int retval;
8947 int i, j;
8948 char_u *p;
8949 int non_suf_match; /* number without matching suffix */
8950
8951 retval = gen_expand_wildcards(num_pat, pat, num_file, file, flags);
8952
8953 /* When keeping all matches, return here */
Bram Moolenaar9e193ac2010-07-19 23:11:27 +02008954 if ((flags & EW_KEEPALL) || retval == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008955 return retval;
8956
8957#ifdef FEAT_WILDIGN
8958 /*
8959 * Remove names that match 'wildignore'.
8960 */
8961 if (*p_wig)
8962 {
8963 char_u *ffname;
8964
8965 /* check all files in (*file)[] */
8966 for (i = 0; i < *num_file; ++i)
8967 {
8968 ffname = FullName_save((*file)[i], FALSE);
8969 if (ffname == NULL) /* out of memory */
8970 break;
8971# ifdef VMS
8972 vms_remove_version(ffname);
8973# endif
8974 if (match_file_list(p_wig, (*file)[i], ffname))
8975 {
8976 /* remove this matching file from the list */
8977 vim_free((*file)[i]);
8978 for (j = i; j + 1 < *num_file; ++j)
8979 (*file)[j] = (*file)[j + 1];
8980 --*num_file;
8981 --i;
8982 }
8983 vim_free(ffname);
8984 }
8985 }
8986#endif
8987
8988 /*
8989 * Move the names where 'suffixes' match to the end.
8990 */
8991 if (*num_file > 1)
8992 {
8993 non_suf_match = 0;
8994 for (i = 0; i < *num_file; ++i)
8995 {
8996 if (!match_suffix((*file)[i]))
8997 {
8998 /*
8999 * Move the name without matching suffix to the front
9000 * of the list.
9001 */
9002 p = (*file)[i];
9003 for (j = i; j > non_suf_match; --j)
9004 (*file)[j] = (*file)[j - 1];
9005 (*file)[non_suf_match++] = p;
9006 }
9007 }
9008 }
9009
9010 return retval;
9011}
9012
9013/*
9014 * Return TRUE if "fname" matches with an entry in 'suffixes'.
9015 */
9016 int
9017match_suffix(fname)
9018 char_u *fname;
9019{
9020 int fnamelen, setsuflen;
9021 char_u *setsuf;
9022#define MAXSUFLEN 30 /* maximum length of a file suffix */
9023 char_u suf_buf[MAXSUFLEN];
9024
9025 fnamelen = (int)STRLEN(fname);
9026 setsuflen = 0;
9027 for (setsuf = p_su; *setsuf; )
9028 {
9029 setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
Bram Moolenaar055a2ba2009-07-14 19:40:21 +00009030 if (setsuflen == 0)
9031 {
9032 char_u *tail = gettail(fname);
9033
9034 /* empty entry: match name without a '.' */
9035 if (vim_strchr(tail, '.') == NULL)
9036 {
9037 setsuflen = 1;
9038 break;
9039 }
9040 }
9041 else
9042 {
9043 if (fnamelen >= setsuflen
9044 && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
9045 (size_t)setsuflen) == 0)
9046 break;
9047 setsuflen = 0;
9048 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009049 }
9050 return (setsuflen != 0);
9051}
9052
9053#if !defined(NO_EXPANDPATH) || defined(PROTO)
9054
9055# ifdef VIM_BACKTICK
9056static int vim_backtick __ARGS((char_u *p));
9057static int expand_backtick __ARGS((garray_T *gap, char_u *pat, int flags));
9058# endif
9059
9060# if defined(MSDOS) || defined(FEAT_GUI_W16) || defined(WIN3264)
9061/*
9062 * File name expansion code for MS-DOS, Win16 and Win32. It's here because
9063 * it's shared between these systems.
9064 */
9065# if defined(DJGPP) || defined(PROTO)
9066# define _cdecl /* DJGPP doesn't have this */
9067# else
9068# ifdef __BORLANDC__
9069# define _cdecl _RTLENTRYF
9070# endif
9071# endif
9072
9073/*
9074 * comparison function for qsort in dos_expandpath()
9075 */
9076 static int _cdecl
9077pstrcmp(const void *a, const void *b)
9078{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00009079 return (pathcmp(*(char **)a, *(char **)b, -1));
Bram Moolenaar071d4272004-06-13 20:20:40 +00009080}
9081
9082# ifndef WIN3264
9083 static void
9084namelowcpy(
9085 char_u *d,
9086 char_u *s)
9087{
9088# ifdef DJGPP
9089 if (USE_LONG_FNAME) /* don't lower case on Windows 95/NT systems */
9090 while (*s)
9091 *d++ = *s++;
9092 else
9093# endif
9094 while (*s)
9095 *d++ = TOLOWER_LOC(*s++);
9096 *d = NUL;
9097}
9098# endif
9099
9100/*
Bram Moolenaar231334e2005-07-25 20:46:57 +00009101 * Recursively expand one path component into all matching files and/or
9102 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009103 * Return the number of matches found.
9104 * "path" has backslashes before chars that are not to be expanded, starting
9105 * at "path[wildoff]".
Bram Moolenaar231334e2005-07-25 20:46:57 +00009106 * Return the number of matches found.
9107 * NOTE: much of this is identical to unix_expandpath(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00009108 */
9109 static int
9110dos_expandpath(
9111 garray_T *gap,
9112 char_u *path,
9113 int wildoff,
Bram Moolenaar231334e2005-07-25 20:46:57 +00009114 int flags, /* EW_* flags */
Bram Moolenaar25394022007-05-10 19:06:20 +00009115 int didstar) /* expanded "**" once already */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009116{
Bram Moolenaar231334e2005-07-25 20:46:57 +00009117 char_u *buf;
9118 char_u *path_end;
9119 char_u *p, *s, *e;
9120 int start_len = gap->ga_len;
9121 char_u *pat;
9122 regmatch_T regmatch;
9123 int starts_with_dot;
9124 int matches;
9125 int len;
9126 int starstar = FALSE;
9127 static int stardepth = 0; /* depth for "**" expansion */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009128#ifdef WIN3264
9129 WIN32_FIND_DATA fb;
9130 HANDLE hFind = (HANDLE)0;
9131# ifdef FEAT_MBYTE
9132 WIN32_FIND_DATAW wfb;
9133 WCHAR *wn = NULL; /* UCS-2 name, NULL when not used. */
9134# endif
9135#else
9136 struct ffblk fb;
9137#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009138 char_u *matchname;
Bram Moolenaar231334e2005-07-25 20:46:57 +00009139 int ok;
9140
9141 /* Expanding "**" may take a long time, check for CTRL-C. */
9142 if (stardepth > 0)
9143 {
9144 ui_breakcheck();
9145 if (got_int)
9146 return 0;
9147 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009148
9149 /* make room for file name */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009150 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009151 if (buf == NULL)
9152 return 0;
9153
9154 /*
9155 * Find the first part in the path name that contains a wildcard or a ~1.
9156 * Copy it into buf, including the preceding characters.
9157 */
9158 p = buf;
9159 s = buf;
9160 e = NULL;
9161 path_end = path;
9162 while (*path_end != NUL)
9163 {
9164 /* May ignore a wildcard that has a backslash before it; it will
9165 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
9166 if (path_end >= path + wildoff && rem_backslash(path_end))
9167 *p++ = *path_end++;
9168 else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
9169 {
9170 if (e != NULL)
9171 break;
9172 s = p + 1;
9173 }
9174 else if (path_end >= path + wildoff
9175 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
9176 e = p;
9177#ifdef FEAT_MBYTE
9178 if (has_mbyte)
9179 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00009180 len = (*mb_ptr2len)(path_end);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009181 STRNCPY(p, path_end, len);
9182 p += len;
9183 path_end += len;
9184 }
9185 else
9186#endif
9187 *p++ = *path_end++;
9188 }
9189 e = p;
9190 *e = NUL;
9191
9192 /* now we have one wildcard component between s and e */
9193 /* Remove backslashes between "wildoff" and the start of the wildcard
9194 * component. */
9195 for (p = buf + wildoff; p < s; ++p)
9196 if (rem_backslash(p))
9197 {
Bram Moolenaar8c8de832008-06-24 22:58:06 +00009198 STRMOVE(p, p + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009199 --e;
9200 --s;
9201 }
9202
Bram Moolenaar231334e2005-07-25 20:46:57 +00009203 /* Check for "**" between "s" and "e". */
9204 for (p = s; p < e; ++p)
9205 if (p[0] == '*' && p[1] == '*')
9206 starstar = TRUE;
9207
Bram Moolenaar071d4272004-06-13 20:20:40 +00009208 starts_with_dot = (*s == '.');
9209 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
9210 if (pat == NULL)
9211 {
9212 vim_free(buf);
9213 return 0;
9214 }
9215
9216 /* compile the regexp into a program */
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009217 if (flags & (EW_NOERROR | EW_NOTWILD))
Bram Moolenaarb5609832011-07-20 15:04:58 +02009218 ++emsg_silent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009219 regmatch.rm_ic = TRUE; /* Always ignore case */
9220 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009221 if (flags & (EW_NOERROR | EW_NOTWILD))
Bram Moolenaarb5609832011-07-20 15:04:58 +02009222 --emsg_silent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009223 vim_free(pat);
9224
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009225 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009226 {
9227 vim_free(buf);
9228 return 0;
9229 }
9230
9231 /* remember the pattern or file name being looked for */
9232 matchname = vim_strsave(s);
9233
Bram Moolenaar231334e2005-07-25 20:46:57 +00009234 /* If "**" is by itself, this is the first time we encounter it and more
9235 * is following then find matches without any directory. */
9236 if (!didstar && stardepth < 100 && starstar && e - s == 2
9237 && *path_end == '/')
9238 {
9239 STRCPY(s, path_end + 1);
9240 ++stardepth;
9241 (void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
9242 --stardepth;
9243 }
9244
Bram Moolenaar071d4272004-06-13 20:20:40 +00009245 /* Scan all files in the directory with "dir/ *.*" */
9246 STRCPY(s, "*.*");
9247#ifdef WIN3264
9248# ifdef FEAT_MBYTE
9249 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
9250 {
9251 /* The active codepage differs from 'encoding'. Attempt using the
9252 * wide function. If it fails because it is not implemented fall back
9253 * to the non-wide version (for Windows 98) */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009254 wn = enc_to_utf16(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009255 if (wn != NULL)
9256 {
9257 hFind = FindFirstFileW(wn, &wfb);
9258 if (hFind == INVALID_HANDLE_VALUE
9259 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
9260 {
9261 vim_free(wn);
9262 wn = NULL;
9263 }
9264 }
9265 }
9266
9267 if (wn == NULL)
9268# endif
9269 hFind = FindFirstFile(buf, &fb);
9270 ok = (hFind != INVALID_HANDLE_VALUE);
9271#else
9272 /* If we are expanding wildcards we try both files and directories */
9273 ok = (findfirst((char *)buf, &fb,
9274 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
9275#endif
9276
9277 while (ok)
9278 {
9279#ifdef WIN3264
9280# ifdef FEAT_MBYTE
9281 if (wn != NULL)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009282 p = utf16_to_enc(wfb.cFileName, NULL); /* p is allocated here */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009283 else
9284# endif
9285 p = (char_u *)fb.cFileName;
9286#else
9287 p = (char_u *)fb.ff_name;
9288#endif
9289 /* Ignore entries starting with a dot, unless when asked for. Accept
9290 * all entries found with "matchname". */
9291 if ((p[0] != '.' || starts_with_dot)
9292 && (matchname == NULL
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009293 || (regmatch.regprog != NULL
9294 && vim_regexec(&regmatch, p, (colnr_T)0))
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009295 || ((flags & EW_NOTWILD)
9296 && fnamencmp(path + (s - buf), p, e - s) == 0)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009297 {
9298#ifdef WIN3264
9299 STRCPY(s, p);
9300#else
9301 namelowcpy(s, p);
9302#endif
9303 len = (int)STRLEN(buf);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009304
9305 if (starstar && stardepth < 100)
9306 {
9307 /* For "**" in the pattern first go deeper in the tree to
9308 * find matches. */
9309 STRCPY(buf + len, "/**");
9310 STRCPY(buf + len + 3, path_end);
9311 ++stardepth;
9312 (void)dos_expandpath(gap, buf, len + 1, flags, TRUE);
9313 --stardepth;
9314 }
9315
Bram Moolenaar071d4272004-06-13 20:20:40 +00009316 STRCPY(buf + len, path_end);
9317 if (mch_has_exp_wildcard(path_end))
9318 {
9319 /* need to expand another component of the path */
9320 /* remove backslashes for the remaining components only */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009321 (void)dos_expandpath(gap, buf, len + 1, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009322 }
9323 else
9324 {
9325 /* no more wildcards, check if there is a match */
9326 /* remove backslashes for the remaining components only */
9327 if (*path_end != 0)
9328 backslash_halve(buf + len + 1);
9329 if (mch_getperm(buf) >= 0) /* add existing file */
9330 addfile(gap, buf, flags);
9331 }
9332 }
9333
9334#ifdef WIN3264
9335# ifdef FEAT_MBYTE
9336 if (wn != NULL)
9337 {
9338 vim_free(p);
9339 ok = FindNextFileW(hFind, &wfb);
9340 }
9341 else
9342# endif
9343 ok = FindNextFile(hFind, &fb);
9344#else
9345 ok = (findnext(&fb) == 0);
9346#endif
9347
9348 /* If no more matches and no match was used, try expanding the name
9349 * itself. Finds the long name of a short filename. */
9350 if (!ok && matchname != NULL && gap->ga_len == start_len)
9351 {
9352 STRCPY(s, matchname);
9353#ifdef WIN3264
9354 FindClose(hFind);
9355# ifdef FEAT_MBYTE
9356 if (wn != NULL)
9357 {
9358 vim_free(wn);
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009359 wn = enc_to_utf16(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009360 if (wn != NULL)
9361 hFind = FindFirstFileW(wn, &wfb);
9362 }
9363 if (wn == NULL)
9364# endif
9365 hFind = FindFirstFile(buf, &fb);
9366 ok = (hFind != INVALID_HANDLE_VALUE);
9367#else
9368 ok = (findfirst((char *)buf, &fb,
9369 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
9370#endif
9371 vim_free(matchname);
9372 matchname = NULL;
9373 }
9374 }
9375
9376#ifdef WIN3264
9377 FindClose(hFind);
9378# ifdef FEAT_MBYTE
9379 vim_free(wn);
9380# endif
9381#endif
9382 vim_free(buf);
9383 vim_free(regmatch.regprog);
9384 vim_free(matchname);
9385
9386 matches = gap->ga_len - start_len;
9387 if (matches > 0)
9388 qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
9389 sizeof(char_u *), pstrcmp);
9390 return matches;
9391}
9392
9393 int
9394mch_expandpath(
9395 garray_T *gap,
9396 char_u *path,
9397 int flags) /* EW_* flags */
9398{
Bram Moolenaar231334e2005-07-25 20:46:57 +00009399 return dos_expandpath(gap, path, 0, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009400}
9401# endif /* MSDOS || FEAT_GUI_W16 || WIN3264 */
9402
Bram Moolenaar231334e2005-07-25 20:46:57 +00009403#if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
9404 || defined(PROTO)
9405/*
9406 * Unix style wildcard expansion code.
9407 * It's here because it's used both for Unix and Mac.
9408 */
9409static int pstrcmp __ARGS((const void *, const void *));
9410
9411 static int
9412pstrcmp(a, b)
9413 const void *a, *b;
9414{
9415 return (pathcmp(*(char **)a, *(char **)b, -1));
9416}
9417
9418/*
9419 * Recursively expand one path component into all matching files and/or
9420 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
9421 * "path" has backslashes before chars that are not to be expanded, starting
9422 * at "path + wildoff".
9423 * Return the number of matches found.
9424 * NOTE: much of this is identical to dos_expandpath(), keep in sync!
9425 */
9426 int
9427unix_expandpath(gap, path, wildoff, flags, didstar)
9428 garray_T *gap;
9429 char_u *path;
9430 int wildoff;
9431 int flags; /* EW_* flags */
9432 int didstar; /* expanded "**" once already */
9433{
9434 char_u *buf;
9435 char_u *path_end;
9436 char_u *p, *s, *e;
9437 int start_len = gap->ga_len;
9438 char_u *pat;
9439 regmatch_T regmatch;
9440 int starts_with_dot;
9441 int matches;
9442 int len;
9443 int starstar = FALSE;
9444 static int stardepth = 0; /* depth for "**" expansion */
9445
9446 DIR *dirp;
9447 struct dirent *dp;
9448
9449 /* Expanding "**" may take a long time, check for CTRL-C. */
9450 if (stardepth > 0)
9451 {
9452 ui_breakcheck();
9453 if (got_int)
9454 return 0;
9455 }
9456
9457 /* make room for file name */
9458 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
9459 if (buf == NULL)
9460 return 0;
9461
9462 /*
9463 * Find the first part in the path name that contains a wildcard.
9464 * Copy it into "buf", including the preceding characters.
9465 */
9466 p = buf;
9467 s = buf;
9468 e = NULL;
9469 path_end = path;
9470 while (*path_end != NUL)
9471 {
9472 /* May ignore a wildcard that has a backslash before it; it will
9473 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
9474 if (path_end >= path + wildoff && rem_backslash(path_end))
9475 *p++ = *path_end++;
9476 else if (*path_end == '/')
9477 {
9478 if (e != NULL)
9479 break;
9480 s = p + 1;
9481 }
9482 else if (path_end >= path + wildoff
9483 && vim_strchr((char_u *)"*?[{~$", *path_end) != NULL)
9484 e = p;
9485#ifdef FEAT_MBYTE
9486 if (has_mbyte)
9487 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00009488 len = (*mb_ptr2len)(path_end);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009489 STRNCPY(p, path_end, len);
9490 p += len;
9491 path_end += len;
9492 }
9493 else
9494#endif
9495 *p++ = *path_end++;
9496 }
9497 e = p;
9498 *e = NUL;
9499
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009500 /* Now we have one wildcard component between "s" and "e". */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009501 /* Remove backslashes between "wildoff" and the start of the wildcard
9502 * component. */
9503 for (p = buf + wildoff; p < s; ++p)
9504 if (rem_backslash(p))
9505 {
Bram Moolenaar8c8de832008-06-24 22:58:06 +00009506 STRMOVE(p, p + 1);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009507 --e;
9508 --s;
9509 }
9510
9511 /* Check for "**" between "s" and "e". */
9512 for (p = s; p < e; ++p)
9513 if (p[0] == '*' && p[1] == '*')
9514 starstar = TRUE;
9515
9516 /* convert the file pattern to a regexp pattern */
9517 starts_with_dot = (*s == '.');
9518 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
9519 if (pat == NULL)
9520 {
9521 vim_free(buf);
9522 return 0;
9523 }
9524
9525 /* compile the regexp into a program */
Bram Moolenaarcc016f52005-12-10 20:23:46 +00009526#ifdef CASE_INSENSITIVE_FILENAME
Bram Moolenaar231334e2005-07-25 20:46:57 +00009527 regmatch.rm_ic = TRUE; /* Behave like Terminal.app */
9528#else
Bram Moolenaar94950a92010-12-02 16:01:29 +01009529 if (flags & EW_ICASE)
9530 regmatch.rm_ic = TRUE; /* 'wildignorecase' set */
9531 else
9532 regmatch.rm_ic = FALSE; /* Don't ignore case */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009533#endif
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009534 if (flags & (EW_NOERROR | EW_NOTWILD))
9535 ++emsg_silent;
Bram Moolenaar231334e2005-07-25 20:46:57 +00009536 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009537 if (flags & (EW_NOERROR | EW_NOTWILD))
9538 --emsg_silent;
Bram Moolenaar231334e2005-07-25 20:46:57 +00009539 vim_free(pat);
9540
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009541 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
Bram Moolenaar231334e2005-07-25 20:46:57 +00009542 {
9543 vim_free(buf);
9544 return 0;
9545 }
9546
9547 /* If "**" is by itself, this is the first time we encounter it and more
9548 * is following then find matches without any directory. */
9549 if (!didstar && stardepth < 100 && starstar && e - s == 2
9550 && *path_end == '/')
9551 {
9552 STRCPY(s, path_end + 1);
9553 ++stardepth;
9554 (void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
9555 --stardepth;
9556 }
9557
9558 /* open the directory for scanning */
9559 *s = NUL;
9560 dirp = opendir(*buf == NUL ? "." : (char *)buf);
9561
9562 /* Find all matching entries */
9563 if (dirp != NULL)
9564 {
9565 for (;;)
9566 {
9567 dp = readdir(dirp);
9568 if (dp == NULL)
9569 break;
9570 if ((dp->d_name[0] != '.' || starts_with_dot)
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009571 && ((regmatch.regprog != NULL && vim_regexec(&regmatch,
9572 (char_u *)dp->d_name, (colnr_T)0))
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009573 || ((flags & EW_NOTWILD)
9574 && fnamencmp(path + (s - buf), dp->d_name, e - s) == 0)))
Bram Moolenaar231334e2005-07-25 20:46:57 +00009575 {
9576 STRCPY(s, dp->d_name);
9577 len = STRLEN(buf);
9578
9579 if (starstar && stardepth < 100)
9580 {
9581 /* For "**" in the pattern first go deeper in the tree to
9582 * find matches. */
9583 STRCPY(buf + len, "/**");
9584 STRCPY(buf + len + 3, path_end);
9585 ++stardepth;
9586 (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
9587 --stardepth;
9588 }
9589
9590 STRCPY(buf + len, path_end);
9591 if (mch_has_exp_wildcard(path_end)) /* handle more wildcards */
9592 {
9593 /* need to expand another component of the path */
9594 /* remove backslashes for the remaining components only */
9595 (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
9596 }
9597 else
9598 {
9599 /* no more wildcards, check if there is a match */
9600 /* remove backslashes for the remaining components only */
9601 if (*path_end != NUL)
9602 backslash_halve(buf + len + 1);
9603 if (mch_getperm(buf) >= 0) /* add existing file */
9604 {
Bram Moolenaar95e9b492006-03-15 23:04:43 +00009605#ifdef MACOS_CONVERT
Bram Moolenaar231334e2005-07-25 20:46:57 +00009606 size_t precomp_len = STRLEN(buf)+1;
9607 char_u *precomp_buf =
9608 mac_precompose_path(buf, precomp_len, &precomp_len);
Bram Moolenaar95e9b492006-03-15 23:04:43 +00009609
Bram Moolenaar231334e2005-07-25 20:46:57 +00009610 if (precomp_buf)
9611 {
9612 mch_memmove(buf, precomp_buf, precomp_len);
9613 vim_free(precomp_buf);
9614 }
9615#endif
9616 addfile(gap, buf, flags);
9617 }
9618 }
9619 }
9620 }
9621
9622 closedir(dirp);
9623 }
9624
9625 vim_free(buf);
9626 vim_free(regmatch.regprog);
9627
9628 matches = gap->ga_len - start_len;
9629 if (matches > 0)
9630 qsort(((char_u **)gap->ga_data) + start_len, matches,
9631 sizeof(char_u *), pstrcmp);
9632 return matches;
9633}
9634#endif
9635
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009636#if defined(FEAT_SEARCHPATH)
9637static int find_previous_pathsep __ARGS((char_u *path, char_u **psep));
9638static int is_unique __ARGS((char_u *maybe_unique, garray_T *gap, int i));
Bram Moolenaar162bd912010-07-28 22:29:10 +02009639static void expand_path_option __ARGS((char_u *curdir, garray_T *gap));
9640static char_u *get_path_cutoff __ARGS((char_u *fname, garray_T *gap));
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009641static void uniquefy_paths __ARGS((garray_T *gap, char_u *pattern));
9642static int expand_in_path __ARGS((garray_T *gap, char_u *pattern, int flags));
9643
9644/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009645 * Moves "*psep" back to the previous path separator in "path".
9646 * Returns FAIL is "*psep" ends up at the beginning of "path".
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009647 */
9648 static int
9649find_previous_pathsep(path, psep)
9650 char_u *path;
9651 char_u **psep;
9652{
9653 /* skip the current separator */
9654 if (*psep > path && vim_ispathsep(**psep))
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009655 --*psep;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009656
9657 /* find the previous separator */
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009658 while (*psep > path)
9659 {
9660 if (vim_ispathsep(**psep))
9661 return OK;
9662 mb_ptr_back(path, *psep);
9663 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009664
9665 return FAIL;
9666}
9667
9668/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009669 * Returns TRUE if "maybe_unique" is unique wrt other_paths in "gap".
9670 * "maybe_unique" is the end portion of "((char_u **)gap->ga_data)[i]".
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009671 */
9672 static int
9673is_unique(maybe_unique, gap, i)
9674 char_u *maybe_unique;
9675 garray_T *gap;
9676 int i;
9677{
9678 int j;
9679 int candidate_len;
9680 int other_path_len;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009681 char_u **other_paths = (char_u **)gap->ga_data;
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009682 char_u *rival;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009683
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009684 for (j = 0; j < gap->ga_len; j++)
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009685 {
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009686 if (j == i)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009687 continue; /* don't compare it with itself */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009688
Bram Moolenaar624c7aa2010-07-16 20:38:52 +02009689 candidate_len = (int)STRLEN(maybe_unique);
9690 other_path_len = (int)STRLEN(other_paths[j]);
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009691 if (other_path_len < candidate_len)
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009692 continue; /* it's different when it's shorter */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009693
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009694 rival = other_paths[j] + other_path_len - candidate_len;
Bram Moolenaarda9836c2010-08-16 21:53:27 +02009695 if (fnamecmp(maybe_unique, rival) == 0
9696 && (rival == other_paths[j] || vim_ispathsep(*(rival - 1))))
Bram Moolenaar162bd912010-07-28 22:29:10 +02009697 return FALSE; /* match */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009698 }
9699
Bram Moolenaar162bd912010-07-28 22:29:10 +02009700 return TRUE; /* no match found */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009701}
9702
9703/*
Bram Moolenaar1a509df2010-08-01 17:59:57 +02009704 * Split the 'path' option into an array of strings in garray_T. Relative
Bram Moolenaar162bd912010-07-28 22:29:10 +02009705 * paths are expanded to their equivalent fullpath. This includes the "."
9706 * (relative to current buffer directory) and empty path (relative to current
9707 * directory) notations.
9708 *
9709 * TODO: handle upward search (;) and path limiter (**N) notations by
9710 * expanding each into their equivalent path(s).
9711 */
9712 static void
9713expand_path_option(curdir, gap)
9714 char_u *curdir;
9715 garray_T *gap;
9716{
9717 char_u *path_option = *curbuf->b_p_path == NUL
9718 ? p_path : curbuf->b_p_path;
9719 char_u *buf;
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009720 char_u *p;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009721 int len;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009722
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +02009723 if ((buf = alloc((int)MAXPATHL)) == NULL)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009724 return;
9725
9726 while (*path_option != NUL)
9727 {
9728 copy_option_part(&path_option, buf, MAXPATHL, " ,");
9729
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009730 if (buf[0] == '.' && (buf[1] == NUL || vim_ispathsep(buf[1])))
Bram Moolenaar162bd912010-07-28 22:29:10 +02009731 {
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009732 /* Relative to current buffer:
9733 * "/path/file" + "." -> "/path/"
9734 * "/path/file" + "./subdir" -> "/path/subdir" */
Bram Moolenaar162bd912010-07-28 22:29:10 +02009735 if (curbuf->b_ffname == NULL)
9736 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009737 p = gettail(curbuf->b_ffname);
9738 len = (int)(p - curbuf->b_ffname);
9739 if (len + (int)STRLEN(buf) >= MAXPATHL)
9740 continue;
9741 if (buf[1] == NUL)
9742 buf[len] = NUL;
9743 else
9744 STRMOVE(buf + len, buf + 2);
9745 mch_memmove(buf, curbuf->b_ffname, len);
9746 simplify_filename(buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009747 }
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009748 else if (buf[0] == NUL)
9749 /* relative to current directory */
Bram Moolenaar162bd912010-07-28 22:29:10 +02009750 STRCPY(buf, curdir);
Bram Moolenaar84f888a2010-08-05 21:40:16 +02009751 else if (path_with_url(buf))
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009752 /* URL can't be used here */
Bram Moolenaar84f888a2010-08-05 21:40:16 +02009753 continue;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009754 else if (!mch_isFullName(buf))
9755 {
9756 /* Expand relative path to their full path equivalent */
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009757 len = (int)STRLEN(curdir);
9758 if (len + (int)STRLEN(buf) + 3 > MAXPATHL)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009759 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009760 STRMOVE(buf + len + 1, buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009761 STRCPY(buf, curdir);
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009762 buf[len] = PATHSEP;
Bram Moolenaar57adda12010-08-03 22:11:29 +02009763 simplify_filename(buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009764 }
9765
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009766 if (ga_grow(gap, 1) == FAIL)
9767 break;
9768 p = vim_strsave(buf);
9769 if (p == NULL)
9770 break;
9771 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009772 }
9773
9774 vim_free(buf);
9775}
9776
9777/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009778 * Returns a pointer to the file or directory name in "fname" that matches the
9779 * longest path in "ga"p, or NULL if there is no match. For example:
Bram Moolenaar162bd912010-07-28 22:29:10 +02009780 *
9781 * path: /foo/bar/baz
9782 * fname: /foo/bar/baz/quux.txt
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009783 * returns: ^this
Bram Moolenaar162bd912010-07-28 22:29:10 +02009784 */
9785 static char_u *
9786get_path_cutoff(fname, gap)
9787 char_u *fname;
9788 garray_T *gap;
9789{
9790 int i;
9791 int maxlen = 0;
9792 char_u **path_part = (char_u **)gap->ga_data;
9793 char_u *cutoff = NULL;
9794
9795 for (i = 0; i < gap->ga_len; i++)
9796 {
9797 int j = 0;
9798
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009799 while ((fname[j] == path_part[i][j]
Bram Moolenaar2d7c47d2010-08-10 19:50:26 +02009800# if defined(MSWIN) || defined(MSDOS)
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009801 || (vim_ispathsep(fname[j]) && vim_ispathsep(path_part[i][j]))
9802#endif
9803 ) && fname[j] != NUL && path_part[i][j] != NUL)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009804 j++;
9805 if (j > maxlen)
9806 {
9807 maxlen = j;
9808 cutoff = &fname[j];
9809 }
9810 }
9811
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009812 /* skip to the file or directory name */
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009813 if (cutoff != NULL)
Bram Moolenaar31710262010-08-13 13:36:15 +02009814 while (vim_ispathsep(*cutoff))
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009815 mb_ptr_adv(cutoff);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009816
9817 return cutoff;
9818}
9819
9820/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009821 * Sorts, removes duplicates and modifies all the fullpath names in "gap" so
9822 * that they are unique with respect to each other while conserving the part
9823 * that matches the pattern. Beware, this is at least O(n^2) wrt "gap->ga_len".
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009824 */
9825 static void
9826uniquefy_paths(gap, pattern)
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +02009827 garray_T *gap;
9828 char_u *pattern;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009829{
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +02009830 int i;
9831 int len;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009832 char_u **fnames = (char_u **)gap->ga_data;
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009833 int sort_again = FALSE;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009834 char_u *pat;
9835 char_u *file_pattern;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009836 char_u *curdir;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009837 regmatch_T regmatch;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009838 garray_T path_ga;
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009839 char_u **in_curdir = NULL;
9840 char_u *short_name;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009841
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +02009842 remove_duplicates(gap);
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009843 ga_init2(&path_ga, (int)sizeof(char_u *), 1);
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009844
9845 /*
9846 * We need to prepend a '*' at the beginning of file_pattern so that the
9847 * regex matches anywhere in the path. FIXME: is this valid for all
Bram Moolenaarb31e4382010-07-24 16:01:56 +02009848 * possible patterns?
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009849 */
Bram Moolenaar624c7aa2010-07-16 20:38:52 +02009850 len = (int)STRLEN(pattern);
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009851 file_pattern = alloc(len + 2);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009852 if (file_pattern == NULL)
9853 return;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009854 file_pattern[0] = '*';
Bram Moolenaar162bd912010-07-28 22:29:10 +02009855 file_pattern[1] = NUL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009856 STRCAT(file_pattern, pattern);
9857 pat = file_pat_to_reg_pat(file_pattern, NULL, NULL, TRUE);
9858 vim_free(file_pattern);
Bram Moolenaarb31e4382010-07-24 16:01:56 +02009859 if (pat == NULL)
9860 return;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009861
Bram Moolenaarb31e4382010-07-24 16:01:56 +02009862 regmatch.rm_ic = TRUE; /* always ignore case */
9863 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
9864 vim_free(pat);
9865 if (regmatch.regprog == NULL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009866 return;
9867
Bram Moolenaar162bd912010-07-28 22:29:10 +02009868 if ((curdir = alloc((int)(MAXPATHL))) == NULL)
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009869 goto theend;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009870 mch_dirname(curdir, MAXPATHL);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009871 expand_path_option(curdir, &path_ga);
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009872
9873 in_curdir = (char_u **)alloc_clear(gap->ga_len * sizeof(char_u *));
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009874 if (in_curdir == NULL)
9875 goto theend;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009876
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009877 for (i = 0; i < gap->ga_len && !got_int; i++)
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009878 {
Bram Moolenaar162bd912010-07-28 22:29:10 +02009879 char_u *path = fnames[i];
9880 int is_in_curdir;
Bram Moolenaar31710262010-08-13 13:36:15 +02009881 char_u *dir_end = gettail_dir(path);
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009882 char_u *pathsep_p;
9883 char_u *path_cutoff;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009884
Bram Moolenaar624c7aa2010-07-16 20:38:52 +02009885 len = (int)STRLEN(path);
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009886 is_in_curdir = fnamencmp(curdir, path, dir_end - path) == 0
Bram Moolenaar162bd912010-07-28 22:29:10 +02009887 && curdir[dir_end - path] == NUL;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009888 if (is_in_curdir)
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009889 in_curdir[i] = vim_strsave(path);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009890
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009891 /* Shorten the filename while maintaining its uniqueness */
9892 path_cutoff = get_path_cutoff(path, &path_ga);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009893
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009894 /* we start at the end of the path */
9895 pathsep_p = path + len - 1;
9896
9897 while (find_previous_pathsep(path, &pathsep_p))
9898 if (vim_regexec(&regmatch, pathsep_p + 1, (colnr_T)0)
9899 && is_unique(pathsep_p + 1, gap, i)
9900 && path_cutoff != NULL && pathsep_p + 1 >= path_cutoff)
9901 {
9902 sort_again = TRUE;
9903 mch_memmove(path, pathsep_p + 1, STRLEN(pathsep_p));
9904 break;
9905 }
Bram Moolenaar9bc040c2010-08-11 22:05:57 +02009906
9907 if (mch_isFullName(path))
9908 {
9909 /*
9910 * Last resort: shorten relative to curdir if possible.
9911 * 'possible' means:
9912 * 1. It is under the current directory.
9913 * 2. The result is actually shorter than the original.
9914 *
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009915 * Before curdir After
9916 * /foo/bar/file.txt /foo/bar ./file.txt
9917 * c:\foo\bar\file.txt c:\foo\bar .\file.txt
9918 * /file.txt / /file.txt
9919 * c:\file.txt c:\ .\file.txt
Bram Moolenaar9bc040c2010-08-11 22:05:57 +02009920 */
9921 short_name = shorten_fname(path, curdir);
Bram Moolenaar31710262010-08-13 13:36:15 +02009922 if (short_name != NULL && short_name > path + 1
9923#if defined(MSWIN) || defined(MSDOS)
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009924 /* On windows,
Bram Moolenaar31710262010-08-13 13:36:15 +02009925 * shorten_fname("c:\a\a.txt", "c:\a\b")
Bram Moolenaar31710262010-08-13 13:36:15 +02009926 * returns "\a\a.txt", which is not really the short
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009927 * name, hence: */
Bram Moolenaar31710262010-08-13 13:36:15 +02009928 && !vim_ispathsep(*short_name)
9929#endif
9930 )
Bram Moolenaar9bc040c2010-08-11 22:05:57 +02009931 {
9932 STRCPY(path, ".");
9933 add_pathsep(path);
Bram Moolenaarcda000e2010-08-14 13:34:39 +02009934 STRMOVE(path + STRLEN(path), short_name);
Bram Moolenaar9bc040c2010-08-11 22:05:57 +02009935 }
9936 }
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009937 ui_breakcheck();
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009938 }
9939
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009940 /* Shorten filenames in /in/current/directory/{filename} */
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009941 for (i = 0; i < gap->ga_len && !got_int; i++)
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009942 {
9943 char_u *rel_path;
9944 char_u *path = in_curdir[i];
9945
9946 if (path == NULL)
9947 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009948
9949 /* If the {filename} is not unique, change it to ./{filename}.
9950 * Else reduce it to {filename} */
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009951 short_name = shorten_fname(path, curdir);
9952 if (short_name == NULL)
9953 short_name = path;
9954 if (is_unique(short_name, gap, i))
9955 {
9956 STRCPY(fnames[i], short_name);
9957 continue;
9958 }
9959
9960 rel_path = alloc((int)(STRLEN(short_name) + STRLEN(PATHSEPSTR) + 2));
9961 if (rel_path == NULL)
9962 goto theend;
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009963 STRCPY(rel_path, ".");
9964 add_pathsep(rel_path);
9965 STRCAT(rel_path, short_name);
9966
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009967 vim_free(fnames[i]);
9968 fnames[i] = rel_path;
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009969 sort_again = TRUE;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009970 ui_breakcheck();
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009971 }
9972
Bram Moolenaar162bd912010-07-28 22:29:10 +02009973theend:
9974 vim_free(curdir);
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009975 if (in_curdir != NULL)
9976 {
9977 for (i = 0; i < gap->ga_len; i++)
9978 vim_free(in_curdir[i]);
9979 vim_free(in_curdir);
9980 }
Bram Moolenaar162bd912010-07-28 22:29:10 +02009981 ga_clear_strings(&path_ga);
Bram Moolenaarb31e4382010-07-24 16:01:56 +02009982 vim_free(regmatch.regprog);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009983
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009984 if (sort_again)
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +02009985 remove_duplicates(gap);
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009986}
9987
9988/*
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +02009989 * Calls globpath() with 'path' values for the given pattern and stores the
9990 * result in "gap".
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009991 * Returns the total number of matches.
9992 */
9993 static int
9994expand_in_path(gap, pattern, flags)
9995 garray_T *gap;
9996 char_u *pattern;
9997 int flags; /* EW_* flags */
9998{
Bram Moolenaar162bd912010-07-28 22:29:10 +02009999 char_u *curdir;
10000 garray_T path_ga;
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010001 char_u *files = NULL;
10002 char_u *s; /* start */
10003 char_u *e; /* end */
10004 char_u *paths = NULL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010005
Bram Moolenaar7f0f6212010-08-03 22:21:00 +020010006 if ((curdir = alloc((unsigned)MAXPATHL)) == NULL)
Bram Moolenaar162bd912010-07-28 22:29:10 +020010007 return 0;
10008 mch_dirname(curdir, MAXPATHL);
10009
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010010 ga_init2(&path_ga, (int)sizeof(char_u *), 1);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010011 expand_path_option(curdir, &path_ga);
10012 vim_free(curdir);
Bram Moolenaar006d2b02010-08-04 12:39:44 +020010013 if (path_ga.ga_len == 0)
10014 return 0;
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010015
10016 paths = ga_concat_strings(&path_ga);
10017 ga_clear_strings(&path_ga);
10018 if (paths == NULL)
Bram Moolenaar7f0f6212010-08-03 22:21:00 +020010019 return 0;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010020
Bram Moolenaar94950a92010-12-02 16:01:29 +010010021 files = globpath(paths, pattern, (flags & EW_ICASE) ? WILD_ICASE : 0);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010022 vim_free(paths);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010023 if (files == NULL)
10024 return 0;
10025
10026 /* Copy each path in files into gap */
10027 s = e = files;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010028 while (*s != NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010029 {
Bram Moolenaar162bd912010-07-28 22:29:10 +020010030 while (*e != '\n' && *e != NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010031 e++;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010032 if (*e == NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010033 {
10034 addfile(gap, s, flags);
10035 break;
10036 }
10037 else
10038 {
10039 /* *e is '\n' */
Bram Moolenaar162bd912010-07-28 22:29:10 +020010040 *e = NUL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010041 addfile(gap, s, flags);
10042 e++;
10043 s = e;
10044 }
10045 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010046 vim_free(files);
10047
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010048 return gap->ga_len;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010049}
10050#endif
10051
Bram Moolenaar1587a1e2010-07-29 20:59:59 +020010052#if defined(FEAT_SEARCHPATH) || defined(FEAT_CMDL_COMPL) || defined(PROTO)
10053/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010054 * Sort "gap" and remove duplicate entries. "gap" is expected to contain a
10055 * list of file names in allocated memory.
Bram Moolenaar1587a1e2010-07-29 20:59:59 +020010056 */
10057 void
10058remove_duplicates(gap)
10059 garray_T *gap;
10060{
10061 int i;
10062 int j;
10063 char_u **fnames = (char_u **)gap->ga_data;
10064
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010065 sort_strings(fnames, gap->ga_len);
Bram Moolenaar1587a1e2010-07-29 20:59:59 +020010066 for (i = gap->ga_len - 1; i > 0; --i)
10067 if (fnamecmp(fnames[i - 1], fnames[i]) == 0)
10068 {
10069 vim_free(fnames[i]);
10070 for (j = i + 1; j < gap->ga_len; ++j)
10071 fnames[j - 1] = fnames[j];
10072 --gap->ga_len;
10073 }
10074}
10075#endif
10076
Bram Moolenaar071d4272004-06-13 20:20:40 +000010077/*
10078 * Generic wildcard expansion code.
10079 *
10080 * Characters in "pat" that should not be expanded must be preceded with a
10081 * backslash. E.g., "/path\ with\ spaces/my\*star*"
10082 *
10083 * Return FAIL when no single file was found. In this case "num_file" is not
10084 * set, and "file" may contain an error message.
10085 * Return OK when some files found. "num_file" is set to the number of
10086 * matches, "file" to the array of matches. Call FreeWild() later.
10087 */
10088 int
10089gen_expand_wildcards(num_pat, pat, num_file, file, flags)
10090 int num_pat; /* number of input patterns */
10091 char_u **pat; /* array of input patterns */
10092 int *num_file; /* resulting number of files */
10093 char_u ***file; /* array of resulting files */
10094 int flags; /* EW_* flags */
10095{
10096 int i;
10097 garray_T ga;
10098 char_u *p;
10099 static int recursive = FALSE;
10100 int add_pat;
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010101#if defined(FEAT_SEARCHPATH)
10102 int did_expand_in_path = FALSE;
10103#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000010104
10105 /*
10106 * expand_env() is called to expand things like "~user". If this fails,
10107 * it calls ExpandOne(), which brings us back here. In this case, always
10108 * call the machine specific expansion function, if possible. Otherwise,
10109 * return FAIL.
10110 */
10111 if (recursive)
10112#ifdef SPECIAL_WILDCHAR
10113 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
10114#else
10115 return FAIL;
10116#endif
10117
10118#ifdef SPECIAL_WILDCHAR
10119 /*
10120 * If there are any special wildcard characters which we cannot handle
10121 * here, call machine specific function for all the expansion. This
10122 * avoids starting the shell for each argument separately.
10123 * For `=expr` do use the internal function.
10124 */
10125 for (i = 0; i < num_pat; i++)
10126 {
10127 if (vim_strpbrk(pat[i], (char_u *)SPECIAL_WILDCHAR) != NULL
10128# ifdef VIM_BACKTICK
10129 && !(vim_backtick(pat[i]) && pat[i][1] == '=')
10130# endif
10131 )
10132 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
10133 }
10134#endif
10135
10136 recursive = TRUE;
10137
10138 /*
10139 * The matching file names are stored in a growarray. Init it empty.
10140 */
10141 ga_init2(&ga, (int)sizeof(char_u *), 30);
10142
10143 for (i = 0; i < num_pat; ++i)
10144 {
10145 add_pat = -1;
10146 p = pat[i];
10147
10148#ifdef VIM_BACKTICK
10149 if (vim_backtick(p))
10150 add_pat = expand_backtick(&ga, p, flags);
10151 else
10152#endif
10153 {
10154 /*
10155 * First expand environment variables, "~/" and "~user/".
10156 */
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010157 if (vim_strchr(p, '$') != NULL || *p == '~')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010158 {
Bram Moolenaar9f0545d2007-09-26 20:36:32 +000010159 p = expand_env_save_opt(p, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010160 if (p == NULL)
10161 p = pat[i];
10162#ifdef UNIX
10163 /*
10164 * On Unix, if expand_env() can't expand an environment
10165 * variable, use the shell to do that. Discard previously
10166 * found file names and start all over again.
10167 */
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010168 else if (vim_strchr(p, '$') != NULL || *p == '~')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010169 {
10170 vim_free(p);
Bram Moolenaar782027e2009-06-24 14:25:49 +000010171 ga_clear_strings(&ga);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010172 i = mch_expand_wildcards(num_pat, pat, num_file, file,
10173 flags);
10174 recursive = FALSE;
10175 return i;
10176 }
10177#endif
10178 }
10179
10180 /*
10181 * If there are wildcards: Expand file names and add each match to
10182 * the list. If there is no match, and EW_NOTFOUND is given, add
10183 * the pattern.
10184 * If there are no wildcards: Add the file name if it exists or
10185 * when EW_NOTFOUND is given.
10186 */
10187 if (mch_has_exp_wildcard(p))
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010188 {
10189#if defined(FEAT_SEARCHPATH)
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010190 if ((flags & EW_PATH)
10191 && !mch_isFullName(p)
10192 && !(p[0] == '.'
10193 && (vim_ispathsep(p[1])
10194 || (p[1] == '.' && vim_ispathsep(p[2]))))
10195 )
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010196 {
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010197 /* :find completion where 'path' is used.
10198 * Recursiveness is OK here. */
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010199 recursive = FALSE;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010200 add_pat = expand_in_path(&ga, p, flags);
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010201 recursive = TRUE;
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010202 did_expand_in_path = TRUE;
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010203 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010204 else
10205#endif
10206 add_pat = mch_expandpath(&ga, p, flags);
10207 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010208 }
10209
10210 if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
10211 {
10212 char_u *t = backslash_halve_save(p);
10213
10214#if defined(MACOS_CLASSIC)
10215 slash_to_colon(t);
10216#endif
10217 /* When EW_NOTFOUND is used, always add files and dirs. Makes
10218 * "vim c:/" work. */
10219 if (flags & EW_NOTFOUND)
10220 addfile(&ga, t, flags | EW_DIR | EW_FILE);
10221 else if (mch_getperm(t) >= 0)
10222 addfile(&ga, t, flags);
10223 vim_free(t);
10224 }
10225
Bram Moolenaarb28ebbc2010-07-14 16:59:57 +020010226#if defined(FEAT_SEARCHPATH)
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010227 if (did_expand_in_path && ga.ga_len > 0 && (flags & EW_PATH))
Bram Moolenaarb28ebbc2010-07-14 16:59:57 +020010228 uniquefy_paths(&ga, p);
10229#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000010230 if (p != pat[i])
10231 vim_free(p);
10232 }
10233
10234 *num_file = ga.ga_len;
10235 *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data : (char_u **)"";
10236
10237 recursive = FALSE;
10238
10239 return (ga.ga_data != NULL) ? OK : FAIL;
10240}
10241
10242# ifdef VIM_BACKTICK
10243
10244/*
10245 * Return TRUE if we can expand this backtick thing here.
10246 */
10247 static int
10248vim_backtick(p)
10249 char_u *p;
10250{
10251 return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
10252}
10253
10254/*
10255 * Expand an item in `backticks` by executing it as a command.
10256 * Currently only works when pat[] starts and ends with a `.
10257 * Returns number of file names found.
10258 */
10259 static int
10260expand_backtick(gap, pat, flags)
10261 garray_T *gap;
10262 char_u *pat;
10263 int flags; /* EW_* flags */
10264{
10265 char_u *p;
10266 char_u *cmd;
10267 char_u *buffer;
10268 int cnt = 0;
10269 int i;
10270
10271 /* Create the command: lop off the backticks. */
10272 cmd = vim_strnsave(pat + 1, (int)STRLEN(pat) - 2);
10273 if (cmd == NULL)
10274 return 0;
10275
10276#ifdef FEAT_EVAL
10277 if (*cmd == '=') /* `={expr}`: Expand expression */
Bram Moolenaar362e1a32006-03-06 23:29:24 +000010278 buffer = eval_to_string(cmd + 1, &p, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010279 else
10280#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010281 buffer = get_cmd_output(cmd, NULL,
10282 (flags & EW_SILENT) ? SHELL_SILENT : 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010283 vim_free(cmd);
10284 if (buffer == NULL)
10285 return 0;
10286
10287 cmd = buffer;
10288 while (*cmd != NUL)
10289 {
10290 cmd = skipwhite(cmd); /* skip over white space */
10291 p = cmd;
10292 while (*p != NUL && *p != '\r' && *p != '\n') /* skip over entry */
10293 ++p;
10294 /* add an entry if it is not empty */
10295 if (p > cmd)
10296 {
10297 i = *p;
10298 *p = NUL;
10299 addfile(gap, cmd, flags);
10300 *p = i;
10301 ++cnt;
10302 }
10303 cmd = p;
10304 while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
10305 ++cmd;
10306 }
10307
10308 vim_free(buffer);
10309 return cnt;
10310}
10311# endif /* VIM_BACKTICK */
10312
10313/*
10314 * Add a file to a file list. Accepted flags:
10315 * EW_DIR add directories
10316 * EW_FILE add files
Bram Moolenaar1f35bf92006-03-07 22:38:47 +000010317 * EW_EXEC add executable files
Bram Moolenaar071d4272004-06-13 20:20:40 +000010318 * EW_NOTFOUND add even when it doesn't exist
10319 * EW_ADDSLASH add slash after directory name
10320 */
10321 void
10322addfile(gap, f, flags)
10323 garray_T *gap;
10324 char_u *f; /* filename */
10325 int flags;
10326{
10327 char_u *p;
10328 int isdir;
10329
10330 /* if the file/dir doesn't exist, may not add it */
10331 if (!(flags & EW_NOTFOUND) && mch_getperm(f) < 0)
10332 return;
10333
10334#ifdef FNAME_ILLEGAL
10335 /* if the file/dir contains illegal characters, don't add it */
10336 if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
10337 return;
10338#endif
10339
10340 isdir = mch_isdir(f);
10341 if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
10342 return;
10343
Bram Moolenaar1f35bf92006-03-07 22:38:47 +000010344 /* If the file isn't executable, may not add it. Do accept directories. */
10345 if (!isdir && (flags & EW_EXEC) && !mch_can_exe(f))
10346 return;
10347
Bram Moolenaar071d4272004-06-13 20:20:40 +000010348 /* Make room for another item in the file list. */
10349 if (ga_grow(gap, 1) == FAIL)
10350 return;
10351
10352 p = alloc((unsigned)(STRLEN(f) + 1 + isdir));
10353 if (p == NULL)
10354 return;
10355
10356 STRCPY(p, f);
10357#ifdef BACKSLASH_IN_FILENAME
10358 slash_adjust(p);
10359#endif
10360 /*
10361 * Append a slash or backslash after directory names if none is present.
10362 */
10363#ifndef DONT_ADD_PATHSEP_TO_DIR
10364 if (isdir && (flags & EW_ADDSLASH))
10365 add_pathsep(p);
10366#endif
10367 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010368}
10369#endif /* !NO_EXPANDPATH */
10370
10371#if defined(VIM_BACKTICK) || defined(FEAT_EVAL) || defined(PROTO)
10372
10373#ifndef SEEK_SET
10374# define SEEK_SET 0
10375#endif
10376#ifndef SEEK_END
10377# define SEEK_END 2
10378#endif
10379
10380/*
10381 * Get the stdout of an external command.
10382 * Returns an allocated string, or NULL for error.
10383 */
10384 char_u *
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010385get_cmd_output(cmd, infile, flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010386 char_u *cmd;
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010387 char_u *infile; /* optional input file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010388 int flags; /* can be SHELL_SILENT */
10389{
10390 char_u *tempname;
10391 char_u *command;
10392 char_u *buffer = NULL;
10393 int len;
10394 int i = 0;
10395 FILE *fd;
10396
10397 if (check_restricted() || check_secure())
10398 return NULL;
10399
10400 /* get a name for the temp file */
10401 if ((tempname = vim_tempname('o')) == NULL)
10402 {
10403 EMSG(_(e_notmp));
10404 return NULL;
10405 }
10406
10407 /* Add the redirection stuff */
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010408 command = make_filter_cmd(cmd, infile, tempname);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010409 if (command == NULL)
10410 goto done;
10411
10412 /*
10413 * Call the shell to execute the command (errors are ignored).
10414 * Don't check timestamps here.
10415 */
10416 ++no_check_timestamps;
10417 call_shell(command, SHELL_DOOUT | SHELL_EXPAND | flags);
10418 --no_check_timestamps;
10419
10420 vim_free(command);
10421
10422 /*
10423 * read the names from the file into memory
10424 */
10425# ifdef VMS
Bram Moolenaar25394022007-05-10 19:06:20 +000010426 /* created temporary file is not always readable as binary */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010427 fd = mch_fopen((char *)tempname, "r");
10428# else
10429 fd = mch_fopen((char *)tempname, READBIN);
10430# endif
10431
10432 if (fd == NULL)
10433 {
10434 EMSG2(_(e_notopen), tempname);
10435 goto done;
10436 }
10437
10438 fseek(fd, 0L, SEEK_END);
10439 len = ftell(fd); /* get size of temp file */
10440 fseek(fd, 0L, SEEK_SET);
10441
10442 buffer = alloc(len + 1);
10443 if (buffer != NULL)
10444 i = (int)fread((char *)buffer, (size_t)1, (size_t)len, fd);
10445 fclose(fd);
10446 mch_remove(tempname);
10447 if (buffer == NULL)
10448 goto done;
10449#ifdef VMS
10450 len = i; /* VMS doesn't give us what we asked for... */
10451#endif
10452 if (i != len)
10453 {
10454 EMSG2(_(e_notread), tempname);
10455 vim_free(buffer);
10456 buffer = NULL;
10457 }
10458 else
Bram Moolenaar162bd912010-07-28 22:29:10 +020010459 buffer[len] = NUL; /* make sure the buffer is terminated */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010460
10461done:
10462 vim_free(tempname);
10463 return buffer;
10464}
10465#endif
10466
10467/*
10468 * Free the list of files returned by expand_wildcards() or other expansion
10469 * functions.
10470 */
10471 void
10472FreeWild(count, files)
10473 int count;
10474 char_u **files;
10475{
Bram Moolenaarfc1421e2006-04-20 22:17:20 +000010476 if (count <= 0 || files == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010477 return;
10478#if defined(__EMX__) && defined(__ALWAYS_HAS_TRAILING_NULL_POINTER) /* XXX */
10479 /*
10480 * Is this still OK for when other functions than expand_wildcards() have
10481 * been used???
10482 */
10483 _fnexplodefree((char **)files);
10484#else
10485 while (count--)
10486 vim_free(files[count]);
10487 vim_free(files);
10488#endif
10489}
10490
10491/*
Bram Moolenaara9dc3752010-07-11 20:46:53 +020010492 * Return TRUE when need to go to Insert mode because of 'insertmode'.
Bram Moolenaar071d4272004-06-13 20:20:40 +000010493 * Don't do this when still processing a command or a mapping.
10494 * Don't do this when inside a ":normal" command.
10495 */
10496 int
10497goto_im()
10498{
10499 return (p_im && stuff_empty() && typebuf_typed());
10500}