blob: cc29239086282e45c4ce81fdb0e1b86a45da9bc5 [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/*
5774 * Return TRUE if we are at the end of a do-while.
5775 * do
5776 * nothing;
5777 * while (foo
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00005778 * && bar); <-- here
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005779 * Adjust the cursor to the line with "while".
5780 */
5781 static int
5782cin_iswhileofdo_end(terminated, ind_maxparen, ind_maxcomment)
5783 int terminated;
5784 int ind_maxparen;
5785 int ind_maxcomment;
5786{
5787 char_u *line;
5788 char_u *p;
5789 char_u *s;
5790 pos_T *trypos;
5791 int i;
5792
5793 if (terminated != ';') /* there must be a ';' at the end */
5794 return FALSE;
5795
5796 p = line = ml_get_curline();
5797 while (*p != NUL)
5798 {
5799 p = cin_skipcomment(p);
5800 if (*p == ')')
5801 {
5802 s = skipwhite(p + 1);
5803 if (*s == ';' && cin_nocode(s + 1))
5804 {
5805 /* Found ");" at end of the line, now check there is "while"
5806 * before the matching '('. XXX */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005807 i = (int)(p - line);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005808 curwin->w_cursor.col = i;
5809 trypos = find_match_paren(ind_maxparen, ind_maxcomment);
5810 if (trypos != NULL)
5811 {
5812 s = cin_skipcomment(ml_get(trypos->lnum));
5813 if (*s == '}') /* accept "} while (cond);" */
5814 s = cin_skipcomment(s + 1);
5815 if (STRNCMP(s, "while", 5) == 0 && !vim_isIDc(s[5]))
5816 {
5817 curwin->w_cursor.lnum = trypos->lnum;
5818 return TRUE;
5819 }
5820 }
5821
5822 /* Searching may have made "line" invalid, get it again. */
5823 line = ml_get_curline();
5824 p = line + i;
5825 }
5826 }
5827 if (*p != NUL)
5828 ++p;
5829 }
5830 return FALSE;
5831}
5832
Bram Moolenaar071d4272004-06-13 20:20:40 +00005833 static int
5834cin_isbreak(p)
5835 char_u *p;
5836{
5837 return (STRNCMP(p, "break", 5) == 0 && !vim_isIDc(p[5]));
5838}
5839
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005840/*
5841 * Find the position of a C++ base-class declaration or
Bram Moolenaar071d4272004-06-13 20:20:40 +00005842 * constructor-initialization. eg:
5843 *
5844 * class MyClass :
5845 * baseClass <-- here
5846 * class MyClass : public baseClass,
5847 * anotherBaseClass <-- here (should probably lineup ??)
5848 * MyClass::MyClass(...) :
5849 * baseClass(...) <-- here (constructor-initialization)
Bram Moolenaar18144c82006-04-12 21:52:12 +00005850 *
5851 * This is a lot of guessing. Watch out for "cond ? func() : foo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005852 */
5853 static int
Bram Moolenaare7c56862007-08-04 10:14:52 +00005854cin_is_cpp_baseclass(col)
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005855 colnr_T *col; /* return: column to align with */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005856{
5857 char_u *s;
5858 int class_or_struct, lookfor_ctor_init, cpp_base_class;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005859 linenr_T lnum = curwin->w_cursor.lnum;
Bram Moolenaare7c56862007-08-04 10:14:52 +00005860 char_u *line = ml_get_curline();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005861
5862 *col = 0;
5863
Bram Moolenaar21cf8232004-07-16 20:18:37 +00005864 s = skipwhite(line);
5865 if (*s == '#') /* skip #define FOO x ? (x) : x */
5866 return FALSE;
5867 s = cin_skipcomment(s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005868 if (*s == NUL)
5869 return FALSE;
5870
5871 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
5872
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005873 /* Search for a line starting with '#', empty, ending in ';' or containing
5874 * '{' or '}' and start below it. This handles the following situations:
5875 * a = cond ?
5876 * func() :
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00005877 * asdf;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005878 * func::foo()
5879 * : something
5880 * {}
5881 * Foo::Foo (int one, int two)
5882 * : something(4),
5883 * somethingelse(3)
5884 * {}
5885 */
5886 while (lnum > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005887 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00005888 line = ml_get(lnum - 1);
5889 s = skipwhite(line);
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005890 if (*s == '#' || *s == NUL)
5891 break;
5892 while (*s != NUL)
5893 {
5894 s = cin_skipcomment(s);
5895 if (*s == '{' || *s == '}'
5896 || (*s == ';' && cin_nocode(s + 1)))
5897 break;
5898 if (*s != NUL)
5899 ++s;
5900 }
5901 if (*s != NUL)
5902 break;
5903 --lnum;
5904 }
5905
Bram Moolenaare7c56862007-08-04 10:14:52 +00005906 line = ml_get(lnum);
5907 s = cin_skipcomment(line);
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005908 for (;;)
5909 {
5910 if (*s == NUL)
5911 {
5912 if (lnum == curwin->w_cursor.lnum)
5913 break;
5914 /* Continue in the cursor line. */
Bram Moolenaare7c56862007-08-04 10:14:52 +00005915 line = ml_get(++lnum);
5916 s = cin_skipcomment(line);
5917 if (*s == NUL)
5918 continue;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005919 }
5920
Bram Moolenaaraede6ce2011-05-10 11:56:30 +02005921 if (s[0] == '"')
5922 s = skip_string(s) + 1;
5923 else if (s[0] == ':')
Bram Moolenaar071d4272004-06-13 20:20:40 +00005924 {
5925 if (s[1] == ':')
5926 {
5927 /* skip double colon. It can't be a constructor
5928 * initialization any more */
5929 lookfor_ctor_init = FALSE;
5930 s = cin_skipcomment(s + 2);
5931 }
5932 else if (lookfor_ctor_init || class_or_struct)
5933 {
5934 /* we have something found, that looks like the start of
Bram Moolenaare21877a2008-02-13 09:58:14 +00005935 * cpp-base-class-declaration or constructor-initialization */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005936 cpp_base_class = TRUE;
5937 lookfor_ctor_init = class_or_struct = FALSE;
5938 *col = 0;
5939 s = cin_skipcomment(s + 1);
5940 }
5941 else
5942 s = cin_skipcomment(s + 1);
5943 }
5944 else if ((STRNCMP(s, "class", 5) == 0 && !vim_isIDc(s[5]))
5945 || (STRNCMP(s, "struct", 6) == 0 && !vim_isIDc(s[6])))
5946 {
5947 class_or_struct = TRUE;
5948 lookfor_ctor_init = FALSE;
5949
5950 if (*s == 'c')
5951 s = cin_skipcomment(s + 5);
5952 else
5953 s = cin_skipcomment(s + 6);
5954 }
5955 else
5956 {
5957 if (s[0] == '{' || s[0] == '}' || s[0] == ';')
5958 {
5959 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
5960 }
5961 else if (s[0] == ')')
5962 {
5963 /* Constructor-initialization is assumed if we come across
5964 * something like "):" */
5965 class_or_struct = FALSE;
5966 lookfor_ctor_init = TRUE;
5967 }
Bram Moolenaar18144c82006-04-12 21:52:12 +00005968 else if (s[0] == '?')
5969 {
5970 /* Avoid seeing '() :' after '?' as constructor init. */
5971 return FALSE;
5972 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005973 else if (!vim_isIDc(s[0]))
5974 {
5975 /* if it is not an identifier, we are wrong */
5976 class_or_struct = FALSE;
5977 lookfor_ctor_init = FALSE;
5978 }
5979 else if (*col == 0)
5980 {
5981 /* it can't be a constructor-initialization any more */
5982 lookfor_ctor_init = FALSE;
5983
5984 /* the first statement starts here: lineup with this one... */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005985 if (cpp_base_class)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005986 *col = (colnr_T)(s - line);
5987 }
5988
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005989 /* When the line ends in a comma don't align with it. */
5990 if (lnum == curwin->w_cursor.lnum && *s == ',' && cin_nocode(s + 1))
5991 *col = 0;
5992
Bram Moolenaar071d4272004-06-13 20:20:40 +00005993 s = cin_skipcomment(s + 1);
5994 }
5995 }
5996
5997 return cpp_base_class;
5998}
5999
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006000 static int
6001get_baseclass_amount(col, ind_maxparen, ind_maxcomment, ind_cpp_baseclass)
6002 int col;
6003 int ind_maxparen;
6004 int ind_maxcomment;
6005 int ind_cpp_baseclass;
6006{
6007 int amount;
6008 colnr_T vcol;
6009 pos_T *trypos;
6010
6011 if (col == 0)
6012 {
6013 amount = get_indent();
6014 if (find_last_paren(ml_get_curline(), '(', ')')
6015 && (trypos = find_match_paren(ind_maxparen,
6016 ind_maxcomment)) != NULL)
6017 amount = get_indent_lnum(trypos->lnum); /* XXX */
6018 if (!cin_ends_in(ml_get_curline(), (char_u *)",", NULL))
6019 amount += ind_cpp_baseclass;
6020 }
6021 else
6022 {
6023 curwin->w_cursor.col = col;
6024 getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
6025 amount = (int)vcol;
6026 }
6027 if (amount < ind_cpp_baseclass)
6028 amount = ind_cpp_baseclass;
6029 return amount;
6030}
6031
Bram Moolenaar071d4272004-06-13 20:20:40 +00006032/*
6033 * Return TRUE if string "s" ends with the string "find", possibly followed by
6034 * white space and comments. Skip strings and comments.
6035 * Ignore "ignore" after "find" if it's not NULL.
6036 */
6037 static int
6038cin_ends_in(s, find, ignore)
6039 char_u *s;
6040 char_u *find;
6041 char_u *ignore;
6042{
6043 char_u *p = s;
6044 char_u *r;
6045 int len = (int)STRLEN(find);
6046
6047 while (*p != NUL)
6048 {
6049 p = cin_skipcomment(p);
6050 if (STRNCMP(p, find, len) == 0)
6051 {
6052 r = skipwhite(p + len);
6053 if (ignore != NULL && STRNCMP(r, ignore, STRLEN(ignore)) == 0)
6054 r = skipwhite(r + STRLEN(ignore));
6055 if (cin_nocode(r))
6056 return TRUE;
6057 }
6058 if (*p != NUL)
6059 ++p;
6060 }
6061 return FALSE;
6062}
6063
6064/*
6065 * Skip strings, chars and comments until at or past "trypos".
6066 * Return the column found.
6067 */
6068 static int
6069cin_skip2pos(trypos)
6070 pos_T *trypos;
6071{
6072 char_u *line;
6073 char_u *p;
6074
6075 p = line = ml_get(trypos->lnum);
6076 while (*p && (colnr_T)(p - line) < trypos->col)
6077 {
6078 if (cin_iscomment(p))
6079 p = cin_skipcomment(p);
6080 else
6081 {
6082 p = skip_string(p);
6083 ++p;
6084 }
6085 }
6086 return (int)(p - line);
6087}
6088
6089/*
6090 * Find the '{' at the start of the block we are in.
6091 * Return NULL if no match found.
6092 * Ignore a '{' that is in a comment, makes indenting the next three lines
6093 * work. */
6094/* foo() */
6095/* { */
6096/* } */
6097
6098 static pos_T *
6099find_start_brace(ind_maxcomment) /* XXX */
6100 int ind_maxcomment;
6101{
6102 pos_T cursor_save;
6103 pos_T *trypos;
6104 pos_T *pos;
6105 static pos_T pos_copy;
6106
6107 cursor_save = curwin->w_cursor;
6108 while ((trypos = findmatchlimit(NULL, '{', FM_BLOCKSTOP, 0)) != NULL)
6109 {
6110 pos_copy = *trypos; /* copy pos_T, next findmatch will change it */
6111 trypos = &pos_copy;
6112 curwin->w_cursor = *trypos;
6113 pos = NULL;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006114 /* ignore the { if it's in a // or / * * / comment */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006115 if ((colnr_T)cin_skip2pos(trypos) == trypos->col
6116 && (pos = find_start_comment(ind_maxcomment)) == NULL) /* XXX */
6117 break;
6118 if (pos != NULL)
6119 curwin->w_cursor.lnum = pos->lnum;
6120 }
6121 curwin->w_cursor = cursor_save;
6122 return trypos;
6123}
6124
6125/*
6126 * Find the matching '(', failing if it is in a comment.
6127 * Return NULL of no match found.
6128 */
6129 static pos_T *
6130find_match_paren(ind_maxparen, ind_maxcomment) /* XXX */
6131 int ind_maxparen;
6132 int ind_maxcomment;
6133{
6134 pos_T cursor_save;
6135 pos_T *trypos;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006136 static pos_T pos_copy;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006137
6138 cursor_save = curwin->w_cursor;
6139 if ((trypos = findmatchlimit(NULL, '(', 0, ind_maxparen)) != NULL)
6140 {
6141 /* check if the ( is in a // comment */
6142 if ((colnr_T)cin_skip2pos(trypos) > trypos->col)
6143 trypos = NULL;
6144 else
6145 {
6146 pos_copy = *trypos; /* copy trypos, findmatch will change it */
6147 trypos = &pos_copy;
6148 curwin->w_cursor = *trypos;
6149 if (find_start_comment(ind_maxcomment) != NULL) /* XXX */
6150 trypos = NULL;
6151 }
6152 }
6153 curwin->w_cursor = cursor_save;
6154 return trypos;
6155}
6156
6157/*
6158 * Return ind_maxparen corrected for the difference in line number between the
6159 * cursor position and "startpos". This makes sure that searching for a
6160 * matching paren above the cursor line doesn't find a match because of
6161 * looking a few lines further.
6162 */
6163 static int
6164corr_ind_maxparen(ind_maxparen, startpos)
6165 int ind_maxparen;
6166 pos_T *startpos;
6167{
6168 long n = (long)startpos->lnum - (long)curwin->w_cursor.lnum;
6169
6170 if (n > 0 && n < ind_maxparen / 2)
6171 return ind_maxparen - (int)n;
6172 return ind_maxparen;
6173}
6174
6175/*
6176 * Set w_cursor.col to the column number of the last unmatched ')' or '{' in
Bram Moolenaar6d8f9c62011-11-30 13:03:28 +01006177 * line "l". "l" must point to the start of the line.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006178 */
6179 static int
6180find_last_paren(l, start, end)
6181 char_u *l;
6182 int start, end;
6183{
6184 int i;
6185 int retval = FALSE;
6186 int open_count = 0;
6187
6188 curwin->w_cursor.col = 0; /* default is start of line */
6189
Bram Moolenaar6d8f9c62011-11-30 13:03:28 +01006190 for (i = 0; l[i] != NUL; i++)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006191 {
6192 i = (int)(cin_skipcomment(l + i) - l); /* ignore parens in comments */
6193 i = (int)(skip_string(l + i) - l); /* ignore parens in quotes */
6194 if (l[i] == start)
6195 ++open_count;
6196 else if (l[i] == end)
6197 {
6198 if (open_count > 0)
6199 --open_count;
6200 else
6201 {
6202 curwin->w_cursor.col = i;
6203 retval = TRUE;
6204 }
6205 }
6206 }
6207 return retval;
6208}
6209
6210 int
6211get_c_indent()
6212{
6213 /*
6214 * spaces from a block's opening brace the prevailing indent for that
6215 * block should be
6216 */
6217 int ind_level = curbuf->b_p_sw;
6218
6219 /*
6220 * spaces from the edge of the line an open brace that's at the end of a
6221 * line is imagined to be.
6222 */
6223 int ind_open_imag = 0;
6224
6225 /*
Bram Moolenaar1a509df2010-08-01 17:59:57 +02006226 * spaces from the prevailing indent for a line that is not preceded by
Bram Moolenaar071d4272004-06-13 20:20:40 +00006227 * an opening brace.
6228 */
6229 int ind_no_brace = 0;
6230
6231 /*
6232 * column where the first { of a function should be located }
6233 */
6234 int ind_first_open = 0;
6235
6236 /*
6237 * spaces from the prevailing indent a leftmost open brace should be
6238 * located
6239 */
6240 int ind_open_extra = 0;
6241
6242 /*
6243 * spaces from the matching open brace (real location for one at the left
6244 * edge; imaginary location from one that ends a line) the matching close
6245 * brace should be located
6246 */
6247 int ind_close_extra = 0;
6248
6249 /*
6250 * spaces from the edge of the line an open brace sitting in the leftmost
6251 * column is imagined to be
6252 */
6253 int ind_open_left_imag = 0;
6254
6255 /*
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006256 * Spaces jump labels should be shifted to the left if N is non-negative,
6257 * otherwise the jump label will be put to column 1.
6258 */
6259 int ind_jump_label = -1;
6260
6261 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006262 * spaces from the switch() indent a "case xx" label should be located
6263 */
6264 int ind_case = curbuf->b_p_sw;
6265
6266 /*
6267 * spaces from the "case xx:" code after a switch() should be located
6268 */
6269 int ind_case_code = curbuf->b_p_sw;
6270
6271 /*
6272 * lineup break at end of case in switch() with case label
6273 */
6274 int ind_case_break = 0;
6275
6276 /*
6277 * spaces from the class declaration indent a scope declaration label
6278 * should be located
6279 */
6280 int ind_scopedecl = curbuf->b_p_sw;
6281
6282 /*
6283 * spaces from the scope declaration label code should be located
6284 */
6285 int ind_scopedecl_code = curbuf->b_p_sw;
6286
6287 /*
6288 * amount K&R-style parameters should be indented
6289 */
6290 int ind_param = curbuf->b_p_sw;
6291
6292 /*
6293 * amount a function type spec should be indented
6294 */
6295 int ind_func_type = curbuf->b_p_sw;
6296
6297 /*
6298 * amount a cpp base class declaration or constructor initialization
6299 * should be indented
6300 */
6301 int ind_cpp_baseclass = curbuf->b_p_sw;
6302
6303 /*
6304 * additional spaces beyond the prevailing indent a continuation line
6305 * should be located
6306 */
6307 int ind_continuation = curbuf->b_p_sw;
6308
6309 /*
6310 * spaces from the indent of the line with an unclosed parentheses
6311 */
6312 int ind_unclosed = curbuf->b_p_sw * 2;
6313
6314 /*
6315 * spaces from the indent of the line with an unclosed parentheses, which
6316 * itself is also unclosed
6317 */
6318 int ind_unclosed2 = curbuf->b_p_sw;
6319
6320 /*
6321 * suppress ignoring spaces from the indent of a line starting with an
6322 * unclosed parentheses.
6323 */
6324 int ind_unclosed_noignore = 0;
6325
6326 /*
6327 * If the opening paren is the last nonwhite character on the line, and
6328 * ind_unclosed_wrapped is nonzero, use this indent relative to the outer
6329 * context (for very long lines).
6330 */
6331 int ind_unclosed_wrapped = 0;
6332
6333 /*
6334 * suppress ignoring white space when lining up with the character after
6335 * an unclosed parentheses.
6336 */
6337 int ind_unclosed_whiteok = 0;
6338
6339 /*
6340 * indent a closing parentheses under the line start of the matching
6341 * opening parentheses.
6342 */
6343 int ind_matching_paren = 0;
6344
6345 /*
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006346 * indent a closing parentheses under the previous line.
6347 */
6348 int ind_paren_prev = 0;
6349
6350 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006351 * Extra indent for comments.
6352 */
6353 int ind_comment = 0;
6354
6355 /*
6356 * spaces from the comment opener when there is nothing after it.
6357 */
6358 int ind_in_comment = 3;
6359
6360 /*
6361 * boolean: if non-zero, use ind_in_comment even if there is something
6362 * after the comment opener.
6363 */
6364 int ind_in_comment2 = 0;
6365
6366 /*
6367 * max lines to search for an open paren
6368 */
6369 int ind_maxparen = 20;
6370
6371 /*
6372 * max lines to search for an open comment
6373 */
6374 int ind_maxcomment = 70;
6375
6376 /*
6377 * handle braces for java code
6378 */
6379 int ind_java = 0;
6380
6381 /*
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006382 * not to confuse JS object properties with labels
6383 */
6384 int ind_js = 0;
6385
6386 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006387 * handle blocked cases correctly
6388 */
6389 int ind_keep_case_label = 0;
6390
Bram Moolenaared38b0a2011-05-25 15:16:18 +02006391 /*
6392 * handle C++ namespace
6393 */
6394 int ind_cpp_namespace = 0;
6395
Bram Moolenaar071d4272004-06-13 20:20:40 +00006396 pos_T cur_curpos;
6397 int amount;
6398 int scope_amount;
Bram Moolenaarb21e5842006-04-16 18:30:08 +00006399 int cur_amount = MAXCOL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006400 colnr_T col;
6401 char_u *theline;
6402 char_u *linecopy;
6403 pos_T *trypos;
6404 pos_T *tryposBrace = NULL;
6405 pos_T our_paren_pos;
6406 char_u *start;
6407 int start_brace;
Bram Moolenaare21877a2008-02-13 09:58:14 +00006408#define BRACE_IN_COL0 1 /* '{' is in column 0 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006409#define BRACE_AT_START 2 /* '{' is at start of line */
6410#define BRACE_AT_END 3 /* '{' is at end of line */
6411 linenr_T ourscope;
6412 char_u *l;
6413 char_u *look;
6414 char_u terminated;
6415 int lookfor;
6416#define LOOKFOR_INITIAL 0
6417#define LOOKFOR_IF 1
6418#define LOOKFOR_DO 2
6419#define LOOKFOR_CASE 3
6420#define LOOKFOR_ANY 4
6421#define LOOKFOR_TERM 5
6422#define LOOKFOR_UNTERM 6
6423#define LOOKFOR_SCOPEDECL 7
6424#define LOOKFOR_NOBREAK 8
6425#define LOOKFOR_CPP_BASECLASS 9
6426#define LOOKFOR_ENUM_OR_INIT 10
6427
6428 int whilelevel;
6429 linenr_T lnum;
6430 char_u *options;
6431 int fraction = 0; /* init for GCC */
6432 int divider;
6433 int n;
6434 int iscase;
6435 int lookfor_break;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02006436 int lookfor_cpp_namespace = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006437 int cont_amount = 0; /* amount for continuation line */
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006438 int original_line_islabel;
Bram Moolenaare79d1532011-10-04 18:03:47 +02006439 int added_to_amount = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006440
6441 for (options = curbuf->b_p_cino; *options; )
6442 {
6443 l = options++;
6444 if (*options == '-')
6445 ++options;
6446 n = getdigits(&options);
6447 divider = 0;
6448 if (*options == '.') /* ".5s" means a fraction */
6449 {
6450 fraction = atol((char *)++options);
6451 while (VIM_ISDIGIT(*options))
6452 {
6453 ++options;
6454 if (divider)
6455 divider *= 10;
6456 else
6457 divider = 10;
6458 }
6459 }
6460 if (*options == 's') /* "2s" means two times 'shiftwidth' */
6461 {
6462 if (n == 0 && fraction == 0)
6463 n = curbuf->b_p_sw; /* just "s" is one 'shiftwidth' */
6464 else
6465 {
6466 n *= curbuf->b_p_sw;
6467 if (divider)
6468 n += (curbuf->b_p_sw * fraction + divider / 2) / divider;
6469 }
6470 ++options;
6471 }
6472 if (l[1] == '-')
6473 n = -n;
6474 /* When adding an entry here, also update the default 'cinoptions' in
Bram Moolenaar39353fd2007-03-27 09:02:11 +00006475 * doc/indent.txt, and add explanation for it! */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006476 switch (*l)
6477 {
6478 case '>': ind_level = n; break;
6479 case 'e': ind_open_imag = n; break;
6480 case 'n': ind_no_brace = n; break;
6481 case 'f': ind_first_open = n; break;
6482 case '{': ind_open_extra = n; break;
6483 case '}': ind_close_extra = n; break;
6484 case '^': ind_open_left_imag = n; break;
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006485 case 'L': ind_jump_label = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006486 case ':': ind_case = n; break;
6487 case '=': ind_case_code = n; break;
6488 case 'b': ind_case_break = n; break;
6489 case 'p': ind_param = n; break;
6490 case 't': ind_func_type = n; break;
6491 case '/': ind_comment = n; break;
6492 case 'c': ind_in_comment = n; break;
6493 case 'C': ind_in_comment2 = n; break;
6494 case 'i': ind_cpp_baseclass = n; break;
6495 case '+': ind_continuation = n; break;
6496 case '(': ind_unclosed = n; break;
6497 case 'u': ind_unclosed2 = n; break;
6498 case 'U': ind_unclosed_noignore = n; break;
6499 case 'W': ind_unclosed_wrapped = n; break;
6500 case 'w': ind_unclosed_whiteok = n; break;
6501 case 'm': ind_matching_paren = n; break;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006502 case 'M': ind_paren_prev = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006503 case ')': ind_maxparen = n; break;
6504 case '*': ind_maxcomment = n; break;
6505 case 'g': ind_scopedecl = n; break;
6506 case 'h': ind_scopedecl_code = n; break;
6507 case 'j': ind_java = n; break;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006508 case 'J': ind_js = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006509 case 'l': ind_keep_case_label = n; break;
Bram Moolenaar39353fd2007-03-27 09:02:11 +00006510 case '#': ind_hash_comment = n; break;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02006511 case 'N': ind_cpp_namespace = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006512 }
Bram Moolenaardfdf3c42010-03-23 18:22:46 +01006513 if (*options == ',')
6514 ++options;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006515 }
6516
6517 /* remember where the cursor was when we started */
6518 cur_curpos = curwin->w_cursor;
6519
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006520 /* if we are at line 1 0 is fine, right? */
6521 if (cur_curpos.lnum == 1)
6522 return 0;
6523
Bram Moolenaar071d4272004-06-13 20:20:40 +00006524 /* Get a copy of the current contents of the line.
6525 * This is required, because only the most recent line obtained with
6526 * ml_get is valid! */
6527 linecopy = vim_strsave(ml_get(cur_curpos.lnum));
6528 if (linecopy == NULL)
6529 return 0;
6530
6531 /*
6532 * In insert mode and the cursor is on a ')' truncate the line at the
6533 * cursor position. We don't want to line up with the matching '(' when
6534 * inserting new stuff.
6535 * For unknown reasons the cursor might be past the end of the line, thus
6536 * check for that.
6537 */
6538 if ((State & INSERT)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006539 && curwin->w_cursor.col < (colnr_T)STRLEN(linecopy)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006540 && linecopy[curwin->w_cursor.col] == ')')
6541 linecopy[curwin->w_cursor.col] = NUL;
6542
6543 theline = skipwhite(linecopy);
6544
6545 /* move the cursor to the start of the line */
6546
6547 curwin->w_cursor.col = 0;
6548
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006549 original_line_islabel = cin_islabel(ind_maxcomment); /* XXX */
6550
Bram Moolenaar071d4272004-06-13 20:20:40 +00006551 /*
6552 * #defines and so on always go at the left when included in 'cinkeys'.
6553 */
6554 if (*theline == '#' && (*linecopy == '#' || in_cinkeys('#', ' ', TRUE)))
6555 {
6556 amount = 0;
6557 }
6558
6559 /*
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006560 * Is it a non-case label? Then that goes at the left margin too unless:
6561 * - JS flag is set.
6562 * - 'L' item has a positive value.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006563 */
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006564 else if (original_line_islabel && !ind_js && ind_jump_label < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006565 {
6566 amount = 0;
6567 }
6568
6569 /*
6570 * If we're inside a "//" comment and there is a "//" comment in a
6571 * previous line, lineup with that one.
6572 */
6573 else if (cin_islinecomment(theline)
6574 && (trypos = find_line_comment()) != NULL) /* XXX */
6575 {
6576 /* find how indented the line beginning the comment is */
6577 getvcol(curwin, trypos, &col, NULL, NULL);
6578 amount = col;
6579 }
6580
6581 /*
6582 * If we're inside a comment and not looking at the start of the
6583 * comment, try using the 'comments' option.
6584 */
6585 else if (!cin_iscomment(theline)
6586 && (trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
6587 {
6588 int lead_start_len = 2;
6589 int lead_middle_len = 1;
6590 char_u lead_start[COM_MAX_LEN]; /* start-comment string */
6591 char_u lead_middle[COM_MAX_LEN]; /* middle-comment string */
6592 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
6593 char_u *p;
6594 int start_align = 0;
6595 int start_off = 0;
6596 int done = FALSE;
6597
6598 /* find how indented the line beginning the comment is */
6599 getvcol(curwin, trypos, &col, NULL, NULL);
6600 amount = col;
Bram Moolenaar4aa97422011-04-11 14:27:38 +02006601 *lead_start = NUL;
6602 *lead_middle = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006603
6604 p = curbuf->b_p_com;
6605 while (*p != NUL)
6606 {
6607 int align = 0;
6608 int off = 0;
6609 int what = 0;
6610
6611 while (*p != NUL && *p != ':')
6612 {
6613 if (*p == COM_START || *p == COM_END || *p == COM_MIDDLE)
6614 what = *p++;
6615 else if (*p == COM_LEFT || *p == COM_RIGHT)
6616 align = *p++;
6617 else if (VIM_ISDIGIT(*p) || *p == '-')
6618 off = getdigits(&p);
6619 else
6620 ++p;
6621 }
6622
6623 if (*p == ':')
6624 ++p;
6625 (void)copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
6626 if (what == COM_START)
6627 {
6628 STRCPY(lead_start, lead_end);
6629 lead_start_len = (int)STRLEN(lead_start);
6630 start_off = off;
6631 start_align = align;
6632 }
6633 else if (what == COM_MIDDLE)
6634 {
6635 STRCPY(lead_middle, lead_end);
6636 lead_middle_len = (int)STRLEN(lead_middle);
6637 }
6638 else if (what == COM_END)
6639 {
6640 /* If our line starts with the middle comment string, line it
6641 * up with the comment opener per the 'comments' option. */
6642 if (STRNCMP(theline, lead_middle, lead_middle_len) == 0
6643 && STRNCMP(theline, lead_end, STRLEN(lead_end)) != 0)
6644 {
6645 done = TRUE;
6646 if (curwin->w_cursor.lnum > 1)
6647 {
6648 /* If the start comment string matches in the previous
Bram Moolenaare21877a2008-02-13 09:58:14 +00006649 * line, use the indent of that line plus offset. If
Bram Moolenaar071d4272004-06-13 20:20:40 +00006650 * the middle comment string matches in the previous
6651 * line, use the indent of that line. XXX */
6652 look = skipwhite(ml_get(curwin->w_cursor.lnum - 1));
6653 if (STRNCMP(look, lead_start, lead_start_len) == 0)
6654 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6655 else if (STRNCMP(look, lead_middle,
6656 lead_middle_len) == 0)
6657 {
6658 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6659 break;
6660 }
6661 /* If the start comment string doesn't match with the
6662 * start of the comment, skip this entry. XXX */
6663 else if (STRNCMP(ml_get(trypos->lnum) + trypos->col,
6664 lead_start, lead_start_len) != 0)
6665 continue;
6666 }
6667 if (start_off != 0)
6668 amount += start_off;
6669 else if (start_align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006670 amount += vim_strsize(lead_start)
6671 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006672 break;
6673 }
6674
6675 /* If our line starts with the end comment string, line it up
6676 * with the middle comment */
6677 if (STRNCMP(theline, lead_middle, lead_middle_len) != 0
6678 && STRNCMP(theline, lead_end, STRLEN(lead_end)) == 0)
6679 {
6680 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6681 /* XXX */
6682 if (off != 0)
6683 amount += off;
6684 else if (align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006685 amount += vim_strsize(lead_start)
6686 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006687 done = TRUE;
6688 break;
6689 }
6690 }
6691 }
6692
6693 /* If our line starts with an asterisk, line up with the
6694 * asterisk in the comment opener; otherwise, line up
6695 * with the first character of the comment text.
6696 */
6697 if (done)
6698 ;
6699 else if (theline[0] == '*')
6700 amount += 1;
6701 else
6702 {
6703 /*
6704 * If we are more than one line away from the comment opener, take
6705 * the indent of the previous non-empty line. If 'cino' has "CO"
6706 * and we are just below the comment opener and there are any
6707 * white characters after it line up with the text after it;
6708 * otherwise, add the amount specified by "c" in 'cino'
6709 */
6710 amount = -1;
6711 for (lnum = cur_curpos.lnum - 1; lnum > trypos->lnum; --lnum)
6712 {
6713 if (linewhite(lnum)) /* skip blank lines */
6714 continue;
6715 amount = get_indent_lnum(lnum); /* XXX */
6716 break;
6717 }
6718 if (amount == -1) /* use the comment opener */
6719 {
6720 if (!ind_in_comment2)
6721 {
6722 start = ml_get(trypos->lnum);
6723 look = start + trypos->col + 2; /* skip / and * */
6724 if (*look != NUL) /* if something after it */
6725 trypos->col = (colnr_T)(skipwhite(look) - start);
6726 }
6727 getvcol(curwin, trypos, &col, NULL, NULL);
6728 amount = col;
6729 if (ind_in_comment2 || *look == NUL)
6730 amount += ind_in_comment;
6731 }
6732 }
6733 }
6734
6735 /*
6736 * Are we inside parentheses or braces?
6737 */ /* XXX */
6738 else if (((trypos = find_match_paren(ind_maxparen, ind_maxcomment)) != NULL
6739 && ind_java == 0)
6740 || (tryposBrace = find_start_brace(ind_maxcomment)) != NULL
6741 || trypos != NULL)
6742 {
6743 if (trypos != NULL && tryposBrace != NULL)
6744 {
6745 /* Both an unmatched '(' and '{' is found. Use the one which is
6746 * closer to the current cursor position, set the other to NULL. */
6747 if (trypos->lnum != tryposBrace->lnum
6748 ? trypos->lnum < tryposBrace->lnum
6749 : trypos->col < tryposBrace->col)
6750 trypos = NULL;
6751 else
6752 tryposBrace = NULL;
6753 }
6754
6755 if (trypos != NULL)
6756 {
6757 /*
6758 * If the matching paren is more than one line away, use the indent of
6759 * a previous non-empty line that matches the same paren.
6760 */
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006761 if (theline[0] == ')' && ind_paren_prev)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006762 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006763 /* Line up with the start of the matching paren line. */
6764 amount = get_indent_lnum(curwin->w_cursor.lnum - 1); /* XXX */
6765 }
6766 else
6767 {
6768 amount = -1;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006769 our_paren_pos = *trypos;
6770 for (lnum = cur_curpos.lnum - 1; lnum > our_paren_pos.lnum; --lnum)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006771 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006772 l = skipwhite(ml_get(lnum));
6773 if (cin_nocode(l)) /* skip comment lines */
6774 continue;
6775 if (cin_ispreproc_cont(&l, &lnum))
6776 continue; /* ignore #define, #if, etc. */
6777 curwin->w_cursor.lnum = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006778
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006779 /* Skip a comment. XXX */
6780 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
6781 {
6782 lnum = trypos->lnum + 1;
6783 continue;
6784 }
6785
6786 /* XXX */
6787 if ((trypos = find_match_paren(
6788 corr_ind_maxparen(ind_maxparen, &cur_curpos),
Bram Moolenaar071d4272004-06-13 20:20:40 +00006789 ind_maxcomment)) != NULL
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006790 && trypos->lnum == our_paren_pos.lnum
6791 && trypos->col == our_paren_pos.col)
6792 {
6793 amount = get_indent_lnum(lnum); /* XXX */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006794
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006795 if (theline[0] == ')')
6796 {
6797 if (our_paren_pos.lnum != lnum
6798 && cur_amount > amount)
6799 cur_amount = amount;
6800 amount = -1;
6801 }
6802 break;
6803 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006804 }
6805 }
6806
6807 /*
6808 * Line up with line where the matching paren is. XXX
6809 * If the line starts with a '(' or the indent for unclosed
6810 * parentheses is zero, line up with the unclosed parentheses.
6811 */
6812 if (amount == -1)
6813 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006814 int ignore_paren_col = 0;
6815
Bram Moolenaar071d4272004-06-13 20:20:40 +00006816 amount = skip_label(our_paren_pos.lnum, &look, ind_maxcomment);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006817 look = skipwhite(look);
6818 if (*look == '(')
6819 {
6820 linenr_T save_lnum = curwin->w_cursor.lnum;
6821 char_u *line;
6822 int look_col;
6823
6824 /* Ignore a '(' in front of the line that has a match before
6825 * our matching '('. */
6826 curwin->w_cursor.lnum = our_paren_pos.lnum;
6827 line = ml_get_curline();
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006828 look_col = (int)(look - line);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006829 curwin->w_cursor.col = look_col + 1;
6830 if ((trypos = findmatchlimit(NULL, ')', 0, ind_maxparen))
6831 != NULL
6832 && trypos->lnum == our_paren_pos.lnum
6833 && trypos->col < our_paren_pos.col)
6834 ignore_paren_col = trypos->col + 1;
6835
6836 curwin->w_cursor.lnum = save_lnum;
6837 look = ml_get(our_paren_pos.lnum) + look_col;
6838 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006839 if (theline[0] == ')' || ind_unclosed == 0
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006840 || (!ind_unclosed_noignore && *look == '('
6841 && ignore_paren_col == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006842 {
6843 /*
6844 * If we're looking at a close paren, line up right there;
6845 * otherwise, line up with the next (non-white) character.
6846 * When ind_unclosed_wrapped is set and the matching paren is
6847 * the last nonwhite character of the line, use either the
6848 * indent of the current line or the indentation of the next
6849 * outer paren and add ind_unclosed_wrapped (for very long
6850 * lines).
6851 */
6852 if (theline[0] != ')')
6853 {
6854 cur_amount = MAXCOL;
6855 l = ml_get(our_paren_pos.lnum);
6856 if (ind_unclosed_wrapped
6857 && cin_ends_in(l, (char_u *)"(", NULL))
6858 {
6859 /* look for opening unmatched paren, indent one level
6860 * for each additional level */
6861 n = 1;
6862 for (col = 0; col < our_paren_pos.col; ++col)
6863 {
6864 switch (l[col])
6865 {
6866 case '(':
6867 case '{': ++n;
6868 break;
6869
6870 case ')':
6871 case '}': if (n > 1)
6872 --n;
6873 break;
6874 }
6875 }
6876
6877 our_paren_pos.col = 0;
6878 amount += n * ind_unclosed_wrapped;
6879 }
6880 else if (ind_unclosed_whiteok)
6881 our_paren_pos.col++;
6882 else
6883 {
6884 col = our_paren_pos.col + 1;
6885 while (vim_iswhite(l[col]))
6886 col++;
6887 if (l[col] != NUL) /* In case of trailing space */
6888 our_paren_pos.col = col;
6889 else
6890 our_paren_pos.col++;
6891 }
6892 }
6893
6894 /*
6895 * Find how indented the paren is, or the character after it
6896 * if we did the above "if".
6897 */
6898 if (our_paren_pos.col > 0)
6899 {
6900 getvcol(curwin, &our_paren_pos, &col, NULL, NULL);
6901 if (cur_amount > (int)col)
6902 cur_amount = col;
6903 }
6904 }
6905
6906 if (theline[0] == ')' && ind_matching_paren)
6907 {
6908 /* Line up with the start of the matching paren line. */
6909 }
6910 else if (ind_unclosed == 0 || (!ind_unclosed_noignore
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006911 && *look == '(' && ignore_paren_col == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006912 {
6913 if (cur_amount != MAXCOL)
6914 amount = cur_amount;
6915 }
6916 else
6917 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006918 /* Add ind_unclosed2 for each '(' before our matching one, but
6919 * ignore (void) before the line (ignore_paren_col). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006920 col = our_paren_pos.col;
Bram Moolenaarb21e5842006-04-16 18:30:08 +00006921 while ((int)our_paren_pos.col > ignore_paren_col)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006922 {
6923 --our_paren_pos.col;
6924 switch (*ml_get_pos(&our_paren_pos))
6925 {
6926 case '(': amount += ind_unclosed2;
6927 col = our_paren_pos.col;
6928 break;
6929 case ')': amount -= ind_unclosed2;
6930 col = MAXCOL;
6931 break;
6932 }
6933 }
6934
6935 /* Use ind_unclosed once, when the first '(' is not inside
6936 * braces */
6937 if (col == MAXCOL)
6938 amount += ind_unclosed;
6939 else
6940 {
6941 curwin->w_cursor.lnum = our_paren_pos.lnum;
6942 curwin->w_cursor.col = col;
Bram Moolenaar367bec82011-04-11 14:26:19 +02006943 if (find_match_paren(ind_maxparen, ind_maxcomment) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006944 amount += ind_unclosed2;
6945 else
6946 amount += ind_unclosed;
6947 }
6948 /*
6949 * For a line starting with ')' use the minimum of the two
6950 * positions, to avoid giving it more indent than the previous
6951 * lines:
6952 * func_long_name( if (x
6953 * arg && yy
6954 * ) ^ not here ) ^ not here
6955 */
6956 if (cur_amount < amount)
6957 amount = cur_amount;
6958 }
6959 }
6960
6961 /* add extra indent for a comment */
6962 if (cin_iscomment(theline))
6963 amount += ind_comment;
6964 }
6965
6966 /*
6967 * Are we at least inside braces, then?
6968 */
6969 else
6970 {
6971 trypos = tryposBrace;
6972
6973 ourscope = trypos->lnum;
6974 start = ml_get(ourscope);
6975
6976 /*
6977 * Now figure out how indented the line is in general.
6978 * If the brace was at the start of the line, we use that;
6979 * otherwise, check out the indentation of the line as
6980 * a whole and then add the "imaginary indent" to that.
6981 */
6982 look = skipwhite(start);
6983 if (*look == '{')
6984 {
6985 getvcol(curwin, trypos, &col, NULL, NULL);
6986 amount = col;
6987 if (*start == '{')
6988 start_brace = BRACE_IN_COL0;
6989 else
6990 start_brace = BRACE_AT_START;
6991 }
6992 else
6993 {
6994 /*
6995 * that opening brace might have been on a continuation
6996 * line. if so, find the start of the line.
6997 */
6998 curwin->w_cursor.lnum = ourscope;
6999
7000 /*
7001 * position the cursor over the rightmost paren, so that
7002 * matching it will take us back to the start of the line.
7003 */
7004 lnum = ourscope;
7005 if (find_last_paren(start, '(', ')')
7006 && (trypos = find_match_paren(ind_maxparen,
7007 ind_maxcomment)) != NULL)
7008 lnum = trypos->lnum;
7009
7010 /*
7011 * It could have been something like
7012 * case 1: if (asdf &&
7013 * ldfd) {
7014 * }
7015 */
Bram Moolenaar6ec154b2011-06-12 21:51:08 +02007016 if (ind_js || (ind_keep_case_label
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007017 && cin_iscase(skipwhite(ml_get_curline()), FALSE)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007018 amount = get_indent();
7019 else
7020 amount = skip_label(lnum, &l, ind_maxcomment);
7021
7022 start_brace = BRACE_AT_END;
7023 }
7024
7025 /*
7026 * if we're looking at a closing brace, that's where
7027 * we want to be. otherwise, add the amount of room
7028 * that an indent is supposed to be.
7029 */
7030 if (theline[0] == '}')
7031 {
7032 /*
7033 * they may want closing braces to line up with something
7034 * other than the open brace. indulge them, if so.
7035 */
7036 amount += ind_close_extra;
7037 }
7038 else
7039 {
7040 /*
7041 * If we're looking at an "else", try to find an "if"
7042 * to match it with.
7043 * If we're looking at a "while", try to find a "do"
7044 * to match it with.
7045 */
7046 lookfor = LOOKFOR_INITIAL;
7047 if (cin_iselse(theline))
7048 lookfor = LOOKFOR_IF;
7049 else if (cin_iswhileofdo(theline, cur_curpos.lnum, ind_maxparen))
7050 /* XXX */
7051 lookfor = LOOKFOR_DO;
7052 if (lookfor != LOOKFOR_INITIAL)
7053 {
7054 curwin->w_cursor.lnum = cur_curpos.lnum;
7055 if (find_match(lookfor, ourscope, ind_maxparen,
7056 ind_maxcomment) == OK)
7057 {
7058 amount = get_indent(); /* XXX */
7059 goto theend;
7060 }
7061 }
7062
7063 /*
7064 * We get here if we are not on an "while-of-do" or "else" (or
7065 * failed to find a matching "if").
7066 * Search backwards for something to line up with.
7067 * First set amount for when we don't find anything.
7068 */
7069
7070 /*
7071 * if the '{' is _really_ at the left margin, use the imaginary
7072 * location of a left-margin brace. Otherwise, correct the
7073 * location for ind_open_extra.
7074 */
7075
7076 if (start_brace == BRACE_IN_COL0) /* '{' is in column 0 */
7077 {
7078 amount = ind_open_left_imag;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007079 lookfor_cpp_namespace = TRUE;
7080 }
7081 else if (start_brace == BRACE_AT_START &&
7082 lookfor_cpp_namespace) /* '{' is at start */
7083 {
7084
7085 lookfor_cpp_namespace = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007086 }
7087 else
7088 {
7089 if (start_brace == BRACE_AT_END) /* '{' is at end of line */
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007090 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007091 amount += ind_open_imag;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007092
7093 l = skipwhite(ml_get_curline());
7094 if (cin_is_cpp_namespace(l))
7095 amount += ind_cpp_namespace;
7096 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007097 else
7098 {
7099 /* Compensate for adding ind_open_extra later. */
7100 amount -= ind_open_extra;
7101 if (amount < 0)
7102 amount = 0;
7103 }
7104 }
7105
7106 lookfor_break = FALSE;
7107
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007108 if (cin_iscase(theline, FALSE)) /* it's a switch() label */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007109 {
7110 lookfor = LOOKFOR_CASE; /* find a previous switch() label */
7111 amount += ind_case;
7112 }
7113 else if (cin_isscopedecl(theline)) /* private:, ... */
7114 {
7115 lookfor = LOOKFOR_SCOPEDECL; /* class decl is this block */
7116 amount += ind_scopedecl;
7117 }
7118 else
7119 {
7120 if (ind_case_break && cin_isbreak(theline)) /* break; ... */
7121 lookfor_break = TRUE;
7122
7123 lookfor = LOOKFOR_INITIAL;
7124 amount += ind_level; /* ind_level from start of block */
7125 }
7126 scope_amount = amount;
7127 whilelevel = 0;
7128
7129 /*
7130 * Search backwards. If we find something we recognize, line up
7131 * with that.
7132 *
7133 * if we're looking at an open brace, indent
7134 * the usual amount relative to the conditional
7135 * that opens the block.
7136 */
7137 curwin->w_cursor = cur_curpos;
7138 for (;;)
7139 {
7140 curwin->w_cursor.lnum--;
7141 curwin->w_cursor.col = 0;
7142
7143 /*
7144 * If we went all the way back to the start of our scope, line
7145 * up with it.
7146 */
7147 if (curwin->w_cursor.lnum <= ourscope)
7148 {
7149 /* we reached end of scope:
7150 * if looking for a enum or structure initialization
7151 * go further back:
7152 * if it is an initializer (enum xxx or xxx =), then
7153 * don't add ind_continuation, otherwise it is a variable
7154 * declaration:
7155 * int x,
7156 * here; <-- add ind_continuation
7157 */
7158 if (lookfor == LOOKFOR_ENUM_OR_INIT)
7159 {
7160 if (curwin->w_cursor.lnum == 0
7161 || curwin->w_cursor.lnum
7162 < ourscope - ind_maxparen)
7163 {
7164 /* nothing found (abuse ind_maxparen as limit)
7165 * assume terminated line (i.e. a variable
7166 * initialization) */
7167 if (cont_amount > 0)
7168 amount = cont_amount;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007169 else if (!ind_js)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007170 amount += ind_continuation;
7171 break;
7172 }
7173
7174 l = ml_get_curline();
7175
7176 /*
7177 * If we're in a comment now, skip to the start of the
7178 * comment.
7179 */
7180 trypos = find_start_comment(ind_maxcomment);
7181 if (trypos != NULL)
7182 {
7183 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007184 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007185 continue;
7186 }
7187
7188 /*
7189 * Skip preprocessor directives and blank lines.
7190 */
7191 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7192 continue;
7193
7194 if (cin_nocode(l))
7195 continue;
7196
7197 terminated = cin_isterminated(l, FALSE, TRUE);
7198
7199 /*
7200 * If we are at top level and the line looks like a
7201 * function declaration, we are done
7202 * (it's a variable declaration).
7203 */
7204 if (start_brace != BRACE_IN_COL0
Bram Moolenaarc367faa2011-12-14 20:21:35 +01007205 || !cin_isfuncdecl(&l, curwin->w_cursor.lnum,
7206 0, ind_maxparen, ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007207 {
7208 /* if the line is terminated with another ','
7209 * it is a continued variable initialization.
7210 * don't add extra indent.
7211 * TODO: does not work, if a function
7212 * declaration is split over multiple lines:
7213 * cin_isfuncdecl returns FALSE then.
7214 */
7215 if (terminated == ',')
7216 break;
7217
7218 /* if it es a enum declaration or an assignment,
7219 * we are done.
7220 */
7221 if (terminated != ';' && cin_isinit())
7222 break;
7223
7224 /* nothing useful found */
7225 if (terminated == 0 || terminated == '{')
7226 continue;
7227 }
7228
7229 if (terminated != ';')
7230 {
7231 /* Skip parens and braces. Position the cursor
7232 * over the rightmost paren, so that matching it
7233 * will take us back to the start of the line.
7234 */ /* XXX */
7235 trypos = NULL;
7236 if (find_last_paren(l, '(', ')'))
7237 trypos = find_match_paren(ind_maxparen,
7238 ind_maxcomment);
7239
7240 if (trypos == NULL && find_last_paren(l, '{', '}'))
7241 trypos = find_start_brace(ind_maxcomment);
7242
7243 if (trypos != NULL)
7244 {
7245 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007246 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007247 continue;
7248 }
7249 }
7250
7251 /* it's a variable declaration, add indentation
7252 * like in
7253 * int a,
7254 * b;
7255 */
7256 if (cont_amount > 0)
7257 amount = cont_amount;
7258 else
7259 amount += ind_continuation;
7260 }
7261 else if (lookfor == LOOKFOR_UNTERM)
7262 {
7263 if (cont_amount > 0)
7264 amount = cont_amount;
7265 else
7266 amount += ind_continuation;
7267 }
Bram Moolenaare79d1532011-10-04 18:03:47 +02007268 else
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007269 {
Bram Moolenaare79d1532011-10-04 18:03:47 +02007270 if (lookfor != LOOKFOR_TERM
Bram Moolenaar071d4272004-06-13 20:20:40 +00007271 && lookfor != LOOKFOR_CPP_BASECLASS)
Bram Moolenaare79d1532011-10-04 18:03:47 +02007272 {
7273 amount = scope_amount;
7274 if (theline[0] == '{')
7275 {
7276 amount += ind_open_extra;
7277 added_to_amount = ind_open_extra;
7278 }
7279 }
7280
7281 if (lookfor_cpp_namespace)
7282 {
7283 /*
7284 * Looking for C++ namespace, need to look further
7285 * back.
7286 */
7287 if (curwin->w_cursor.lnum == ourscope)
7288 continue;
7289
7290 if (curwin->w_cursor.lnum == 0
7291 || curwin->w_cursor.lnum
7292 < ourscope - FIND_NAMESPACE_LIM)
7293 break;
7294
7295 l = ml_get_curline();
7296
7297 /* If we're in a comment now, skip to the start of
7298 * the comment. */
7299 trypos = find_start_comment(ind_maxcomment);
7300 if (trypos != NULL)
7301 {
7302 curwin->w_cursor.lnum = trypos->lnum + 1;
7303 curwin->w_cursor.col = 0;
7304 continue;
7305 }
7306
7307 /* Skip preprocessor directives and blank lines. */
7308 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7309 continue;
7310
7311 /* Finally the actual check for "namespace". */
7312 if (cin_is_cpp_namespace(l))
7313 {
7314 amount += ind_cpp_namespace - added_to_amount;
7315 break;
7316 }
7317
7318 if (cin_nocode(l))
7319 continue;
7320 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007321 }
7322 break;
7323 }
7324
7325 /*
7326 * If we're in a comment now, skip to the start of the comment.
7327 */ /* XXX */
7328 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
7329 {
7330 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007331 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007332 continue;
7333 }
7334
7335 l = ml_get_curline();
7336
7337 /*
7338 * If this is a switch() label, may line up relative to that.
Bram Moolenaar18144c82006-04-12 21:52:12 +00007339 * If this is a C++ scope declaration, do the same.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007340 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007341 iscase = cin_iscase(l, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007342 if (iscase || cin_isscopedecl(l))
7343 {
7344 /* we are only looking for cpp base class
7345 * declaration/initialization any longer */
7346 if (lookfor == LOOKFOR_CPP_BASECLASS)
7347 break;
7348
7349 /* When looking for a "do" we are not interested in
7350 * labels. */
7351 if (whilelevel > 0)
7352 continue;
7353
7354 /*
7355 * case xx:
7356 * c = 99 + <- this indent plus continuation
7357 *-> here;
7358 */
7359 if (lookfor == LOOKFOR_UNTERM
7360 || lookfor == LOOKFOR_ENUM_OR_INIT)
7361 {
7362 if (cont_amount > 0)
7363 amount = cont_amount;
7364 else
7365 amount += ind_continuation;
7366 break;
7367 }
7368
7369 /*
7370 * case xx: <- line up with this case
7371 * x = 333;
7372 * case yy:
7373 */
7374 if ( (iscase && lookfor == LOOKFOR_CASE)
7375 || (iscase && lookfor_break)
7376 || (!iscase && lookfor == LOOKFOR_SCOPEDECL))
7377 {
7378 /*
7379 * Check that this case label is not for another
7380 * switch()
7381 */ /* XXX */
7382 if ((trypos = find_start_brace(ind_maxcomment)) ==
7383 NULL || trypos->lnum == ourscope)
7384 {
7385 amount = get_indent(); /* XXX */
7386 break;
7387 }
7388 continue;
7389 }
7390
7391 n = get_indent_nolabel(curwin->w_cursor.lnum); /* XXX */
7392
7393 /*
7394 * case xx: if (cond) <- line up with this if
7395 * y = y + 1;
7396 * -> s = 99;
7397 *
7398 * case xx:
7399 * if (cond) <- line up with this line
7400 * y = y + 1;
7401 * -> s = 99;
7402 */
7403 if (lookfor == LOOKFOR_TERM)
7404 {
7405 if (n)
7406 amount = n;
7407
7408 if (!lookfor_break)
7409 break;
7410 }
7411
7412 /*
7413 * case xx: x = x + 1; <- line up with this x
7414 * -> y = y + 1;
7415 *
7416 * case xx: if (cond) <- line up with this if
7417 * -> y = y + 1;
7418 */
7419 if (n)
7420 {
7421 amount = n;
7422 l = after_label(ml_get_curline());
7423 if (l != NULL && cin_is_cinword(l))
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007424 {
7425 if (theline[0] == '{')
7426 amount += ind_open_extra;
7427 else
7428 amount += ind_level + ind_no_brace;
7429 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007430 break;
7431 }
7432
7433 /*
7434 * Try to get the indent of a statement before the switch
7435 * label. If nothing is found, line up relative to the
7436 * switch label.
7437 * break; <- may line up with this line
7438 * case xx:
7439 * -> y = 1;
7440 */
7441 scope_amount = get_indent() + (iscase /* XXX */
7442 ? ind_case_code : ind_scopedecl_code);
7443 lookfor = ind_case_break ? LOOKFOR_NOBREAK : LOOKFOR_ANY;
7444 continue;
7445 }
7446
7447 /*
7448 * Looking for a switch() label or C++ scope declaration,
7449 * ignore other lines, skip {}-blocks.
7450 */
7451 if (lookfor == LOOKFOR_CASE || lookfor == LOOKFOR_SCOPEDECL)
7452 {
7453 if (find_last_paren(l, '{', '}') && (trypos =
7454 find_start_brace(ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007455 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007456 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007457 curwin->w_cursor.col = 0;
7458 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007459 continue;
7460 }
7461
7462 /*
7463 * Ignore jump labels with nothing after them.
7464 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007465 if (!ind_js && cin_islabel(ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007466 {
7467 l = after_label(ml_get_curline());
7468 if (l == NULL || cin_nocode(l))
7469 continue;
7470 }
7471
7472 /*
7473 * Ignore #defines, #if, etc.
7474 * Ignore comment and empty lines.
7475 * (need to get the line again, cin_islabel() may have
7476 * unlocked it)
7477 */
7478 l = ml_get_curline();
7479 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum)
7480 || cin_nocode(l))
7481 continue;
7482
7483 /*
7484 * Are we at the start of a cpp base class declaration or
7485 * constructor initialization?
7486 */ /* XXX */
Bram Moolenaar18144c82006-04-12 21:52:12 +00007487 n = FALSE;
7488 if (lookfor != LOOKFOR_TERM && ind_cpp_baseclass > 0)
7489 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00007490 n = cin_is_cpp_baseclass(&col);
Bram Moolenaar18144c82006-04-12 21:52:12 +00007491 l = ml_get_curline();
7492 }
7493 if (n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007494 {
7495 if (lookfor == LOOKFOR_UNTERM)
7496 {
7497 if (cont_amount > 0)
7498 amount = cont_amount;
7499 else
7500 amount += ind_continuation;
7501 }
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007502 else if (theline[0] == '{')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007503 {
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007504 /* Need to find start of the declaration. */
7505 lookfor = LOOKFOR_UNTERM;
7506 ind_continuation = 0;
7507 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007508 }
7509 else
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007510 /* XXX */
7511 amount = get_baseclass_amount(col, ind_maxparen,
7512 ind_maxcomment, ind_cpp_baseclass);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007513 break;
7514 }
7515 else if (lookfor == LOOKFOR_CPP_BASECLASS)
7516 {
7517 /* only look, whether there is a cpp base class
Bram Moolenaar18144c82006-04-12 21:52:12 +00007518 * declaration or initialization before the opening brace.
7519 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007520 if (cin_isterminated(l, TRUE, FALSE))
7521 break;
7522 else
7523 continue;
7524 }
7525
7526 /*
7527 * What happens next depends on the line being terminated.
7528 * If terminated with a ',' only consider it terminating if
Bram Moolenaar25394022007-05-10 19:06:20 +00007529 * there is another unterminated statement behind, eg:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007530 * 123,
7531 * sizeof
7532 * here
7533 * Otherwise check whether it is a enumeration or structure
7534 * initialisation (not indented) or a variable declaration
7535 * (indented).
7536 */
7537 terminated = cin_isterminated(l, FALSE, TRUE);
7538
7539 if (terminated == 0 || (lookfor != LOOKFOR_UNTERM
7540 && terminated == ','))
7541 {
7542 /*
7543 * if we're in the middle of a paren thing,
7544 * go back to the line that starts it so
7545 * we can get the right prevailing indent
7546 * if ( foo &&
7547 * bar )
7548 */
7549 /*
7550 * position the cursor over the rightmost paren, so that
7551 * matching it will take us back to the start of the line.
7552 */
7553 (void)find_last_paren(l, '(', ')');
7554 trypos = find_match_paren(
7555 corr_ind_maxparen(ind_maxparen, &cur_curpos),
7556 ind_maxcomment);
7557
7558 /*
7559 * If we are looking for ',', we also look for matching
7560 * braces.
7561 */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007562 if (trypos == NULL && terminated == ','
7563 && find_last_paren(l, '{', '}'))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007564 trypos = find_start_brace(ind_maxcomment);
7565
7566 if (trypos != NULL)
7567 {
7568 /*
7569 * Check if we are on a case label now. This is
7570 * handled above.
7571 * case xx: if ( asdf &&
7572 * asdf)
7573 */
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007574 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007575 l = ml_get_curline();
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007576 if (cin_iscase(l, FALSE) || cin_isscopedecl(l))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007577 {
7578 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007579 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007580 continue;
7581 }
7582 }
7583
7584 /*
7585 * Skip over continuation lines to find the one to get the
7586 * indent from
7587 * char *usethis = "bla\
7588 * bla",
7589 * here;
7590 */
7591 if (terminated == ',')
7592 {
7593 while (curwin->w_cursor.lnum > 1)
7594 {
7595 l = ml_get(curwin->w_cursor.lnum - 1);
7596 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
7597 break;
7598 --curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007599 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007600 }
7601 }
7602
7603 /*
7604 * Get indent and pointer to text for current line,
7605 * ignoring any jump label. XXX
7606 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007607 if (!ind_js)
7608 cur_amount = skip_label(curwin->w_cursor.lnum,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007609 &l, ind_maxcomment);
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007610 else
7611 cur_amount = get_indent();
Bram Moolenaar071d4272004-06-13 20:20:40 +00007612 /*
7613 * If this is just above the line we are indenting, and it
7614 * starts with a '{', line it up with this line.
7615 * while (not)
7616 * -> {
7617 * }
7618 */
7619 if (terminated != ',' && lookfor != LOOKFOR_TERM
7620 && theline[0] == '{')
7621 {
7622 amount = cur_amount;
7623 /*
7624 * Only add ind_open_extra when the current line
7625 * doesn't start with a '{', which must have a match
7626 * in the same line (scope is the same). Probably:
7627 * { 1, 2 },
7628 * -> { 3, 4 }
7629 */
7630 if (*skipwhite(l) != '{')
7631 amount += ind_open_extra;
7632
7633 if (ind_cpp_baseclass)
7634 {
7635 /* have to look back, whether it is a cpp base
7636 * class declaration or initialization */
7637 lookfor = LOOKFOR_CPP_BASECLASS;
7638 continue;
7639 }
7640 break;
7641 }
7642
7643 /*
7644 * Check if we are after an "if", "while", etc.
7645 * Also allow " } else".
7646 */
7647 if (cin_is_cinword(l) || cin_iselse(skipwhite(l)))
7648 {
7649 /*
7650 * Found an unterminated line after an if (), line up
7651 * with the last one.
7652 * if (cond)
7653 * 100 +
7654 * -> here;
7655 */
7656 if (lookfor == LOOKFOR_UNTERM
7657 || lookfor == LOOKFOR_ENUM_OR_INIT)
7658 {
7659 if (cont_amount > 0)
7660 amount = cont_amount;
7661 else
7662 amount += ind_continuation;
7663 break;
7664 }
7665
7666 /*
7667 * If this is just above the line we are indenting, we
7668 * are finished.
7669 * while (not)
7670 * -> here;
7671 * Otherwise this indent can be used when the line
7672 * before this is terminated.
7673 * yyy;
7674 * if (stat)
7675 * while (not)
7676 * xxx;
7677 * -> here;
7678 */
7679 amount = cur_amount;
7680 if (theline[0] == '{')
7681 amount += ind_open_extra;
7682 if (lookfor != LOOKFOR_TERM)
7683 {
7684 amount += ind_level + ind_no_brace;
7685 break;
7686 }
7687
7688 /*
7689 * Special trick: when expecting the while () after a
7690 * do, line up with the while()
7691 * do
7692 * x = 1;
7693 * -> here
7694 */
7695 l = skipwhite(ml_get_curline());
7696 if (cin_isdo(l))
7697 {
7698 if (whilelevel == 0)
7699 break;
7700 --whilelevel;
7701 }
7702
7703 /*
7704 * When searching for a terminated line, don't use the
Bram Moolenaar334adf02011-05-25 13:34:04 +02007705 * one between the "if" and the matching "else".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007706 * Need to use the scope of this "else". XXX
7707 * If whilelevel != 0 continue looking for a "do {".
7708 */
Bram Moolenaar334adf02011-05-25 13:34:04 +02007709 if (cin_iselse(l) && whilelevel == 0)
7710 {
7711 /* If we're looking at "} else", let's make sure we
7712 * find the opening brace of the enclosing scope,
7713 * not the one from "if () {". */
7714 if (*l == '}')
7715 curwin->w_cursor.col =
Bram Moolenaar9b83c2f2011-05-25 17:29:44 +02007716 (colnr_T)(l - ml_get_curline()) + 1;
Bram Moolenaar334adf02011-05-25 13:34:04 +02007717
7718 if ((trypos = find_start_brace(ind_maxcomment))
7719 == NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007720 || find_match(LOOKFOR_IF, trypos->lnum,
Bram Moolenaar334adf02011-05-25 13:34:04 +02007721 ind_maxparen, ind_maxcomment) == FAIL)
7722 break;
7723 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007724 }
7725
7726 /*
7727 * If we're below an unterminated line that is not an
7728 * "if" or something, we may line up with this line or
Bram Moolenaar25394022007-05-10 19:06:20 +00007729 * add something for a continuation line, depending on
Bram Moolenaar071d4272004-06-13 20:20:40 +00007730 * the line before this one.
7731 */
7732 else
7733 {
7734 /*
7735 * Found two unterminated lines on a row, line up with
7736 * the last one.
7737 * c = 99 +
7738 * 100 +
7739 * -> here;
7740 */
7741 if (lookfor == LOOKFOR_UNTERM)
7742 {
7743 /* When line ends in a comma add extra indent */
7744 if (terminated == ',')
7745 amount += ind_continuation;
7746 break;
7747 }
7748
7749 if (lookfor == LOOKFOR_ENUM_OR_INIT)
7750 {
7751 /* Found two lines ending in ',', lineup with the
7752 * lowest one, but check for cpp base class
7753 * declaration/initialization, if it is an
7754 * opening brace or we are looking just for
7755 * enumerations/initializations. */
7756 if (terminated == ',')
7757 {
7758 if (ind_cpp_baseclass == 0)
7759 break;
7760
7761 lookfor = LOOKFOR_CPP_BASECLASS;
7762 continue;
7763 }
7764
7765 /* Ignore unterminated lines in between, but
7766 * reduce indent. */
7767 if (amount > cur_amount)
7768 amount = cur_amount;
7769 }
7770 else
7771 {
7772 /*
7773 * Found first unterminated line on a row, may
7774 * line up with this line, remember its indent
7775 * 100 +
7776 * -> here;
7777 */
7778 amount = cur_amount;
7779
7780 /*
7781 * If previous line ends in ',', check whether we
7782 * are in an initialization or enum
7783 * struct xxx =
7784 * {
7785 * sizeof a,
7786 * 124 };
7787 * or a normal possible continuation line.
7788 * but only, of no other statement has been found
7789 * yet.
7790 */
7791 if (lookfor == LOOKFOR_INITIAL && terminated == ',')
7792 {
7793 lookfor = LOOKFOR_ENUM_OR_INIT;
7794 cont_amount = cin_first_id_amount();
7795 }
7796 else
7797 {
7798 if (lookfor == LOOKFOR_INITIAL
7799 && *l != NUL
7800 && l[STRLEN(l) - 1] == '\\')
7801 /* XXX */
7802 cont_amount = cin_get_equal_amount(
7803 curwin->w_cursor.lnum);
7804 if (lookfor != LOOKFOR_TERM)
7805 lookfor = LOOKFOR_UNTERM;
7806 }
7807 }
7808 }
7809 }
7810
7811 /*
7812 * Check if we are after a while (cond);
7813 * If so: Ignore until the matching "do".
7814 */
7815 /* XXX */
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007816 else if (cin_iswhileofdo_end(terminated, ind_maxparen,
7817 ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007818 {
7819 /*
7820 * Found an unterminated line after a while ();, line up
7821 * with the last one.
7822 * while (cond);
7823 * 100 + <- line up with this one
7824 * -> here;
7825 */
7826 if (lookfor == LOOKFOR_UNTERM
7827 || lookfor == LOOKFOR_ENUM_OR_INIT)
7828 {
7829 if (cont_amount > 0)
7830 amount = cont_amount;
7831 else
7832 amount += ind_continuation;
7833 break;
7834 }
7835
7836 if (whilelevel == 0)
7837 {
7838 lookfor = LOOKFOR_TERM;
7839 amount = get_indent(); /* XXX */
7840 if (theline[0] == '{')
7841 amount += ind_open_extra;
7842 }
7843 ++whilelevel;
7844 }
7845
7846 /*
7847 * We are after a "normal" statement.
7848 * If we had another statement we can stop now and use the
7849 * indent of that other statement.
7850 * Otherwise the indent of the current statement may be used,
7851 * search backwards for the next "normal" statement.
7852 */
7853 else
7854 {
7855 /*
7856 * Skip single break line, if before a switch label. It
7857 * may be lined up with the case label.
7858 */
7859 if (lookfor == LOOKFOR_NOBREAK
7860 && cin_isbreak(skipwhite(ml_get_curline())))
7861 {
7862 lookfor = LOOKFOR_ANY;
7863 continue;
7864 }
7865
7866 /*
7867 * Handle "do {" line.
7868 */
7869 if (whilelevel > 0)
7870 {
7871 l = cin_skipcomment(ml_get_curline());
7872 if (cin_isdo(l))
7873 {
7874 amount = get_indent(); /* XXX */
7875 --whilelevel;
7876 continue;
7877 }
7878 }
7879
7880 /*
7881 * Found a terminated line above an unterminated line. Add
7882 * the amount for a continuation line.
7883 * x = 1;
7884 * y = foo +
7885 * -> here;
7886 * or
7887 * int x = 1;
7888 * int foo,
7889 * -> here;
7890 */
7891 if (lookfor == LOOKFOR_UNTERM
7892 || lookfor == LOOKFOR_ENUM_OR_INIT)
7893 {
7894 if (cont_amount > 0)
7895 amount = cont_amount;
7896 else
7897 amount += ind_continuation;
7898 break;
7899 }
7900
7901 /*
7902 * Found a terminated line above a terminated line or "if"
7903 * etc. line. Use the amount of the line below us.
7904 * x = 1; x = 1;
7905 * if (asdf) y = 2;
7906 * while (asdf) ->here;
7907 * here;
7908 * ->foo;
7909 */
7910 if (lookfor == LOOKFOR_TERM)
7911 {
7912 if (!lookfor_break && whilelevel == 0)
7913 break;
7914 }
7915
7916 /*
7917 * First line above the one we're indenting is terminated.
7918 * To know what needs to be done look further backward for
7919 * a terminated line.
7920 */
7921 else
7922 {
7923 /*
7924 * position the cursor over the rightmost paren, so
7925 * that matching it will take us back to the start of
7926 * the line. Helps for:
7927 * func(asdr,
7928 * asdfasdf);
7929 * here;
7930 */
7931term_again:
7932 l = ml_get_curline();
7933 if (find_last_paren(l, '(', ')')
7934 && (trypos = find_match_paren(ind_maxparen,
7935 ind_maxcomment)) != NULL)
7936 {
7937 /*
7938 * Check if we are on a case label now. This is
7939 * handled above.
7940 * case xx: if ( asdf &&
7941 * asdf)
7942 */
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007943 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007944 l = ml_get_curline();
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007945 if (cin_iscase(l, FALSE) || cin_isscopedecl(l))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007946 {
7947 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007948 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007949 continue;
7950 }
7951 }
7952
7953 /* When aligning with the case statement, don't align
7954 * with a statement after it.
7955 * case 1: { <-- don't use this { position
7956 * stat;
7957 * }
7958 * case 2:
7959 * stat;
7960 * }
7961 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007962 iscase = (ind_keep_case_label && cin_iscase(l, FALSE));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007963
7964 /*
7965 * Get indent and pointer to text for current line,
7966 * ignoring any jump label.
7967 */
7968 amount = skip_label(curwin->w_cursor.lnum,
7969 &l, ind_maxcomment);
7970
7971 if (theline[0] == '{')
7972 amount += ind_open_extra;
7973 /* See remark above: "Only add ind_open_extra.." */
Bram Moolenaar18144c82006-04-12 21:52:12 +00007974 l = skipwhite(l);
7975 if (*l == '{')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007976 amount -= ind_open_extra;
7977 lookfor = iscase ? LOOKFOR_ANY : LOOKFOR_TERM;
7978
7979 /*
Bram Moolenaar18144c82006-04-12 21:52:12 +00007980 * When a terminated line starts with "else" skip to
7981 * the matching "if":
7982 * else 3;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00007983 * indent this;
Bram Moolenaar18144c82006-04-12 21:52:12 +00007984 * Need to use the scope of this "else". XXX
7985 * If whilelevel != 0 continue looking for a "do {".
7986 */
7987 if (lookfor == LOOKFOR_TERM
7988 && *l != '}'
7989 && cin_iselse(l)
7990 && whilelevel == 0)
7991 {
7992 if ((trypos = find_start_brace(ind_maxcomment))
7993 == NULL
7994 || find_match(LOOKFOR_IF, trypos->lnum,
7995 ind_maxparen, ind_maxcomment) == FAIL)
7996 break;
7997 continue;
7998 }
7999
8000 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008001 * If we're at the end of a block, skip to the start of
8002 * that block.
8003 */
Bram Moolenaar6d8f9c62011-11-30 13:03:28 +01008004 l = ml_get_curline();
Bram Moolenaar50f42ca2011-07-15 14:12:30 +02008005 if (find_last_paren(l, '{', '}')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008006 && (trypos = find_start_brace(ind_maxcomment))
8007 != NULL) /* XXX */
8008 {
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008009 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008010 /* if not "else {" check for terminated again */
8011 /* but skip block for "} else {" */
8012 l = cin_skipcomment(ml_get_curline());
8013 if (*l == '}' || !cin_iselse(l))
8014 goto term_again;
8015 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008016 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008017 }
8018 }
8019 }
8020 }
8021 }
8022 }
8023
8024 /* add extra indent for a comment */
8025 if (cin_iscomment(theline))
8026 amount += ind_comment;
Bram Moolenaar02c707a2010-07-17 17:12:06 +02008027
8028 /* subtract extra left-shift for jump labels */
8029 if (ind_jump_label > 0 && original_line_islabel)
8030 amount -= ind_jump_label;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008031 }
8032
8033 /*
8034 * ok -- we're not inside any sort of structure at all!
8035 *
8036 * this means we're at the top level, and everything should
8037 * basically just match where the previous line is, except
8038 * for the lines immediately following a function declaration,
8039 * which are K&R-style parameters and need to be indented.
8040 */
8041 else
8042 {
8043 /*
8044 * if our line starts with an open brace, forget about any
8045 * prevailing indent and make sure it looks like the start
8046 * of a function
8047 */
8048
8049 if (theline[0] == '{')
8050 {
8051 amount = ind_first_open;
8052 }
8053
8054 /*
8055 * If the NEXT line is a function declaration, the current
8056 * line needs to be indented as a function type spec.
Bram Moolenaar1a89bbe2010-03-02 12:38:22 +01008057 * Don't do this if the current line looks like a comment or if the
8058 * current line is terminated, ie. ends in ';', or if the current line
8059 * contains { or }: "void f() {\n if (1)"
Bram Moolenaar071d4272004-06-13 20:20:40 +00008060 */
8061 else if (cur_curpos.lnum < curbuf->b_ml.ml_line_count
8062 && !cin_nocode(theline)
Bram Moolenaar1a89bbe2010-03-02 12:38:22 +01008063 && vim_strchr(theline, '{') == NULL
8064 && vim_strchr(theline, '}') == NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00008065 && !cin_ends_in(theline, (char_u *)":", NULL)
8066 && !cin_ends_in(theline, (char_u *)",", NULL)
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008067 && cin_isfuncdecl(NULL, cur_curpos.lnum + 1,
8068 cur_curpos.lnum + 1,
8069 ind_maxparen, ind_maxcomment)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008070 && !cin_isterminated(theline, FALSE, TRUE))
8071 {
8072 amount = ind_func_type;
8073 }
8074 else
8075 {
8076 amount = 0;
8077 curwin->w_cursor = cur_curpos;
8078
8079 /* search backwards until we find something we recognize */
8080
8081 while (curwin->w_cursor.lnum > 1)
8082 {
8083 curwin->w_cursor.lnum--;
8084 curwin->w_cursor.col = 0;
8085
8086 l = ml_get_curline();
8087
8088 /*
8089 * If we're in a comment now, skip to the start of the comment.
8090 */ /* XXX */
8091 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
8092 {
8093 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008094 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008095 continue;
8096 }
8097
8098 /*
Bram Moolenaar18144c82006-04-12 21:52:12 +00008099 * Are we at the start of a cpp base class declaration or
8100 * constructor initialization?
Bram Moolenaar071d4272004-06-13 20:20:40 +00008101 */ /* XXX */
Bram Moolenaar18144c82006-04-12 21:52:12 +00008102 n = FALSE;
8103 if (ind_cpp_baseclass != 0 && theline[0] != '{')
8104 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00008105 n = cin_is_cpp_baseclass(&col);
Bram Moolenaar18144c82006-04-12 21:52:12 +00008106 l = ml_get_curline();
8107 }
8108 if (n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008109 {
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00008110 /* XXX */
8111 amount = get_baseclass_amount(col, ind_maxparen,
8112 ind_maxcomment, ind_cpp_baseclass);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008113 break;
8114 }
8115
8116 /*
8117 * Skip preprocessor directives and blank lines.
8118 */
8119 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
8120 continue;
8121
8122 if (cin_nocode(l))
8123 continue;
8124
8125 /*
8126 * If the previous line ends in ',', use one level of
8127 * indentation:
8128 * int foo,
8129 * bar;
8130 * do this before checking for '}' in case of eg.
8131 * enum foobar
8132 * {
8133 * ...
8134 * } foo,
8135 * bar;
8136 */
8137 n = 0;
8138 if (cin_ends_in(l, (char_u *)",", NULL)
8139 || (*l != NUL && (n = l[STRLEN(l) - 1]) == '\\'))
8140 {
8141 /* take us back to opening paren */
8142 if (find_last_paren(l, '(', ')')
8143 && (trypos = find_match_paren(ind_maxparen,
8144 ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008145 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008146
8147 /* For a line ending in ',' that is a continuation line go
8148 * back to the first line with a backslash:
8149 * char *foo = "bla\
8150 * bla",
8151 * here;
8152 */
8153 while (n == 0 && curwin->w_cursor.lnum > 1)
8154 {
8155 l = ml_get(curwin->w_cursor.lnum - 1);
8156 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
8157 break;
8158 --curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008159 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008160 }
8161
8162 amount = get_indent(); /* XXX */
8163
8164 if (amount == 0)
8165 amount = cin_first_id_amount();
8166 if (amount == 0)
8167 amount = ind_continuation;
8168 break;
8169 }
8170
8171 /*
8172 * If the line looks like a function declaration, and we're
8173 * not in a comment, put it the left margin.
8174 */
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008175 if (cin_isfuncdecl(NULL, cur_curpos.lnum, 0,
8176 ind_maxparen, ind_maxcomment)) /* XXX */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008177 break;
8178 l = ml_get_curline();
8179
8180 /*
8181 * Finding the closing '}' of a previous function. Put
8182 * current line at the left margin. For when 'cino' has "fs".
8183 */
8184 if (*skipwhite(l) == '}')
8185 break;
8186
8187 /* (matching {)
8188 * If the previous line ends on '};' (maybe followed by
8189 * comments) align at column 0. For example:
8190 * char *string_array[] = { "foo",
8191 * / * x * / "b};ar" }; / * foobar * /
8192 */
8193 if (cin_ends_in(l, (char_u *)"};", NULL))
8194 break;
8195
8196 /*
Bram Moolenaar3388bb42011-11-30 17:20:23 +01008197 * Find a line only has a semicolon that belongs to a previous
8198 * line ending in '}', e.g. before an #endif. Don't increase
8199 * indent then.
8200 */
8201 if (*(look = skipwhite(l)) == ';' && cin_nocode(look + 1))
8202 {
8203 pos_T curpos_save = curwin->w_cursor;
8204
8205 while (curwin->w_cursor.lnum > 1)
8206 {
8207 look = ml_get(--curwin->w_cursor.lnum);
8208 if (!(cin_nocode(look) || cin_ispreproc_cont(
8209 &look, &curwin->w_cursor.lnum)))
8210 break;
8211 }
8212 if (curwin->w_cursor.lnum > 0
8213 && cin_ends_in(look, (char_u *)"}", NULL))
8214 break;
8215
8216 curwin->w_cursor = curpos_save;
8217 }
8218
8219 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008220 * If the PREVIOUS line is a function declaration, the current
8221 * line (and the ones that follow) needs to be indented as
8222 * parameters.
8223 */
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008224 if (cin_isfuncdecl(&l, curwin->w_cursor.lnum, 0,
8225 ind_maxparen, ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008226 {
8227 amount = ind_param;
8228 break;
8229 }
8230
8231 /*
8232 * If the previous line ends in ';' and the line before the
8233 * previous line ends in ',' or '\', ident to column zero:
8234 * int foo,
8235 * bar;
8236 * indent_to_0 here;
8237 */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00008238 if (cin_ends_in(l, (char_u *)";", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008239 {
8240 l = ml_get(curwin->w_cursor.lnum - 1);
8241 if (cin_ends_in(l, (char_u *)",", NULL)
8242 || (*l != NUL && l[STRLEN(l) - 1] == '\\'))
8243 break;
8244 l = ml_get_curline();
8245 }
8246
8247 /*
8248 * Doesn't look like anything interesting -- so just
8249 * use the indent of this line.
8250 *
8251 * Position the cursor over the rightmost paren, so that
8252 * matching it will take us back to the start of the line.
8253 */
8254 find_last_paren(l, '(', ')');
8255
8256 if ((trypos = find_match_paren(ind_maxparen,
8257 ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008258 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008259 amount = get_indent(); /* XXX */
8260 break;
8261 }
8262
8263 /* add extra indent for a comment */
8264 if (cin_iscomment(theline))
8265 amount += ind_comment;
8266
8267 /* add extra indent if the previous line ended in a backslash:
8268 * "asdfasdf\
8269 * here";
8270 * char *foo = "asdf\
8271 * here";
8272 */
8273 if (cur_curpos.lnum > 1)
8274 {
8275 l = ml_get(cur_curpos.lnum - 1);
8276 if (*l != NUL && l[STRLEN(l) - 1] == '\\')
8277 {
8278 cur_amount = cin_get_equal_amount(cur_curpos.lnum - 1);
8279 if (cur_amount > 0)
8280 amount = cur_amount;
8281 else if (cur_amount == 0)
8282 amount += ind_continuation;
8283 }
8284 }
8285 }
8286 }
8287
8288theend:
8289 /* put the cursor back where it belongs */
8290 curwin->w_cursor = cur_curpos;
8291
8292 vim_free(linecopy);
8293
8294 if (amount < 0)
8295 return 0;
8296 return amount;
8297}
8298
8299 static int
8300find_match(lookfor, ourscope, ind_maxparen, ind_maxcomment)
8301 int lookfor;
8302 linenr_T ourscope;
8303 int ind_maxparen;
8304 int ind_maxcomment;
8305{
8306 char_u *look;
8307 pos_T *theirscope;
8308 char_u *mightbeif;
8309 int elselevel;
8310 int whilelevel;
8311
8312 if (lookfor == LOOKFOR_IF)
8313 {
8314 elselevel = 1;
8315 whilelevel = 0;
8316 }
8317 else
8318 {
8319 elselevel = 0;
8320 whilelevel = 1;
8321 }
8322
8323 curwin->w_cursor.col = 0;
8324
8325 while (curwin->w_cursor.lnum > ourscope + 1)
8326 {
8327 curwin->w_cursor.lnum--;
8328 curwin->w_cursor.col = 0;
8329
8330 look = cin_skipcomment(ml_get_curline());
8331 if (cin_iselse(look)
8332 || cin_isif(look)
8333 || cin_isdo(look) /* XXX */
8334 || cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
8335 {
8336 /*
8337 * if we've gone outside the braces entirely,
8338 * we must be out of scope...
8339 */
8340 theirscope = find_start_brace(ind_maxcomment); /* XXX */
8341 if (theirscope == NULL)
8342 break;
8343
8344 /*
8345 * and if the brace enclosing this is further
8346 * back than the one enclosing the else, we're
8347 * out of luck too.
8348 */
8349 if (theirscope->lnum < ourscope)
8350 break;
8351
8352 /*
8353 * and if they're enclosed in a *deeper* brace,
8354 * then we can ignore it because it's in a
8355 * different scope...
8356 */
8357 if (theirscope->lnum > ourscope)
8358 continue;
8359
8360 /*
8361 * if it was an "else" (that's not an "else if")
8362 * then we need to go back to another if, so
8363 * increment elselevel
8364 */
8365 look = cin_skipcomment(ml_get_curline());
8366 if (cin_iselse(look))
8367 {
8368 mightbeif = cin_skipcomment(look + 4);
8369 if (!cin_isif(mightbeif))
8370 ++elselevel;
8371 continue;
8372 }
8373
8374 /*
8375 * if it was a "while" then we need to go back to
8376 * another "do", so increment whilelevel. XXX
8377 */
8378 if (cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
8379 {
8380 ++whilelevel;
8381 continue;
8382 }
8383
8384 /* If it's an "if" decrement elselevel */
8385 look = cin_skipcomment(ml_get_curline());
8386 if (cin_isif(look))
8387 {
8388 elselevel--;
8389 /*
8390 * When looking for an "if" ignore "while"s that
8391 * get in the way.
8392 */
8393 if (elselevel == 0 && lookfor == LOOKFOR_IF)
8394 whilelevel = 0;
8395 }
8396
8397 /* If it's a "do" decrement whilelevel */
8398 if (cin_isdo(look))
8399 whilelevel--;
8400
8401 /*
8402 * if we've used up all the elses, then
8403 * this must be the if that we want!
8404 * match the indent level of that if.
8405 */
8406 if (elselevel <= 0 && whilelevel <= 0)
8407 {
8408 return OK;
8409 }
8410 }
8411 }
8412 return FAIL;
8413}
8414
8415# if defined(FEAT_EVAL) || defined(PROTO)
8416/*
8417 * Get indent level from 'indentexpr'.
8418 */
8419 int
8420get_expr_indent()
8421{
8422 int indent;
8423 pos_T pos;
8424 int save_State;
Bram Moolenaard1f56e62006-02-22 21:25:37 +00008425 int use_sandbox = was_set_insecurely((char_u *)"indentexpr",
8426 OPT_LOCAL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008427
8428 pos = curwin->w_cursor;
8429 set_vim_var_nr(VV_LNUM, curwin->w_cursor.lnum);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00008430 if (use_sandbox)
8431 ++sandbox;
8432 ++textlock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008433 indent = eval_to_number(curbuf->b_p_inde);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00008434 if (use_sandbox)
8435 --sandbox;
8436 --textlock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008437
8438 /* Restore the cursor position so that 'indentexpr' doesn't need to.
8439 * Pretend to be in Insert mode, allow cursor past end of line for "o"
8440 * command. */
8441 save_State = State;
8442 State = INSERT;
8443 curwin->w_cursor = pos;
8444 check_cursor();
8445 State = save_State;
8446
8447 /* If there is an error, just keep the current indent. */
8448 if (indent < 0)
8449 indent = get_indent();
8450
8451 return indent;
8452}
8453# endif
8454
8455#endif /* FEAT_CINDENT */
8456
8457#if defined(FEAT_LISP) || defined(PROTO)
8458
8459static int lisp_match __ARGS((char_u *p));
8460
8461 static int
8462lisp_match(p)
8463 char_u *p;
8464{
8465 char_u buf[LSIZE];
8466 int len;
8467 char_u *word = p_lispwords;
8468
8469 while (*word != NUL)
8470 {
8471 (void)copy_option_part(&word, buf, LSIZE, ",");
8472 len = (int)STRLEN(buf);
8473 if (STRNCMP(buf, p, len) == 0 && p[len] == ' ')
8474 return TRUE;
8475 }
8476 return FALSE;
8477}
8478
8479/*
8480 * When 'p' is present in 'cpoptions, a Vi compatible method is used.
8481 * The incompatible newer method is quite a bit better at indenting
8482 * code in lisp-like languages than the traditional one; it's still
8483 * mostly heuristics however -- Dirk van Deun, dirk@rave.org
8484 *
8485 * TODO:
8486 * Findmatch() should be adapted for lisp, also to make showmatch
8487 * work correctly: now (v5.3) it seems all C/C++ oriented:
8488 * - it does not recognize the #\( and #\) notations as character literals
8489 * - it doesn't know about comments starting with a semicolon
8490 * - it incorrectly interprets '(' as a character literal
8491 * All this messes up get_lisp_indent in some rare cases.
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008492 * Update from Sergey Khorev:
8493 * I tried to fix the first two issues.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008494 */
8495 int
8496get_lisp_indent()
8497{
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008498 pos_T *pos, realpos, paren;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008499 int amount;
8500 char_u *that;
8501 colnr_T col;
8502 colnr_T firsttry;
8503 int parencount, quotecount;
8504 int vi_lisp;
8505
8506 /* Set vi_lisp to use the vi-compatible method */
8507 vi_lisp = (vim_strchr(p_cpo, CPO_LISP) != NULL);
8508
8509 realpos = curwin->w_cursor;
8510 curwin->w_cursor.col = 0;
8511
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008512 if ((pos = findmatch(NULL, '(')) == NULL)
8513 pos = findmatch(NULL, '[');
8514 else
8515 {
8516 paren = *pos;
8517 pos = findmatch(NULL, '[');
8518 if (pos == NULL || ltp(pos, &paren))
8519 pos = &paren;
8520 }
8521 if (pos != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008522 {
8523 /* Extra trick: Take the indent of the first previous non-white
8524 * line that is at the same () level. */
8525 amount = -1;
8526 parencount = 0;
8527
8528 while (--curwin->w_cursor.lnum >= pos->lnum)
8529 {
8530 if (linewhite(curwin->w_cursor.lnum))
8531 continue;
8532 for (that = ml_get_curline(); *that != NUL; ++that)
8533 {
8534 if (*that == ';')
8535 {
8536 while (*(that + 1) != NUL)
8537 ++that;
8538 continue;
8539 }
8540 if (*that == '\\')
8541 {
8542 if (*(that + 1) != NUL)
8543 ++that;
8544 continue;
8545 }
8546 if (*that == '"' && *(that + 1) != NUL)
8547 {
Bram Moolenaar15ff6c12006-09-15 18:18:09 +00008548 while (*++that && *that != '"')
8549 {
8550 /* skipping escaped characters in the string */
8551 if (*that == '\\')
8552 {
8553 if (*++that == NUL)
8554 break;
8555 if (that[1] == NUL)
8556 {
8557 ++that;
8558 break;
8559 }
8560 }
8561 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008562 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008563 if (*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008564 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008565 else if (*that == ')' || *that == ']')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008566 --parencount;
8567 }
8568 if (parencount == 0)
8569 {
8570 amount = get_indent();
8571 break;
8572 }
8573 }
8574
8575 if (amount == -1)
8576 {
8577 curwin->w_cursor.lnum = pos->lnum;
8578 curwin->w_cursor.col = pos->col;
8579 col = pos->col;
8580
8581 that = ml_get_curline();
8582
8583 if (vi_lisp && get_indent() == 0)
8584 amount = 2;
8585 else
8586 {
8587 amount = 0;
8588 while (*that && col)
8589 {
8590 amount += lbr_chartabsize_adv(&that, (colnr_T)amount);
8591 col--;
8592 }
8593
8594 /*
8595 * Some keywords require "body" indenting rules (the
8596 * non-standard-lisp ones are Scheme special forms):
8597 *
8598 * (let ((a 1)) instead (let ((a 1))
8599 * (...)) of (...))
8600 */
8601
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008602 if (!vi_lisp && (*that == '(' || *that == '[')
8603 && lisp_match(that + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008604 amount += 2;
8605 else
8606 {
8607 that++;
8608 amount++;
8609 firsttry = amount;
8610
8611 while (vim_iswhite(*that))
8612 {
8613 amount += lbr_chartabsize(that, (colnr_T)amount);
8614 ++that;
8615 }
8616
8617 if (*that && *that != ';') /* not a comment line */
8618 {
Bram Moolenaare21877a2008-02-13 09:58:14 +00008619 /* test *that != '(' to accommodate first let/do
Bram Moolenaar071d4272004-06-13 20:20:40 +00008620 * argument if it is more than one line */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008621 if (!vi_lisp && *that != '(' && *that != '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008622 firsttry++;
8623
8624 parencount = 0;
8625 quotecount = 0;
8626
8627 if (vi_lisp
8628 || (*that != '"'
8629 && *that != '\''
8630 && *that != '#'
8631 && (*that < '0' || *that > '9')))
8632 {
8633 while (*that
8634 && (!vim_iswhite(*that)
8635 || quotecount
8636 || parencount)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008637 && (!((*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008638 && !quotecount
8639 && !parencount
8640 && vi_lisp)))
8641 {
8642 if (*that == '"')
8643 quotecount = !quotecount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008644 if ((*that == '(' || *that == '[')
8645 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008646 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008647 if ((*that == ')' || *that == ']')
8648 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008649 --parencount;
8650 if (*that == '\\' && *(that+1) != NUL)
8651 amount += lbr_chartabsize_adv(&that,
8652 (colnr_T)amount);
8653 amount += lbr_chartabsize_adv(&that,
8654 (colnr_T)amount);
8655 }
8656 }
8657 while (vim_iswhite(*that))
8658 {
8659 amount += lbr_chartabsize(that, (colnr_T)amount);
8660 that++;
8661 }
8662 if (!*that || *that == ';')
8663 amount = firsttry;
8664 }
8665 }
8666 }
8667 }
8668 }
8669 else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008670 amount = 0; /* no matching '(' or '[' found, use zero indent */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008671
8672 curwin->w_cursor = realpos;
8673
8674 return amount;
8675}
8676#endif /* FEAT_LISP */
8677
8678 void
8679prepare_to_exit()
8680{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00008681#if defined(SIGHUP) && defined(SIG_IGN)
8682 /* Ignore SIGHUP, because a dropped connection causes a read error, which
8683 * makes Vim exit and then handling SIGHUP causes various reentrance
8684 * problems. */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00008685 signal(SIGHUP, SIG_IGN);
8686#endif
8687
Bram Moolenaar071d4272004-06-13 20:20:40 +00008688#ifdef FEAT_GUI
8689 if (gui.in_use)
8690 {
8691 gui.dying = TRUE;
8692 out_trash(); /* trash any pending output */
8693 }
8694 else
8695#endif
8696 {
8697 windgoto((int)Rows - 1, 0);
8698
8699 /*
8700 * Switch terminal mode back now, so messages end up on the "normal"
8701 * screen (if there are two screens).
8702 */
8703 settmode(TMODE_COOK);
8704#ifdef WIN3264
8705 if (can_end_termcap_mode(FALSE) == TRUE)
8706#endif
8707 stoptermcap();
8708 out_flush();
8709 }
8710}
8711
8712/*
8713 * Preserve files and exit.
8714 * When called IObuff must contain a message.
8715 */
8716 void
8717preserve_exit()
8718{
8719 buf_T *buf;
8720
8721 prepare_to_exit();
8722
Bram Moolenaar4770d092006-01-12 23:22:24 +00008723 /* Setting this will prevent free() calls. That avoids calling free()
8724 * recursively when free() was invoked with a bad pointer. */
8725 really_exiting = TRUE;
8726
Bram Moolenaar071d4272004-06-13 20:20:40 +00008727 out_str(IObuff);
8728 screen_start(); /* don't know where cursor is now */
8729 out_flush();
8730
8731 ml_close_notmod(); /* close all not-modified buffers */
8732
8733 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8734 {
8735 if (buf->b_ml.ml_mfp != NULL && buf->b_ml.ml_mfp->mf_fname != NULL)
8736 {
8737 OUT_STR(_("Vim: preserving files...\n"));
8738 screen_start(); /* don't know where cursor is now */
8739 out_flush();
8740 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
8741 break;
8742 }
8743 }
8744
8745 ml_close_all(FALSE); /* close all memfiles, without deleting */
8746
8747 OUT_STR(_("Vim: Finished.\n"));
8748
8749 getout(1);
8750}
8751
8752/*
8753 * return TRUE if "fname" exists.
8754 */
8755 int
8756vim_fexists(fname)
8757 char_u *fname;
8758{
8759 struct stat st;
8760
8761 if (mch_stat((char *)fname, &st))
8762 return FALSE;
8763 return TRUE;
8764}
8765
8766/*
8767 * Check for CTRL-C pressed, but only once in a while.
8768 * Should be used instead of ui_breakcheck() for functions that check for
8769 * each line in the file. Calling ui_breakcheck() each time takes too much
8770 * time, because it can be a system call.
8771 */
8772
8773#ifndef BREAKCHECK_SKIP
8774# ifdef FEAT_GUI /* assume the GUI only runs on fast computers */
8775# define BREAKCHECK_SKIP 200
8776# else
8777# define BREAKCHECK_SKIP 32
8778# endif
8779#endif
8780
8781static int breakcheck_count = 0;
8782
8783 void
8784line_breakcheck()
8785{
8786 if (++breakcheck_count >= BREAKCHECK_SKIP)
8787 {
8788 breakcheck_count = 0;
8789 ui_breakcheck();
8790 }
8791}
8792
8793/*
8794 * Like line_breakcheck() but check 10 times less often.
8795 */
8796 void
8797fast_breakcheck()
8798{
8799 if (++breakcheck_count >= BREAKCHECK_SKIP * 10)
8800 {
8801 breakcheck_count = 0;
8802 ui_breakcheck();
8803 }
8804}
8805
8806/*
Bram Moolenaard7834d32009-12-02 16:14:36 +00008807 * Invoke expand_wildcards() for one pattern.
8808 * Expand items like "%:h" before the expansion.
8809 * Returns OK or FAIL.
8810 */
8811 int
8812expand_wildcards_eval(pat, num_file, file, flags)
8813 char_u **pat; /* pointer to input pattern */
8814 int *num_file; /* resulting number of files */
8815 char_u ***file; /* array of resulting files */
8816 int flags; /* EW_DIR, etc. */
8817{
8818 int ret = FAIL;
8819 char_u *eval_pat = NULL;
8820 char_u *exp_pat = *pat;
8821 char_u *ignored_msg;
8822 int usedlen;
8823
8824 if (*exp_pat == '%' || *exp_pat == '#' || *exp_pat == '<')
8825 {
8826 ++emsg_off;
8827 eval_pat = eval_vars(exp_pat, exp_pat, &usedlen,
8828 NULL, &ignored_msg, NULL);
8829 --emsg_off;
8830 if (eval_pat != NULL)
8831 exp_pat = concat_str(eval_pat, exp_pat + usedlen);
8832 }
8833
8834 if (exp_pat != NULL)
8835 ret = expand_wildcards(1, &exp_pat, num_file, file, flags);
8836
8837 if (eval_pat != NULL)
8838 {
8839 vim_free(exp_pat);
8840 vim_free(eval_pat);
8841 }
8842
8843 return ret;
8844}
8845
8846/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008847 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching
8848 * 'wildignore'.
Bram Moolenaar9e193ac2010-07-19 23:11:27 +02008849 * Returns OK or FAIL. When FAIL then "num_file" won't be set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008850 */
8851 int
8852expand_wildcards(num_pat, pat, num_file, file, flags)
8853 int num_pat; /* number of input patterns */
8854 char_u **pat; /* array of input patterns */
8855 int *num_file; /* resulting number of files */
8856 char_u ***file; /* array of resulting files */
8857 int flags; /* EW_DIR, etc. */
8858{
8859 int retval;
8860 int i, j;
8861 char_u *p;
8862 int non_suf_match; /* number without matching suffix */
8863
8864 retval = gen_expand_wildcards(num_pat, pat, num_file, file, flags);
8865
8866 /* When keeping all matches, return here */
Bram Moolenaar9e193ac2010-07-19 23:11:27 +02008867 if ((flags & EW_KEEPALL) || retval == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008868 return retval;
8869
8870#ifdef FEAT_WILDIGN
8871 /*
8872 * Remove names that match 'wildignore'.
8873 */
8874 if (*p_wig)
8875 {
8876 char_u *ffname;
8877
8878 /* check all files in (*file)[] */
8879 for (i = 0; i < *num_file; ++i)
8880 {
8881 ffname = FullName_save((*file)[i], FALSE);
8882 if (ffname == NULL) /* out of memory */
8883 break;
8884# ifdef VMS
8885 vms_remove_version(ffname);
8886# endif
8887 if (match_file_list(p_wig, (*file)[i], ffname))
8888 {
8889 /* remove this matching file from the list */
8890 vim_free((*file)[i]);
8891 for (j = i; j + 1 < *num_file; ++j)
8892 (*file)[j] = (*file)[j + 1];
8893 --*num_file;
8894 --i;
8895 }
8896 vim_free(ffname);
8897 }
8898 }
8899#endif
8900
8901 /*
8902 * Move the names where 'suffixes' match to the end.
8903 */
8904 if (*num_file > 1)
8905 {
8906 non_suf_match = 0;
8907 for (i = 0; i < *num_file; ++i)
8908 {
8909 if (!match_suffix((*file)[i]))
8910 {
8911 /*
8912 * Move the name without matching suffix to the front
8913 * of the list.
8914 */
8915 p = (*file)[i];
8916 for (j = i; j > non_suf_match; --j)
8917 (*file)[j] = (*file)[j - 1];
8918 (*file)[non_suf_match++] = p;
8919 }
8920 }
8921 }
8922
8923 return retval;
8924}
8925
8926/*
8927 * Return TRUE if "fname" matches with an entry in 'suffixes'.
8928 */
8929 int
8930match_suffix(fname)
8931 char_u *fname;
8932{
8933 int fnamelen, setsuflen;
8934 char_u *setsuf;
8935#define MAXSUFLEN 30 /* maximum length of a file suffix */
8936 char_u suf_buf[MAXSUFLEN];
8937
8938 fnamelen = (int)STRLEN(fname);
8939 setsuflen = 0;
8940 for (setsuf = p_su; *setsuf; )
8941 {
8942 setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
Bram Moolenaar055a2ba2009-07-14 19:40:21 +00008943 if (setsuflen == 0)
8944 {
8945 char_u *tail = gettail(fname);
8946
8947 /* empty entry: match name without a '.' */
8948 if (vim_strchr(tail, '.') == NULL)
8949 {
8950 setsuflen = 1;
8951 break;
8952 }
8953 }
8954 else
8955 {
8956 if (fnamelen >= setsuflen
8957 && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
8958 (size_t)setsuflen) == 0)
8959 break;
8960 setsuflen = 0;
8961 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008962 }
8963 return (setsuflen != 0);
8964}
8965
8966#if !defined(NO_EXPANDPATH) || defined(PROTO)
8967
8968# ifdef VIM_BACKTICK
8969static int vim_backtick __ARGS((char_u *p));
8970static int expand_backtick __ARGS((garray_T *gap, char_u *pat, int flags));
8971# endif
8972
8973# if defined(MSDOS) || defined(FEAT_GUI_W16) || defined(WIN3264)
8974/*
8975 * File name expansion code for MS-DOS, Win16 and Win32. It's here because
8976 * it's shared between these systems.
8977 */
8978# if defined(DJGPP) || defined(PROTO)
8979# define _cdecl /* DJGPP doesn't have this */
8980# else
8981# ifdef __BORLANDC__
8982# define _cdecl _RTLENTRYF
8983# endif
8984# endif
8985
8986/*
8987 * comparison function for qsort in dos_expandpath()
8988 */
8989 static int _cdecl
8990pstrcmp(const void *a, const void *b)
8991{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00008992 return (pathcmp(*(char **)a, *(char **)b, -1));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008993}
8994
8995# ifndef WIN3264
8996 static void
8997namelowcpy(
8998 char_u *d,
8999 char_u *s)
9000{
9001# ifdef DJGPP
9002 if (USE_LONG_FNAME) /* don't lower case on Windows 95/NT systems */
9003 while (*s)
9004 *d++ = *s++;
9005 else
9006# endif
9007 while (*s)
9008 *d++ = TOLOWER_LOC(*s++);
9009 *d = NUL;
9010}
9011# endif
9012
9013/*
Bram Moolenaar231334e2005-07-25 20:46:57 +00009014 * Recursively expand one path component into all matching files and/or
9015 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009016 * Return the number of matches found.
9017 * "path" has backslashes before chars that are not to be expanded, starting
9018 * at "path[wildoff]".
Bram Moolenaar231334e2005-07-25 20:46:57 +00009019 * Return the number of matches found.
9020 * NOTE: much of this is identical to unix_expandpath(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00009021 */
9022 static int
9023dos_expandpath(
9024 garray_T *gap,
9025 char_u *path,
9026 int wildoff,
Bram Moolenaar231334e2005-07-25 20:46:57 +00009027 int flags, /* EW_* flags */
Bram Moolenaar25394022007-05-10 19:06:20 +00009028 int didstar) /* expanded "**" once already */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009029{
Bram Moolenaar231334e2005-07-25 20:46:57 +00009030 char_u *buf;
9031 char_u *path_end;
9032 char_u *p, *s, *e;
9033 int start_len = gap->ga_len;
9034 char_u *pat;
9035 regmatch_T regmatch;
9036 int starts_with_dot;
9037 int matches;
9038 int len;
9039 int starstar = FALSE;
9040 static int stardepth = 0; /* depth for "**" expansion */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009041#ifdef WIN3264
9042 WIN32_FIND_DATA fb;
9043 HANDLE hFind = (HANDLE)0;
9044# ifdef FEAT_MBYTE
9045 WIN32_FIND_DATAW wfb;
9046 WCHAR *wn = NULL; /* UCS-2 name, NULL when not used. */
9047# endif
9048#else
9049 struct ffblk fb;
9050#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009051 char_u *matchname;
Bram Moolenaar231334e2005-07-25 20:46:57 +00009052 int ok;
9053
9054 /* Expanding "**" may take a long time, check for CTRL-C. */
9055 if (stardepth > 0)
9056 {
9057 ui_breakcheck();
9058 if (got_int)
9059 return 0;
9060 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009061
9062 /* make room for file name */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009063 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009064 if (buf == NULL)
9065 return 0;
9066
9067 /*
9068 * Find the first part in the path name that contains a wildcard or a ~1.
9069 * Copy it into buf, including the preceding characters.
9070 */
9071 p = buf;
9072 s = buf;
9073 e = NULL;
9074 path_end = path;
9075 while (*path_end != NUL)
9076 {
9077 /* May ignore a wildcard that has a backslash before it; it will
9078 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
9079 if (path_end >= path + wildoff && rem_backslash(path_end))
9080 *p++ = *path_end++;
9081 else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
9082 {
9083 if (e != NULL)
9084 break;
9085 s = p + 1;
9086 }
9087 else if (path_end >= path + wildoff
9088 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
9089 e = p;
9090#ifdef FEAT_MBYTE
9091 if (has_mbyte)
9092 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00009093 len = (*mb_ptr2len)(path_end);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009094 STRNCPY(p, path_end, len);
9095 p += len;
9096 path_end += len;
9097 }
9098 else
9099#endif
9100 *p++ = *path_end++;
9101 }
9102 e = p;
9103 *e = NUL;
9104
9105 /* now we have one wildcard component between s and e */
9106 /* Remove backslashes between "wildoff" and the start of the wildcard
9107 * component. */
9108 for (p = buf + wildoff; p < s; ++p)
9109 if (rem_backslash(p))
9110 {
Bram Moolenaar8c8de832008-06-24 22:58:06 +00009111 STRMOVE(p, p + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009112 --e;
9113 --s;
9114 }
9115
Bram Moolenaar231334e2005-07-25 20:46:57 +00009116 /* Check for "**" between "s" and "e". */
9117 for (p = s; p < e; ++p)
9118 if (p[0] == '*' && p[1] == '*')
9119 starstar = TRUE;
9120
Bram Moolenaar071d4272004-06-13 20:20:40 +00009121 starts_with_dot = (*s == '.');
9122 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
9123 if (pat == NULL)
9124 {
9125 vim_free(buf);
9126 return 0;
9127 }
9128
9129 /* compile the regexp into a program */
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009130 if (flags & (EW_NOERROR | EW_NOTWILD))
Bram Moolenaarb5609832011-07-20 15:04:58 +02009131 ++emsg_silent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009132 regmatch.rm_ic = TRUE; /* Always ignore case */
9133 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009134 if (flags & (EW_NOERROR | EW_NOTWILD))
Bram Moolenaarb5609832011-07-20 15:04:58 +02009135 --emsg_silent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009136 vim_free(pat);
9137
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009138 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009139 {
9140 vim_free(buf);
9141 return 0;
9142 }
9143
9144 /* remember the pattern or file name being looked for */
9145 matchname = vim_strsave(s);
9146
Bram Moolenaar231334e2005-07-25 20:46:57 +00009147 /* If "**" is by itself, this is the first time we encounter it and more
9148 * is following then find matches without any directory. */
9149 if (!didstar && stardepth < 100 && starstar && e - s == 2
9150 && *path_end == '/')
9151 {
9152 STRCPY(s, path_end + 1);
9153 ++stardepth;
9154 (void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
9155 --stardepth;
9156 }
9157
Bram Moolenaar071d4272004-06-13 20:20:40 +00009158 /* Scan all files in the directory with "dir/ *.*" */
9159 STRCPY(s, "*.*");
9160#ifdef WIN3264
9161# ifdef FEAT_MBYTE
9162 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
9163 {
9164 /* The active codepage differs from 'encoding'. Attempt using the
9165 * wide function. If it fails because it is not implemented fall back
9166 * to the non-wide version (for Windows 98) */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009167 wn = enc_to_utf16(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009168 if (wn != NULL)
9169 {
9170 hFind = FindFirstFileW(wn, &wfb);
9171 if (hFind == INVALID_HANDLE_VALUE
9172 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
9173 {
9174 vim_free(wn);
9175 wn = NULL;
9176 }
9177 }
9178 }
9179
9180 if (wn == NULL)
9181# endif
9182 hFind = FindFirstFile(buf, &fb);
9183 ok = (hFind != INVALID_HANDLE_VALUE);
9184#else
9185 /* If we are expanding wildcards we try both files and directories */
9186 ok = (findfirst((char *)buf, &fb,
9187 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
9188#endif
9189
9190 while (ok)
9191 {
9192#ifdef WIN3264
9193# ifdef FEAT_MBYTE
9194 if (wn != NULL)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009195 p = utf16_to_enc(wfb.cFileName, NULL); /* p is allocated here */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009196 else
9197# endif
9198 p = (char_u *)fb.cFileName;
9199#else
9200 p = (char_u *)fb.ff_name;
9201#endif
9202 /* Ignore entries starting with a dot, unless when asked for. Accept
9203 * all entries found with "matchname". */
9204 if ((p[0] != '.' || starts_with_dot)
9205 && (matchname == NULL
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009206 || (regmatch.regprog != NULL
9207 && vim_regexec(&regmatch, p, (colnr_T)0))
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009208 || ((flags & EW_NOTWILD)
9209 && fnamencmp(path + (s - buf), p, e - s) == 0)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009210 {
9211#ifdef WIN3264
9212 STRCPY(s, p);
9213#else
9214 namelowcpy(s, p);
9215#endif
9216 len = (int)STRLEN(buf);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009217
9218 if (starstar && stardepth < 100)
9219 {
9220 /* For "**" in the pattern first go deeper in the tree to
9221 * find matches. */
9222 STRCPY(buf + len, "/**");
9223 STRCPY(buf + len + 3, path_end);
9224 ++stardepth;
9225 (void)dos_expandpath(gap, buf, len + 1, flags, TRUE);
9226 --stardepth;
9227 }
9228
Bram Moolenaar071d4272004-06-13 20:20:40 +00009229 STRCPY(buf + len, path_end);
9230 if (mch_has_exp_wildcard(path_end))
9231 {
9232 /* need to expand another component of the path */
9233 /* remove backslashes for the remaining components only */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009234 (void)dos_expandpath(gap, buf, len + 1, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009235 }
9236 else
9237 {
9238 /* no more wildcards, check if there is a match */
9239 /* remove backslashes for the remaining components only */
9240 if (*path_end != 0)
9241 backslash_halve(buf + len + 1);
9242 if (mch_getperm(buf) >= 0) /* add existing file */
9243 addfile(gap, buf, flags);
9244 }
9245 }
9246
9247#ifdef WIN3264
9248# ifdef FEAT_MBYTE
9249 if (wn != NULL)
9250 {
9251 vim_free(p);
9252 ok = FindNextFileW(hFind, &wfb);
9253 }
9254 else
9255# endif
9256 ok = FindNextFile(hFind, &fb);
9257#else
9258 ok = (findnext(&fb) == 0);
9259#endif
9260
9261 /* If no more matches and no match was used, try expanding the name
9262 * itself. Finds the long name of a short filename. */
9263 if (!ok && matchname != NULL && gap->ga_len == start_len)
9264 {
9265 STRCPY(s, matchname);
9266#ifdef WIN3264
9267 FindClose(hFind);
9268# ifdef FEAT_MBYTE
9269 if (wn != NULL)
9270 {
9271 vim_free(wn);
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009272 wn = enc_to_utf16(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009273 if (wn != NULL)
9274 hFind = FindFirstFileW(wn, &wfb);
9275 }
9276 if (wn == NULL)
9277# endif
9278 hFind = FindFirstFile(buf, &fb);
9279 ok = (hFind != INVALID_HANDLE_VALUE);
9280#else
9281 ok = (findfirst((char *)buf, &fb,
9282 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
9283#endif
9284 vim_free(matchname);
9285 matchname = NULL;
9286 }
9287 }
9288
9289#ifdef WIN3264
9290 FindClose(hFind);
9291# ifdef FEAT_MBYTE
9292 vim_free(wn);
9293# endif
9294#endif
9295 vim_free(buf);
9296 vim_free(regmatch.regprog);
9297 vim_free(matchname);
9298
9299 matches = gap->ga_len - start_len;
9300 if (matches > 0)
9301 qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
9302 sizeof(char_u *), pstrcmp);
9303 return matches;
9304}
9305
9306 int
9307mch_expandpath(
9308 garray_T *gap,
9309 char_u *path,
9310 int flags) /* EW_* flags */
9311{
Bram Moolenaar231334e2005-07-25 20:46:57 +00009312 return dos_expandpath(gap, path, 0, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009313}
9314# endif /* MSDOS || FEAT_GUI_W16 || WIN3264 */
9315
Bram Moolenaar231334e2005-07-25 20:46:57 +00009316#if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
9317 || defined(PROTO)
9318/*
9319 * Unix style wildcard expansion code.
9320 * It's here because it's used both for Unix and Mac.
9321 */
9322static int pstrcmp __ARGS((const void *, const void *));
9323
9324 static int
9325pstrcmp(a, b)
9326 const void *a, *b;
9327{
9328 return (pathcmp(*(char **)a, *(char **)b, -1));
9329}
9330
9331/*
9332 * Recursively expand one path component into all matching files and/or
9333 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
9334 * "path" has backslashes before chars that are not to be expanded, starting
9335 * at "path + wildoff".
9336 * Return the number of matches found.
9337 * NOTE: much of this is identical to dos_expandpath(), keep in sync!
9338 */
9339 int
9340unix_expandpath(gap, path, wildoff, flags, didstar)
9341 garray_T *gap;
9342 char_u *path;
9343 int wildoff;
9344 int flags; /* EW_* flags */
9345 int didstar; /* expanded "**" once already */
9346{
9347 char_u *buf;
9348 char_u *path_end;
9349 char_u *p, *s, *e;
9350 int start_len = gap->ga_len;
9351 char_u *pat;
9352 regmatch_T regmatch;
9353 int starts_with_dot;
9354 int matches;
9355 int len;
9356 int starstar = FALSE;
9357 static int stardepth = 0; /* depth for "**" expansion */
9358
9359 DIR *dirp;
9360 struct dirent *dp;
9361
9362 /* Expanding "**" may take a long time, check for CTRL-C. */
9363 if (stardepth > 0)
9364 {
9365 ui_breakcheck();
9366 if (got_int)
9367 return 0;
9368 }
9369
9370 /* make room for file name */
9371 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
9372 if (buf == NULL)
9373 return 0;
9374
9375 /*
9376 * Find the first part in the path name that contains a wildcard.
9377 * Copy it into "buf", including the preceding characters.
9378 */
9379 p = buf;
9380 s = buf;
9381 e = NULL;
9382 path_end = path;
9383 while (*path_end != NUL)
9384 {
9385 /* May ignore a wildcard that has a backslash before it; it will
9386 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
9387 if (path_end >= path + wildoff && rem_backslash(path_end))
9388 *p++ = *path_end++;
9389 else if (*path_end == '/')
9390 {
9391 if (e != NULL)
9392 break;
9393 s = p + 1;
9394 }
9395 else if (path_end >= path + wildoff
9396 && vim_strchr((char_u *)"*?[{~$", *path_end) != NULL)
9397 e = p;
9398#ifdef FEAT_MBYTE
9399 if (has_mbyte)
9400 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00009401 len = (*mb_ptr2len)(path_end);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009402 STRNCPY(p, path_end, len);
9403 p += len;
9404 path_end += len;
9405 }
9406 else
9407#endif
9408 *p++ = *path_end++;
9409 }
9410 e = p;
9411 *e = NUL;
9412
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009413 /* Now we have one wildcard component between "s" and "e". */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009414 /* Remove backslashes between "wildoff" and the start of the wildcard
9415 * component. */
9416 for (p = buf + wildoff; p < s; ++p)
9417 if (rem_backslash(p))
9418 {
Bram Moolenaar8c8de832008-06-24 22:58:06 +00009419 STRMOVE(p, p + 1);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009420 --e;
9421 --s;
9422 }
9423
9424 /* Check for "**" between "s" and "e". */
9425 for (p = s; p < e; ++p)
9426 if (p[0] == '*' && p[1] == '*')
9427 starstar = TRUE;
9428
9429 /* convert the file pattern to a regexp pattern */
9430 starts_with_dot = (*s == '.');
9431 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
9432 if (pat == NULL)
9433 {
9434 vim_free(buf);
9435 return 0;
9436 }
9437
9438 /* compile the regexp into a program */
Bram Moolenaarcc016f52005-12-10 20:23:46 +00009439#ifdef CASE_INSENSITIVE_FILENAME
Bram Moolenaar231334e2005-07-25 20:46:57 +00009440 regmatch.rm_ic = TRUE; /* Behave like Terminal.app */
9441#else
Bram Moolenaar94950a92010-12-02 16:01:29 +01009442 if (flags & EW_ICASE)
9443 regmatch.rm_ic = TRUE; /* 'wildignorecase' set */
9444 else
9445 regmatch.rm_ic = FALSE; /* Don't ignore case */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009446#endif
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009447 if (flags & (EW_NOERROR | EW_NOTWILD))
9448 ++emsg_silent;
Bram Moolenaar231334e2005-07-25 20:46:57 +00009449 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009450 if (flags & (EW_NOERROR | EW_NOTWILD))
9451 --emsg_silent;
Bram Moolenaar231334e2005-07-25 20:46:57 +00009452 vim_free(pat);
9453
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009454 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
Bram Moolenaar231334e2005-07-25 20:46:57 +00009455 {
9456 vim_free(buf);
9457 return 0;
9458 }
9459
9460 /* If "**" is by itself, this is the first time we encounter it and more
9461 * is following then find matches without any directory. */
9462 if (!didstar && stardepth < 100 && starstar && e - s == 2
9463 && *path_end == '/')
9464 {
9465 STRCPY(s, path_end + 1);
9466 ++stardepth;
9467 (void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
9468 --stardepth;
9469 }
9470
9471 /* open the directory for scanning */
9472 *s = NUL;
9473 dirp = opendir(*buf == NUL ? "." : (char *)buf);
9474
9475 /* Find all matching entries */
9476 if (dirp != NULL)
9477 {
9478 for (;;)
9479 {
9480 dp = readdir(dirp);
9481 if (dp == NULL)
9482 break;
9483 if ((dp->d_name[0] != '.' || starts_with_dot)
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009484 && ((regmatch.regprog != NULL && vim_regexec(&regmatch,
9485 (char_u *)dp->d_name, (colnr_T)0))
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009486 || ((flags & EW_NOTWILD)
9487 && fnamencmp(path + (s - buf), dp->d_name, e - s) == 0)))
Bram Moolenaar231334e2005-07-25 20:46:57 +00009488 {
9489 STRCPY(s, dp->d_name);
9490 len = STRLEN(buf);
9491
9492 if (starstar && stardepth < 100)
9493 {
9494 /* For "**" in the pattern first go deeper in the tree to
9495 * find matches. */
9496 STRCPY(buf + len, "/**");
9497 STRCPY(buf + len + 3, path_end);
9498 ++stardepth;
9499 (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
9500 --stardepth;
9501 }
9502
9503 STRCPY(buf + len, path_end);
9504 if (mch_has_exp_wildcard(path_end)) /* handle more wildcards */
9505 {
9506 /* need to expand another component of the path */
9507 /* remove backslashes for the remaining components only */
9508 (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
9509 }
9510 else
9511 {
9512 /* no more wildcards, check if there is a match */
9513 /* remove backslashes for the remaining components only */
9514 if (*path_end != NUL)
9515 backslash_halve(buf + len + 1);
9516 if (mch_getperm(buf) >= 0) /* add existing file */
9517 {
Bram Moolenaar95e9b492006-03-15 23:04:43 +00009518#ifdef MACOS_CONVERT
Bram Moolenaar231334e2005-07-25 20:46:57 +00009519 size_t precomp_len = STRLEN(buf)+1;
9520 char_u *precomp_buf =
9521 mac_precompose_path(buf, precomp_len, &precomp_len);
Bram Moolenaar95e9b492006-03-15 23:04:43 +00009522
Bram Moolenaar231334e2005-07-25 20:46:57 +00009523 if (precomp_buf)
9524 {
9525 mch_memmove(buf, precomp_buf, precomp_len);
9526 vim_free(precomp_buf);
9527 }
9528#endif
9529 addfile(gap, buf, flags);
9530 }
9531 }
9532 }
9533 }
9534
9535 closedir(dirp);
9536 }
9537
9538 vim_free(buf);
9539 vim_free(regmatch.regprog);
9540
9541 matches = gap->ga_len - start_len;
9542 if (matches > 0)
9543 qsort(((char_u **)gap->ga_data) + start_len, matches,
9544 sizeof(char_u *), pstrcmp);
9545 return matches;
9546}
9547#endif
9548
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009549#if defined(FEAT_SEARCHPATH)
9550static int find_previous_pathsep __ARGS((char_u *path, char_u **psep));
9551static int is_unique __ARGS((char_u *maybe_unique, garray_T *gap, int i));
Bram Moolenaar162bd912010-07-28 22:29:10 +02009552static void expand_path_option __ARGS((char_u *curdir, garray_T *gap));
9553static char_u *get_path_cutoff __ARGS((char_u *fname, garray_T *gap));
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009554static void uniquefy_paths __ARGS((garray_T *gap, char_u *pattern));
9555static int expand_in_path __ARGS((garray_T *gap, char_u *pattern, int flags));
9556
9557/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009558 * Moves "*psep" back to the previous path separator in "path".
9559 * Returns FAIL is "*psep" ends up at the beginning of "path".
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009560 */
9561 static int
9562find_previous_pathsep(path, psep)
9563 char_u *path;
9564 char_u **psep;
9565{
9566 /* skip the current separator */
9567 if (*psep > path && vim_ispathsep(**psep))
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009568 --*psep;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009569
9570 /* find the previous separator */
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009571 while (*psep > path)
9572 {
9573 if (vim_ispathsep(**psep))
9574 return OK;
9575 mb_ptr_back(path, *psep);
9576 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009577
9578 return FAIL;
9579}
9580
9581/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009582 * Returns TRUE if "maybe_unique" is unique wrt other_paths in "gap".
9583 * "maybe_unique" is the end portion of "((char_u **)gap->ga_data)[i]".
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009584 */
9585 static int
9586is_unique(maybe_unique, gap, i)
9587 char_u *maybe_unique;
9588 garray_T *gap;
9589 int i;
9590{
9591 int j;
9592 int candidate_len;
9593 int other_path_len;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009594 char_u **other_paths = (char_u **)gap->ga_data;
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009595 char_u *rival;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009596
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009597 for (j = 0; j < gap->ga_len; j++)
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009598 {
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009599 if (j == i)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009600 continue; /* don't compare it with itself */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009601
Bram Moolenaar624c7aa2010-07-16 20:38:52 +02009602 candidate_len = (int)STRLEN(maybe_unique);
9603 other_path_len = (int)STRLEN(other_paths[j]);
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009604 if (other_path_len < candidate_len)
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009605 continue; /* it's different when it's shorter */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009606
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009607 rival = other_paths[j] + other_path_len - candidate_len;
Bram Moolenaarda9836c2010-08-16 21:53:27 +02009608 if (fnamecmp(maybe_unique, rival) == 0
9609 && (rival == other_paths[j] || vim_ispathsep(*(rival - 1))))
Bram Moolenaar162bd912010-07-28 22:29:10 +02009610 return FALSE; /* match */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009611 }
9612
Bram Moolenaar162bd912010-07-28 22:29:10 +02009613 return TRUE; /* no match found */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009614}
9615
9616/*
Bram Moolenaar1a509df2010-08-01 17:59:57 +02009617 * Split the 'path' option into an array of strings in garray_T. Relative
Bram Moolenaar162bd912010-07-28 22:29:10 +02009618 * paths are expanded to their equivalent fullpath. This includes the "."
9619 * (relative to current buffer directory) and empty path (relative to current
9620 * directory) notations.
9621 *
9622 * TODO: handle upward search (;) and path limiter (**N) notations by
9623 * expanding each into their equivalent path(s).
9624 */
9625 static void
9626expand_path_option(curdir, gap)
9627 char_u *curdir;
9628 garray_T *gap;
9629{
9630 char_u *path_option = *curbuf->b_p_path == NUL
9631 ? p_path : curbuf->b_p_path;
9632 char_u *buf;
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009633 char_u *p;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009634 int len;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009635
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +02009636 if ((buf = alloc((int)MAXPATHL)) == NULL)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009637 return;
9638
9639 while (*path_option != NUL)
9640 {
9641 copy_option_part(&path_option, buf, MAXPATHL, " ,");
9642
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009643 if (buf[0] == '.' && (buf[1] == NUL || vim_ispathsep(buf[1])))
Bram Moolenaar162bd912010-07-28 22:29:10 +02009644 {
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009645 /* Relative to current buffer:
9646 * "/path/file" + "." -> "/path/"
9647 * "/path/file" + "./subdir" -> "/path/subdir" */
Bram Moolenaar162bd912010-07-28 22:29:10 +02009648 if (curbuf->b_ffname == NULL)
9649 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009650 p = gettail(curbuf->b_ffname);
9651 len = (int)(p - curbuf->b_ffname);
9652 if (len + (int)STRLEN(buf) >= MAXPATHL)
9653 continue;
9654 if (buf[1] == NUL)
9655 buf[len] = NUL;
9656 else
9657 STRMOVE(buf + len, buf + 2);
9658 mch_memmove(buf, curbuf->b_ffname, len);
9659 simplify_filename(buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009660 }
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009661 else if (buf[0] == NUL)
9662 /* relative to current directory */
Bram Moolenaar162bd912010-07-28 22:29:10 +02009663 STRCPY(buf, curdir);
Bram Moolenaar84f888a2010-08-05 21:40:16 +02009664 else if (path_with_url(buf))
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009665 /* URL can't be used here */
Bram Moolenaar84f888a2010-08-05 21:40:16 +02009666 continue;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009667 else if (!mch_isFullName(buf))
9668 {
9669 /* Expand relative path to their full path equivalent */
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009670 len = (int)STRLEN(curdir);
9671 if (len + (int)STRLEN(buf) + 3 > MAXPATHL)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009672 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009673 STRMOVE(buf + len + 1, buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009674 STRCPY(buf, curdir);
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009675 buf[len] = PATHSEP;
Bram Moolenaar57adda12010-08-03 22:11:29 +02009676 simplify_filename(buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009677 }
9678
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009679 if (ga_grow(gap, 1) == FAIL)
9680 break;
9681 p = vim_strsave(buf);
9682 if (p == NULL)
9683 break;
9684 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009685 }
9686
9687 vim_free(buf);
9688}
9689
9690/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009691 * Returns a pointer to the file or directory name in "fname" that matches the
9692 * longest path in "ga"p, or NULL if there is no match. For example:
Bram Moolenaar162bd912010-07-28 22:29:10 +02009693 *
9694 * path: /foo/bar/baz
9695 * fname: /foo/bar/baz/quux.txt
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009696 * returns: ^this
Bram Moolenaar162bd912010-07-28 22:29:10 +02009697 */
9698 static char_u *
9699get_path_cutoff(fname, gap)
9700 char_u *fname;
9701 garray_T *gap;
9702{
9703 int i;
9704 int maxlen = 0;
9705 char_u **path_part = (char_u **)gap->ga_data;
9706 char_u *cutoff = NULL;
9707
9708 for (i = 0; i < gap->ga_len; i++)
9709 {
9710 int j = 0;
9711
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009712 while ((fname[j] == path_part[i][j]
Bram Moolenaar2d7c47d2010-08-10 19:50:26 +02009713# if defined(MSWIN) || defined(MSDOS)
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009714 || (vim_ispathsep(fname[j]) && vim_ispathsep(path_part[i][j]))
9715#endif
9716 ) && fname[j] != NUL && path_part[i][j] != NUL)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009717 j++;
9718 if (j > maxlen)
9719 {
9720 maxlen = j;
9721 cutoff = &fname[j];
9722 }
9723 }
9724
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009725 /* skip to the file or directory name */
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009726 if (cutoff != NULL)
Bram Moolenaar31710262010-08-13 13:36:15 +02009727 while (vim_ispathsep(*cutoff))
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009728 mb_ptr_adv(cutoff);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009729
9730 return cutoff;
9731}
9732
9733/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009734 * Sorts, removes duplicates and modifies all the fullpath names in "gap" so
9735 * that they are unique with respect to each other while conserving the part
9736 * that matches the pattern. Beware, this is at least O(n^2) wrt "gap->ga_len".
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009737 */
9738 static void
9739uniquefy_paths(gap, pattern)
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +02009740 garray_T *gap;
9741 char_u *pattern;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009742{
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +02009743 int i;
9744 int len;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009745 char_u **fnames = (char_u **)gap->ga_data;
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009746 int sort_again = FALSE;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009747 char_u *pat;
9748 char_u *file_pattern;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009749 char_u *curdir;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009750 regmatch_T regmatch;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009751 garray_T path_ga;
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009752 char_u **in_curdir = NULL;
9753 char_u *short_name;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009754
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +02009755 remove_duplicates(gap);
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009756 ga_init2(&path_ga, (int)sizeof(char_u *), 1);
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009757
9758 /*
9759 * We need to prepend a '*' at the beginning of file_pattern so that the
9760 * regex matches anywhere in the path. FIXME: is this valid for all
Bram Moolenaarb31e4382010-07-24 16:01:56 +02009761 * possible patterns?
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009762 */
Bram Moolenaar624c7aa2010-07-16 20:38:52 +02009763 len = (int)STRLEN(pattern);
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009764 file_pattern = alloc(len + 2);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009765 if (file_pattern == NULL)
9766 return;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009767 file_pattern[0] = '*';
Bram Moolenaar162bd912010-07-28 22:29:10 +02009768 file_pattern[1] = NUL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009769 STRCAT(file_pattern, pattern);
9770 pat = file_pat_to_reg_pat(file_pattern, NULL, NULL, TRUE);
9771 vim_free(file_pattern);
Bram Moolenaarb31e4382010-07-24 16:01:56 +02009772 if (pat == NULL)
9773 return;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009774
Bram Moolenaarb31e4382010-07-24 16:01:56 +02009775 regmatch.rm_ic = TRUE; /* always ignore case */
9776 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
9777 vim_free(pat);
9778 if (regmatch.regprog == NULL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009779 return;
9780
Bram Moolenaar162bd912010-07-28 22:29:10 +02009781 if ((curdir = alloc((int)(MAXPATHL))) == NULL)
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009782 goto theend;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009783 mch_dirname(curdir, MAXPATHL);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009784 expand_path_option(curdir, &path_ga);
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009785
9786 in_curdir = (char_u **)alloc_clear(gap->ga_len * sizeof(char_u *));
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009787 if (in_curdir == NULL)
9788 goto theend;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009789
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009790 for (i = 0; i < gap->ga_len && !got_int; i++)
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009791 {
Bram Moolenaar162bd912010-07-28 22:29:10 +02009792 char_u *path = fnames[i];
9793 int is_in_curdir;
Bram Moolenaar31710262010-08-13 13:36:15 +02009794 char_u *dir_end = gettail_dir(path);
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009795 char_u *pathsep_p;
9796 char_u *path_cutoff;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009797
Bram Moolenaar624c7aa2010-07-16 20:38:52 +02009798 len = (int)STRLEN(path);
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009799 is_in_curdir = fnamencmp(curdir, path, dir_end - path) == 0
Bram Moolenaar162bd912010-07-28 22:29:10 +02009800 && curdir[dir_end - path] == NUL;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009801 if (is_in_curdir)
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009802 in_curdir[i] = vim_strsave(path);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009803
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009804 /* Shorten the filename while maintaining its uniqueness */
9805 path_cutoff = get_path_cutoff(path, &path_ga);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009806
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009807 /* we start at the end of the path */
9808 pathsep_p = path + len - 1;
9809
9810 while (find_previous_pathsep(path, &pathsep_p))
9811 if (vim_regexec(&regmatch, pathsep_p + 1, (colnr_T)0)
9812 && is_unique(pathsep_p + 1, gap, i)
9813 && path_cutoff != NULL && pathsep_p + 1 >= path_cutoff)
9814 {
9815 sort_again = TRUE;
9816 mch_memmove(path, pathsep_p + 1, STRLEN(pathsep_p));
9817 break;
9818 }
Bram Moolenaar9bc040c2010-08-11 22:05:57 +02009819
9820 if (mch_isFullName(path))
9821 {
9822 /*
9823 * Last resort: shorten relative to curdir if possible.
9824 * 'possible' means:
9825 * 1. It is under the current directory.
9826 * 2. The result is actually shorter than the original.
9827 *
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009828 * Before curdir After
9829 * /foo/bar/file.txt /foo/bar ./file.txt
9830 * c:\foo\bar\file.txt c:\foo\bar .\file.txt
9831 * /file.txt / /file.txt
9832 * c:\file.txt c:\ .\file.txt
Bram Moolenaar9bc040c2010-08-11 22:05:57 +02009833 */
9834 short_name = shorten_fname(path, curdir);
Bram Moolenaar31710262010-08-13 13:36:15 +02009835 if (short_name != NULL && short_name > path + 1
9836#if defined(MSWIN) || defined(MSDOS)
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009837 /* On windows,
Bram Moolenaar31710262010-08-13 13:36:15 +02009838 * shorten_fname("c:\a\a.txt", "c:\a\b")
Bram Moolenaar31710262010-08-13 13:36:15 +02009839 * returns "\a\a.txt", which is not really the short
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009840 * name, hence: */
Bram Moolenaar31710262010-08-13 13:36:15 +02009841 && !vim_ispathsep(*short_name)
9842#endif
9843 )
Bram Moolenaar9bc040c2010-08-11 22:05:57 +02009844 {
9845 STRCPY(path, ".");
9846 add_pathsep(path);
Bram Moolenaarcda000e2010-08-14 13:34:39 +02009847 STRMOVE(path + STRLEN(path), short_name);
Bram Moolenaar9bc040c2010-08-11 22:05:57 +02009848 }
9849 }
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009850 ui_breakcheck();
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009851 }
9852
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009853 /* Shorten filenames in /in/current/directory/{filename} */
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009854 for (i = 0; i < gap->ga_len && !got_int; i++)
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009855 {
9856 char_u *rel_path;
9857 char_u *path = in_curdir[i];
9858
9859 if (path == NULL)
9860 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009861
9862 /* If the {filename} is not unique, change it to ./{filename}.
9863 * Else reduce it to {filename} */
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009864 short_name = shorten_fname(path, curdir);
9865 if (short_name == NULL)
9866 short_name = path;
9867 if (is_unique(short_name, gap, i))
9868 {
9869 STRCPY(fnames[i], short_name);
9870 continue;
9871 }
9872
9873 rel_path = alloc((int)(STRLEN(short_name) + STRLEN(PATHSEPSTR) + 2));
9874 if (rel_path == NULL)
9875 goto theend;
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009876 STRCPY(rel_path, ".");
9877 add_pathsep(rel_path);
9878 STRCAT(rel_path, short_name);
9879
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009880 vim_free(fnames[i]);
9881 fnames[i] = rel_path;
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009882 sort_again = TRUE;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009883 ui_breakcheck();
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009884 }
9885
Bram Moolenaar162bd912010-07-28 22:29:10 +02009886theend:
9887 vim_free(curdir);
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009888 if (in_curdir != NULL)
9889 {
9890 for (i = 0; i < gap->ga_len; i++)
9891 vim_free(in_curdir[i]);
9892 vim_free(in_curdir);
9893 }
Bram Moolenaar162bd912010-07-28 22:29:10 +02009894 ga_clear_strings(&path_ga);
Bram Moolenaarb31e4382010-07-24 16:01:56 +02009895 vim_free(regmatch.regprog);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009896
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009897 if (sort_again)
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +02009898 remove_duplicates(gap);
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009899}
9900
9901/*
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +02009902 * Calls globpath() with 'path' values for the given pattern and stores the
9903 * result in "gap".
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009904 * Returns the total number of matches.
9905 */
9906 static int
9907expand_in_path(gap, pattern, flags)
9908 garray_T *gap;
9909 char_u *pattern;
9910 int flags; /* EW_* flags */
9911{
Bram Moolenaar162bd912010-07-28 22:29:10 +02009912 char_u *curdir;
9913 garray_T path_ga;
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009914 char_u *files = NULL;
9915 char_u *s; /* start */
9916 char_u *e; /* end */
9917 char_u *paths = NULL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009918
Bram Moolenaar7f0f6212010-08-03 22:21:00 +02009919 if ((curdir = alloc((unsigned)MAXPATHL)) == NULL)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009920 return 0;
9921 mch_dirname(curdir, MAXPATHL);
9922
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009923 ga_init2(&path_ga, (int)sizeof(char_u *), 1);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009924 expand_path_option(curdir, &path_ga);
9925 vim_free(curdir);
Bram Moolenaar006d2b02010-08-04 12:39:44 +02009926 if (path_ga.ga_len == 0)
9927 return 0;
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +02009928
9929 paths = ga_concat_strings(&path_ga);
9930 ga_clear_strings(&path_ga);
9931 if (paths == NULL)
Bram Moolenaar7f0f6212010-08-03 22:21:00 +02009932 return 0;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009933
Bram Moolenaar94950a92010-12-02 16:01:29 +01009934 files = globpath(paths, pattern, (flags & EW_ICASE) ? WILD_ICASE : 0);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009935 vim_free(paths);
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009936 if (files == NULL)
9937 return 0;
9938
9939 /* Copy each path in files into gap */
9940 s = e = files;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009941 while (*s != NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009942 {
Bram Moolenaar162bd912010-07-28 22:29:10 +02009943 while (*e != '\n' && *e != NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009944 e++;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009945 if (*e == NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009946 {
9947 addfile(gap, s, flags);
9948 break;
9949 }
9950 else
9951 {
9952 /* *e is '\n' */
Bram Moolenaar162bd912010-07-28 22:29:10 +02009953 *e = NUL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009954 addfile(gap, s, flags);
9955 e++;
9956 s = e;
9957 }
9958 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009959 vim_free(files);
9960
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009961 return gap->ga_len;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009962}
9963#endif
9964
Bram Moolenaar1587a1e2010-07-29 20:59:59 +02009965#if defined(FEAT_SEARCHPATH) || defined(FEAT_CMDL_COMPL) || defined(PROTO)
9966/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009967 * Sort "gap" and remove duplicate entries. "gap" is expected to contain a
9968 * list of file names in allocated memory.
Bram Moolenaar1587a1e2010-07-29 20:59:59 +02009969 */
9970 void
9971remove_duplicates(gap)
9972 garray_T *gap;
9973{
9974 int i;
9975 int j;
9976 char_u **fnames = (char_u **)gap->ga_data;
9977
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009978 sort_strings(fnames, gap->ga_len);
Bram Moolenaar1587a1e2010-07-29 20:59:59 +02009979 for (i = gap->ga_len - 1; i > 0; --i)
9980 if (fnamecmp(fnames[i - 1], fnames[i]) == 0)
9981 {
9982 vim_free(fnames[i]);
9983 for (j = i + 1; j < gap->ga_len; ++j)
9984 fnames[j - 1] = fnames[j];
9985 --gap->ga_len;
9986 }
9987}
9988#endif
9989
Bram Moolenaar071d4272004-06-13 20:20:40 +00009990/*
9991 * Generic wildcard expansion code.
9992 *
9993 * Characters in "pat" that should not be expanded must be preceded with a
9994 * backslash. E.g., "/path\ with\ spaces/my\*star*"
9995 *
9996 * Return FAIL when no single file was found. In this case "num_file" is not
9997 * set, and "file" may contain an error message.
9998 * Return OK when some files found. "num_file" is set to the number of
9999 * matches, "file" to the array of matches. Call FreeWild() later.
10000 */
10001 int
10002gen_expand_wildcards(num_pat, pat, num_file, file, flags)
10003 int num_pat; /* number of input patterns */
10004 char_u **pat; /* array of input patterns */
10005 int *num_file; /* resulting number of files */
10006 char_u ***file; /* array of resulting files */
10007 int flags; /* EW_* flags */
10008{
10009 int i;
10010 garray_T ga;
10011 char_u *p;
10012 static int recursive = FALSE;
10013 int add_pat;
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010014#if defined(FEAT_SEARCHPATH)
10015 int did_expand_in_path = FALSE;
10016#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000010017
10018 /*
10019 * expand_env() is called to expand things like "~user". If this fails,
10020 * it calls ExpandOne(), which brings us back here. In this case, always
10021 * call the machine specific expansion function, if possible. Otherwise,
10022 * return FAIL.
10023 */
10024 if (recursive)
10025#ifdef SPECIAL_WILDCHAR
10026 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
10027#else
10028 return FAIL;
10029#endif
10030
10031#ifdef SPECIAL_WILDCHAR
10032 /*
10033 * If there are any special wildcard characters which we cannot handle
10034 * here, call machine specific function for all the expansion. This
10035 * avoids starting the shell for each argument separately.
10036 * For `=expr` do use the internal function.
10037 */
10038 for (i = 0; i < num_pat; i++)
10039 {
10040 if (vim_strpbrk(pat[i], (char_u *)SPECIAL_WILDCHAR) != NULL
10041# ifdef VIM_BACKTICK
10042 && !(vim_backtick(pat[i]) && pat[i][1] == '=')
10043# endif
10044 )
10045 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
10046 }
10047#endif
10048
10049 recursive = TRUE;
10050
10051 /*
10052 * The matching file names are stored in a growarray. Init it empty.
10053 */
10054 ga_init2(&ga, (int)sizeof(char_u *), 30);
10055
10056 for (i = 0; i < num_pat; ++i)
10057 {
10058 add_pat = -1;
10059 p = pat[i];
10060
10061#ifdef VIM_BACKTICK
10062 if (vim_backtick(p))
10063 add_pat = expand_backtick(&ga, p, flags);
10064 else
10065#endif
10066 {
10067 /*
10068 * First expand environment variables, "~/" and "~user/".
10069 */
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010070 if (vim_strchr(p, '$') != NULL || *p == '~')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010071 {
Bram Moolenaar9f0545d2007-09-26 20:36:32 +000010072 p = expand_env_save_opt(p, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010073 if (p == NULL)
10074 p = pat[i];
10075#ifdef UNIX
10076 /*
10077 * On Unix, if expand_env() can't expand an environment
10078 * variable, use the shell to do that. Discard previously
10079 * found file names and start all over again.
10080 */
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010081 else if (vim_strchr(p, '$') != NULL || *p == '~')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010082 {
10083 vim_free(p);
Bram Moolenaar782027e2009-06-24 14:25:49 +000010084 ga_clear_strings(&ga);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010085 i = mch_expand_wildcards(num_pat, pat, num_file, file,
10086 flags);
10087 recursive = FALSE;
10088 return i;
10089 }
10090#endif
10091 }
10092
10093 /*
10094 * If there are wildcards: Expand file names and add each match to
10095 * the list. If there is no match, and EW_NOTFOUND is given, add
10096 * the pattern.
10097 * If there are no wildcards: Add the file name if it exists or
10098 * when EW_NOTFOUND is given.
10099 */
10100 if (mch_has_exp_wildcard(p))
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010101 {
10102#if defined(FEAT_SEARCHPATH)
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010103 if ((flags & EW_PATH)
10104 && !mch_isFullName(p)
10105 && !(p[0] == '.'
10106 && (vim_ispathsep(p[1])
10107 || (p[1] == '.' && vim_ispathsep(p[2]))))
10108 )
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010109 {
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010110 /* :find completion where 'path' is used.
10111 * Recursiveness is OK here. */
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010112 recursive = FALSE;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010113 add_pat = expand_in_path(&ga, p, flags);
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010114 recursive = TRUE;
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010115 did_expand_in_path = TRUE;
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010116 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010117 else
10118#endif
10119 add_pat = mch_expandpath(&ga, p, flags);
10120 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010121 }
10122
10123 if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
10124 {
10125 char_u *t = backslash_halve_save(p);
10126
10127#if defined(MACOS_CLASSIC)
10128 slash_to_colon(t);
10129#endif
10130 /* When EW_NOTFOUND is used, always add files and dirs. Makes
10131 * "vim c:/" work. */
10132 if (flags & EW_NOTFOUND)
10133 addfile(&ga, t, flags | EW_DIR | EW_FILE);
10134 else if (mch_getperm(t) >= 0)
10135 addfile(&ga, t, flags);
10136 vim_free(t);
10137 }
10138
Bram Moolenaarb28ebbc2010-07-14 16:59:57 +020010139#if defined(FEAT_SEARCHPATH)
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010140 if (did_expand_in_path && ga.ga_len > 0 && (flags & EW_PATH))
Bram Moolenaarb28ebbc2010-07-14 16:59:57 +020010141 uniquefy_paths(&ga, p);
10142#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000010143 if (p != pat[i])
10144 vim_free(p);
10145 }
10146
10147 *num_file = ga.ga_len;
10148 *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data : (char_u **)"";
10149
10150 recursive = FALSE;
10151
10152 return (ga.ga_data != NULL) ? OK : FAIL;
10153}
10154
10155# ifdef VIM_BACKTICK
10156
10157/*
10158 * Return TRUE if we can expand this backtick thing here.
10159 */
10160 static int
10161vim_backtick(p)
10162 char_u *p;
10163{
10164 return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
10165}
10166
10167/*
10168 * Expand an item in `backticks` by executing it as a command.
10169 * Currently only works when pat[] starts and ends with a `.
10170 * Returns number of file names found.
10171 */
10172 static int
10173expand_backtick(gap, pat, flags)
10174 garray_T *gap;
10175 char_u *pat;
10176 int flags; /* EW_* flags */
10177{
10178 char_u *p;
10179 char_u *cmd;
10180 char_u *buffer;
10181 int cnt = 0;
10182 int i;
10183
10184 /* Create the command: lop off the backticks. */
10185 cmd = vim_strnsave(pat + 1, (int)STRLEN(pat) - 2);
10186 if (cmd == NULL)
10187 return 0;
10188
10189#ifdef FEAT_EVAL
10190 if (*cmd == '=') /* `={expr}`: Expand expression */
Bram Moolenaar362e1a32006-03-06 23:29:24 +000010191 buffer = eval_to_string(cmd + 1, &p, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010192 else
10193#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010194 buffer = get_cmd_output(cmd, NULL,
10195 (flags & EW_SILENT) ? SHELL_SILENT : 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010196 vim_free(cmd);
10197 if (buffer == NULL)
10198 return 0;
10199
10200 cmd = buffer;
10201 while (*cmd != NUL)
10202 {
10203 cmd = skipwhite(cmd); /* skip over white space */
10204 p = cmd;
10205 while (*p != NUL && *p != '\r' && *p != '\n') /* skip over entry */
10206 ++p;
10207 /* add an entry if it is not empty */
10208 if (p > cmd)
10209 {
10210 i = *p;
10211 *p = NUL;
10212 addfile(gap, cmd, flags);
10213 *p = i;
10214 ++cnt;
10215 }
10216 cmd = p;
10217 while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
10218 ++cmd;
10219 }
10220
10221 vim_free(buffer);
10222 return cnt;
10223}
10224# endif /* VIM_BACKTICK */
10225
10226/*
10227 * Add a file to a file list. Accepted flags:
10228 * EW_DIR add directories
10229 * EW_FILE add files
Bram Moolenaar1f35bf92006-03-07 22:38:47 +000010230 * EW_EXEC add executable files
Bram Moolenaar071d4272004-06-13 20:20:40 +000010231 * EW_NOTFOUND add even when it doesn't exist
10232 * EW_ADDSLASH add slash after directory name
10233 */
10234 void
10235addfile(gap, f, flags)
10236 garray_T *gap;
10237 char_u *f; /* filename */
10238 int flags;
10239{
10240 char_u *p;
10241 int isdir;
10242
10243 /* if the file/dir doesn't exist, may not add it */
10244 if (!(flags & EW_NOTFOUND) && mch_getperm(f) < 0)
10245 return;
10246
10247#ifdef FNAME_ILLEGAL
10248 /* if the file/dir contains illegal characters, don't add it */
10249 if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
10250 return;
10251#endif
10252
10253 isdir = mch_isdir(f);
10254 if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
10255 return;
10256
Bram Moolenaar1f35bf92006-03-07 22:38:47 +000010257 /* If the file isn't executable, may not add it. Do accept directories. */
10258 if (!isdir && (flags & EW_EXEC) && !mch_can_exe(f))
10259 return;
10260
Bram Moolenaar071d4272004-06-13 20:20:40 +000010261 /* Make room for another item in the file list. */
10262 if (ga_grow(gap, 1) == FAIL)
10263 return;
10264
10265 p = alloc((unsigned)(STRLEN(f) + 1 + isdir));
10266 if (p == NULL)
10267 return;
10268
10269 STRCPY(p, f);
10270#ifdef BACKSLASH_IN_FILENAME
10271 slash_adjust(p);
10272#endif
10273 /*
10274 * Append a slash or backslash after directory names if none is present.
10275 */
10276#ifndef DONT_ADD_PATHSEP_TO_DIR
10277 if (isdir && (flags & EW_ADDSLASH))
10278 add_pathsep(p);
10279#endif
10280 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010281}
10282#endif /* !NO_EXPANDPATH */
10283
10284#if defined(VIM_BACKTICK) || defined(FEAT_EVAL) || defined(PROTO)
10285
10286#ifndef SEEK_SET
10287# define SEEK_SET 0
10288#endif
10289#ifndef SEEK_END
10290# define SEEK_END 2
10291#endif
10292
10293/*
10294 * Get the stdout of an external command.
10295 * Returns an allocated string, or NULL for error.
10296 */
10297 char_u *
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010298get_cmd_output(cmd, infile, flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010299 char_u *cmd;
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010300 char_u *infile; /* optional input file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010301 int flags; /* can be SHELL_SILENT */
10302{
10303 char_u *tempname;
10304 char_u *command;
10305 char_u *buffer = NULL;
10306 int len;
10307 int i = 0;
10308 FILE *fd;
10309
10310 if (check_restricted() || check_secure())
10311 return NULL;
10312
10313 /* get a name for the temp file */
10314 if ((tempname = vim_tempname('o')) == NULL)
10315 {
10316 EMSG(_(e_notmp));
10317 return NULL;
10318 }
10319
10320 /* Add the redirection stuff */
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010321 command = make_filter_cmd(cmd, infile, tempname);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010322 if (command == NULL)
10323 goto done;
10324
10325 /*
10326 * Call the shell to execute the command (errors are ignored).
10327 * Don't check timestamps here.
10328 */
10329 ++no_check_timestamps;
10330 call_shell(command, SHELL_DOOUT | SHELL_EXPAND | flags);
10331 --no_check_timestamps;
10332
10333 vim_free(command);
10334
10335 /*
10336 * read the names from the file into memory
10337 */
10338# ifdef VMS
Bram Moolenaar25394022007-05-10 19:06:20 +000010339 /* created temporary file is not always readable as binary */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010340 fd = mch_fopen((char *)tempname, "r");
10341# else
10342 fd = mch_fopen((char *)tempname, READBIN);
10343# endif
10344
10345 if (fd == NULL)
10346 {
10347 EMSG2(_(e_notopen), tempname);
10348 goto done;
10349 }
10350
10351 fseek(fd, 0L, SEEK_END);
10352 len = ftell(fd); /* get size of temp file */
10353 fseek(fd, 0L, SEEK_SET);
10354
10355 buffer = alloc(len + 1);
10356 if (buffer != NULL)
10357 i = (int)fread((char *)buffer, (size_t)1, (size_t)len, fd);
10358 fclose(fd);
10359 mch_remove(tempname);
10360 if (buffer == NULL)
10361 goto done;
10362#ifdef VMS
10363 len = i; /* VMS doesn't give us what we asked for... */
10364#endif
10365 if (i != len)
10366 {
10367 EMSG2(_(e_notread), tempname);
10368 vim_free(buffer);
10369 buffer = NULL;
10370 }
10371 else
Bram Moolenaar162bd912010-07-28 22:29:10 +020010372 buffer[len] = NUL; /* make sure the buffer is terminated */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010373
10374done:
10375 vim_free(tempname);
10376 return buffer;
10377}
10378#endif
10379
10380/*
10381 * Free the list of files returned by expand_wildcards() or other expansion
10382 * functions.
10383 */
10384 void
10385FreeWild(count, files)
10386 int count;
10387 char_u **files;
10388{
Bram Moolenaarfc1421e2006-04-20 22:17:20 +000010389 if (count <= 0 || files == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010390 return;
10391#if defined(__EMX__) && defined(__ALWAYS_HAS_TRAILING_NULL_POINTER) /* XXX */
10392 /*
10393 * Is this still OK for when other functions than expand_wildcards() have
10394 * been used???
10395 */
10396 _fnexplodefree((char **)files);
10397#else
10398 while (count--)
10399 vim_free(files[count]);
10400 vim_free(files);
10401#endif
10402}
10403
10404/*
Bram Moolenaara9dc3752010-07-11 20:46:53 +020010405 * Return TRUE when need to go to Insert mode because of 'insertmode'.
Bram Moolenaar071d4272004-06-13 20:20:40 +000010406 * Don't do this when still processing a command or a mapping.
10407 * Don't do this when inside a ":normal" command.
10408 */
10409 int
10410goto_im()
10411{
10412 return (p_im && stuff_empty() && typebuf_typed());
10413}