blob: 988e368d7a52e5f03c495b1215d5c23aa03f53bf [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)
Bram Moolenaar81340392012-06-06 16:12:59 +0200674 lead_len = get_leader_len(ptr, NULL, FALSE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000675 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)
Bram Moolenaar81340392012-06-06 16:12:59 +0200696 lead_len = get_leader_len(ptr, NULL, FALSE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000697 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)
Bram Moolenaar81340392012-06-06 16:12:59 +0200839 lead_len = get_leader_len(saved_line, &lead_flags, dir == BACKWARD, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000840 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.
Bram Moolenaar81340392012-06-06 16:12:59 +02001551 * If "include_space" is set, include trailing whitespace while calculating the
1552 * length.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001553 */
1554 int
Bram Moolenaar81340392012-06-06 16:12:59 +02001555get_leader_len(line, flags, backward, include_space)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001556 char_u *line;
1557 char_u **flags;
1558 int backward;
Bram Moolenaar81340392012-06-06 16:12:59 +02001559 int include_space;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001560{
1561 int i, j;
Bram Moolenaar81340392012-06-06 16:12:59 +02001562 int result;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001563 int got_com = FALSE;
1564 int found_one;
1565 char_u part_buf[COM_MAX_LEN]; /* buffer for one option part */
1566 char_u *string; /* pointer to comment string */
1567 char_u *list;
Bram Moolenaara4271d52011-05-10 13:38:27 +02001568 int middle_match_len = 0;
1569 char_u *prev_list;
Bram Moolenaar05da4282011-05-10 14:44:11 +02001570 char_u *saved_flags = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001571
Bram Moolenaar81340392012-06-06 16:12:59 +02001572 result = i = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001573 while (vim_iswhite(line[i])) /* leading white space is ignored */
1574 ++i;
1575
1576 /*
1577 * Repeat to match several nested comment strings.
1578 */
Bram Moolenaara4271d52011-05-10 13:38:27 +02001579 while (line[i] != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001580 {
1581 /*
1582 * scan through the 'comments' option for a match
1583 */
1584 found_one = FALSE;
1585 for (list = curbuf->b_p_com; *list; )
1586 {
Bram Moolenaara4271d52011-05-10 13:38:27 +02001587 /* Get one option part into part_buf[]. Advance "list" to next
1588 * one. Put "string" at start of string. */
1589 if (!got_com && flags != NULL)
1590 *flags = list; /* remember where flags started */
1591 prev_list = list;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001592 (void)copy_option_part(&list, part_buf, COM_MAX_LEN, ",");
1593 string = vim_strchr(part_buf, ':');
1594 if (string == NULL) /* missing ':', ignore this part */
1595 continue;
1596 *string++ = NUL; /* isolate flags from string */
1597
Bram Moolenaara4271d52011-05-10 13:38:27 +02001598 /* If we found a middle match previously, use that match when this
1599 * is not a middle or end. */
1600 if (middle_match_len != 0
1601 && vim_strchr(part_buf, COM_MIDDLE) == NULL
1602 && vim_strchr(part_buf, COM_END) == NULL)
1603 break;
1604
1605 /* When we already found a nested comment, only accept further
1606 * nested comments. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001607 if (got_com && vim_strchr(part_buf, COM_NEST) == NULL)
1608 continue;
1609
Bram Moolenaara4271d52011-05-10 13:38:27 +02001610 /* When 'O' flag present and using "O" command skip this one. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001611 if (backward && vim_strchr(part_buf, COM_NOBACK) != NULL)
1612 continue;
1613
Bram Moolenaara4271d52011-05-10 13:38:27 +02001614 /* Line contents and string must match.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001615 * When string starts with white space, must have some white space
1616 * (but the amount does not need to match, there might be a mix of
Bram Moolenaara4271d52011-05-10 13:38:27 +02001617 * TABs and spaces). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001618 if (vim_iswhite(string[0]))
1619 {
1620 if (i == 0 || !vim_iswhite(line[i - 1]))
Bram Moolenaara4271d52011-05-10 13:38:27 +02001621 continue; /* missing shite space */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001622 while (vim_iswhite(string[0]))
1623 ++string;
1624 }
1625 for (j = 0; string[j] != NUL && string[j] == line[i + j]; ++j)
1626 ;
1627 if (string[j] != NUL)
Bram Moolenaara4271d52011-05-10 13:38:27 +02001628 continue; /* string doesn't match */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001629
Bram Moolenaara4271d52011-05-10 13:38:27 +02001630 /* When 'b' flag used, there must be white space or an
1631 * end-of-line after the string in the line. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001632 if (vim_strchr(part_buf, COM_BLANK) != NULL
1633 && !vim_iswhite(line[i + j]) && line[i + j] != NUL)
1634 continue;
1635
Bram Moolenaara4271d52011-05-10 13:38:27 +02001636 /* We have found a match, stop searching unless this is a middle
1637 * comment. The middle comment can be a substring of the end
1638 * comment in which case it's better to return the length of the
1639 * end comment and its flags. Thus we keep searching with middle
1640 * and end matches and use an end match if it matches better. */
1641 if (vim_strchr(part_buf, COM_MIDDLE) != NULL)
1642 {
1643 if (middle_match_len == 0)
1644 {
1645 middle_match_len = j;
1646 saved_flags = prev_list;
1647 }
1648 continue;
1649 }
1650 if (middle_match_len != 0 && j > middle_match_len)
1651 /* Use this match instead of the middle match, since it's a
1652 * longer thus better match. */
1653 middle_match_len = 0;
1654
1655 if (middle_match_len == 0)
1656 i += j;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001657 found_one = TRUE;
1658 break;
1659 }
1660
Bram Moolenaara4271d52011-05-10 13:38:27 +02001661 if (middle_match_len != 0)
1662 {
1663 /* Use the previously found middle match after failing to find a
1664 * match with an end. */
1665 if (!got_com && flags != NULL)
1666 *flags = saved_flags;
1667 i += middle_match_len;
1668 found_one = TRUE;
1669 }
1670
1671 /* No match found, stop scanning. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001672 if (!found_one)
1673 break;
1674
Bram Moolenaar81340392012-06-06 16:12:59 +02001675 result = i;
1676
Bram Moolenaara4271d52011-05-10 13:38:27 +02001677 /* Include any trailing white space. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001678 while (vim_iswhite(line[i]))
1679 ++i;
1680
Bram Moolenaar81340392012-06-06 16:12:59 +02001681 if (include_space)
1682 result = i;
1683
Bram Moolenaara4271d52011-05-10 13:38:27 +02001684 /* If this comment doesn't nest, stop here. */
1685 got_com = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001686 if (vim_strchr(part_buf, COM_NEST) == NULL)
1687 break;
1688 }
Bram Moolenaar81340392012-06-06 16:12:59 +02001689 return result;
1690}
Bram Moolenaara4271d52011-05-10 13:38:27 +02001691
Bram Moolenaar81340392012-06-06 16:12:59 +02001692/*
1693 * Return the offset at which the last comment in line starts. If there is no
1694 * comment in the whole line, -1 is returned.
1695 *
1696 * When "flags" is not null, it is set to point to the flags describing the
1697 * recognized comment leader.
1698 */
1699 int
1700get_last_leader_offset(line, flags)
1701 char_u *line;
1702 char_u **flags;
1703{
1704 int result = -1;
1705 int i, j;
1706 int lower_check_bound = 0;
1707 char_u *string;
1708 char_u *com_leader;
1709 char_u *com_flags;
1710 char_u *list;
1711 int found_one;
1712 char_u part_buf[COM_MAX_LEN]; /* buffer for one option part */
1713
1714 /*
1715 * Repeat to match several nested comment strings.
1716 */
1717 i = (int)STRLEN(line);
1718 while (--i >= lower_check_bound)
1719 {
1720 /*
1721 * scan through the 'comments' option for a match
1722 */
1723 found_one = FALSE;
1724 for (list = curbuf->b_p_com; *list; )
1725 {
1726 char_u *flags_save = list;
1727
1728 /*
1729 * Get one option part into part_buf[]. Advance list to next one.
1730 * put string at start of string.
1731 */
1732 (void)copy_option_part(&list, part_buf, COM_MAX_LEN, ",");
1733 string = vim_strchr(part_buf, ':');
1734 if (string == NULL) /* If everything is fine, this cannot actually
1735 * happen. */
1736 {
1737 continue;
1738 }
1739 *string++ = NUL; /* Isolate flags from string. */
1740 com_leader = string;
1741
1742 /*
1743 * Line contents and string must match.
1744 * When string starts with white space, must have some white space
1745 * (but the amount does not need to match, there might be a mix of
1746 * TABs and spaces).
1747 */
1748 if (vim_iswhite(string[0]))
1749 {
1750 if (i == 0 || !vim_iswhite(line[i - 1]))
1751 continue;
1752 while (vim_iswhite(string[0]))
1753 ++string;
1754 }
1755 for (j = 0; string[j] != NUL && string[j] == line[i + j]; ++j)
1756 /* do nothing */;
1757 if (string[j] != NUL)
1758 continue;
1759
1760 /*
1761 * When 'b' flag used, there must be white space or an
1762 * end-of-line after the string in the line.
1763 */
1764 if (vim_strchr(part_buf, COM_BLANK) != NULL
1765 && !vim_iswhite(line[i + j]) && line[i + j] != NUL)
1766 {
1767 continue;
1768 }
1769
1770 /*
1771 * We have found a match, stop searching.
1772 */
1773 found_one = TRUE;
1774
1775 if (flags)
1776 *flags = flags_save;
1777 com_flags = flags_save;
1778
1779 break;
1780 }
1781
1782 if (found_one)
1783 {
1784 char_u part_buf2[COM_MAX_LEN]; /* buffer for one option part */
1785 int len1, len2, off;
1786
1787 result = i;
1788 /*
1789 * If this comment nests, continue searching.
1790 */
1791 if (vim_strchr(part_buf, COM_NEST) != NULL)
1792 continue;
1793
1794 lower_check_bound = i;
1795
1796 /* Let's verify whether the comment leader found is a substring
1797 * of other comment leaders. If it is, let's adjust the
1798 * lower_check_bound so that we make sure that we have determined
1799 * the comment leader correctly.
1800 */
1801
1802 while (vim_iswhite(*com_leader))
1803 ++com_leader;
1804 len1 = (int)STRLEN(com_leader);
1805
1806 for (list = curbuf->b_p_com; *list; )
1807 {
1808 char_u *flags_save = list;
1809
1810 (void)copy_option_part(&list, part_buf2, COM_MAX_LEN, ",");
1811 if (flags_save == com_flags)
1812 continue;
1813 string = vim_strchr(part_buf2, ':');
1814 ++string;
1815 while (vim_iswhite(*string))
1816 ++string;
1817 len2 = (int)STRLEN(string);
1818 if (len2 == 0)
1819 continue;
1820
1821 /* Now we have to verify whether string ends with a substring
1822 * beginning the com_leader. */
1823 for (off = (len2 > i ? i : len2); off > 0 && off + len1 > len2;)
1824 {
1825 --off;
1826 if (!STRNCMP(string + off, com_leader, len2 - off))
1827 {
1828 if (i - off < lower_check_bound)
1829 lower_check_bound = i - off;
1830 }
1831 }
1832 }
1833 }
1834 }
1835 return result;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001836}
1837#endif
1838
1839/*
1840 * Return the number of window lines occupied by buffer line "lnum".
1841 */
1842 int
1843plines(lnum)
1844 linenr_T lnum;
1845{
1846 return plines_win(curwin, lnum, TRUE);
1847}
1848
1849 int
1850plines_win(wp, lnum, winheight)
1851 win_T *wp;
1852 linenr_T lnum;
1853 int winheight; /* when TRUE limit to window height */
1854{
1855#if defined(FEAT_DIFF) || defined(PROTO)
1856 /* Check for filler lines above this buffer line. When folded the result
1857 * is one line anyway. */
1858 return plines_win_nofill(wp, lnum, winheight) + diff_check_fill(wp, lnum);
1859}
1860
1861 int
1862plines_nofill(lnum)
1863 linenr_T lnum;
1864{
1865 return plines_win_nofill(curwin, lnum, TRUE);
1866}
1867
1868 int
1869plines_win_nofill(wp, lnum, winheight)
1870 win_T *wp;
1871 linenr_T lnum;
1872 int winheight; /* when TRUE limit to window height */
1873{
1874#endif
1875 int lines;
1876
1877 if (!wp->w_p_wrap)
1878 return 1;
1879
1880#ifdef FEAT_VERTSPLIT
1881 if (wp->w_width == 0)
1882 return 1;
1883#endif
1884
1885#ifdef FEAT_FOLDING
1886 /* A folded lines is handled just like an empty line. */
1887 /* NOTE: Caller must handle lines that are MAYBE folded. */
1888 if (lineFolded(wp, lnum) == TRUE)
1889 return 1;
1890#endif
1891
1892 lines = plines_win_nofold(wp, lnum);
1893 if (winheight > 0 && lines > wp->w_height)
1894 return (int)wp->w_height;
1895 return lines;
1896}
1897
1898/*
1899 * Return number of window lines physical line "lnum" will occupy in window
1900 * "wp". Does not care about folding, 'wrap' or 'diff'.
1901 */
1902 int
1903plines_win_nofold(wp, lnum)
1904 win_T *wp;
1905 linenr_T lnum;
1906{
1907 char_u *s;
1908 long col;
1909 int width;
1910
1911 s = ml_get_buf(wp->w_buffer, lnum, FALSE);
1912 if (*s == NUL) /* empty line */
1913 return 1;
1914 col = win_linetabsize(wp, s, (colnr_T)MAXCOL);
1915
1916 /*
1917 * If list mode is on, then the '$' at the end of the line may take up one
1918 * extra column.
1919 */
1920 if (wp->w_p_list && lcs_eol != NUL)
1921 col += 1;
1922
1923 /*
Bram Moolenaar64486672010-05-16 15:46:46 +02001924 * Add column offset for 'number', 'relativenumber' and 'foldcolumn'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001925 */
1926 width = W_WIDTH(wp) - win_col_off(wp);
1927 if (width <= 0)
1928 return 32000;
1929 if (col <= width)
1930 return 1;
1931 col -= width;
1932 width += win_col_off2(wp);
1933 return (col + (width - 1)) / width + 1;
1934}
1935
1936/*
1937 * Like plines_win(), but only reports the number of physical screen lines
1938 * used from the start of the line to the given column number.
1939 */
1940 int
1941plines_win_col(wp, lnum, column)
1942 win_T *wp;
1943 linenr_T lnum;
1944 long column;
1945{
1946 long col;
1947 char_u *s;
1948 int lines = 0;
1949 int width;
1950
1951#ifdef FEAT_DIFF
1952 /* Check for filler lines above this buffer line. When folded the result
1953 * is one line anyway. */
1954 lines = diff_check_fill(wp, lnum);
1955#endif
1956
1957 if (!wp->w_p_wrap)
1958 return lines + 1;
1959
1960#ifdef FEAT_VERTSPLIT
1961 if (wp->w_width == 0)
1962 return lines + 1;
1963#endif
1964
1965 s = ml_get_buf(wp->w_buffer, lnum, FALSE);
1966
1967 col = 0;
1968 while (*s != NUL && --column >= 0)
1969 {
1970 col += win_lbr_chartabsize(wp, s, (colnr_T)col, NULL);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001971 mb_ptr_adv(s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001972 }
1973
1974 /*
1975 * If *s is a TAB, and the TAB is not displayed as ^I, and we're not in
1976 * INSERT mode, then col must be adjusted so that it represents the last
1977 * screen position of the TAB. This only fixes an error when the TAB wraps
1978 * from one screen line to the next (when 'columns' is not a multiple of
1979 * 'ts') -- webb.
1980 */
1981 if (*s == TAB && (State & NORMAL) && (!wp->w_p_list || lcs_tab1))
1982 col += win_lbr_chartabsize(wp, s, (colnr_T)col, NULL) - 1;
1983
1984 /*
Bram Moolenaar64486672010-05-16 15:46:46 +02001985 * Add column offset for 'number', 'relativenumber', 'foldcolumn', etc.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001986 */
1987 width = W_WIDTH(wp) - win_col_off(wp);
Bram Moolenaar26470632006-10-24 19:12:40 +00001988 if (width <= 0)
1989 return 9999;
1990
1991 lines += 1;
1992 if (col > width)
1993 lines += (col - width) / (width + win_col_off2(wp)) + 1;
1994 return lines;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001995}
1996
1997 int
1998plines_m_win(wp, first, last)
1999 win_T *wp;
2000 linenr_T first, last;
2001{
2002 int count = 0;
2003
2004 while (first <= last)
2005 {
2006#ifdef FEAT_FOLDING
2007 int x;
2008
2009 /* Check if there are any really folded lines, but also included lines
2010 * that are maybe folded. */
2011 x = foldedCount(wp, first, NULL);
2012 if (x > 0)
2013 {
2014 ++count; /* count 1 for "+-- folded" line */
2015 first += x;
2016 }
2017 else
2018#endif
2019 {
2020#ifdef FEAT_DIFF
2021 if (first == wp->w_topline)
2022 count += plines_win_nofill(wp, first, TRUE) + wp->w_topfill;
2023 else
2024#endif
2025 count += plines_win(wp, first, TRUE);
2026 ++first;
2027 }
2028 }
2029 return (count);
2030}
2031
2032#if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) || defined(PROTO)
2033/*
2034 * Insert string "p" at the cursor position. Stops at a NUL byte.
2035 * Handles Replace mode and multi-byte characters.
2036 */
2037 void
2038ins_bytes(p)
2039 char_u *p;
2040{
2041 ins_bytes_len(p, (int)STRLEN(p));
2042}
2043#endif
2044
2045#if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) \
2046 || defined(FEAT_COMMENTS) || defined(FEAT_MBYTE) || defined(PROTO)
2047/*
2048 * Insert string "p" with length "len" at the cursor position.
2049 * Handles Replace mode and multi-byte characters.
2050 */
2051 void
2052ins_bytes_len(p, len)
2053 char_u *p;
2054 int len;
2055{
2056 int i;
2057# ifdef FEAT_MBYTE
2058 int n;
2059
Bram Moolenaar176dd1e2008-06-21 14:30:28 +00002060 if (has_mbyte)
2061 for (i = 0; i < len; i += n)
2062 {
2063 if (enc_utf8)
2064 /* avoid reading past p[len] */
2065 n = utfc_ptr2len_len(p + i, len - i);
2066 else
2067 n = (*mb_ptr2len)(p + i);
2068 ins_char_bytes(p + i, n);
2069 }
2070 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002071# endif
Bram Moolenaar176dd1e2008-06-21 14:30:28 +00002072 for (i = 0; i < len; ++i)
2073 ins_char(p[i]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002074}
2075#endif
2076
2077/*
2078 * Insert or replace a single character at the cursor position.
2079 * When in REPLACE or VREPLACE mode, replace any existing character.
2080 * Caller must have prepared for undo.
2081 * For multi-byte characters we get the whole character, the caller must
2082 * convert bytes to a character.
2083 */
2084 void
2085ins_char(c)
2086 int c;
2087{
2088#if defined(FEAT_MBYTE) || defined(PROTO)
Bram Moolenaar9a920d82012-06-01 15:21:02 +02002089 char_u buf[MB_MAXBYTES + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002090 int n;
2091
2092 n = (*mb_char2bytes)(c, buf);
2093
2094 /* When "c" is 0x100, 0x200, etc. we don't want to insert a NUL byte.
2095 * Happens for CTRL-Vu9900. */
2096 if (buf[0] == 0)
2097 buf[0] = '\n';
2098
2099 ins_char_bytes(buf, n);
2100}
2101
2102 void
2103ins_char_bytes(buf, charlen)
2104 char_u *buf;
2105 int charlen;
2106{
2107 int c = buf[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002108#endif
2109 int newlen; /* nr of bytes inserted */
2110 int oldlen; /* nr of bytes deleted (0 when not replacing) */
2111 char_u *p;
2112 char_u *newp;
2113 char_u *oldp;
2114 int linelen; /* length of old line including NUL */
2115 colnr_T col;
2116 linenr_T lnum = curwin->w_cursor.lnum;
2117 int i;
2118
2119#ifdef FEAT_VIRTUALEDIT
2120 /* Break tabs if needed. */
2121 if (virtual_active() && curwin->w_cursor.coladd > 0)
2122 coladvance_force(getviscol());
2123#endif
2124
2125 col = curwin->w_cursor.col;
2126 oldp = ml_get(lnum);
2127 linelen = (int)STRLEN(oldp) + 1;
2128
2129 /* The lengths default to the values for when not replacing. */
2130 oldlen = 0;
2131#ifdef FEAT_MBYTE
2132 newlen = charlen;
2133#else
2134 newlen = 1;
2135#endif
2136
2137 if (State & REPLACE_FLAG)
2138 {
2139#ifdef FEAT_VREPLACE
2140 if (State & VREPLACE_FLAG)
2141 {
2142 colnr_T new_vcol = 0; /* init for GCC */
2143 colnr_T vcol;
2144 int old_list;
2145#ifndef FEAT_MBYTE
2146 char_u buf[2];
2147#endif
2148
2149 /*
2150 * Disable 'list' temporarily, unless 'cpo' contains the 'L' flag.
2151 * Returns the old value of list, so when finished,
2152 * curwin->w_p_list should be set back to this.
2153 */
2154 old_list = curwin->w_p_list;
2155 if (old_list && vim_strchr(p_cpo, CPO_LISTWM) == NULL)
2156 curwin->w_p_list = FALSE;
2157
2158 /*
2159 * In virtual replace mode each character may replace one or more
2160 * characters (zero if it's a TAB). Count the number of bytes to
2161 * be deleted to make room for the new character, counting screen
2162 * cells. May result in adding spaces to fill a gap.
2163 */
2164 getvcol(curwin, &curwin->w_cursor, NULL, &vcol, NULL);
2165#ifndef FEAT_MBYTE
2166 buf[0] = c;
2167 buf[1] = NUL;
2168#endif
2169 new_vcol = vcol + chartabsize(buf, vcol);
2170 while (oldp[col + oldlen] != NUL && vcol < new_vcol)
2171 {
2172 vcol += chartabsize(oldp + col + oldlen, vcol);
2173 /* Don't need to remove a TAB that takes us to the right
2174 * position. */
2175 if (vcol > new_vcol && oldp[col + oldlen] == TAB)
2176 break;
2177#ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002178 oldlen += (*mb_ptr2len)(oldp + col + oldlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002179#else
2180 ++oldlen;
2181#endif
2182 /* Deleted a bit too much, insert spaces. */
2183 if (vcol > new_vcol)
2184 newlen += vcol - new_vcol;
2185 }
2186 curwin->w_p_list = old_list;
2187 }
2188 else
2189#endif
2190 if (oldp[col] != NUL)
2191 {
2192 /* normal replace */
2193#ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002194 oldlen = (*mb_ptr2len)(oldp + col);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002195#else
2196 oldlen = 1;
2197#endif
2198 }
2199
2200
2201 /* Push the replaced bytes onto the replace stack, so that they can be
2202 * put back when BS is used. The bytes of a multi-byte character are
2203 * done the other way around, so that the first byte is popped off
2204 * first (it tells the byte length of the character). */
2205 replace_push(NUL);
2206 for (i = 0; i < oldlen; ++i)
2207 {
2208#ifdef FEAT_MBYTE
Bram Moolenaar2c994e82008-01-02 16:49:36 +00002209 if (has_mbyte)
2210 i += replace_push_mb(oldp + col + i) - 1;
2211 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002212#endif
Bram Moolenaar2c994e82008-01-02 16:49:36 +00002213 replace_push(oldp[col + i]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002214 }
2215 }
2216
2217 newp = alloc_check((unsigned)(linelen + newlen - oldlen));
2218 if (newp == NULL)
2219 return;
2220
2221 /* Copy bytes before the cursor. */
2222 if (col > 0)
2223 mch_memmove(newp, oldp, (size_t)col);
2224
2225 /* Copy bytes after the changed character(s). */
2226 p = newp + col;
2227 mch_memmove(p + newlen, oldp + col + oldlen,
2228 (size_t)(linelen - col - oldlen));
2229
2230 /* Insert or overwrite the new character. */
2231#ifdef FEAT_MBYTE
2232 mch_memmove(p, buf, charlen);
2233 i = charlen;
2234#else
2235 *p = c;
2236 i = 1;
2237#endif
2238
2239 /* Fill with spaces when necessary. */
2240 while (i < newlen)
2241 p[i++] = ' ';
2242
2243 /* Replace the line in the buffer. */
2244 ml_replace(lnum, newp, FALSE);
2245
2246 /* mark the buffer as changed and prepare for displaying */
2247 changed_bytes(lnum, col);
2248
2249 /*
2250 * If we're in Insert or Replace mode and 'showmatch' is set, then briefly
2251 * show the match for right parens and braces.
2252 */
2253 if (p_sm && (State & INSERT)
2254 && msg_silent == 0
2255#ifdef FEAT_MBYTE
2256 && charlen == 1
2257#endif
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00002258#ifdef FEAT_INS_EXPAND
2259 && !ins_compl_active()
2260#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002261 )
2262 showmatch(c);
2263
2264#ifdef FEAT_RIGHTLEFT
2265 if (!p_ri || (State & REPLACE_FLAG))
2266#endif
2267 {
2268 /* Normal insert: move cursor right */
2269#ifdef FEAT_MBYTE
2270 curwin->w_cursor.col += charlen;
2271#else
2272 ++curwin->w_cursor.col;
2273#endif
2274 }
2275 /*
2276 * TODO: should try to update w_row here, to avoid recomputing it later.
2277 */
2278}
2279
2280/*
2281 * Insert a string at the cursor position.
2282 * Note: Does NOT handle Replace mode.
2283 * Caller must have prepared for undo.
2284 */
2285 void
2286ins_str(s)
2287 char_u *s;
2288{
2289 char_u *oldp, *newp;
2290 int newlen = (int)STRLEN(s);
2291 int oldlen;
2292 colnr_T col;
2293 linenr_T lnum = curwin->w_cursor.lnum;
2294
2295#ifdef FEAT_VIRTUALEDIT
2296 if (virtual_active() && curwin->w_cursor.coladd > 0)
2297 coladvance_force(getviscol());
2298#endif
2299
2300 col = curwin->w_cursor.col;
2301 oldp = ml_get(lnum);
2302 oldlen = (int)STRLEN(oldp);
2303
2304 newp = alloc_check((unsigned)(oldlen + newlen + 1));
2305 if (newp == NULL)
2306 return;
2307 if (col > 0)
2308 mch_memmove(newp, oldp, (size_t)col);
2309 mch_memmove(newp + col, s, (size_t)newlen);
2310 mch_memmove(newp + col + newlen, oldp + col, (size_t)(oldlen - col + 1));
2311 ml_replace(lnum, newp, FALSE);
2312 changed_bytes(lnum, col);
2313 curwin->w_cursor.col += newlen;
2314}
2315
2316/*
2317 * Delete one character under the cursor.
2318 * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
2319 * Caller must have prepared for undo.
2320 *
2321 * return FAIL for failure, OK otherwise
2322 */
2323 int
2324del_char(fixpos)
2325 int fixpos;
2326{
2327#ifdef FEAT_MBYTE
2328 if (has_mbyte)
2329 {
2330 /* Make sure the cursor is at the start of a character. */
2331 mb_adjust_cursor();
2332 if (*ml_get_cursor() == NUL)
2333 return FAIL;
2334 return del_chars(1L, fixpos);
2335 }
2336#endif
Bram Moolenaare3226be2005-12-18 22:10:00 +00002337 return del_bytes(1L, fixpos, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002338}
2339
2340#if defined(FEAT_MBYTE) || defined(PROTO)
2341/*
2342 * Like del_bytes(), but delete characters instead of bytes.
2343 */
2344 int
2345del_chars(count, fixpos)
2346 long count;
2347 int fixpos;
2348{
2349 long bytes = 0;
2350 long i;
2351 char_u *p;
2352 int l;
2353
2354 p = ml_get_cursor();
2355 for (i = 0; i < count && *p != NUL; ++i)
2356 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002357 l = (*mb_ptr2len)(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002358 bytes += l;
2359 p += l;
2360 }
Bram Moolenaare3226be2005-12-18 22:10:00 +00002361 return del_bytes(bytes, fixpos, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002362}
2363#endif
2364
2365/*
2366 * Delete "count" bytes under the cursor.
2367 * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
2368 * Caller must have prepared for undo.
2369 *
2370 * return FAIL for failure, OK otherwise
2371 */
2372 int
Bram Moolenaarca003e12006-03-17 23:19:38 +00002373del_bytes(count, fixpos_arg, use_delcombine)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002374 long count;
Bram Moolenaarca003e12006-03-17 23:19:38 +00002375 int fixpos_arg;
Bram Moolenaar78a15312009-05-15 19:33:18 +00002376 int use_delcombine UNUSED; /* 'delcombine' option applies */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002377{
2378 char_u *oldp, *newp;
2379 colnr_T oldlen;
2380 linenr_T lnum = curwin->w_cursor.lnum;
2381 colnr_T col = curwin->w_cursor.col;
2382 int was_alloced;
2383 long movelen;
Bram Moolenaarca003e12006-03-17 23:19:38 +00002384 int fixpos = fixpos_arg;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002385
2386 oldp = ml_get(lnum);
2387 oldlen = (int)STRLEN(oldp);
2388
2389 /*
2390 * Can't do anything when the cursor is on the NUL after the line.
2391 */
2392 if (col >= oldlen)
2393 return FAIL;
2394
2395#ifdef FEAT_MBYTE
2396 /* If 'delcombine' is set and deleting (less than) one character, only
2397 * delete the last combining character. */
Bram Moolenaare3226be2005-12-18 22:10:00 +00002398 if (p_deco && use_delcombine && enc_utf8
2399 && utfc_ptr2len(oldp + col) >= count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002400 {
Bram Moolenaar362e1a32006-03-06 23:29:24 +00002401 int cc[MAX_MCO];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002402 int n;
2403
Bram Moolenaar362e1a32006-03-06 23:29:24 +00002404 (void)utfc_ptr2char(oldp + col, cc);
2405 if (cc[0] != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002406 {
2407 /* Find the last composing char, there can be several. */
2408 n = col;
2409 do
2410 {
2411 col = n;
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002412 count = utf_ptr2len(oldp + n);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002413 n += count;
2414 } while (UTF_COMPOSINGLIKE(oldp + col, oldp + n));
2415 fixpos = 0;
2416 }
2417 }
2418#endif
2419
2420 /*
2421 * When count is too big, reduce it.
2422 */
2423 movelen = (long)oldlen - (long)col - count + 1; /* includes trailing NUL */
2424 if (movelen <= 1)
2425 {
2426 /*
2427 * If we just took off the last character of a non-blank line, and
Bram Moolenaarca003e12006-03-17 23:19:38 +00002428 * fixpos is TRUE, we don't want to end up positioned at the NUL,
2429 * unless "restart_edit" is set or 'virtualedit' contains "onemore".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002430 */
Bram Moolenaarca003e12006-03-17 23:19:38 +00002431 if (col > 0 && fixpos && restart_edit == 0
2432#ifdef FEAT_VIRTUALEDIT
2433 && (ve_flags & VE_ONEMORE) == 0
2434#endif
2435 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00002436 {
2437 --curwin->w_cursor.col;
2438#ifdef FEAT_VIRTUALEDIT
2439 curwin->w_cursor.coladd = 0;
2440#endif
2441#ifdef FEAT_MBYTE
2442 if (has_mbyte)
2443 curwin->w_cursor.col -=
2444 (*mb_head_off)(oldp, oldp + curwin->w_cursor.col);
2445#endif
2446 }
2447 count = oldlen - col;
2448 movelen = 1;
2449 }
2450
2451 /*
2452 * If the old line has been allocated the deletion can be done in the
2453 * existing line. Otherwise a new line has to be allocated
Bram Moolenaare21877a2008-02-13 09:58:14 +00002454 * Can't do this when using Netbeans, because we would need to invoke
2455 * netbeans_removed(), which deallocates the line. Let ml_replace() take
Bram Moolenaar1a509df2010-08-01 17:59:57 +02002456 * care of notifying Netbeans.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002457 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002458#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02002459 if (netbeans_active())
Bram Moolenaare21877a2008-02-13 09:58:14 +00002460 was_alloced = FALSE;
2461 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002462#endif
Bram Moolenaare21877a2008-02-13 09:58:14 +00002463 was_alloced = ml_line_alloced(); /* check if oldp was allocated */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002464 if (was_alloced)
2465 newp = oldp; /* use same allocated memory */
2466 else
2467 { /* need to allocate a new line */
2468 newp = alloc((unsigned)(oldlen + 1 - count));
2469 if (newp == NULL)
2470 return FAIL;
2471 mch_memmove(newp, oldp, (size_t)col);
2472 }
2473 mch_memmove(newp + col, oldp + col + count, (size_t)movelen);
2474 if (!was_alloced)
2475 ml_replace(lnum, newp, FALSE);
2476
2477 /* mark the buffer as changed and prepare for displaying */
2478 changed_bytes(lnum, curwin->w_cursor.col);
2479
2480 return OK;
2481}
2482
2483/*
2484 * Delete from cursor to end of line.
2485 * Caller must have prepared for undo.
2486 *
2487 * return FAIL for failure, OK otherwise
2488 */
2489 int
2490truncate_line(fixpos)
2491 int fixpos; /* if TRUE fix the cursor position when done */
2492{
2493 char_u *newp;
2494 linenr_T lnum = curwin->w_cursor.lnum;
2495 colnr_T col = curwin->w_cursor.col;
2496
2497 if (col == 0)
2498 newp = vim_strsave((char_u *)"");
2499 else
2500 newp = vim_strnsave(ml_get(lnum), col);
2501
2502 if (newp == NULL)
2503 return FAIL;
2504
2505 ml_replace(lnum, newp, FALSE);
2506
2507 /* mark the buffer as changed and prepare for displaying */
2508 changed_bytes(lnum, curwin->w_cursor.col);
2509
2510 /*
2511 * If "fixpos" is TRUE we don't want to end up positioned at the NUL.
2512 */
2513 if (fixpos && curwin->w_cursor.col > 0)
2514 --curwin->w_cursor.col;
2515
2516 return OK;
2517}
2518
2519/*
2520 * Delete "nlines" lines at the cursor.
2521 * Saves the lines for undo first if "undo" is TRUE.
2522 */
2523 void
2524del_lines(nlines, undo)
2525 long nlines; /* number of lines to delete */
2526 int undo; /* if TRUE, prepare for undo */
2527{
2528 long n;
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002529 linenr_T first = curwin->w_cursor.lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002530
2531 if (nlines <= 0)
2532 return;
2533
2534 /* save the deleted lines for undo */
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002535 if (undo && u_savedel(first, nlines) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002536 return;
2537
2538 for (n = 0; n < nlines; )
2539 {
2540 if (curbuf->b_ml.ml_flags & ML_EMPTY) /* nothing to delete */
2541 break;
2542
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002543 ml_delete(first, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002544 ++n;
2545
2546 /* If we delete the last line in the file, stop */
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002547 if (first > curbuf->b_ml.ml_line_count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002548 break;
2549 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002550
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002551 /* Correct the cursor position before calling deleted_lines_mark(), it may
2552 * trigger a callback to display the cursor. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002553 curwin->w_cursor.col = 0;
2554 check_cursor_lnum();
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002555
2556 /* adjust marks, mark the buffer as changed and prepare for displaying */
2557 deleted_lines_mark(first, n);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002558}
2559
2560 int
2561gchar_pos(pos)
2562 pos_T *pos;
2563{
2564 char_u *ptr = ml_get_pos(pos);
2565
2566#ifdef FEAT_MBYTE
2567 if (has_mbyte)
2568 return (*mb_ptr2char)(ptr);
2569#endif
2570 return (int)*ptr;
2571}
2572
2573 int
2574gchar_cursor()
2575{
2576#ifdef FEAT_MBYTE
2577 if (has_mbyte)
2578 return (*mb_ptr2char)(ml_get_cursor());
2579#endif
2580 return (int)*ml_get_cursor();
2581}
2582
2583/*
2584 * Write a character at the current cursor position.
2585 * It is directly written into the block.
2586 */
2587 void
2588pchar_cursor(c)
2589 int c;
2590{
2591 *(ml_get_buf(curbuf, curwin->w_cursor.lnum, TRUE)
2592 + curwin->w_cursor.col) = c;
2593}
2594
Bram Moolenaar071d4272004-06-13 20:20:40 +00002595/*
2596 * When extra == 0: Return TRUE if the cursor is before or on the first
2597 * non-blank in the line.
2598 * When extra == 1: Return TRUE if the cursor is before the first non-blank in
2599 * the line.
2600 */
2601 int
2602inindent(extra)
2603 int extra;
2604{
2605 char_u *ptr;
2606 colnr_T col;
2607
2608 for (col = 0, ptr = ml_get_curline(); vim_iswhite(*ptr); ++col)
2609 ++ptr;
2610 if (col >= curwin->w_cursor.col + extra)
2611 return TRUE;
2612 else
2613 return FALSE;
2614}
2615
2616/*
2617 * Skip to next part of an option argument: Skip space and comma.
2618 */
2619 char_u *
2620skip_to_option_part(p)
2621 char_u *p;
2622{
2623 if (*p == ',')
2624 ++p;
2625 while (*p == ' ')
2626 ++p;
2627 return p;
2628}
2629
2630/*
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002631 * Call this function when something in the current buffer is changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002632 *
2633 * Most often called through changed_bytes() and changed_lines(), which also
2634 * mark the area of the display to be redrawn.
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002635 *
2636 * Careful: may trigger autocommands that reload the buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002637 */
2638 void
2639changed()
2640{
2641#if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
2642 /* The text of the preediting area is inserted, but this doesn't
2643 * mean a change of the buffer yet. That is delayed until the
2644 * text is committed. (this means preedit becomes empty) */
2645 if (im_is_preediting() && !xim_changed_while_preediting)
2646 return;
2647 xim_changed_while_preediting = FALSE;
2648#endif
2649
2650 if (!curbuf->b_changed)
2651 {
2652 int save_msg_scroll = msg_scroll;
2653
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002654 /* Give a warning about changing a read-only file. This may also
2655 * check-out the file, thus change "curbuf"! */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002656 change_warning(0);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002657
Bram Moolenaar071d4272004-06-13 20:20:40 +00002658 /* Create a swap file if that is wanted.
2659 * Don't do this for "nofile" and "nowrite" buffer types. */
2660 if (curbuf->b_may_swap
2661#ifdef FEAT_QUICKFIX
2662 && !bt_dontwrite(curbuf)
2663#endif
2664 )
2665 {
2666 ml_open_file(curbuf);
2667
2668 /* The ml_open_file() can cause an ATTENTION message.
2669 * Wait two seconds, to make sure the user reads this unexpected
2670 * message. Since we could be anywhere, call wait_return() now,
2671 * and don't let the emsg() set msg_scroll. */
2672 if (need_wait_return && emsg_silent == 0)
2673 {
2674 out_flush();
2675 ui_delay(2000L, TRUE);
2676 wait_return(TRUE);
2677 msg_scroll = save_msg_scroll;
2678 }
2679 }
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02002680 changed_int();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002681 }
2682 ++curbuf->b_changedtick;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002683}
2684
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02002685/*
2686 * Internal part of changed(), no user interaction.
2687 */
2688 void
2689changed_int()
2690{
2691 curbuf->b_changed = TRUE;
2692 ml_setflags(curbuf);
2693#ifdef FEAT_WINDOWS
2694 check_status(curbuf);
2695 redraw_tabline = TRUE;
2696#endif
2697#ifdef FEAT_TITLE
2698 need_maketitle = TRUE; /* set window title later */
2699#endif
2700}
2701
Bram Moolenaardba8a912005-04-24 22:08:39 +00002702static void changedOneline __ARGS((buf_T *buf, linenr_T lnum));
2703static void changed_lines_buf __ARGS((buf_T *buf, linenr_T lnum, linenr_T lnume, long xtra));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002704static void changed_common __ARGS((linenr_T lnum, colnr_T col, linenr_T lnume, long xtra));
2705
2706/*
2707 * Changed bytes within a single line for the current buffer.
2708 * - marks the windows on this buffer to be redisplayed
2709 * - marks the buffer changed by calling changed()
2710 * - invalidates cached values
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002711 * Careful: may trigger autocommands that reload the buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002712 */
2713 void
2714changed_bytes(lnum, col)
2715 linenr_T lnum;
2716 colnr_T col;
2717{
Bram Moolenaardba8a912005-04-24 22:08:39 +00002718 changedOneline(curbuf, lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002719 changed_common(lnum, col, lnum + 1, 0L);
Bram Moolenaardba8a912005-04-24 22:08:39 +00002720
2721#ifdef FEAT_DIFF
2722 /* Diff highlighting in other diff windows may need to be updated too. */
2723 if (curwin->w_p_diff)
2724 {
2725 win_T *wp;
2726 linenr_T wlnum;
2727
2728 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2729 if (wp->w_p_diff && wp != curwin)
2730 {
2731 redraw_win_later(wp, VALID);
2732 wlnum = diff_lnum_win(lnum, wp);
2733 if (wlnum > 0)
2734 changedOneline(wp->w_buffer, wlnum);
2735 }
2736 }
2737#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002738}
2739
2740 static void
Bram Moolenaardba8a912005-04-24 22:08:39 +00002741changedOneline(buf, lnum)
2742 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002743 linenr_T lnum;
2744{
Bram Moolenaardba8a912005-04-24 22:08:39 +00002745 if (buf->b_mod_set)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002746 {
2747 /* find the maximum area that must be redisplayed */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002748 if (lnum < buf->b_mod_top)
2749 buf->b_mod_top = lnum;
2750 else if (lnum >= buf->b_mod_bot)
2751 buf->b_mod_bot = lnum + 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002752 }
2753 else
2754 {
2755 /* set the area that must be redisplayed to one line */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002756 buf->b_mod_set = TRUE;
2757 buf->b_mod_top = lnum;
2758 buf->b_mod_bot = lnum + 1;
2759 buf->b_mod_xlines = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002760 }
2761}
2762
2763/*
2764 * Appended "count" lines below line "lnum" in the current buffer.
2765 * Must be called AFTER the change and after mark_adjust().
2766 * Takes care of marking the buffer to be redrawn and sets the changed flag.
2767 */
2768 void
2769appended_lines(lnum, count)
2770 linenr_T lnum;
2771 long count;
2772{
2773 changed_lines(lnum + 1, 0, lnum + 1, count);
2774}
2775
2776/*
2777 * Like appended_lines(), but adjust marks first.
2778 */
2779 void
2780appended_lines_mark(lnum, count)
2781 linenr_T lnum;
2782 long count;
2783{
2784 mark_adjust(lnum + 1, (linenr_T)MAXLNUM, count, 0L);
2785 changed_lines(lnum + 1, 0, lnum + 1, count);
2786}
2787
2788/*
2789 * Deleted "count" lines at line "lnum" in the current buffer.
2790 * Must be called AFTER the change and after mark_adjust().
2791 * Takes care of marking the buffer to be redrawn and sets the changed flag.
2792 */
2793 void
2794deleted_lines(lnum, count)
2795 linenr_T lnum;
2796 long count;
2797{
2798 changed_lines(lnum, 0, lnum + count, -count);
2799}
2800
2801/*
2802 * Like deleted_lines(), but adjust marks first.
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002803 * Make sure the cursor is on a valid line before calling, a GUI callback may
2804 * be triggered to display the cursor.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002805 */
2806 void
2807deleted_lines_mark(lnum, count)
2808 linenr_T lnum;
2809 long count;
2810{
2811 mark_adjust(lnum, (linenr_T)(lnum + count - 1), (long)MAXLNUM, -count);
2812 changed_lines(lnum, 0, lnum + count, -count);
2813}
2814
2815/*
2816 * Changed lines for the current buffer.
2817 * Must be called AFTER the change and after mark_adjust().
2818 * - mark the buffer changed by calling changed()
2819 * - mark the windows on this buffer to be redisplayed
2820 * - invalidate cached values
2821 * "lnum" is the first line that needs displaying, "lnume" the first line
2822 * below the changed lines (BEFORE the change).
2823 * When only inserting lines, "lnum" and "lnume" are equal.
2824 * Takes care of calling changed() and updating b_mod_*.
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002825 * Careful: may trigger autocommands that reload the buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002826 */
2827 void
2828changed_lines(lnum, col, lnume, xtra)
2829 linenr_T lnum; /* first line with change */
2830 colnr_T col; /* column in first line with change */
2831 linenr_T lnume; /* line below last changed line */
2832 long xtra; /* number of extra lines (negative when deleting) */
2833{
Bram Moolenaardba8a912005-04-24 22:08:39 +00002834 changed_lines_buf(curbuf, lnum, lnume, xtra);
2835
2836#ifdef FEAT_DIFF
2837 if (xtra == 0 && curwin->w_p_diff)
2838 {
2839 /* When the number of lines doesn't change then mark_adjust() isn't
2840 * called and other diff buffers still need to be marked for
2841 * displaying. */
2842 win_T *wp;
2843 linenr_T wlnum;
2844
2845 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2846 if (wp->w_p_diff && wp != curwin)
2847 {
2848 redraw_win_later(wp, VALID);
2849 wlnum = diff_lnum_win(lnum, wp);
2850 if (wlnum > 0)
2851 changed_lines_buf(wp->w_buffer, wlnum,
2852 lnume - lnum + wlnum, 0L);
2853 }
2854 }
2855#endif
2856
2857 changed_common(lnum, col, lnume, xtra);
2858}
2859
2860 static void
2861changed_lines_buf(buf, lnum, lnume, xtra)
2862 buf_T *buf;
2863 linenr_T lnum; /* first line with change */
2864 linenr_T lnume; /* line below last changed line */
2865 long xtra; /* number of extra lines (negative when deleting) */
2866{
2867 if (buf->b_mod_set)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002868 {
2869 /* find the maximum area that must be redisplayed */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002870 if (lnum < buf->b_mod_top)
2871 buf->b_mod_top = lnum;
2872 if (lnum < buf->b_mod_bot)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002873 {
2874 /* adjust old bot position for xtra lines */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002875 buf->b_mod_bot += xtra;
2876 if (buf->b_mod_bot < lnum)
2877 buf->b_mod_bot = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002878 }
Bram Moolenaardba8a912005-04-24 22:08:39 +00002879 if (lnume + xtra > buf->b_mod_bot)
2880 buf->b_mod_bot = lnume + xtra;
2881 buf->b_mod_xlines += xtra;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002882 }
2883 else
2884 {
2885 /* set the area that must be redisplayed */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002886 buf->b_mod_set = TRUE;
2887 buf->b_mod_top = lnum;
2888 buf->b_mod_bot = lnume + xtra;
2889 buf->b_mod_xlines = xtra;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002890 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002891}
2892
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002893/*
2894 * Common code for when a change is was made.
2895 * See changed_lines() for the arguments.
2896 * Careful: may trigger autocommands that reload the buffer.
2897 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002898 static void
2899changed_common(lnum, col, lnume, xtra)
2900 linenr_T lnum;
2901 colnr_T col;
2902 linenr_T lnume;
2903 long xtra;
2904{
2905 win_T *wp;
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00002906#ifdef FEAT_WINDOWS
2907 tabpage_T *tp;
2908#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002909 int i;
2910#ifdef FEAT_JUMPLIST
2911 int cols;
2912 pos_T *p;
2913 int add;
2914#endif
2915
2916 /* mark the buffer as modified */
2917 changed();
2918
2919 /* set the '. mark */
2920 if (!cmdmod.keepjumps)
2921 {
2922 curbuf->b_last_change.lnum = lnum;
2923 curbuf->b_last_change.col = col;
2924
2925#ifdef FEAT_JUMPLIST
2926 /* Create a new entry if a new undo-able change was started or we
2927 * don't have an entry yet. */
2928 if (curbuf->b_new_change || curbuf->b_changelistlen == 0)
2929 {
2930 if (curbuf->b_changelistlen == 0)
2931 add = TRUE;
2932 else
2933 {
2934 /* Don't create a new entry when the line number is the same
2935 * as the last one and the column is not too far away. Avoids
2936 * creating many entries for typing "xxxxx". */
2937 p = &curbuf->b_changelist[curbuf->b_changelistlen - 1];
2938 if (p->lnum != lnum)
2939 add = TRUE;
2940 else
2941 {
2942 cols = comp_textwidth(FALSE);
2943 if (cols == 0)
2944 cols = 79;
2945 add = (p->col + cols < col || col + cols < p->col);
2946 }
2947 }
2948 if (add)
2949 {
2950 /* This is the first of a new sequence of undo-able changes
2951 * and it's at some distance of the last change. Use a new
2952 * position in the changelist. */
2953 curbuf->b_new_change = FALSE;
2954
2955 if (curbuf->b_changelistlen == JUMPLISTSIZE)
2956 {
2957 /* changelist is full: remove oldest entry */
2958 curbuf->b_changelistlen = JUMPLISTSIZE - 1;
2959 mch_memmove(curbuf->b_changelist, curbuf->b_changelist + 1,
2960 sizeof(pos_T) * (JUMPLISTSIZE - 1));
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00002961 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002962 {
2963 /* Correct position in changelist for other windows on
2964 * this buffer. */
2965 if (wp->w_buffer == curbuf && wp->w_changelistidx > 0)
2966 --wp->w_changelistidx;
2967 }
2968 }
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00002969 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002970 {
2971 /* For other windows, if the position in the changelist is
2972 * at the end it stays at the end. */
2973 if (wp->w_buffer == curbuf
2974 && wp->w_changelistidx == curbuf->b_changelistlen)
2975 ++wp->w_changelistidx;
2976 }
2977 ++curbuf->b_changelistlen;
2978 }
2979 }
2980 curbuf->b_changelist[curbuf->b_changelistlen - 1] =
2981 curbuf->b_last_change;
2982 /* The current window is always after the last change, so that "g,"
2983 * takes you back to it. */
2984 curwin->w_changelistidx = curbuf->b_changelistlen;
2985#endif
2986 }
2987
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00002988 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002989 {
2990 if (wp->w_buffer == curbuf)
2991 {
2992 /* Mark this window to be redrawn later. */
2993 if (wp->w_redr_type < VALID)
2994 wp->w_redr_type = VALID;
2995
2996 /* Check if a change in the buffer has invalidated the cached
2997 * values for the cursor. */
2998#ifdef FEAT_FOLDING
2999 /*
3000 * Update the folds for this window. Can't postpone this, because
3001 * a following operator might work on the whole fold: ">>dd".
3002 */
3003 foldUpdate(wp, lnum, lnume + xtra - 1);
3004
3005 /* The change may cause lines above or below the change to become
3006 * included in a fold. Set lnum/lnume to the first/last line that
3007 * might be displayed differently.
3008 * Set w_cline_folded here as an efficient way to update it when
3009 * inserting lines just above a closed fold. */
3010 i = hasFoldingWin(wp, lnum, &lnum, NULL, FALSE, NULL);
3011 if (wp->w_cursor.lnum == lnum)
3012 wp->w_cline_folded = i;
3013 i = hasFoldingWin(wp, lnume, NULL, &lnume, FALSE, NULL);
3014 if (wp->w_cursor.lnum == lnume)
3015 wp->w_cline_folded = i;
3016
3017 /* If the changed line is in a range of previously folded lines,
3018 * compare with the first line in that range. */
3019 if (wp->w_cursor.lnum <= lnum)
3020 {
3021 i = find_wl_entry(wp, lnum);
3022 if (i >= 0 && wp->w_cursor.lnum > wp->w_lines[i].wl_lnum)
3023 changed_line_abv_curs_win(wp);
3024 }
3025#endif
3026
3027 if (wp->w_cursor.lnum > lnum)
3028 changed_line_abv_curs_win(wp);
3029 else if (wp->w_cursor.lnum == lnum && wp->w_cursor.col >= col)
3030 changed_cline_bef_curs_win(wp);
3031 if (wp->w_botline >= lnum)
3032 {
3033 /* Assume that botline doesn't change (inserted lines make
3034 * other lines scroll down below botline). */
3035 approximate_botline_win(wp);
3036 }
3037
3038 /* Check if any w_lines[] entries have become invalid.
3039 * For entries below the change: Correct the lnums for
3040 * inserted/deleted lines. Makes it possible to stop displaying
3041 * after the change. */
3042 for (i = 0; i < wp->w_lines_valid; ++i)
3043 if (wp->w_lines[i].wl_valid)
3044 {
3045 if (wp->w_lines[i].wl_lnum >= lnum)
3046 {
3047 if (wp->w_lines[i].wl_lnum < lnume)
3048 {
3049 /* line included in change */
3050 wp->w_lines[i].wl_valid = FALSE;
3051 }
3052 else if (xtra != 0)
3053 {
3054 /* line below change */
3055 wp->w_lines[i].wl_lnum += xtra;
3056#ifdef FEAT_FOLDING
3057 wp->w_lines[i].wl_lastlnum += xtra;
3058#endif
3059 }
3060 }
3061#ifdef FEAT_FOLDING
3062 else if (wp->w_lines[i].wl_lastlnum >= lnum)
3063 {
3064 /* change somewhere inside this range of folded lines,
3065 * may need to be redrawn */
3066 wp->w_lines[i].wl_valid = FALSE;
3067 }
3068#endif
3069 }
Bram Moolenaar3234cc62009-11-03 17:47:12 +00003070
3071#ifdef FEAT_FOLDING
3072 /* Take care of side effects for setting w_topline when folds have
3073 * changed. Esp. when the buffer was changed in another window. */
3074 if (hasAnyFolding(wp))
3075 set_topline(wp, wp->w_topline);
3076#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003077 }
3078 }
3079
3080 /* Call update_screen() later, which checks out what needs to be redrawn,
3081 * since it notices b_mod_set and then uses b_mod_*. */
3082 if (must_redraw < VALID)
3083 must_redraw = VALID;
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00003084
3085#ifdef FEAT_AUTOCMD
3086 /* when the cursor line is changed always trigger CursorMoved */
Bram Moolenaare163f1c2006-10-17 09:12:21 +00003087 if (lnum <= curwin->w_cursor.lnum
3088 && lnume + (xtra < 0 ? -xtra : xtra) > curwin->w_cursor.lnum)
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00003089 last_cursormoved.lnum = 0;
3090#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003091}
3092
3093/*
3094 * unchanged() is called when the changed flag must be reset for buffer 'buf'
3095 */
3096 void
3097unchanged(buf, ff)
3098 buf_T *buf;
3099 int ff; /* also reset 'fileformat' */
3100{
Bram Moolenaar164c60f2011-01-22 00:11:50 +01003101 if (buf->b_changed || (ff && file_ff_differs(buf, FALSE)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003102 {
3103 buf->b_changed = 0;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003104 ml_setflags(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003105 if (ff)
3106 save_file_ff(buf);
3107#ifdef FEAT_WINDOWS
3108 check_status(buf);
Bram Moolenaar997fb4b2006-02-17 21:53:23 +00003109 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003110#endif
3111#ifdef FEAT_TITLE
3112 need_maketitle = TRUE; /* set window title later */
3113#endif
3114 }
3115 ++buf->b_changedtick;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003116#ifdef FEAT_NETBEANS_INTG
3117 netbeans_unmodified(buf);
3118#endif
3119}
3120
3121#if defined(FEAT_WINDOWS) || defined(PROTO)
3122/*
3123 * check_status: called when the status bars for the buffer 'buf'
3124 * need to be updated
3125 */
3126 void
3127check_status(buf)
3128 buf_T *buf;
3129{
3130 win_T *wp;
3131
3132 for (wp = firstwin; wp != NULL; wp = wp->w_next)
3133 if (wp->w_buffer == buf && wp->w_status_height)
3134 {
3135 wp->w_redr_status = TRUE;
3136 if (must_redraw < VALID)
3137 must_redraw = VALID;
3138 }
3139}
3140#endif
3141
3142/*
3143 * If the file is readonly, give a warning message with the first change.
3144 * Don't do this for autocommands.
3145 * Don't use emsg(), because it flushes the macro buffer.
Bram Moolenaard5cdbeb2005-10-10 20:59:28 +00003146 * If we have undone all changes b_changed will be FALSE, but "b_did_warn"
Bram Moolenaar071d4272004-06-13 20:20:40 +00003147 * will be TRUE.
Bram Moolenaarb0b50882010-07-07 18:26:28 +02003148 * Careful: may trigger autocommands that reload the buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003149 */
3150 void
3151change_warning(col)
3152 int col; /* column for message; non-zero when in insert
3153 mode and 'showmode' is on */
3154{
Bram Moolenaar496c5262009-03-18 14:42:00 +00003155 static char *w_readonly = N_("W10: Warning: Changing a readonly file");
3156
Bram Moolenaar071d4272004-06-13 20:20:40 +00003157 if (curbuf->b_did_warn == FALSE
3158 && curbufIsChanged() == 0
3159#ifdef FEAT_AUTOCMD
3160 && !autocmd_busy
3161#endif
3162 && curbuf->b_p_ro)
3163 {
3164#ifdef FEAT_AUTOCMD
Bram Moolenaar910f66f2006-04-05 20:41:53 +00003165 ++curbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003166 apply_autocmds(EVENT_FILECHANGEDRO, NULL, NULL, FALSE, curbuf);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00003167 --curbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003168 if (!curbuf->b_p_ro)
3169 return;
3170#endif
3171 /*
3172 * Do what msg() does, but with a column offset if the warning should
3173 * be after the mode message.
3174 */
3175 msg_start();
3176 if (msg_row == Rows - 1)
3177 msg_col = col;
Bram Moolenaar2df6dcc2004-07-12 15:53:54 +00003178 msg_source(hl_attr(HLF_W));
Bram Moolenaar496c5262009-03-18 14:42:00 +00003179 MSG_PUTS_ATTR(_(w_readonly), hl_attr(HLF_W) | MSG_HIST);
3180#ifdef FEAT_EVAL
3181 set_vim_var_string(VV_WARNINGMSG, (char_u *)_(w_readonly), -1);
3182#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003183 msg_clr_eos();
3184 (void)msg_end();
3185 if (msg_silent == 0 && !silent_mode)
3186 {
3187 out_flush();
3188 ui_delay(1000L, TRUE); /* give the user time to think about it */
3189 }
3190 curbuf->b_did_warn = TRUE;
3191 redraw_cmdline = FALSE; /* don't redraw and erase the message */
3192 if (msg_row < Rows - 1)
3193 showmode();
3194 }
3195}
3196
3197/*
3198 * Ask for a reply from the user, a 'y' or a 'n'.
3199 * No other characters are accepted, the message is repeated until a valid
3200 * reply is entered or CTRL-C is hit.
3201 * If direct is TRUE, don't use vgetc() but ui_inchar(), don't get characters
3202 * from any buffers but directly from the user.
3203 *
3204 * return the 'y' or 'n'
3205 */
3206 int
3207ask_yesno(str, direct)
3208 char_u *str;
3209 int direct;
3210{
3211 int r = ' ';
3212 int save_State = State;
3213
3214 if (exiting) /* put terminal in raw mode for this question */
3215 settmode(TMODE_RAW);
3216 ++no_wait_return;
3217#ifdef USE_ON_FLY_SCROLL
3218 dont_scroll = TRUE; /* disallow scrolling here */
3219#endif
3220 State = CONFIRM; /* mouse behaves like with :confirm */
3221#ifdef FEAT_MOUSE
3222 setmouse(); /* disables mouse for xterm */
3223#endif
3224 ++no_mapping;
3225 ++allow_keys; /* no mapping here, but recognize keys */
3226
3227 while (r != 'y' && r != 'n')
3228 {
3229 /* same highlighting as for wait_return */
3230 smsg_attr(hl_attr(HLF_R), (char_u *)"%s (y/n)?", str);
3231 if (direct)
3232 r = get_keystroke();
3233 else
Bram Moolenaar913626c2008-01-03 11:43:42 +00003234 r = plain_vgetc();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003235 if (r == Ctrl_C || r == ESC)
3236 r = 'n';
3237 msg_putchar(r); /* show what you typed */
3238 out_flush();
3239 }
3240 --no_wait_return;
3241 State = save_State;
3242#ifdef FEAT_MOUSE
3243 setmouse();
3244#endif
3245 --no_mapping;
3246 --allow_keys;
3247
3248 return r;
3249}
3250
3251/*
3252 * Get a key stroke directly from the user.
3253 * Ignores mouse clicks and scrollbar events, except a click for the left
3254 * button (used at the more prompt).
3255 * Doesn't use vgetc(), because it syncs undo and eats mapped characters.
3256 * Disadvantage: typeahead is ignored.
3257 * Translates the interrupt character for unix to ESC.
3258 */
3259 int
3260get_keystroke()
3261{
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003262 char_u *buf = NULL;
3263 int buflen = 150;
3264 int maxlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003265 int len = 0;
3266 int n;
3267 int save_mapped_ctrl_c = mapped_ctrl_c;
Bram Moolenaar4395a712006-09-05 18:57:57 +00003268 int waited = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003269
3270 mapped_ctrl_c = FALSE; /* mappings are not used here */
3271 for (;;)
3272 {
3273 cursor_on();
3274 out_flush();
3275
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003276 /* Leave some room for check_termcode() to insert a key code into (max
3277 * 5 chars plus NUL). And fix_input_buffer() can triple the number of
3278 * bytes. */
3279 maxlen = (buflen - 6 - len) / 3;
3280 if (buf == NULL)
3281 buf = alloc(buflen);
3282 else if (maxlen < 10)
3283 {
3284 /* Need some more space. This migth happen when receiving a long
3285 * escape sequence. */
3286 buflen += 100;
3287 buf = vim_realloc(buf, buflen);
3288 maxlen = (buflen - 6 - len) / 3;
3289 }
3290 if (buf == NULL)
3291 {
3292 do_outofmem_msg((long_u)buflen);
3293 return ESC; /* panic! */
3294 }
3295
Bram Moolenaar071d4272004-06-13 20:20:40 +00003296 /* First time: blocking wait. Second time: wait up to 100ms for a
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003297 * terminal code to complete. */
3298 n = ui_inchar(buf + len, maxlen, len == 0 ? -1L : 100L, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003299 if (n > 0)
3300 {
3301 /* Replace zero and CSI by a special key code. */
3302 n = fix_input_buffer(buf + len, n, FALSE);
3303 len += n;
Bram Moolenaar4395a712006-09-05 18:57:57 +00003304 waited = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003305 }
Bram Moolenaar4395a712006-09-05 18:57:57 +00003306 else if (len > 0)
3307 ++waited; /* keep track of the waiting time */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003308
Bram Moolenaar4395a712006-09-05 18:57:57 +00003309 /* Incomplete termcode and not timed out yet: get more characters */
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003310 if ((n = check_termcode(1, buf, buflen, &len)) < 0
Bram Moolenaar4395a712006-09-05 18:57:57 +00003311 && (!p_ttimeout || waited * 100L < (p_ttm < 0 ? p_tm : p_ttm)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003312 continue;
Bram Moolenaar4395a712006-09-05 18:57:57 +00003313
Bram Moolenaar946ffd42010-12-30 12:30:31 +01003314 if (n == KEYLEN_REMOVED) /* key code removed */
Bram Moolenaar6eb634e2011-03-03 15:04:08 +01003315 {
Bram Moolenaarfd30cd42011-03-22 13:07:26 +01003316 if (must_redraw != 0 && !need_wait_return && (State & CMDLINE) == 0)
Bram Moolenaar6eb634e2011-03-03 15:04:08 +01003317 {
3318 /* Redrawing was postponed, do it now. */
3319 update_screen(0);
3320 setcursor(); /* put cursor back where it belongs */
3321 }
Bram Moolenaar946ffd42010-12-30 12:30:31 +01003322 continue;
Bram Moolenaar6eb634e2011-03-03 15:04:08 +01003323 }
Bram Moolenaar946ffd42010-12-30 12:30:31 +01003324 if (n > 0) /* found a termcode: adjust length */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003325 len = n;
Bram Moolenaar946ffd42010-12-30 12:30:31 +01003326 if (len == 0) /* nothing typed yet */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003327 continue;
3328
3329 /* Handle modifier and/or special key code. */
3330 n = buf[0];
3331 if (n == K_SPECIAL)
3332 {
3333 n = TO_SPECIAL(buf[1], buf[2]);
3334 if (buf[1] == KS_MODIFIER
3335 || n == K_IGNORE
3336#ifdef FEAT_MOUSE
3337 || n == K_LEFTMOUSE_NM
3338 || n == K_LEFTDRAG
3339 || n == K_LEFTRELEASE
3340 || n == K_LEFTRELEASE_NM
3341 || n == K_MIDDLEMOUSE
3342 || n == K_MIDDLEDRAG
3343 || n == K_MIDDLERELEASE
3344 || n == K_RIGHTMOUSE
3345 || n == K_RIGHTDRAG
3346 || n == K_RIGHTRELEASE
3347 || n == K_MOUSEDOWN
3348 || n == K_MOUSEUP
Bram Moolenaar8d9b40e2010-07-25 15:49:07 +02003349 || n == K_MOUSELEFT
3350 || n == K_MOUSERIGHT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003351 || n == K_X1MOUSE
3352 || n == K_X1DRAG
3353 || n == K_X1RELEASE
3354 || n == K_X2MOUSE
3355 || n == K_X2DRAG
3356 || n == K_X2RELEASE
3357# ifdef FEAT_GUI
3358 || n == K_VER_SCROLLBAR
3359 || n == K_HOR_SCROLLBAR
3360# endif
3361#endif
3362 )
3363 {
3364 if (buf[1] == KS_MODIFIER)
3365 mod_mask = buf[2];
3366 len -= 3;
3367 if (len > 0)
3368 mch_memmove(buf, buf + 3, (size_t)len);
3369 continue;
3370 }
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00003371 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003372 }
3373#ifdef FEAT_MBYTE
3374 if (has_mbyte)
3375 {
3376 if (MB_BYTE2LEN(n) > len)
3377 continue; /* more bytes to get */
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003378 buf[len >= buflen ? buflen - 1 : len] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003379 n = (*mb_ptr2char)(buf);
3380 }
3381#endif
3382#ifdef UNIX
3383 if (n == intr_char)
3384 n = ESC;
3385#endif
3386 break;
3387 }
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003388 vim_free(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003389
3390 mapped_ctrl_c = save_mapped_ctrl_c;
3391 return n;
3392}
3393
3394/*
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003395 * Get a number from the user.
3396 * When "mouse_used" is not NULL allow using the mouse.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003397 */
3398 int
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003399get_number(colon, mouse_used)
3400 int colon; /* allow colon to abort */
3401 int *mouse_used;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003402{
3403 int n = 0;
3404 int c;
Bram Moolenaar3991dab2006-03-27 17:01:56 +00003405 int typed = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003406
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003407 if (mouse_used != NULL)
3408 *mouse_used = FALSE;
3409
Bram Moolenaar071d4272004-06-13 20:20:40 +00003410 /* When not printing messages, the user won't know what to type, return a
3411 * zero (as if CR was hit). */
3412 if (msg_silent != 0)
3413 return 0;
3414
3415#ifdef USE_ON_FLY_SCROLL
3416 dont_scroll = TRUE; /* disallow scrolling here */
3417#endif
3418 ++no_mapping;
3419 ++allow_keys; /* no mapping here, but recognize keys */
3420 for (;;)
3421 {
3422 windgoto(msg_row, msg_col);
3423 c = safe_vgetc();
3424 if (VIM_ISDIGIT(c))
3425 {
3426 n = n * 10 + c - '0';
3427 msg_putchar(c);
Bram Moolenaar3991dab2006-03-27 17:01:56 +00003428 ++typed;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003429 }
3430 else if (c == K_DEL || c == K_KDEL || c == K_BS || c == Ctrl_H)
3431 {
Bram Moolenaar3991dab2006-03-27 17:01:56 +00003432 if (typed > 0)
3433 {
3434 MSG_PUTS("\b \b");
3435 --typed;
3436 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003437 n /= 10;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003438 }
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003439#ifdef FEAT_MOUSE
3440 else if (mouse_used != NULL && c == K_LEFTMOUSE)
3441 {
3442 *mouse_used = TRUE;
3443 n = mouse_row + 1;
3444 break;
3445 }
3446#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003447 else if (n == 0 && c == ':' && colon)
3448 {
3449 stuffcharReadbuff(':');
3450 if (!exmode_active)
3451 cmdline_row = msg_row;
3452 skip_redraw = TRUE; /* skip redraw once */
3453 do_redraw = FALSE;
3454 break;
3455 }
3456 else if (c == CAR || c == NL || c == Ctrl_C || c == ESC)
3457 break;
3458 }
3459 --no_mapping;
3460 --allow_keys;
3461 return n;
3462}
3463
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003464/*
3465 * Ask the user to enter a number.
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003466 * When "mouse_used" is not NULL allow using the mouse and in that case return
3467 * the line number.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003468 */
3469 int
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003470prompt_for_number(mouse_used)
3471 int *mouse_used;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003472{
3473 int i;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003474 int save_cmdline_row;
3475 int save_State;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003476
3477 /* When using ":silent" assume that <CR> was entered. */
Bram Moolenaar42eeac32005-06-29 22:40:58 +00003478 if (mouse_used != NULL)
Bram Moolenaard812df62008-11-09 12:46:09 +00003479 MSG_PUTS(_("Type number and <Enter> or click with mouse (empty cancels): "));
Bram Moolenaar42eeac32005-06-29 22:40:58 +00003480 else
Bram Moolenaard812df62008-11-09 12:46:09 +00003481 MSG_PUTS(_("Type number and <Enter> (empty cancels): "));
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003482
Bram Moolenaar203335e2006-09-03 14:35:42 +00003483 /* Set the state such that text can be selected/copied/pasted and we still
3484 * get mouse events. */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003485 save_cmdline_row = cmdline_row;
Bram Moolenaar203335e2006-09-03 14:35:42 +00003486 cmdline_row = 0;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003487 save_State = State;
Bram Moolenaar203335e2006-09-03 14:35:42 +00003488 State = CMDLINE;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003489
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003490 i = get_number(TRUE, mouse_used);
3491 if (KeyTyped)
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003492 {
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003493 /* don't call wait_return() now */
3494 /* msg_putchar('\n'); */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003495 cmdline_row = msg_row - 1;
3496 need_wait_return = FALSE;
3497 msg_didany = FALSE;
Bram Moolenaarb2450162009-07-22 09:04:20 +00003498 msg_didout = FALSE;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003499 }
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003500 else
3501 cmdline_row = save_cmdline_row;
3502 State = save_State;
3503
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003504 return i;
3505}
3506
Bram Moolenaar071d4272004-06-13 20:20:40 +00003507 void
3508msgmore(n)
3509 long n;
3510{
3511 long pn;
3512
3513 if (global_busy /* no messages now, wait until global is finished */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003514 || !messaging()) /* 'lazyredraw' set, don't do messages now */
3515 return;
3516
Bram Moolenaar7df2d662005-01-25 22:18:08 +00003517 /* We don't want to overwrite another important message, but do overwrite
3518 * a previous "more lines" or "fewer lines" message, so that "5dd" and
3519 * then "put" reports the last action. */
3520 if (keep_msg != NULL && !keep_msg_more)
3521 return;
3522
Bram Moolenaar071d4272004-06-13 20:20:40 +00003523 if (n > 0)
3524 pn = n;
3525 else
3526 pn = -n;
3527
3528 if (pn > p_report)
3529 {
3530 if (pn == 1)
3531 {
3532 if (n > 0)
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003533 vim_strncpy(msg_buf, (char_u *)_("1 more line"),
3534 MSG_BUF_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003535 else
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003536 vim_strncpy(msg_buf, (char_u *)_("1 line less"),
3537 MSG_BUF_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003538 }
3539 else
3540 {
3541 if (n > 0)
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003542 vim_snprintf((char *)msg_buf, MSG_BUF_LEN,
3543 _("%ld more lines"), pn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003544 else
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003545 vim_snprintf((char *)msg_buf, MSG_BUF_LEN,
3546 _("%ld fewer lines"), pn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003547 }
3548 if (got_int)
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003549 vim_strcat(msg_buf, (char_u *)_(" (Interrupted)"), MSG_BUF_LEN);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003550 if (msg(msg_buf))
3551 {
Bram Moolenaar238a5642006-02-21 22:12:05 +00003552 set_keep_msg(msg_buf, 0);
Bram Moolenaar7df2d662005-01-25 22:18:08 +00003553 keep_msg_more = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003554 }
3555 }
3556}
3557
3558/*
3559 * flush map and typeahead buffers and give a warning for an error
3560 */
3561 void
3562beep_flush()
3563{
3564 if (emsg_silent == 0)
3565 {
3566 flush_buffers(FALSE);
3567 vim_beep();
3568 }
3569}
3570
3571/*
3572 * give a warning for an error
3573 */
3574 void
3575vim_beep()
3576{
3577 if (emsg_silent == 0)
3578 {
3579 if (p_vb
3580#ifdef FEAT_GUI
3581 /* While the GUI is starting up the termcap is set for the GUI
3582 * but the output still goes to a terminal. */
3583 && !(gui.in_use && gui.starting)
3584#endif
3585 )
3586 {
3587 out_str(T_VB);
3588 }
3589 else
3590 {
3591#ifdef MSDOS
3592 /*
3593 * The number of beeps outputted is reduced to avoid having to wait
3594 * for all the beeps to finish. This is only a problem on systems
3595 * where the beeps don't overlap.
3596 */
3597 if (beep_count == 0 || beep_count == 10)
3598 {
3599 out_char(BELL);
3600 beep_count = 1;
3601 }
3602 else
3603 ++beep_count;
3604#else
3605 out_char(BELL);
3606#endif
3607 }
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003608
3609 /* When 'verbose' is set and we are sourcing a script or executing a
3610 * function give the user a hint where the beep comes from. */
3611 if (vim_strchr(p_debug, 'e') != NULL)
3612 {
3613 msg_source(hl_attr(HLF_W));
3614 msg_attr((char_u *)_("Beep!"), hl_attr(HLF_W));
3615 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003616 }
3617}
3618
3619/*
3620 * To get the "real" home directory:
3621 * - get value of $HOME
3622 * For Unix:
3623 * - go to that directory
3624 * - do mch_dirname() to get the real name of that directory.
3625 * This also works with mounts and links.
3626 * Don't do this for MS-DOS, it will change the "current dir" for a drive.
3627 */
3628static char_u *homedir = NULL;
3629
3630 void
3631init_homedir()
3632{
3633 char_u *var;
3634
Bram Moolenaar05159a02005-02-26 23:04:13 +00003635 /* In case we are called a second time (when 'encoding' changes). */
3636 vim_free(homedir);
3637 homedir = NULL;
3638
Bram Moolenaar071d4272004-06-13 20:20:40 +00003639#ifdef VMS
3640 var = mch_getenv((char_u *)"SYS$LOGIN");
3641#else
3642 var = mch_getenv((char_u *)"HOME");
3643#endif
3644
3645 if (var != NULL && *var == NUL) /* empty is same as not set */
3646 var = NULL;
3647
3648#ifdef WIN3264
3649 /*
3650 * Weird but true: $HOME may contain an indirect reference to another
3651 * variable, esp. "%USERPROFILE%". Happens when $USERPROFILE isn't set
3652 * when $HOME is being set.
3653 */
3654 if (var != NULL && *var == '%')
3655 {
3656 char_u *p;
3657 char_u *exp;
3658
3659 p = vim_strchr(var + 1, '%');
3660 if (p != NULL)
3661 {
Bram Moolenaarce0842a2005-07-18 21:58:11 +00003662 vim_strncpy(NameBuff, var + 1, p - (var + 1));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003663 exp = mch_getenv(NameBuff);
3664 if (exp != NULL && *exp != NUL
3665 && STRLEN(exp) + STRLEN(p) < MAXPATHL)
3666 {
Bram Moolenaar555b2802005-05-19 21:08:39 +00003667 vim_snprintf((char *)NameBuff, MAXPATHL, "%s%s", exp, p + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003668 var = NameBuff;
3669 /* Also set $HOME, it's needed for _viminfo. */
3670 vim_setenv((char_u *)"HOME", NameBuff);
3671 }
3672 }
3673 }
3674
3675 /*
3676 * Typically, $HOME is not defined on Windows, unless the user has
3677 * specifically defined it for Vim's sake. However, on Windows NT
3678 * platforms, $HOMEDRIVE and $HOMEPATH are automatically defined for
3679 * each user. Try constructing $HOME from these.
3680 */
3681 if (var == NULL)
3682 {
3683 char_u *homedrive, *homepath;
3684
3685 homedrive = mch_getenv((char_u *)"HOMEDRIVE");
3686 homepath = mch_getenv((char_u *)"HOMEPATH");
Bram Moolenaar6f977012010-01-06 17:53:38 +01003687 if (homepath == NULL || *homepath == NUL)
3688 homepath = "\\";
3689 if (homedrive != NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00003690 && STRLEN(homedrive) + STRLEN(homepath) < MAXPATHL)
3691 {
3692 sprintf((char *)NameBuff, "%s%s", homedrive, homepath);
3693 if (NameBuff[0] != NUL)
3694 {
3695 var = NameBuff;
3696 /* Also set $HOME, it's needed for _viminfo. */
3697 vim_setenv((char_u *)"HOME", NameBuff);
3698 }
3699 }
3700 }
Bram Moolenaar05159a02005-02-26 23:04:13 +00003701
3702# if defined(FEAT_MBYTE)
3703 if (enc_utf8 && var != NULL)
3704 {
3705 int len;
Bram Moolenaarb453a532011-04-28 17:48:44 +02003706 char_u *pp = NULL;
Bram Moolenaar05159a02005-02-26 23:04:13 +00003707
3708 /* Convert from active codepage to UTF-8. Other conversions are
3709 * not done, because they would fail for non-ASCII characters. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003710 acp_to_enc(var, (int)STRLEN(var), &pp, &len);
Bram Moolenaar05159a02005-02-26 23:04:13 +00003711 if (pp != NULL)
3712 {
3713 homedir = pp;
3714 return;
3715 }
3716 }
3717# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003718#endif
3719
3720#if defined(OS2) || defined(MSDOS) || defined(MSWIN)
3721 /*
3722 * Default home dir is C:/
3723 * Best assumption we can make in such a situation.
3724 */
3725 if (var == NULL)
3726 var = "C:/";
3727#endif
3728 if (var != NULL)
3729 {
3730#ifdef UNIX
3731 /*
3732 * Change to the directory and get the actual path. This resolves
3733 * links. Don't do it when we can't return.
3734 */
3735 if (mch_dirname(NameBuff, MAXPATHL) == OK
3736 && mch_chdir((char *)NameBuff) == 0)
3737 {
3738 if (!mch_chdir((char *)var) && mch_dirname(IObuff, IOSIZE) == OK)
3739 var = IObuff;
3740 if (mch_chdir((char *)NameBuff) != 0)
3741 EMSG(_(e_prev_dir));
3742 }
3743#endif
3744 homedir = vim_strsave(var);
3745 }
3746}
3747
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003748#if defined(EXITFREE) || defined(PROTO)
3749 void
3750free_homedir()
3751{
3752 vim_free(homedir);
3753}
3754#endif
3755
Bram Moolenaar071d4272004-06-13 20:20:40 +00003756/*
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003757 * Call expand_env() and store the result in an allocated string.
3758 * This is not very memory efficient, this expects the result to be freed
3759 * again soon.
3760 */
3761 char_u *
3762expand_env_save(src)
3763 char_u *src;
3764{
3765 return expand_env_save_opt(src, FALSE);
3766}
3767
3768/*
3769 * Idem, but when "one" is TRUE handle the string as one file name, only
3770 * expand "~" at the start.
3771 */
3772 char_u *
3773expand_env_save_opt(src, one)
3774 char_u *src;
3775 int one;
3776{
3777 char_u *p;
3778
3779 p = alloc(MAXPATHL);
3780 if (p != NULL)
3781 expand_env_esc(src, p, MAXPATHL, FALSE, one, NULL);
3782 return p;
3783}
3784
3785/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003786 * Expand environment variable with path name.
3787 * "~/" is also expanded, using $HOME. For Unix "~user/" is expanded.
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003788 * Skips over "\ ", "\~" and "\$" (not for Win32 though).
Bram Moolenaar071d4272004-06-13 20:20:40 +00003789 * If anything fails no expansion is done and dst equals src.
3790 */
3791 void
3792expand_env(src, dst, dstlen)
3793 char_u *src; /* input string e.g. "$HOME/vim.hlp" */
3794 char_u *dst; /* where to put the result */
3795 int dstlen; /* maximum length of the result */
3796{
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003797 expand_env_esc(src, dst, dstlen, FALSE, FALSE, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003798}
3799
3800 void
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003801expand_env_esc(srcp, dst, dstlen, esc, one, startstr)
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003802 char_u *srcp; /* input string e.g. "$HOME/vim.hlp" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003803 char_u *dst; /* where to put the result */
3804 int dstlen; /* maximum length of the result */
3805 int esc; /* escape spaces in expanded variables */
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003806 int one; /* "srcp" is one file name */
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003807 char_u *startstr; /* start again after this (can be NULL) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003808{
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003809 char_u *src;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003810 char_u *tail;
3811 int c;
3812 char_u *var;
3813 int copy_char;
3814 int mustfree; /* var was allocated, need to free it later */
3815 int at_start = TRUE; /* at start of a name */
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003816 int startstr_len = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003817
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003818 if (startstr != NULL)
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003819 startstr_len = (int)STRLEN(startstr);
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003820
3821 src = skipwhite(srcp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003822 --dstlen; /* leave one char space for "\," */
3823 while (*src && dstlen > 0)
3824 {
3825 copy_char = TRUE;
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003826 if ((*src == '$'
3827#ifdef VMS
3828 && at_start
3829#endif
3830 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003831#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3832 || *src == '%'
3833#endif
3834 || (*src == '~' && at_start))
3835 {
3836 mustfree = FALSE;
3837
3838 /*
3839 * The variable name is copied into dst temporarily, because it may
3840 * be a string in read-only memory and a NUL needs to be appended.
3841 */
3842 if (*src != '~') /* environment var */
3843 {
3844 tail = src + 1;
3845 var = dst;
3846 c = dstlen - 1;
3847
3848#ifdef UNIX
3849 /* Unix has ${var-name} type environment vars */
3850 if (*tail == '{' && !vim_isIDc('{'))
3851 {
3852 tail++; /* ignore '{' */
3853 while (c-- > 0 && *tail && *tail != '}')
3854 *var++ = *tail++;
3855 }
3856 else
3857#endif
3858 {
3859 while (c-- > 0 && *tail != NUL && ((vim_isIDc(*tail))
3860#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3861 || (*src == '%' && *tail != '%')
3862#endif
3863 ))
3864 {
3865#ifdef OS2 /* env vars only in uppercase */
3866 *var++ = TOUPPER_LOC(*tail);
3867 tail++; /* toupper() may be a macro! */
3868#else
3869 *var++ = *tail++;
3870#endif
3871 }
3872 }
3873
3874#if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
3875# ifdef UNIX
3876 if (src[1] == '{' && *tail != '}')
3877# else
3878 if (*src == '%' && *tail != '%')
3879# endif
3880 var = NULL;
3881 else
3882 {
3883# ifdef UNIX
3884 if (src[1] == '{')
3885# else
3886 if (*src == '%')
3887#endif
3888 ++tail;
3889#endif
3890 *var = NUL;
3891 var = vim_getenv(dst, &mustfree);
3892#if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
3893 }
3894#endif
3895 }
3896 /* home directory */
3897 else if ( src[1] == NUL
3898 || vim_ispathsep(src[1])
3899 || vim_strchr((char_u *)" ,\t\n", src[1]) != NULL)
3900 {
3901 var = homedir;
3902 tail = src + 1;
3903 }
3904 else /* user directory */
3905 {
3906#if defined(UNIX) || (defined(VMS) && defined(USER_HOME))
3907 /*
3908 * Copy ~user to dst[], so we can put a NUL after it.
3909 */
3910 tail = src;
3911 var = dst;
3912 c = dstlen - 1;
3913 while ( c-- > 0
3914 && *tail
3915 && vim_isfilec(*tail)
3916 && !vim_ispathsep(*tail))
3917 *var++ = *tail++;
3918 *var = NUL;
3919# ifdef UNIX
3920 /*
3921 * If the system supports getpwnam(), use it.
3922 * Otherwise, or if getpwnam() fails, the shell is used to
3923 * expand ~user. This is slower and may fail if the shell
3924 * does not support ~user (old versions of /bin/sh).
3925 */
3926# if defined(HAVE_GETPWNAM) && defined(HAVE_PWD_H)
3927 {
3928 struct passwd *pw;
3929
Bram Moolenaara40ceaf2006-01-13 22:35:40 +00003930 /* Note: memory allocated by getpwnam() is never freed.
3931 * Calling endpwent() apparently doesn't help. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003932 pw = getpwnam((char *)dst + 1);
3933 if (pw != NULL)
3934 var = (char_u *)pw->pw_dir;
3935 else
3936 var = NULL;
3937 }
3938 if (var == NULL)
3939# endif
3940 {
3941 expand_T xpc;
3942
3943 ExpandInit(&xpc);
3944 xpc.xp_context = EXPAND_FILES;
3945 var = ExpandOne(&xpc, dst, NULL,
3946 WILD_ADD_SLASH|WILD_SILENT, WILD_EXPAND_FREE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003947 mustfree = TRUE;
3948 }
3949
3950# else /* !UNIX, thus VMS */
3951 /*
3952 * USER_HOME is a comma-separated list of
3953 * directories to search for the user account in.
3954 */
3955 {
3956 char_u test[MAXPATHL], paths[MAXPATHL];
3957 char_u *path, *next_path, *ptr;
3958 struct stat st;
3959
3960 STRCPY(paths, USER_HOME);
3961 next_path = paths;
3962 while (*next_path)
3963 {
3964 for (path = next_path; *next_path && *next_path != ',';
3965 next_path++);
3966 if (*next_path)
3967 *next_path++ = NUL;
3968 STRCPY(test, path);
3969 STRCAT(test, "/");
3970 STRCAT(test, dst + 1);
3971 if (mch_stat(test, &st) == 0)
3972 {
3973 var = alloc(STRLEN(test) + 1);
3974 STRCPY(var, test);
3975 mustfree = TRUE;
3976 break;
3977 }
3978 }
3979 }
3980# endif /* UNIX */
3981#else
3982 /* cannot expand user's home directory, so don't try */
3983 var = NULL;
3984 tail = (char_u *)""; /* for gcc */
3985#endif /* UNIX || VMS */
3986 }
3987
3988#ifdef BACKSLASH_IN_FILENAME
3989 /* If 'shellslash' is set change backslashes to forward slashes.
3990 * Can't use slash_adjust(), p_ssl may be set temporarily. */
3991 if (p_ssl && var != NULL && vim_strchr(var, '\\') != NULL)
3992 {
3993 char_u *p = vim_strsave(var);
3994
3995 if (p != NULL)
3996 {
3997 if (mustfree)
3998 vim_free(var);
3999 var = p;
4000 mustfree = TRUE;
4001 forward_slash(var);
4002 }
4003 }
4004#endif
4005
4006 /* If "var" contains white space, escape it with a backslash.
4007 * Required for ":e ~/tt" when $HOME includes a space. */
4008 if (esc && var != NULL && vim_strpbrk(var, (char_u *)" \t") != NULL)
4009 {
4010 char_u *p = vim_strsave_escaped(var, (char_u *)" \t");
4011
4012 if (p != NULL)
4013 {
4014 if (mustfree)
4015 vim_free(var);
4016 var = p;
4017 mustfree = TRUE;
4018 }
4019 }
4020
4021 if (var != NULL && *var != NUL
4022 && (STRLEN(var) + STRLEN(tail) + 1 < (unsigned)dstlen))
4023 {
4024 STRCPY(dst, var);
4025 dstlen -= (int)STRLEN(var);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004026 c = (int)STRLEN(var);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004027 /* if var[] ends in a path separator and tail[] starts
4028 * with it, skip a character */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004029 if (*var != NUL && after_pathsep(dst, dst + c)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004030#if defined(BACKSLASH_IN_FILENAME) || defined(AMIGA)
4031 && dst[-1] != ':'
4032#endif
4033 && vim_ispathsep(*tail))
4034 ++tail;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004035 dst += c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004036 src = tail;
4037 copy_char = FALSE;
4038 }
4039 if (mustfree)
4040 vim_free(var);
4041 }
4042
4043 if (copy_char) /* copy at least one char */
4044 {
4045 /*
Bram Moolenaar25394022007-05-10 19:06:20 +00004046 * Recognize the start of a new name, for '~'.
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00004047 * Don't do this when "one" is TRUE, to avoid expanding "~" in
4048 * ":edit foo ~ foo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00004049 */
4050 at_start = FALSE;
4051 if (src[0] == '\\' && src[1] != NUL)
4052 {
4053 *dst++ = *src++;
4054 --dstlen;
4055 }
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00004056 else if ((src[0] == ' ' || src[0] == ',') && !one)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004057 at_start = TRUE;
4058 *dst++ = *src++;
4059 --dstlen;
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00004060
4061 if (startstr != NULL && src - startstr_len >= srcp
4062 && STRNCMP(src - startstr_len, startstr, startstr_len) == 0)
4063 at_start = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004064 }
4065 }
4066 *dst = NUL;
4067}
4068
4069/*
4070 * Vim's version of getenv().
4071 * Special handling of $HOME, $VIM and $VIMRUNTIME.
Bram Moolenaar2f6b0b82005-03-08 22:43:10 +00004072 * Also does ACP to 'enc' conversion for Win32.
Bram Moolenaarb453a532011-04-28 17:48:44 +02004073 * "mustfree" is set to TRUE when returned is allocated, it must be
4074 * initialized to FALSE by the caller.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004075 */
4076 char_u *
4077vim_getenv(name, mustfree)
4078 char_u *name;
Bram Moolenaarb453a532011-04-28 17:48:44 +02004079 int *mustfree;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004080{
4081 char_u *p;
4082 char_u *pend;
4083 int vimruntime;
4084
4085#if defined(OS2) || defined(MSDOS) || defined(MSWIN)
4086 /* use "C:/" when $HOME is not set */
4087 if (STRCMP(name, "HOME") == 0)
4088 return homedir;
4089#endif
4090
4091 p = mch_getenv(name);
4092 if (p != NULL && *p == NUL) /* empty is the same as not set */
4093 p = NULL;
4094
4095 if (p != NULL)
Bram Moolenaar05159a02005-02-26 23:04:13 +00004096 {
4097#if defined(FEAT_MBYTE) && defined(WIN3264)
4098 if (enc_utf8)
4099 {
4100 int len;
Bram Moolenaarb453a532011-04-28 17:48:44 +02004101 char_u *pp = NULL;
Bram Moolenaar05159a02005-02-26 23:04:13 +00004102
4103 /* Convert from active codepage to UTF-8. Other conversions are
4104 * not done, because they would fail for non-ASCII characters. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004105 acp_to_enc(p, (int)STRLEN(p), &pp, &len);
Bram Moolenaar05159a02005-02-26 23:04:13 +00004106 if (pp != NULL)
4107 {
4108 p = pp;
4109 *mustfree = TRUE;
4110 }
4111 }
4112#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004113 return p;
Bram Moolenaar05159a02005-02-26 23:04:13 +00004114 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004115
4116 vimruntime = (STRCMP(name, "VIMRUNTIME") == 0);
4117 if (!vimruntime && STRCMP(name, "VIM") != 0)
4118 return NULL;
4119
4120 /*
4121 * When expanding $VIMRUNTIME fails, try using $VIM/vim<version> or $VIM.
4122 * Don't do this when default_vimruntime_dir is non-empty.
4123 */
4124 if (vimruntime
4125#ifdef HAVE_PATHDEF
4126 && *default_vimruntime_dir == NUL
4127#endif
4128 )
4129 {
4130 p = mch_getenv((char_u *)"VIM");
4131 if (p != NULL && *p == NUL) /* empty is the same as not set */
4132 p = NULL;
4133 if (p != NULL)
4134 {
4135 p = vim_version_dir(p);
4136 if (p != NULL)
4137 *mustfree = TRUE;
4138 else
4139 p = mch_getenv((char_u *)"VIM");
Bram Moolenaar05159a02005-02-26 23:04:13 +00004140
4141#if defined(FEAT_MBYTE) && defined(WIN3264)
4142 if (enc_utf8)
4143 {
4144 int len;
Bram Moolenaarb453a532011-04-28 17:48:44 +02004145 char_u *pp = NULL;
Bram Moolenaar05159a02005-02-26 23:04:13 +00004146
4147 /* Convert from active codepage to UTF-8. Other conversions
4148 * are not done, because they would fail for non-ASCII
4149 * characters. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004150 acp_to_enc(p, (int)STRLEN(p), &pp, &len);
Bram Moolenaar05159a02005-02-26 23:04:13 +00004151 if (pp != NULL)
4152 {
Bram Moolenaarb453a532011-04-28 17:48:44 +02004153 if (*mustfree)
Bram Moolenaar05159a02005-02-26 23:04:13 +00004154 vim_free(p);
4155 p = pp;
4156 *mustfree = TRUE;
4157 }
4158 }
4159#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004160 }
4161 }
4162
4163 /*
4164 * When expanding $VIM or $VIMRUNTIME fails, try using:
4165 * - the directory name from 'helpfile' (unless it contains '$')
4166 * - the executable name from argv[0]
4167 */
4168 if (p == NULL)
4169 {
4170 if (p_hf != NULL && vim_strchr(p_hf, '$') == NULL)
4171 p = p_hf;
4172#ifdef USE_EXE_NAME
4173 /*
4174 * Use the name of the executable, obtained from argv[0].
4175 */
4176 else
4177 p = exe_name;
4178#endif
4179 if (p != NULL)
4180 {
4181 /* remove the file name */
4182 pend = gettail(p);
4183
4184 /* remove "doc/" from 'helpfile', if present */
4185 if (p == p_hf)
4186 pend = remove_tail(p, pend, (char_u *)"doc");
4187
4188#ifdef USE_EXE_NAME
4189# ifdef MACOS_X
Bram Moolenaar95e9b492006-03-15 23:04:43 +00004190 /* remove "MacOS" from exe_name and add "Resources/vim" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004191 if (p == exe_name)
4192 {
4193 char_u *pend1;
Bram Moolenaar95e9b492006-03-15 23:04:43 +00004194 char_u *pnew;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004195
Bram Moolenaar95e9b492006-03-15 23:04:43 +00004196 pend1 = remove_tail(p, pend, (char_u *)"MacOS");
4197 if (pend1 != pend)
4198 {
4199 pnew = alloc((unsigned)(pend1 - p) + 15);
4200 if (pnew != NULL)
4201 {
4202 STRNCPY(pnew, p, (pend1 - p));
4203 STRCPY(pnew + (pend1 - p), "Resources/vim");
4204 p = pnew;
4205 pend = p + STRLEN(p);
4206 }
4207 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004208 }
4209# endif
4210 /* remove "src/" from exe_name, if present */
4211 if (p == exe_name)
4212 pend = remove_tail(p, pend, (char_u *)"src");
4213#endif
4214
4215 /* for $VIM, remove "runtime/" or "vim54/", if present */
4216 if (!vimruntime)
4217 {
4218 pend = remove_tail(p, pend, (char_u *)RUNTIME_DIRNAME);
4219 pend = remove_tail(p, pend, (char_u *)VIM_VERSION_NODOT);
4220 }
4221
4222 /* remove trailing path separator */
4223#ifndef MACOS_CLASSIC
4224 /* With MacOS path (with colons) the final colon is required */
Bram Moolenaare21877a2008-02-13 09:58:14 +00004225 /* to avoid confusion between absolute and relative path */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004226 if (pend > p && after_pathsep(p, pend))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004227 --pend;
4228#endif
4229
Bram Moolenaar95e9b492006-03-15 23:04:43 +00004230#ifdef MACOS_X
4231 if (p == exe_name || p == p_hf)
4232#endif
4233 /* check that the result is a directory name */
4234 p = vim_strnsave(p, (int)(pend - p));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004235
4236 if (p != NULL && !mch_isdir(p))
4237 {
4238 vim_free(p);
4239 p = NULL;
4240 }
4241 else
4242 {
4243#ifdef USE_EXE_NAME
4244 /* may add "/vim54" or "/runtime" if it exists */
4245 if (vimruntime && (pend = vim_version_dir(p)) != NULL)
4246 {
4247 vim_free(p);
4248 p = pend;
4249 }
4250#endif
4251 *mustfree = TRUE;
4252 }
4253 }
4254 }
4255
4256#ifdef HAVE_PATHDEF
4257 /* When there is a pathdef.c file we can use default_vim_dir and
4258 * default_vimruntime_dir */
4259 if (p == NULL)
4260 {
4261 /* Only use default_vimruntime_dir when it is not empty */
4262 if (vimruntime && *default_vimruntime_dir != NUL)
4263 {
4264 p = default_vimruntime_dir;
4265 *mustfree = FALSE;
4266 }
4267 else if (*default_vim_dir != NUL)
4268 {
4269 if (vimruntime && (p = vim_version_dir(default_vim_dir)) != NULL)
4270 *mustfree = TRUE;
4271 else
4272 {
4273 p = default_vim_dir;
4274 *mustfree = FALSE;
4275 }
4276 }
4277 }
4278#endif
4279
4280 /*
4281 * Set the environment variable, so that the new value can be found fast
4282 * next time, and others can also use it (e.g. Perl).
4283 */
4284 if (p != NULL)
4285 {
4286 if (vimruntime)
4287 {
4288 vim_setenv((char_u *)"VIMRUNTIME", p);
4289 didset_vimruntime = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004290 }
4291 else
4292 {
4293 vim_setenv((char_u *)"VIM", p);
4294 didset_vim = TRUE;
4295 }
4296 }
4297 return p;
4298}
4299
4300/*
4301 * Check if the directory "vimdir/<version>" or "vimdir/runtime" exists.
4302 * Return NULL if not, return its name in allocated memory otherwise.
4303 */
4304 static char_u *
4305vim_version_dir(vimdir)
4306 char_u *vimdir;
4307{
4308 char_u *p;
4309
4310 if (vimdir == NULL || *vimdir == NUL)
4311 return NULL;
4312 p = concat_fnames(vimdir, (char_u *)VIM_VERSION_NODOT, TRUE);
4313 if (p != NULL && mch_isdir(p))
4314 return p;
4315 vim_free(p);
4316 p = concat_fnames(vimdir, (char_u *)RUNTIME_DIRNAME, TRUE);
4317 if (p != NULL && mch_isdir(p))
4318 return p;
4319 vim_free(p);
4320 return NULL;
4321}
4322
4323/*
4324 * If the string between "p" and "pend" ends in "name/", return "pend" minus
4325 * the length of "name/". Otherwise return "pend".
4326 */
4327 static char_u *
4328remove_tail(p, pend, name)
4329 char_u *p;
4330 char_u *pend;
4331 char_u *name;
4332{
4333 int len = (int)STRLEN(name) + 1;
4334 char_u *newend = pend - len;
4335
4336 if (newend >= p
4337 && fnamencmp(newend, name, len - 1) == 0
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004338 && (newend == p || after_pathsep(p, newend)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004339 return newend;
4340 return pend;
4341}
4342
Bram Moolenaar071d4272004-06-13 20:20:40 +00004343/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004344 * Our portable version of setenv.
4345 */
4346 void
4347vim_setenv(name, val)
4348 char_u *name;
4349 char_u *val;
4350{
4351#ifdef HAVE_SETENV
4352 mch_setenv((char *)name, (char *)val, 1);
4353#else
4354 char_u *envbuf;
4355
4356 /*
4357 * Putenv does not copy the string, it has to remain
4358 * valid. The allocated memory will never be freed.
4359 */
4360 envbuf = alloc((unsigned)(STRLEN(name) + STRLEN(val) + 2));
4361 if (envbuf != NULL)
4362 {
4363 sprintf((char *)envbuf, "%s=%s", name, val);
4364 putenv((char *)envbuf);
4365 }
4366#endif
Bram Moolenaar011a34d2012-02-29 13:49:09 +01004367#ifdef FEAT_GETTEXT
4368 /*
4369 * When setting $VIMRUNTIME adjust the directory to find message
4370 * translations to $VIMRUNTIME/lang.
4371 */
4372 if (*val != NUL && STRICMP(name, "VIMRUNTIME") == 0)
4373 {
4374 char_u *buf = concat_str(val, (char_u *)"/lang");
4375
4376 if (buf != NULL)
4377 {
4378 bindtextdomain(VIMPACKAGE, (char *)buf);
4379 vim_free(buf);
4380 }
4381 }
4382#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004383}
4384
4385#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
4386/*
4387 * Function given to ExpandGeneric() to obtain an environment variable name.
4388 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004389 char_u *
4390get_env_name(xp, idx)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00004391 expand_T *xp UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004392 int idx;
4393{
4394# if defined(AMIGA) || defined(__MRC__) || defined(__SC__)
4395 /*
4396 * No environ[] on the Amiga and on the Mac (using MPW).
4397 */
4398 return NULL;
4399# else
4400# ifndef __WIN32__
4401 /* Borland C++ 5.2 has this in a header file. */
4402 extern char **environ;
4403# endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00004404# define ENVNAMELEN 100
4405 static char_u name[ENVNAMELEN];
Bram Moolenaar071d4272004-06-13 20:20:40 +00004406 char_u *str;
4407 int n;
4408
4409 str = (char_u *)environ[idx];
4410 if (str == NULL)
4411 return NULL;
4412
Bram Moolenaar21cf8232004-07-16 20:18:37 +00004413 for (n = 0; n < ENVNAMELEN - 1; ++n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004414 {
4415 if (str[n] == '=' || str[n] == NUL)
4416 break;
4417 name[n] = str[n];
4418 }
4419 name[n] = NUL;
4420 return name;
4421# endif
4422}
4423#endif
4424
4425/*
4426 * Replace home directory by "~" in each space or comma separated file name in
4427 * 'src'.
4428 * If anything fails (except when out of space) dst equals src.
4429 */
4430 void
4431home_replace(buf, src, dst, dstlen, one)
4432 buf_T *buf; /* when not NULL, check for help files */
4433 char_u *src; /* input file name */
4434 char_u *dst; /* where to put the result */
4435 int dstlen; /* maximum length of the result */
4436 int one; /* if TRUE, only replace one file name, include
4437 spaces and commas in the file name. */
4438{
4439 size_t dirlen = 0, envlen = 0;
4440 size_t len;
4441 char_u *homedir_env;
4442 char_u *p;
4443
4444 if (src == NULL)
4445 {
4446 *dst = NUL;
4447 return;
4448 }
4449
4450 /*
4451 * If the file is a help file, remove the path completely.
4452 */
4453 if (buf != NULL && buf->b_help)
4454 {
4455 STRCPY(dst, gettail(src));
4456 return;
4457 }
4458
4459 /*
4460 * We check both the value of the $HOME environment variable and the
4461 * "real" home directory.
4462 */
4463 if (homedir != NULL)
4464 dirlen = STRLEN(homedir);
4465
4466#ifdef VMS
4467 homedir_env = mch_getenv((char_u *)"SYS$LOGIN");
4468#else
4469 homedir_env = mch_getenv((char_u *)"HOME");
4470#endif
4471
4472 if (homedir_env != NULL && *homedir_env == NUL)
4473 homedir_env = NULL;
4474 if (homedir_env != NULL)
4475 envlen = STRLEN(homedir_env);
4476
4477 if (!one)
4478 src = skipwhite(src);
4479 while (*src && dstlen > 0)
4480 {
4481 /*
4482 * Here we are at the beginning of a file name.
4483 * First, check to see if the beginning of the file name matches
4484 * $HOME or the "real" home directory. Check that there is a '/'
4485 * after the match (so that if e.g. the file is "/home/pieter/bla",
4486 * and the home directory is "/home/piet", the file does not end up
4487 * as "~er/bla" (which would seem to indicate the file "bla" in user
4488 * er's home directory)).
4489 */
4490 p = homedir;
4491 len = dirlen;
4492 for (;;)
4493 {
4494 if ( len
4495 && fnamencmp(src, p, len) == 0
4496 && (vim_ispathsep(src[len])
4497 || (!one && (src[len] == ',' || src[len] == ' '))
4498 || src[len] == NUL))
4499 {
4500 src += len;
4501 if (--dstlen > 0)
4502 *dst++ = '~';
4503
4504 /*
4505 * If it's just the home directory, add "/".
4506 */
4507 if (!vim_ispathsep(src[0]) && --dstlen > 0)
4508 *dst++ = '/';
4509 break;
4510 }
4511 if (p == homedir_env)
4512 break;
4513 p = homedir_env;
4514 len = envlen;
4515 }
4516
4517 /* if (!one) skip to separator: space or comma */
4518 while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
4519 *dst++ = *src++;
4520 /* skip separator */
4521 while ((*src == ' ' || *src == ',') && --dstlen > 0)
4522 *dst++ = *src++;
4523 }
4524 /* if (dstlen == 0) out of space, what to do??? */
4525
4526 *dst = NUL;
4527}
4528
4529/*
4530 * Like home_replace, store the replaced string in allocated memory.
4531 * When something fails, NULL is returned.
4532 */
4533 char_u *
4534home_replace_save(buf, src)
4535 buf_T *buf; /* when not NULL, check for help files */
4536 char_u *src; /* input file name */
4537{
4538 char_u *dst;
4539 unsigned len;
4540
4541 len = 3; /* space for "~/" and trailing NUL */
4542 if (src != NULL) /* just in case */
4543 len += (unsigned)STRLEN(src);
4544 dst = alloc(len);
4545 if (dst != NULL)
4546 home_replace(buf, src, dst, len, TRUE);
4547 return dst;
4548}
4549
4550/*
4551 * Compare two file names and return:
4552 * FPC_SAME if they both exist and are the same file.
4553 * FPC_SAMEX if they both don't exist and have the same file name.
4554 * FPC_DIFF if they both exist and are different files.
4555 * FPC_NOTX if they both don't exist.
4556 * FPC_DIFFX if one of them doesn't exist.
4557 * For the first name environment variables are expanded
4558 */
4559 int
4560fullpathcmp(s1, s2, checkname)
4561 char_u *s1, *s2;
4562 int checkname; /* when both don't exist, check file names */
4563{
4564#ifdef UNIX
4565 char_u exp1[MAXPATHL];
4566 char_u full1[MAXPATHL];
4567 char_u full2[MAXPATHL];
4568 struct stat st1, st2;
4569 int r1, r2;
4570
4571 expand_env(s1, exp1, MAXPATHL);
4572 r1 = mch_stat((char *)exp1, &st1);
4573 r2 = mch_stat((char *)s2, &st2);
4574 if (r1 != 0 && r2 != 0)
4575 {
4576 /* if mch_stat() doesn't work, may compare the names */
4577 if (checkname)
4578 {
4579 if (fnamecmp(exp1, s2) == 0)
4580 return FPC_SAMEX;
4581 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4582 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4583 if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
4584 return FPC_SAMEX;
4585 }
4586 return FPC_NOTX;
4587 }
4588 if (r1 != 0 || r2 != 0)
4589 return FPC_DIFFX;
4590 if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
4591 return FPC_SAME;
4592 return FPC_DIFF;
4593#else
4594 char_u *exp1; /* expanded s1 */
4595 char_u *full1; /* full path of s1 */
4596 char_u *full2; /* full path of s2 */
4597 int retval = FPC_DIFF;
4598 int r1, r2;
4599
4600 /* allocate one buffer to store three paths (alloc()/free() is slow!) */
4601 if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
4602 {
4603 full1 = exp1 + MAXPATHL;
4604 full2 = full1 + MAXPATHL;
4605
4606 expand_env(s1, exp1, MAXPATHL);
4607 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4608 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4609
4610 /* If vim_FullName() fails, the file probably doesn't exist. */
4611 if (r1 != OK && r2 != OK)
4612 {
4613 if (checkname && fnamecmp(exp1, s2) == 0)
4614 retval = FPC_SAMEX;
4615 else
4616 retval = FPC_NOTX;
4617 }
4618 else if (r1 != OK || r2 != OK)
4619 retval = FPC_DIFFX;
4620 else if (fnamecmp(full1, full2))
4621 retval = FPC_DIFF;
4622 else
4623 retval = FPC_SAME;
4624 vim_free(exp1);
4625 }
4626 return retval;
4627#endif
4628}
4629
4630/*
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004631 * Get the tail of a path: the file name.
Bram Moolenaar31710262010-08-13 13:36:15 +02004632 * When the path ends in a path separator the tail is the NUL after it.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004633 * Fail safe: never returns NULL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004634 */
4635 char_u *
4636gettail(fname)
4637 char_u *fname;
4638{
4639 char_u *p1, *p2;
4640
4641 if (fname == NULL)
4642 return (char_u *)"";
4643 for (p1 = p2 = fname; *p2; ) /* find last part of path */
4644 {
4645 if (vim_ispathsep(*p2))
4646 p1 = p2 + 1;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004647 mb_ptr_adv(p2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004648 }
4649 return p1;
4650}
4651
Bram Moolenaar31710262010-08-13 13:36:15 +02004652#if defined(FEAT_SEARCHPATH)
4653static char_u *gettail_dir __ARGS((char_u *fname));
4654
4655/*
4656 * Return the end of the directory name, on the first path
4657 * separator:
4658 * "/path/file", "/path/dir/", "/path//dir", "/file"
4659 * ^ ^ ^ ^
4660 */
4661 static char_u *
4662gettail_dir(fname)
4663 char_u *fname;
4664{
4665 char_u *dir_end = fname;
4666 char_u *next_dir_end = fname;
4667 int look_for_sep = TRUE;
4668 char_u *p;
4669
4670 for (p = fname; *p != NUL; )
4671 {
4672 if (vim_ispathsep(*p))
4673 {
4674 if (look_for_sep)
4675 {
4676 next_dir_end = p;
4677 look_for_sep = FALSE;
4678 }
4679 }
4680 else
4681 {
4682 if (!look_for_sep)
4683 dir_end = next_dir_end;
4684 look_for_sep = TRUE;
4685 }
4686 mb_ptr_adv(p);
4687 }
4688 return dir_end;
4689}
4690#endif
4691
Bram Moolenaar071d4272004-06-13 20:20:40 +00004692/*
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004693 * Get pointer to tail of "fname", including path separators. Putting a NUL
4694 * here leaves the directory name. Takes care of "c:/" and "//".
4695 * Always returns a valid pointer.
4696 */
4697 char_u *
4698gettail_sep(fname)
4699 char_u *fname;
4700{
4701 char_u *p;
4702 char_u *t;
4703
4704 p = get_past_head(fname); /* don't remove the '/' from "c:/file" */
4705 t = gettail(fname);
4706 while (t > p && after_pathsep(fname, t))
4707 --t;
4708#ifdef VMS
4709 /* path separator is part of the path */
4710 ++t;
4711#endif
4712 return t;
4713}
4714
4715/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004716 * get the next path component (just after the next path separator).
4717 */
4718 char_u *
4719getnextcomp(fname)
4720 char_u *fname;
4721{
4722 while (*fname && !vim_ispathsep(*fname))
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004723 mb_ptr_adv(fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004724 if (*fname)
4725 ++fname;
4726 return fname;
4727}
4728
Bram Moolenaar071d4272004-06-13 20:20:40 +00004729/*
4730 * Get a pointer to one character past the head of a path name.
4731 * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
4732 * If there is no head, path is returned.
4733 */
4734 char_u *
4735get_past_head(path)
4736 char_u *path;
4737{
4738 char_u *retval;
4739
4740#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
4741 /* may skip "c:" */
4742 if (isalpha(path[0]) && path[1] == ':')
4743 retval = path + 2;
4744 else
4745 retval = path;
4746#else
4747# if defined(AMIGA)
4748 /* may skip "label:" */
4749 retval = vim_strchr(path, ':');
4750 if (retval == NULL)
4751 retval = path;
4752# else /* Unix */
4753 retval = path;
4754# endif
4755#endif
4756
4757 while (vim_ispathsep(*retval))
4758 ++retval;
4759
4760 return retval;
4761}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004762
4763/*
4764 * return TRUE if 'c' is a path separator.
4765 */
4766 int
4767vim_ispathsep(c)
4768 int c;
4769{
Bram Moolenaare60acc12011-05-10 16:41:25 +02004770#ifdef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00004771 return (c == '/'); /* UNIX has ':' inside file names */
Bram Moolenaare60acc12011-05-10 16:41:25 +02004772#else
4773# ifdef BACKSLASH_IN_FILENAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00004774 return (c == ':' || c == '/' || c == '\\');
Bram Moolenaare60acc12011-05-10 16:41:25 +02004775# else
4776# ifdef VMS
Bram Moolenaar071d4272004-06-13 20:20:40 +00004777 /* server"user passwd"::device:[full.path.name]fname.extension;version" */
4778 return (c == ':' || c == '[' || c == ']' || c == '/'
4779 || c == '<' || c == '>' || c == '"' );
Bram Moolenaare60acc12011-05-10 16:41:25 +02004780# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004781 return (c == ':' || c == '/');
Bram Moolenaare60acc12011-05-10 16:41:25 +02004782# endif /* VMS */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004783# endif
Bram Moolenaare60acc12011-05-10 16:41:25 +02004784#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004785}
4786
4787#if defined(FEAT_SEARCHPATH) || defined(PROTO)
4788/*
4789 * return TRUE if 'c' is a path list separator.
4790 */
4791 int
4792vim_ispathlistsep(c)
4793 int c;
4794{
4795#ifdef UNIX
4796 return (c == ':');
4797#else
Bram Moolenaar25394022007-05-10 19:06:20 +00004798 return (c == ';'); /* might not be right for every system... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004799#endif
4800}
4801#endif
4802
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004803#if defined(FEAT_GUI_TABLINE) || defined(FEAT_WINDOWS) \
4804 || defined(FEAT_EVAL) || defined(PROTO)
4805/*
4806 * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
4807 * It's done in-place.
4808 */
4809 void
4810shorten_dir(str)
4811 char_u *str;
4812{
4813 char_u *tail, *s, *d;
4814 int skip = FALSE;
4815
4816 tail = gettail(str);
4817 d = str;
4818 for (s = str; ; ++s)
4819 {
4820 if (s >= tail) /* copy the whole tail */
4821 {
4822 *d++ = *s;
4823 if (*s == NUL)
4824 break;
4825 }
4826 else if (vim_ispathsep(*s)) /* copy '/' and next char */
4827 {
4828 *d++ = *s;
4829 skip = FALSE;
4830 }
4831 else if (!skip)
4832 {
4833 *d++ = *s; /* copy next char */
4834 if (*s != '~' && *s != '.') /* and leading "~" and "." */
4835 skip = TRUE;
4836# ifdef FEAT_MBYTE
4837 if (has_mbyte)
4838 {
4839 int l = mb_ptr2len(s);
4840
4841 while (--l > 0)
Bram Moolenaarb6baca52006-08-15 20:24:14 +00004842 *d++ = *++s;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004843 }
4844# endif
4845 }
4846 }
4847}
4848#endif
4849
Bram Moolenaar900b4d72005-12-12 22:05:50 +00004850/*
4851 * Return TRUE if the directory of "fname" exists, FALSE otherwise.
4852 * Also returns TRUE if there is no directory name.
4853 * "fname" must be writable!.
4854 */
4855 int
4856dir_of_file_exists(fname)
4857 char_u *fname;
4858{
4859 char_u *p;
4860 int c;
4861 int retval;
4862
4863 p = gettail_sep(fname);
4864 if (p == fname)
4865 return TRUE;
4866 c = *p;
4867 *p = NUL;
4868 retval = mch_isdir(fname);
4869 *p = c;
4870 return retval;
4871}
4872
Bram Moolenaar071d4272004-06-13 20:20:40 +00004873#if (defined(CASE_INSENSITIVE_FILENAME) && defined(BACKSLASH_IN_FILENAME)) \
4874 || defined(PROTO)
4875/*
4876 * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally.
4877 */
4878 int
4879vim_fnamecmp(x, y)
4880 char_u *x, *y;
4881{
4882 return vim_fnamencmp(x, y, MAXPATHL);
4883}
4884
4885 int
4886vim_fnamencmp(x, y, len)
4887 char_u *x, *y;
4888 size_t len;
4889{
4890 while (len > 0 && *x && *y)
4891 {
4892 if (TOLOWER_LOC(*x) != TOLOWER_LOC(*y)
4893 && !(*x == '/' && *y == '\\')
4894 && !(*x == '\\' && *y == '/'))
4895 break;
4896 ++x;
4897 ++y;
4898 --len;
4899 }
4900 if (len == 0)
4901 return 0;
4902 return (*x - *y);
4903}
4904#endif
4905
4906/*
4907 * Concatenate file names fname1 and fname2 into allocated memory.
Bram Moolenaar25394022007-05-10 19:06:20 +00004908 * Only add a '/' or '\\' when 'sep' is TRUE and it is necessary.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004909 */
4910 char_u *
4911concat_fnames(fname1, fname2, sep)
4912 char_u *fname1;
4913 char_u *fname2;
4914 int sep;
4915{
4916 char_u *dest;
4917
4918 dest = alloc((unsigned)(STRLEN(fname1) + STRLEN(fname2) + 3));
4919 if (dest != NULL)
4920 {
4921 STRCPY(dest, fname1);
4922 if (sep)
4923 add_pathsep(dest);
4924 STRCAT(dest, fname2);
4925 }
4926 return dest;
4927}
4928
Bram Moolenaard6754642005-01-17 22:18:45 +00004929/*
4930 * Concatenate two strings and return the result in allocated memory.
4931 * Returns NULL when out of memory.
4932 */
4933 char_u *
4934concat_str(str1, str2)
4935 char_u *str1;
4936 char_u *str2;
4937{
4938 char_u *dest;
4939 size_t l = STRLEN(str1);
4940
4941 dest = alloc((unsigned)(l + STRLEN(str2) + 1L));
4942 if (dest != NULL)
4943 {
4944 STRCPY(dest, str1);
4945 STRCPY(dest + l, str2);
4946 }
4947 return dest;
4948}
Bram Moolenaard6754642005-01-17 22:18:45 +00004949
Bram Moolenaar071d4272004-06-13 20:20:40 +00004950/*
4951 * Add a path separator to a file name, unless it already ends in a path
4952 * separator.
4953 */
4954 void
4955add_pathsep(p)
4956 char_u *p;
4957{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004958 if (*p != NUL && !after_pathsep(p, p + STRLEN(p)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004959 STRCAT(p, PATHSEPSTR);
4960}
4961
4962/*
4963 * FullName_save - Make an allocated copy of a full file name.
4964 * Returns NULL when out of memory.
4965 */
4966 char_u *
4967FullName_save(fname, force)
4968 char_u *fname;
4969 int force; /* force expansion, even when it already looks
4970 like a full path name */
4971{
4972 char_u *buf;
4973 char_u *new_fname = NULL;
4974
4975 if (fname == NULL)
4976 return NULL;
4977
4978 buf = alloc((unsigned)MAXPATHL);
4979 if (buf != NULL)
4980 {
4981 if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
4982 new_fname = vim_strsave(buf);
4983 else
4984 new_fname = vim_strsave(fname);
4985 vim_free(buf);
4986 }
4987 return new_fname;
4988}
4989
4990#if defined(FEAT_CINDENT) || defined(FEAT_SYN_HL)
4991
4992static char_u *skip_string __ARGS((char_u *p));
4993
4994/*
4995 * Find the start of a comment, not knowing if we are in a comment right now.
4996 * Search starts at w_cursor.lnum and goes backwards.
4997 */
4998 pos_T *
4999find_start_comment(ind_maxcomment) /* XXX */
5000 int ind_maxcomment;
5001{
5002 pos_T *pos;
5003 char_u *line;
5004 char_u *p;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005005 int cur_maxcomment = ind_maxcomment;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005006
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005007 for (;;)
5008 {
5009 pos = findmatchlimit(NULL, '*', FM_BACKWARD, cur_maxcomment);
5010 if (pos == NULL)
5011 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005012
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005013 /*
5014 * Check if the comment start we found is inside a string.
5015 * If it is then restrict the search to below this line and try again.
5016 */
5017 line = ml_get(pos->lnum);
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00005018 for (p = line; *p && (colnr_T)(p - line) < pos->col; ++p)
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005019 p = skip_string(p);
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00005020 if ((colnr_T)(p - line) <= pos->col)
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005021 break;
5022 cur_maxcomment = curwin->w_cursor.lnum - pos->lnum - 1;
5023 if (cur_maxcomment <= 0)
5024 {
5025 pos = NULL;
5026 break;
5027 }
5028 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005029 return pos;
5030}
5031
5032/*
5033 * Skip to the end of a "string" and a 'c' character.
5034 * If there is no string or character, return argument unmodified.
5035 */
5036 static char_u *
5037skip_string(p)
5038 char_u *p;
5039{
5040 int i;
5041
5042 /*
5043 * We loop, because strings may be concatenated: "date""time".
5044 */
5045 for ( ; ; ++p)
5046 {
5047 if (p[0] == '\'') /* 'c' or '\n' or '\000' */
5048 {
5049 if (!p[1]) /* ' at end of line */
5050 break;
5051 i = 2;
5052 if (p[1] == '\\') /* '\n' or '\000' */
5053 {
5054 ++i;
5055 while (vim_isdigit(p[i - 1])) /* '\000' */
5056 ++i;
5057 }
5058 if (p[i] == '\'') /* check for trailing ' */
5059 {
5060 p += i;
5061 continue;
5062 }
5063 }
5064 else if (p[0] == '"') /* start of string */
5065 {
5066 for (++p; p[0]; ++p)
5067 {
5068 if (p[0] == '\\' && p[1] != NUL)
5069 ++p;
5070 else if (p[0] == '"') /* end of string */
5071 break;
5072 }
5073 if (p[0] == '"')
5074 continue;
5075 }
5076 break; /* no string found */
5077 }
5078 if (!*p)
5079 --p; /* backup from NUL */
5080 return p;
5081}
5082#endif /* FEAT_CINDENT || FEAT_SYN_HL */
5083
5084#if defined(FEAT_CINDENT) || defined(PROTO)
5085
5086/*
5087 * Do C or expression indenting on the current line.
5088 */
5089 void
5090do_c_expr_indent()
5091{
5092# ifdef FEAT_EVAL
5093 if (*curbuf->b_p_inde != NUL)
5094 fixthisline(get_expr_indent);
5095 else
5096# endif
5097 fixthisline(get_c_indent);
5098}
5099
5100/*
5101 * Functions for C-indenting.
5102 * Most of this originally comes from Eric Fischer.
5103 */
5104/*
5105 * Below "XXX" means that this function may unlock the current line.
5106 */
5107
5108static char_u *cin_skipcomment __ARGS((char_u *));
5109static int cin_nocode __ARGS((char_u *));
5110static pos_T *find_line_comment __ARGS((void));
5111static int cin_islabel_skip __ARGS((char_u **));
5112static int cin_isdefault __ARGS((char_u *));
5113static char_u *after_label __ARGS((char_u *l));
5114static int get_indent_nolabel __ARGS((linenr_T lnum));
5115static int skip_label __ARGS((linenr_T, char_u **pp, int ind_maxcomment));
5116static int cin_first_id_amount __ARGS((void));
5117static int cin_get_equal_amount __ARGS((linenr_T lnum));
5118static int cin_ispreproc __ARGS((char_u *));
5119static int cin_ispreproc_cont __ARGS((char_u **pp, linenr_T *lnump));
5120static int cin_iscomment __ARGS((char_u *));
5121static int cin_islinecomment __ARGS((char_u *));
5122static int cin_isterminated __ARGS((char_u *, int, int));
5123static int cin_isinit __ARGS((void));
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005124static int cin_isfuncdecl __ARGS((char_u **, linenr_T, linenr_T, int, int));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005125static int cin_isif __ARGS((char_u *));
5126static int cin_iselse __ARGS((char_u *));
5127static int cin_isdo __ARGS((char_u *));
5128static int cin_iswhileofdo __ARGS((char_u *, linenr_T, int));
Bram Moolenaarb345d492012-04-09 20:42:26 +02005129static int cin_is_if_for_while_before_offset __ARGS((char_u *line, int *poffset));
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005130static int cin_iswhileofdo_end __ARGS((int terminated, int ind_maxparen, int ind_maxcomment));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005131static int cin_isbreak __ARGS((char_u *));
Bram Moolenaare7c56862007-08-04 10:14:52 +00005132static int cin_is_cpp_baseclass __ARGS((colnr_T *col));
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005133static int get_baseclass_amount __ARGS((int col, int ind_maxparen, int ind_maxcomment, int ind_cpp_baseclass));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005134static int cin_ends_in __ARGS((char_u *, char_u *, char_u *));
5135static int cin_skip2pos __ARGS((pos_T *trypos));
5136static pos_T *find_start_brace __ARGS((int));
5137static pos_T *find_match_paren __ARGS((int, int));
5138static int corr_ind_maxparen __ARGS((int ind_maxparen, pos_T *startpos));
5139static int find_last_paren __ARGS((char_u *l, int start, int end));
5140static int find_match __ARGS((int lookfor, linenr_T ourscope, int ind_maxparen, int ind_maxcomment));
Bram Moolenaared38b0a2011-05-25 15:16:18 +02005141static int cin_is_cpp_namespace __ARGS((char_u *));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005142
Bram Moolenaar39353fd2007-03-27 09:02:11 +00005143static int ind_hash_comment = 0; /* # starts a comment */
5144
Bram Moolenaar071d4272004-06-13 20:20:40 +00005145/*
5146 * Skip over white space and C comments within the line.
Bram Moolenaar39353fd2007-03-27 09:02:11 +00005147 * Also skip over Perl/shell comments if desired.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005148 */
5149 static char_u *
5150cin_skipcomment(s)
5151 char_u *s;
5152{
5153 while (*s)
5154 {
Bram Moolenaar39353fd2007-03-27 09:02:11 +00005155 char_u *prev_s = s;
5156
Bram Moolenaar071d4272004-06-13 20:20:40 +00005157 s = skipwhite(s);
Bram Moolenaar39353fd2007-03-27 09:02:11 +00005158
5159 /* Perl/shell # comment comment continues until eol. Require a space
5160 * before # to avoid recognizing $#array. */
5161 if (ind_hash_comment != 0 && s != prev_s && *s == '#')
5162 {
5163 s += STRLEN(s);
5164 break;
5165 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005166 if (*s != '/')
5167 break;
5168 ++s;
5169 if (*s == '/') /* slash-slash comment continues till eol */
5170 {
5171 s += STRLEN(s);
5172 break;
5173 }
5174 if (*s != '*')
5175 break;
5176 for (++s; *s; ++s) /* skip slash-star comment */
5177 if (s[0] == '*' && s[1] == '/')
5178 {
5179 s += 2;
5180 break;
5181 }
5182 }
5183 return s;
5184}
5185
5186/*
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005187 * Return TRUE if there is no code at *s. White space and comments are
Bram Moolenaar071d4272004-06-13 20:20:40 +00005188 * not considered code.
5189 */
5190 static int
5191cin_nocode(s)
5192 char_u *s;
5193{
5194 return *cin_skipcomment(s) == NUL;
5195}
5196
5197/*
5198 * Check previous lines for a "//" line comment, skipping over blank lines.
5199 */
5200 static pos_T *
5201find_line_comment() /* XXX */
5202{
5203 static pos_T pos;
5204 char_u *line;
5205 char_u *p;
5206
5207 pos = curwin->w_cursor;
5208 while (--pos.lnum > 0)
5209 {
5210 line = ml_get(pos.lnum);
5211 p = skipwhite(line);
5212 if (cin_islinecomment(p))
5213 {
5214 pos.col = (int)(p - line);
5215 return &pos;
5216 }
5217 if (*p != NUL)
5218 break;
5219 }
5220 return NULL;
5221}
5222
5223/*
5224 * Check if string matches "label:"; move to character after ':' if true.
5225 */
5226 static int
5227cin_islabel_skip(s)
5228 char_u **s;
5229{
5230 if (!vim_isIDc(**s)) /* need at least one ID character */
5231 return FALSE;
5232
5233 while (vim_isIDc(**s))
5234 (*s)++;
5235
5236 *s = cin_skipcomment(*s);
5237
5238 /* "::" is not a label, it's C++ */
5239 return (**s == ':' && *++*s != ':');
5240}
5241
5242/*
5243 * Recognize a label: "label:".
5244 * Note: curwin->w_cursor must be where we are looking for the label.
5245 */
5246 int
5247cin_islabel(ind_maxcomment) /* XXX */
5248 int ind_maxcomment;
5249{
5250 char_u *s;
5251
5252 s = cin_skipcomment(ml_get_curline());
5253
5254 /*
5255 * Exclude "default" from labels, since it should be indented
5256 * like a switch label. Same for C++ scope declarations.
5257 */
5258 if (cin_isdefault(s))
5259 return FALSE;
5260 if (cin_isscopedecl(s))
5261 return FALSE;
5262
5263 if (cin_islabel_skip(&s))
5264 {
5265 /*
5266 * Only accept a label if the previous line is terminated or is a case
5267 * label.
5268 */
5269 pos_T cursor_save;
5270 pos_T *trypos;
5271 char_u *line;
5272
5273 cursor_save = curwin->w_cursor;
5274 while (curwin->w_cursor.lnum > 1)
5275 {
5276 --curwin->w_cursor.lnum;
5277
5278 /*
5279 * If we're in a comment now, skip to the start of the comment.
5280 */
5281 curwin->w_cursor.col = 0;
5282 if ((trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
5283 curwin->w_cursor = *trypos;
5284
5285 line = ml_get_curline();
5286 if (cin_ispreproc(line)) /* ignore #defines, #if, etc. */
5287 continue;
5288 if (*(line = cin_skipcomment(line)) == NUL)
5289 continue;
5290
5291 curwin->w_cursor = cursor_save;
5292 if (cin_isterminated(line, TRUE, FALSE)
5293 || cin_isscopedecl(line)
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005294 || cin_iscase(line, TRUE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005295 || (cin_islabel_skip(&line) && cin_nocode(line)))
5296 return TRUE;
5297 return FALSE;
5298 }
5299 curwin->w_cursor = cursor_save;
5300 return TRUE; /* label at start of file??? */
5301 }
5302 return FALSE;
5303}
5304
5305/*
5306 * Recognize structure initialization and enumerations.
5307 * Q&D-Implementation:
5308 * check for "=" at end or "[typedef] enum" at beginning of line.
5309 */
5310 static int
5311cin_isinit(void)
5312{
5313 char_u *s;
5314
5315 s = cin_skipcomment(ml_get_curline());
5316
5317 if (STRNCMP(s, "typedef", 7) == 0 && !vim_isIDc(s[7]))
5318 s = cin_skipcomment(s + 7);
5319
Bram Moolenaara5285652011-12-14 20:05:21 +01005320 if (STRNCMP(s, "static", 6) == 0 && !vim_isIDc(s[6]))
5321 s = cin_skipcomment(s + 6);
5322
Bram Moolenaar071d4272004-06-13 20:20:40 +00005323 if (STRNCMP(s, "enum", 4) == 0 && !vim_isIDc(s[4]))
5324 return TRUE;
5325
5326 if (cin_ends_in(s, (char_u *)"=", (char_u *)"{"))
5327 return TRUE;
5328
5329 return FALSE;
5330}
5331
5332/*
5333 * Recognize a switch label: "case .*:" or "default:".
5334 */
5335 int
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005336cin_iscase(s, strict)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005337 char_u *s;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005338 int strict; /* Allow relaxed check of case statement for JS */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005339{
5340 s = cin_skipcomment(s);
5341 if (STRNCMP(s, "case", 4) == 0 && !vim_isIDc(s[4]))
5342 {
5343 for (s += 4; *s; ++s)
5344 {
5345 s = cin_skipcomment(s);
5346 if (*s == ':')
5347 {
5348 if (s[1] == ':') /* skip over "::" for C++ */
5349 ++s;
5350 else
5351 return TRUE;
5352 }
5353 if (*s == '\'' && s[1] && s[2] == '\'')
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005354 s += 2; /* skip over ':' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005355 else if (*s == '/' && (s[1] == '*' || s[1] == '/'))
5356 return FALSE; /* stop at comment */
5357 else if (*s == '"')
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005358 {
5359 /* JS etc. */
5360 if (strict)
5361 return FALSE; /* stop at string */
5362 else
5363 return TRUE;
5364 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005365 }
5366 return FALSE;
5367 }
5368
5369 if (cin_isdefault(s))
5370 return TRUE;
5371 return FALSE;
5372}
5373
5374/*
5375 * Recognize a "default" switch label.
5376 */
5377 static int
5378cin_isdefault(s)
5379 char_u *s;
5380{
5381 return (STRNCMP(s, "default", 7) == 0
5382 && *(s = cin_skipcomment(s + 7)) == ':'
5383 && s[1] != ':');
5384}
5385
5386/*
Bram Moolenaar1a509df2010-08-01 17:59:57 +02005387 * Recognize a "public/private/protected" scope declaration label.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005388 */
5389 int
5390cin_isscopedecl(s)
5391 char_u *s;
5392{
5393 int i;
5394
5395 s = cin_skipcomment(s);
5396 if (STRNCMP(s, "public", 6) == 0)
5397 i = 6;
5398 else if (STRNCMP(s, "protected", 9) == 0)
5399 i = 9;
5400 else if (STRNCMP(s, "private", 7) == 0)
5401 i = 7;
5402 else
5403 return FALSE;
5404 return (*(s = cin_skipcomment(s + i)) == ':' && s[1] != ':');
5405}
5406
Bram Moolenaared38b0a2011-05-25 15:16:18 +02005407/* Maximum number of lines to search back for a "namespace" line. */
5408#define FIND_NAMESPACE_LIM 20
5409
5410/*
5411 * Recognize a "namespace" scope declaration.
5412 */
5413 static int
5414cin_is_cpp_namespace(s)
5415 char_u *s;
5416{
5417 char_u *p;
5418 int has_name = FALSE;
5419
5420 s = cin_skipcomment(s);
5421 if (STRNCMP(s, "namespace", 9) == 0 && (s[9] == NUL || !vim_iswordc(s[9])))
5422 {
5423 p = cin_skipcomment(skipwhite(s + 9));
5424 while (*p != NUL)
5425 {
5426 if (vim_iswhite(*p))
5427 {
5428 has_name = TRUE; /* found end of a name */
5429 p = cin_skipcomment(skipwhite(p));
5430 }
5431 else if (*p == '{')
5432 {
5433 break;
5434 }
5435 else if (vim_iswordc(*p))
5436 {
5437 if (has_name)
5438 return FALSE; /* word character after skipping past name */
5439 ++p;
5440 }
5441 else
5442 {
5443 return FALSE;
5444 }
5445 }
5446 return TRUE;
5447 }
5448 return FALSE;
5449}
5450
Bram Moolenaar071d4272004-06-13 20:20:40 +00005451/*
5452 * Return a pointer to the first non-empty non-comment character after a ':'.
5453 * Return NULL if not found.
5454 * case 234: a = b;
5455 * ^
5456 */
5457 static char_u *
5458after_label(l)
5459 char_u *l;
5460{
5461 for ( ; *l; ++l)
5462 {
5463 if (*l == ':')
5464 {
5465 if (l[1] == ':') /* skip over "::" for C++ */
5466 ++l;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005467 else if (!cin_iscase(l + 1, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005468 break;
5469 }
5470 else if (*l == '\'' && l[1] && l[2] == '\'')
5471 l += 2; /* skip over 'x' */
5472 }
5473 if (*l == NUL)
5474 return NULL;
5475 l = cin_skipcomment(l + 1);
5476 if (*l == NUL)
5477 return NULL;
5478 return l;
5479}
5480
5481/*
5482 * Get indent of line "lnum", skipping a label.
5483 * Return 0 if there is nothing after the label.
5484 */
5485 static int
5486get_indent_nolabel(lnum) /* XXX */
5487 linenr_T lnum;
5488{
5489 char_u *l;
5490 pos_T fp;
5491 colnr_T col;
5492 char_u *p;
5493
5494 l = ml_get(lnum);
5495 p = after_label(l);
5496 if (p == NULL)
5497 return 0;
5498
5499 fp.col = (colnr_T)(p - l);
5500 fp.lnum = lnum;
5501 getvcol(curwin, &fp, &col, NULL, NULL);
5502 return (int)col;
5503}
5504
5505/*
5506 * Find indent for line "lnum", ignoring any case or jump label.
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005507 * Also return a pointer to the text (after the label) in "pp".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005508 * label: if (asdf && asdfasdf)
5509 * ^
5510 */
5511 static int
5512skip_label(lnum, pp, ind_maxcomment)
5513 linenr_T lnum;
5514 char_u **pp;
5515 int ind_maxcomment;
5516{
5517 char_u *l;
5518 int amount;
5519 pos_T cursor_save;
5520
5521 cursor_save = curwin->w_cursor;
5522 curwin->w_cursor.lnum = lnum;
5523 l = ml_get_curline();
5524 /* XXX */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005525 if (cin_iscase(l, FALSE) || cin_isscopedecl(l)
5526 || cin_islabel(ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005527 {
5528 amount = get_indent_nolabel(lnum);
5529 l = after_label(ml_get_curline());
5530 if (l == NULL) /* just in case */
5531 l = ml_get_curline();
5532 }
5533 else
5534 {
5535 amount = get_indent();
5536 l = ml_get_curline();
5537 }
5538 *pp = l;
5539
5540 curwin->w_cursor = cursor_save;
5541 return amount;
5542}
5543
5544/*
5545 * Return the indent of the first variable name after a type in a declaration.
5546 * int a, indent of "a"
5547 * static struct foo b, indent of "b"
5548 * enum bla c, indent of "c"
5549 * Returns zero when it doesn't look like a declaration.
5550 */
5551 static int
5552cin_first_id_amount()
5553{
5554 char_u *line, *p, *s;
5555 int len;
5556 pos_T fp;
5557 colnr_T col;
5558
5559 line = ml_get_curline();
5560 p = skipwhite(line);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005561 len = (int)(skiptowhite(p) - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005562 if (len == 6 && STRNCMP(p, "static", 6) == 0)
5563 {
5564 p = skipwhite(p + 6);
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00005565 len = (int)(skiptowhite(p) - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005566 }
5567 if (len == 6 && STRNCMP(p, "struct", 6) == 0)
5568 p = skipwhite(p + 6);
5569 else if (len == 4 && STRNCMP(p, "enum", 4) == 0)
5570 p = skipwhite(p + 4);
5571 else if ((len == 8 && STRNCMP(p, "unsigned", 8) == 0)
5572 || (len == 6 && STRNCMP(p, "signed", 6) == 0))
5573 {
5574 s = skipwhite(p + len);
5575 if ((STRNCMP(s, "int", 3) == 0 && vim_iswhite(s[3]))
5576 || (STRNCMP(s, "long", 4) == 0 && vim_iswhite(s[4]))
5577 || (STRNCMP(s, "short", 5) == 0 && vim_iswhite(s[5]))
5578 || (STRNCMP(s, "char", 4) == 0 && vim_iswhite(s[4])))
5579 p = s;
5580 }
5581 for (len = 0; vim_isIDc(p[len]); ++len)
5582 ;
5583 if (len == 0 || !vim_iswhite(p[len]) || cin_nocode(p))
5584 return 0;
5585
5586 p = skipwhite(p + len);
5587 fp.lnum = curwin->w_cursor.lnum;
5588 fp.col = (colnr_T)(p - line);
5589 getvcol(curwin, &fp, &col, NULL, NULL);
5590 return (int)col;
5591}
5592
5593/*
5594 * Return the indent of the first non-blank after an equal sign.
5595 * char *foo = "here";
5596 * Return zero if no (useful) equal sign found.
5597 * Return -1 if the line above "lnum" ends in a backslash.
5598 * foo = "asdf\
5599 * asdf\
5600 * here";
5601 */
5602 static int
5603cin_get_equal_amount(lnum)
5604 linenr_T lnum;
5605{
5606 char_u *line;
5607 char_u *s;
5608 colnr_T col;
5609 pos_T fp;
5610
5611 if (lnum > 1)
5612 {
5613 line = ml_get(lnum - 1);
5614 if (*line != NUL && line[STRLEN(line) - 1] == '\\')
5615 return -1;
5616 }
5617
5618 line = s = ml_get(lnum);
5619 while (*s != NUL && vim_strchr((char_u *)"=;{}\"'", *s) == NULL)
5620 {
5621 if (cin_iscomment(s)) /* ignore comments */
5622 s = cin_skipcomment(s);
5623 else
5624 ++s;
5625 }
5626 if (*s != '=')
5627 return 0;
5628
5629 s = skipwhite(s + 1);
5630 if (cin_nocode(s))
5631 return 0;
5632
5633 if (*s == '"') /* nice alignment for continued strings */
5634 ++s;
5635
5636 fp.lnum = lnum;
5637 fp.col = (colnr_T)(s - line);
5638 getvcol(curwin, &fp, &col, NULL, NULL);
5639 return (int)col;
5640}
5641
5642/*
5643 * Recognize a preprocessor statement: Any line that starts with '#'.
5644 */
5645 static int
5646cin_ispreproc(s)
5647 char_u *s;
5648{
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005649 if (*skipwhite(s) == '#')
Bram Moolenaar071d4272004-06-13 20:20:40 +00005650 return TRUE;
5651 return FALSE;
5652}
5653
5654/*
5655 * Return TRUE if line "*pp" at "*lnump" is a preprocessor statement or a
5656 * continuation line of a preprocessor statement. Decrease "*lnump" to the
5657 * start and return the line in "*pp".
5658 */
5659 static int
5660cin_ispreproc_cont(pp, lnump)
5661 char_u **pp;
5662 linenr_T *lnump;
5663{
5664 char_u *line = *pp;
5665 linenr_T lnum = *lnump;
5666 int retval = FALSE;
5667
Bram Moolenaard8e9bb22005-07-09 21:14:46 +00005668 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005669 {
5670 if (cin_ispreproc(line))
5671 {
5672 retval = TRUE;
5673 *lnump = lnum;
5674 break;
5675 }
5676 if (lnum == 1)
5677 break;
5678 line = ml_get(--lnum);
5679 if (*line == NUL || line[STRLEN(line) - 1] != '\\')
5680 break;
5681 }
5682
5683 if (lnum != *lnump)
5684 *pp = ml_get(*lnump);
5685 return retval;
5686}
5687
5688/*
5689 * Recognize the start of a C or C++ comment.
5690 */
5691 static int
5692cin_iscomment(p)
5693 char_u *p;
5694{
5695 return (p[0] == '/' && (p[1] == '*' || p[1] == '/'));
5696}
5697
5698/*
5699 * Recognize the start of a "//" comment.
5700 */
5701 static int
5702cin_islinecomment(p)
5703 char_u *p;
5704{
5705 return (p[0] == '/' && p[1] == '/');
5706}
5707
5708/*
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005709 * Recognize a line that starts with '{' or '}', or ends with ';', ',', '{' or
5710 * '}'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005711 * Don't consider "} else" a terminated line.
Bram Moolenaar496f9512011-05-19 16:35:09 +02005712 * If a line begins with an "else", only consider it terminated if no unmatched
5713 * opening braces follow (handle "else { foo();" correctly).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005714 * Return the character terminating the line (ending char's have precedence if
5715 * both apply in order to determine initializations).
5716 */
5717 static int
5718cin_isterminated(s, incl_open, incl_comma)
5719 char_u *s;
5720 int incl_open; /* include '{' at the end as terminator */
5721 int incl_comma; /* recognize a trailing comma */
5722{
Bram Moolenaar496f9512011-05-19 16:35:09 +02005723 char_u found_start = 0;
5724 unsigned n_open = 0;
5725 int is_else = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005726
5727 s = cin_skipcomment(s);
5728
5729 if (*s == '{' || (*s == '}' && !cin_iselse(s)))
5730 found_start = *s;
5731
Bram Moolenaar496f9512011-05-19 16:35:09 +02005732 if (!found_start)
5733 is_else = cin_iselse(s);
5734
Bram Moolenaar071d4272004-06-13 20:20:40 +00005735 while (*s)
5736 {
5737 /* skip over comments, "" strings and 'c'haracters */
5738 s = skip_string(cin_skipcomment(s));
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005739 if (*s == '}' && n_open > 0)
5740 --n_open;
Bram Moolenaar496f9512011-05-19 16:35:09 +02005741 if ((!is_else || n_open == 0)
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005742 && (*s == ';' || *s == '}' || (incl_comma && *s == ','))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005743 && cin_nocode(s + 1))
5744 return *s;
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005745 else if (*s == '{')
5746 {
5747 if (incl_open && cin_nocode(s + 1))
5748 return *s;
5749 else
5750 ++n_open;
5751 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005752
5753 if (*s)
5754 s++;
5755 }
5756 return found_start;
5757}
5758
5759/*
5760 * Recognize the basic picture of a function declaration -- it needs to
5761 * have an open paren somewhere and a close paren at the end of the line and
5762 * no semicolons anywhere.
5763 * When a line ends in a comma we continue looking in the next line.
5764 * "sp" points to a string with the line. When looking at other lines it must
5765 * be restored to the line. When it's NULL fetch lines here.
5766 * "lnum" is where we start looking.
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005767 * "min_lnum" is the line before which we will not be looking.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005768 */
5769 static int
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005770cin_isfuncdecl(sp, first_lnum, min_lnum, ind_maxparen, ind_maxcomment)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005771 char_u **sp;
5772 linenr_T first_lnum;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005773 linenr_T min_lnum;
5774 int ind_maxparen;
5775 int ind_maxcomment;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005776{
5777 char_u *s;
5778 linenr_T lnum = first_lnum;
5779 int retval = FALSE;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005780 pos_T *trypos;
5781 int just_started = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005782
5783 if (sp == NULL)
5784 s = ml_get(lnum);
5785 else
5786 s = *sp;
5787
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005788 if (find_last_paren(s, '(', ')')
5789 && (trypos = find_match_paren(ind_maxparen, ind_maxcomment)) != NULL)
5790 {
5791 lnum = trypos->lnum;
5792 if (lnum < min_lnum)
5793 return FALSE;
5794
5795 s = ml_get(lnum);
5796 }
5797
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005798 /* Ignore line starting with #. */
5799 if (cin_ispreproc(s))
5800 return FALSE;
5801
Bram Moolenaar071d4272004-06-13 20:20:40 +00005802 while (*s && *s != '(' && *s != ';' && *s != '\'' && *s != '"')
5803 {
5804 if (cin_iscomment(s)) /* ignore comments */
5805 s = cin_skipcomment(s);
5806 else
5807 ++s;
5808 }
5809 if (*s != '(')
5810 return FALSE; /* ';', ' or " before any () or no '(' */
5811
5812 while (*s && *s != ';' && *s != '\'' && *s != '"')
5813 {
5814 if (*s == ')' && cin_nocode(s + 1))
5815 {
5816 /* ')' at the end: may have found a match
5817 * Check for he previous line not to end in a backslash:
5818 * #if defined(x) && \
5819 * defined(y)
5820 */
5821 lnum = first_lnum - 1;
5822 s = ml_get(lnum);
5823 if (*s == NUL || s[STRLEN(s) - 1] != '\\')
5824 retval = TRUE;
5825 goto done;
5826 }
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005827 if ((*s == ',' && cin_nocode(s + 1)) || s[1] == NUL || cin_nocode(s))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005828 {
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005829 int comma = (*s == ',');
5830
5831 /* ',' at the end: continue looking in the next line.
5832 * At the end: check for ',' in the next line, for this style:
5833 * func(arg1
5834 * , arg2) */
5835 for (;;)
5836 {
5837 if (lnum >= curbuf->b_ml.ml_line_count)
5838 break;
5839 s = ml_get(++lnum);
5840 if (!cin_ispreproc(s))
5841 break;
5842 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005843 if (lnum >= curbuf->b_ml.ml_line_count)
5844 break;
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005845 /* Require a comma at end of the line or a comma or ')' at the
5846 * start of next line. */
5847 s = skipwhite(s);
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005848 if (!just_started && (!comma && *s != ',' && *s != ')'))
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005849 break;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005850 just_started = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005851 }
5852 else if (cin_iscomment(s)) /* ignore comments */
5853 s = cin_skipcomment(s);
5854 else
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005855 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005856 ++s;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005857 just_started = FALSE;
5858 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005859 }
5860
5861done:
5862 if (lnum != first_lnum && sp != NULL)
5863 *sp = ml_get(first_lnum);
5864
5865 return retval;
5866}
5867
5868 static int
5869cin_isif(p)
5870 char_u *p;
5871{
5872 return (STRNCMP(p, "if", 2) == 0 && !vim_isIDc(p[2]));
5873}
5874
5875 static int
5876cin_iselse(p)
5877 char_u *p;
5878{
5879 if (*p == '}') /* accept "} else" */
5880 p = cin_skipcomment(p + 1);
5881 return (STRNCMP(p, "else", 4) == 0 && !vim_isIDc(p[4]));
5882}
5883
5884 static int
5885cin_isdo(p)
5886 char_u *p;
5887{
5888 return (STRNCMP(p, "do", 2) == 0 && !vim_isIDc(p[2]));
5889}
5890
5891/*
5892 * Check if this is a "while" that should have a matching "do".
5893 * We only accept a "while (condition) ;", with only white space between the
5894 * ')' and ';'. The condition may be spread over several lines.
5895 */
5896 static int
5897cin_iswhileofdo(p, lnum, ind_maxparen) /* XXX */
5898 char_u *p;
5899 linenr_T lnum;
5900 int ind_maxparen;
5901{
5902 pos_T cursor_save;
5903 pos_T *trypos;
5904 int retval = FALSE;
5905
5906 p = cin_skipcomment(p);
5907 if (*p == '}') /* accept "} while (cond);" */
5908 p = cin_skipcomment(p + 1);
5909 if (STRNCMP(p, "while", 5) == 0 && !vim_isIDc(p[5]))
5910 {
5911 cursor_save = curwin->w_cursor;
5912 curwin->w_cursor.lnum = lnum;
5913 curwin->w_cursor.col = 0;
5914 p = ml_get_curline();
5915 while (*p && *p != 'w') /* skip any '}', until the 'w' of the "while" */
5916 {
5917 ++p;
5918 ++curwin->w_cursor.col;
5919 }
5920 if ((trypos = findmatchlimit(NULL, 0, 0, ind_maxparen)) != NULL
5921 && *cin_skipcomment(ml_get_pos(trypos) + 1) == ';')
5922 retval = TRUE;
5923 curwin->w_cursor = cursor_save;
5924 }
5925 return retval;
5926}
5927
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005928/*
Bram Moolenaarb345d492012-04-09 20:42:26 +02005929 * Check whether in "p" there is an "if", "for" or "while" before "*poffset".
Bram Moolenaar3675fa02012-04-05 17:17:42 +02005930 * Return 0 if there is none.
5931 * Otherwise return !0 and update "*poffset" to point to the place where the
5932 * string was found.
5933 */
5934 static int
Bram Moolenaarb345d492012-04-09 20:42:26 +02005935cin_is_if_for_while_before_offset(line, poffset)
Bram Moolenaar3675fa02012-04-05 17:17:42 +02005936 char_u *line;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02005937 int *poffset;
5938{
Bram Moolenaarb345d492012-04-09 20:42:26 +02005939 int offset = *poffset;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02005940
5941 if (offset-- < 2)
5942 return 0;
5943 while (offset > 2 && vim_iswhite(line[offset]))
5944 --offset;
5945
5946 offset -= 1;
5947 if (!STRNCMP(line + offset, "if", 2))
5948 goto probablyFound;
5949
5950 if (offset >= 1)
5951 {
5952 offset -= 1;
5953 if (!STRNCMP(line + offset, "for", 3))
5954 goto probablyFound;
5955
5956 if (offset >= 2)
5957 {
5958 offset -= 2;
5959 if (!STRNCMP(line + offset, "while", 5))
5960 goto probablyFound;
5961 }
5962 }
Bram Moolenaar3675fa02012-04-05 17:17:42 +02005963 return 0;
Bram Moolenaarb345d492012-04-09 20:42:26 +02005964
Bram Moolenaar3675fa02012-04-05 17:17:42 +02005965probablyFound:
5966 if (!offset || !vim_isIDc(line[offset - 1]))
5967 {
5968 *poffset = offset;
5969 return 1;
5970 }
5971 return 0;
5972}
5973
5974/*
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005975 * Return TRUE if we are at the end of a do-while.
5976 * do
5977 * nothing;
5978 * while (foo
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00005979 * && bar); <-- here
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005980 * Adjust the cursor to the line with "while".
5981 */
5982 static int
5983cin_iswhileofdo_end(terminated, ind_maxparen, ind_maxcomment)
5984 int terminated;
5985 int ind_maxparen;
5986 int ind_maxcomment;
5987{
5988 char_u *line;
5989 char_u *p;
5990 char_u *s;
5991 pos_T *trypos;
5992 int i;
5993
5994 if (terminated != ';') /* there must be a ';' at the end */
5995 return FALSE;
5996
5997 p = line = ml_get_curline();
5998 while (*p != NUL)
5999 {
6000 p = cin_skipcomment(p);
6001 if (*p == ')')
6002 {
6003 s = skipwhite(p + 1);
6004 if (*s == ';' && cin_nocode(s + 1))
6005 {
6006 /* Found ");" at end of the line, now check there is "while"
6007 * before the matching '('. XXX */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006008 i = (int)(p - line);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006009 curwin->w_cursor.col = i;
6010 trypos = find_match_paren(ind_maxparen, ind_maxcomment);
6011 if (trypos != NULL)
6012 {
6013 s = cin_skipcomment(ml_get(trypos->lnum));
6014 if (*s == '}') /* accept "} while (cond);" */
6015 s = cin_skipcomment(s + 1);
6016 if (STRNCMP(s, "while", 5) == 0 && !vim_isIDc(s[5]))
6017 {
6018 curwin->w_cursor.lnum = trypos->lnum;
6019 return TRUE;
6020 }
6021 }
6022
6023 /* Searching may have made "line" invalid, get it again. */
6024 line = ml_get_curline();
6025 p = line + i;
6026 }
6027 }
6028 if (*p != NUL)
6029 ++p;
6030 }
6031 return FALSE;
6032}
6033
Bram Moolenaar071d4272004-06-13 20:20:40 +00006034 static int
6035cin_isbreak(p)
6036 char_u *p;
6037{
6038 return (STRNCMP(p, "break", 5) == 0 && !vim_isIDc(p[5]));
6039}
6040
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006041/*
6042 * Find the position of a C++ base-class declaration or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006043 * constructor-initialization. eg:
6044 *
6045 * class MyClass :
6046 * baseClass <-- here
6047 * class MyClass : public baseClass,
6048 * anotherBaseClass <-- here (should probably lineup ??)
6049 * MyClass::MyClass(...) :
6050 * baseClass(...) <-- here (constructor-initialization)
Bram Moolenaar18144c82006-04-12 21:52:12 +00006051 *
6052 * This is a lot of guessing. Watch out for "cond ? func() : foo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00006053 */
6054 static int
Bram Moolenaare7c56862007-08-04 10:14:52 +00006055cin_is_cpp_baseclass(col)
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006056 colnr_T *col; /* return: column to align with */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006057{
6058 char_u *s;
6059 int class_or_struct, lookfor_ctor_init, cpp_base_class;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006060 linenr_T lnum = curwin->w_cursor.lnum;
Bram Moolenaare7c56862007-08-04 10:14:52 +00006061 char_u *line = ml_get_curline();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006062
6063 *col = 0;
6064
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006065 s = skipwhite(line);
6066 if (*s == '#') /* skip #define FOO x ? (x) : x */
6067 return FALSE;
6068 s = cin_skipcomment(s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006069 if (*s == NUL)
6070 return FALSE;
6071
6072 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
6073
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006074 /* Search for a line starting with '#', empty, ending in ';' or containing
6075 * '{' or '}' and start below it. This handles the following situations:
6076 * a = cond ?
6077 * func() :
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00006078 * asdf;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006079 * func::foo()
6080 * : something
6081 * {}
6082 * Foo::Foo (int one, int two)
6083 * : something(4),
6084 * somethingelse(3)
6085 * {}
6086 */
6087 while (lnum > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006088 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00006089 line = ml_get(lnum - 1);
6090 s = skipwhite(line);
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006091 if (*s == '#' || *s == NUL)
6092 break;
6093 while (*s != NUL)
6094 {
6095 s = cin_skipcomment(s);
6096 if (*s == '{' || *s == '}'
6097 || (*s == ';' && cin_nocode(s + 1)))
6098 break;
6099 if (*s != NUL)
6100 ++s;
6101 }
6102 if (*s != NUL)
6103 break;
6104 --lnum;
6105 }
6106
Bram Moolenaare7c56862007-08-04 10:14:52 +00006107 line = ml_get(lnum);
6108 s = cin_skipcomment(line);
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006109 for (;;)
6110 {
6111 if (*s == NUL)
6112 {
6113 if (lnum == curwin->w_cursor.lnum)
6114 break;
6115 /* Continue in the cursor line. */
Bram Moolenaare7c56862007-08-04 10:14:52 +00006116 line = ml_get(++lnum);
6117 s = cin_skipcomment(line);
6118 if (*s == NUL)
6119 continue;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006120 }
6121
Bram Moolenaaraede6ce2011-05-10 11:56:30 +02006122 if (s[0] == '"')
6123 s = skip_string(s) + 1;
6124 else if (s[0] == ':')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006125 {
6126 if (s[1] == ':')
6127 {
6128 /* skip double colon. It can't be a constructor
6129 * initialization any more */
6130 lookfor_ctor_init = FALSE;
6131 s = cin_skipcomment(s + 2);
6132 }
6133 else if (lookfor_ctor_init || class_or_struct)
6134 {
6135 /* we have something found, that looks like the start of
Bram Moolenaare21877a2008-02-13 09:58:14 +00006136 * cpp-base-class-declaration or constructor-initialization */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006137 cpp_base_class = TRUE;
6138 lookfor_ctor_init = class_or_struct = FALSE;
6139 *col = 0;
6140 s = cin_skipcomment(s + 1);
6141 }
6142 else
6143 s = cin_skipcomment(s + 1);
6144 }
6145 else if ((STRNCMP(s, "class", 5) == 0 && !vim_isIDc(s[5]))
6146 || (STRNCMP(s, "struct", 6) == 0 && !vim_isIDc(s[6])))
6147 {
6148 class_or_struct = TRUE;
6149 lookfor_ctor_init = FALSE;
6150
6151 if (*s == 'c')
6152 s = cin_skipcomment(s + 5);
6153 else
6154 s = cin_skipcomment(s + 6);
6155 }
6156 else
6157 {
6158 if (s[0] == '{' || s[0] == '}' || s[0] == ';')
6159 {
6160 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
6161 }
6162 else if (s[0] == ')')
6163 {
6164 /* Constructor-initialization is assumed if we come across
6165 * something like "):" */
6166 class_or_struct = FALSE;
6167 lookfor_ctor_init = TRUE;
6168 }
Bram Moolenaar18144c82006-04-12 21:52:12 +00006169 else if (s[0] == '?')
6170 {
6171 /* Avoid seeing '() :' after '?' as constructor init. */
6172 return FALSE;
6173 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006174 else if (!vim_isIDc(s[0]))
6175 {
6176 /* if it is not an identifier, we are wrong */
6177 class_or_struct = FALSE;
6178 lookfor_ctor_init = FALSE;
6179 }
6180 else if (*col == 0)
6181 {
6182 /* it can't be a constructor-initialization any more */
6183 lookfor_ctor_init = FALSE;
6184
6185 /* the first statement starts here: lineup with this one... */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006186 if (cpp_base_class)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006187 *col = (colnr_T)(s - line);
6188 }
6189
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006190 /* When the line ends in a comma don't align with it. */
6191 if (lnum == curwin->w_cursor.lnum && *s == ',' && cin_nocode(s + 1))
6192 *col = 0;
6193
Bram Moolenaar071d4272004-06-13 20:20:40 +00006194 s = cin_skipcomment(s + 1);
6195 }
6196 }
6197
6198 return cpp_base_class;
6199}
6200
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006201 static int
6202get_baseclass_amount(col, ind_maxparen, ind_maxcomment, ind_cpp_baseclass)
6203 int col;
6204 int ind_maxparen;
6205 int ind_maxcomment;
6206 int ind_cpp_baseclass;
6207{
6208 int amount;
6209 colnr_T vcol;
6210 pos_T *trypos;
6211
6212 if (col == 0)
6213 {
6214 amount = get_indent();
6215 if (find_last_paren(ml_get_curline(), '(', ')')
6216 && (trypos = find_match_paren(ind_maxparen,
6217 ind_maxcomment)) != NULL)
6218 amount = get_indent_lnum(trypos->lnum); /* XXX */
6219 if (!cin_ends_in(ml_get_curline(), (char_u *)",", NULL))
6220 amount += ind_cpp_baseclass;
6221 }
6222 else
6223 {
6224 curwin->w_cursor.col = col;
6225 getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
6226 amount = (int)vcol;
6227 }
6228 if (amount < ind_cpp_baseclass)
6229 amount = ind_cpp_baseclass;
6230 return amount;
6231}
6232
Bram Moolenaar071d4272004-06-13 20:20:40 +00006233/*
6234 * Return TRUE if string "s" ends with the string "find", possibly followed by
6235 * white space and comments. Skip strings and comments.
6236 * Ignore "ignore" after "find" if it's not NULL.
6237 */
6238 static int
6239cin_ends_in(s, find, ignore)
6240 char_u *s;
6241 char_u *find;
6242 char_u *ignore;
6243{
6244 char_u *p = s;
6245 char_u *r;
6246 int len = (int)STRLEN(find);
6247
6248 while (*p != NUL)
6249 {
6250 p = cin_skipcomment(p);
6251 if (STRNCMP(p, find, len) == 0)
6252 {
6253 r = skipwhite(p + len);
6254 if (ignore != NULL && STRNCMP(r, ignore, STRLEN(ignore)) == 0)
6255 r = skipwhite(r + STRLEN(ignore));
6256 if (cin_nocode(r))
6257 return TRUE;
6258 }
6259 if (*p != NUL)
6260 ++p;
6261 }
6262 return FALSE;
6263}
6264
6265/*
6266 * Skip strings, chars and comments until at or past "trypos".
6267 * Return the column found.
6268 */
6269 static int
6270cin_skip2pos(trypos)
6271 pos_T *trypos;
6272{
6273 char_u *line;
6274 char_u *p;
6275
6276 p = line = ml_get(trypos->lnum);
6277 while (*p && (colnr_T)(p - line) < trypos->col)
6278 {
6279 if (cin_iscomment(p))
6280 p = cin_skipcomment(p);
6281 else
6282 {
6283 p = skip_string(p);
6284 ++p;
6285 }
6286 }
6287 return (int)(p - line);
6288}
6289
6290/*
6291 * Find the '{' at the start of the block we are in.
6292 * Return NULL if no match found.
6293 * Ignore a '{' that is in a comment, makes indenting the next three lines
6294 * work. */
6295/* foo() */
6296/* { */
6297/* } */
6298
6299 static pos_T *
6300find_start_brace(ind_maxcomment) /* XXX */
6301 int ind_maxcomment;
6302{
6303 pos_T cursor_save;
6304 pos_T *trypos;
6305 pos_T *pos;
6306 static pos_T pos_copy;
6307
6308 cursor_save = curwin->w_cursor;
6309 while ((trypos = findmatchlimit(NULL, '{', FM_BLOCKSTOP, 0)) != NULL)
6310 {
6311 pos_copy = *trypos; /* copy pos_T, next findmatch will change it */
6312 trypos = &pos_copy;
6313 curwin->w_cursor = *trypos;
6314 pos = NULL;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006315 /* ignore the { if it's in a // or / * * / comment */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006316 if ((colnr_T)cin_skip2pos(trypos) == trypos->col
6317 && (pos = find_start_comment(ind_maxcomment)) == NULL) /* XXX */
6318 break;
6319 if (pos != NULL)
6320 curwin->w_cursor.lnum = pos->lnum;
6321 }
6322 curwin->w_cursor = cursor_save;
6323 return trypos;
6324}
6325
6326/*
6327 * Find the matching '(', failing if it is in a comment.
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006328 * Return NULL if no match found.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006329 */
6330 static pos_T *
6331find_match_paren(ind_maxparen, ind_maxcomment) /* XXX */
6332 int ind_maxparen;
6333 int ind_maxcomment;
6334{
6335 pos_T cursor_save;
6336 pos_T *trypos;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006337 static pos_T pos_copy;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006338
6339 cursor_save = curwin->w_cursor;
6340 if ((trypos = findmatchlimit(NULL, '(', 0, ind_maxparen)) != NULL)
6341 {
6342 /* check if the ( is in a // comment */
6343 if ((colnr_T)cin_skip2pos(trypos) > trypos->col)
6344 trypos = NULL;
6345 else
6346 {
6347 pos_copy = *trypos; /* copy trypos, findmatch will change it */
6348 trypos = &pos_copy;
6349 curwin->w_cursor = *trypos;
6350 if (find_start_comment(ind_maxcomment) != NULL) /* XXX */
6351 trypos = NULL;
6352 }
6353 }
6354 curwin->w_cursor = cursor_save;
6355 return trypos;
6356}
6357
6358/*
6359 * Return ind_maxparen corrected for the difference in line number between the
6360 * cursor position and "startpos". This makes sure that searching for a
6361 * matching paren above the cursor line doesn't find a match because of
6362 * looking a few lines further.
6363 */
6364 static int
6365corr_ind_maxparen(ind_maxparen, startpos)
6366 int ind_maxparen;
6367 pos_T *startpos;
6368{
6369 long n = (long)startpos->lnum - (long)curwin->w_cursor.lnum;
6370
6371 if (n > 0 && n < ind_maxparen / 2)
6372 return ind_maxparen - (int)n;
6373 return ind_maxparen;
6374}
6375
6376/*
6377 * Set w_cursor.col to the column number of the last unmatched ')' or '{' in
Bram Moolenaar6d8f9c62011-11-30 13:03:28 +01006378 * line "l". "l" must point to the start of the line.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006379 */
6380 static int
6381find_last_paren(l, start, end)
6382 char_u *l;
6383 int start, end;
6384{
6385 int i;
6386 int retval = FALSE;
6387 int open_count = 0;
6388
6389 curwin->w_cursor.col = 0; /* default is start of line */
6390
Bram Moolenaar6d8f9c62011-11-30 13:03:28 +01006391 for (i = 0; l[i] != NUL; i++)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006392 {
6393 i = (int)(cin_skipcomment(l + i) - l); /* ignore parens in comments */
6394 i = (int)(skip_string(l + i) - l); /* ignore parens in quotes */
6395 if (l[i] == start)
6396 ++open_count;
6397 else if (l[i] == end)
6398 {
6399 if (open_count > 0)
6400 --open_count;
6401 else
6402 {
6403 curwin->w_cursor.col = i;
6404 retval = TRUE;
6405 }
6406 }
6407 }
6408 return retval;
6409}
6410
6411 int
6412get_c_indent()
6413{
6414 /*
6415 * spaces from a block's opening brace the prevailing indent for that
6416 * block should be
6417 */
6418 int ind_level = curbuf->b_p_sw;
6419
6420 /*
6421 * spaces from the edge of the line an open brace that's at the end of a
6422 * line is imagined to be.
6423 */
6424 int ind_open_imag = 0;
6425
6426 /*
Bram Moolenaar1a509df2010-08-01 17:59:57 +02006427 * spaces from the prevailing indent for a line that is not preceded by
Bram Moolenaar071d4272004-06-13 20:20:40 +00006428 * an opening brace.
6429 */
6430 int ind_no_brace = 0;
6431
6432 /*
6433 * column where the first { of a function should be located }
6434 */
6435 int ind_first_open = 0;
6436
6437 /*
6438 * spaces from the prevailing indent a leftmost open brace should be
6439 * located
6440 */
6441 int ind_open_extra = 0;
6442
6443 /*
6444 * spaces from the matching open brace (real location for one at the left
6445 * edge; imaginary location from one that ends a line) the matching close
6446 * brace should be located
6447 */
6448 int ind_close_extra = 0;
6449
6450 /*
6451 * spaces from the edge of the line an open brace sitting in the leftmost
6452 * column is imagined to be
6453 */
6454 int ind_open_left_imag = 0;
6455
6456 /*
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006457 * Spaces jump labels should be shifted to the left if N is non-negative,
6458 * otherwise the jump label will be put to column 1.
6459 */
6460 int ind_jump_label = -1;
6461
6462 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006463 * spaces from the switch() indent a "case xx" label should be located
6464 */
6465 int ind_case = curbuf->b_p_sw;
6466
6467 /*
6468 * spaces from the "case xx:" code after a switch() should be located
6469 */
6470 int ind_case_code = curbuf->b_p_sw;
6471
6472 /*
6473 * lineup break at end of case in switch() with case label
6474 */
6475 int ind_case_break = 0;
6476
6477 /*
6478 * spaces from the class declaration indent a scope declaration label
6479 * should be located
6480 */
6481 int ind_scopedecl = curbuf->b_p_sw;
6482
6483 /*
6484 * spaces from the scope declaration label code should be located
6485 */
6486 int ind_scopedecl_code = curbuf->b_p_sw;
6487
6488 /*
6489 * amount K&R-style parameters should be indented
6490 */
6491 int ind_param = curbuf->b_p_sw;
6492
6493 /*
6494 * amount a function type spec should be indented
6495 */
6496 int ind_func_type = curbuf->b_p_sw;
6497
6498 /*
6499 * amount a cpp base class declaration or constructor initialization
6500 * should be indented
6501 */
6502 int ind_cpp_baseclass = curbuf->b_p_sw;
6503
6504 /*
6505 * additional spaces beyond the prevailing indent a continuation line
6506 * should be located
6507 */
6508 int ind_continuation = curbuf->b_p_sw;
6509
6510 /*
6511 * spaces from the indent of the line with an unclosed parentheses
6512 */
6513 int ind_unclosed = curbuf->b_p_sw * 2;
6514
6515 /*
6516 * spaces from the indent of the line with an unclosed parentheses, which
6517 * itself is also unclosed
6518 */
6519 int ind_unclosed2 = curbuf->b_p_sw;
6520
6521 /*
6522 * suppress ignoring spaces from the indent of a line starting with an
6523 * unclosed parentheses.
6524 */
6525 int ind_unclosed_noignore = 0;
6526
6527 /*
6528 * If the opening paren is the last nonwhite character on the line, and
6529 * ind_unclosed_wrapped is nonzero, use this indent relative to the outer
6530 * context (for very long lines).
6531 */
6532 int ind_unclosed_wrapped = 0;
6533
6534 /*
6535 * suppress ignoring white space when lining up with the character after
6536 * an unclosed parentheses.
6537 */
6538 int ind_unclosed_whiteok = 0;
6539
6540 /*
6541 * indent a closing parentheses under the line start of the matching
6542 * opening parentheses.
6543 */
6544 int ind_matching_paren = 0;
6545
6546 /*
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006547 * indent a closing parentheses under the previous line.
6548 */
6549 int ind_paren_prev = 0;
6550
6551 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006552 * Extra indent for comments.
6553 */
6554 int ind_comment = 0;
6555
6556 /*
6557 * spaces from the comment opener when there is nothing after it.
6558 */
6559 int ind_in_comment = 3;
6560
6561 /*
6562 * boolean: if non-zero, use ind_in_comment even if there is something
6563 * after the comment opener.
6564 */
6565 int ind_in_comment2 = 0;
6566
6567 /*
6568 * max lines to search for an open paren
6569 */
6570 int ind_maxparen = 20;
6571
6572 /*
6573 * max lines to search for an open comment
6574 */
6575 int ind_maxcomment = 70;
6576
6577 /*
6578 * handle braces for java code
6579 */
6580 int ind_java = 0;
6581
6582 /*
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006583 * not to confuse JS object properties with labels
6584 */
6585 int ind_js = 0;
6586
6587 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006588 * handle blocked cases correctly
6589 */
6590 int ind_keep_case_label = 0;
6591
Bram Moolenaared38b0a2011-05-25 15:16:18 +02006592 /*
6593 * handle C++ namespace
6594 */
6595 int ind_cpp_namespace = 0;
6596
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006597 /*
6598 * handle continuation lines containing conditions of if(), for() and
6599 * while()
6600 */
6601 int ind_if_for_while = 0;
6602
Bram Moolenaar071d4272004-06-13 20:20:40 +00006603 pos_T cur_curpos;
6604 int amount;
6605 int scope_amount;
Bram Moolenaarb21e5842006-04-16 18:30:08 +00006606 int cur_amount = MAXCOL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006607 colnr_T col;
6608 char_u *theline;
6609 char_u *linecopy;
6610 pos_T *trypos;
6611 pos_T *tryposBrace = NULL;
6612 pos_T our_paren_pos;
6613 char_u *start;
6614 int start_brace;
Bram Moolenaare21877a2008-02-13 09:58:14 +00006615#define BRACE_IN_COL0 1 /* '{' is in column 0 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006616#define BRACE_AT_START 2 /* '{' is at start of line */
6617#define BRACE_AT_END 3 /* '{' is at end of line */
6618 linenr_T ourscope;
6619 char_u *l;
6620 char_u *look;
6621 char_u terminated;
6622 int lookfor;
6623#define LOOKFOR_INITIAL 0
6624#define LOOKFOR_IF 1
6625#define LOOKFOR_DO 2
6626#define LOOKFOR_CASE 3
6627#define LOOKFOR_ANY 4
6628#define LOOKFOR_TERM 5
6629#define LOOKFOR_UNTERM 6
6630#define LOOKFOR_SCOPEDECL 7
6631#define LOOKFOR_NOBREAK 8
6632#define LOOKFOR_CPP_BASECLASS 9
6633#define LOOKFOR_ENUM_OR_INIT 10
6634
6635 int whilelevel;
6636 linenr_T lnum;
6637 char_u *options;
Bram Moolenaar48d27922012-06-13 13:40:48 +02006638 char_u *digits;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006639 int fraction = 0; /* init for GCC */
6640 int divider;
6641 int n;
6642 int iscase;
6643 int lookfor_break;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02006644 int lookfor_cpp_namespace = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006645 int cont_amount = 0; /* amount for continuation line */
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006646 int original_line_islabel;
Bram Moolenaare79d1532011-10-04 18:03:47 +02006647 int added_to_amount = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006648
6649 for (options = curbuf->b_p_cino; *options; )
6650 {
6651 l = options++;
6652 if (*options == '-')
6653 ++options;
Bram Moolenaar48d27922012-06-13 13:40:48 +02006654 digits = options; /* remember where the digits start */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006655 n = getdigits(&options);
6656 divider = 0;
6657 if (*options == '.') /* ".5s" means a fraction */
6658 {
6659 fraction = atol((char *)++options);
6660 while (VIM_ISDIGIT(*options))
6661 {
6662 ++options;
6663 if (divider)
6664 divider *= 10;
6665 else
6666 divider = 10;
6667 }
6668 }
6669 if (*options == 's') /* "2s" means two times 'shiftwidth' */
6670 {
Bram Moolenaar48d27922012-06-13 13:40:48 +02006671 if (options == digits)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006672 n = curbuf->b_p_sw; /* just "s" is one 'shiftwidth' */
6673 else
6674 {
6675 n *= curbuf->b_p_sw;
6676 if (divider)
6677 n += (curbuf->b_p_sw * fraction + divider / 2) / divider;
6678 }
6679 ++options;
6680 }
6681 if (l[1] == '-')
6682 n = -n;
6683 /* When adding an entry here, also update the default 'cinoptions' in
Bram Moolenaar39353fd2007-03-27 09:02:11 +00006684 * doc/indent.txt, and add explanation for it! */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006685 switch (*l)
6686 {
6687 case '>': ind_level = n; break;
6688 case 'e': ind_open_imag = n; break;
6689 case 'n': ind_no_brace = n; break;
6690 case 'f': ind_first_open = n; break;
6691 case '{': ind_open_extra = n; break;
6692 case '}': ind_close_extra = n; break;
6693 case '^': ind_open_left_imag = n; break;
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006694 case 'L': ind_jump_label = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006695 case ':': ind_case = n; break;
6696 case '=': ind_case_code = n; break;
6697 case 'b': ind_case_break = n; break;
6698 case 'p': ind_param = n; break;
6699 case 't': ind_func_type = n; break;
6700 case '/': ind_comment = n; break;
6701 case 'c': ind_in_comment = n; break;
6702 case 'C': ind_in_comment2 = n; break;
6703 case 'i': ind_cpp_baseclass = n; break;
6704 case '+': ind_continuation = n; break;
6705 case '(': ind_unclosed = n; break;
6706 case 'u': ind_unclosed2 = n; break;
6707 case 'U': ind_unclosed_noignore = n; break;
6708 case 'W': ind_unclosed_wrapped = n; break;
6709 case 'w': ind_unclosed_whiteok = n; break;
6710 case 'm': ind_matching_paren = n; break;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006711 case 'M': ind_paren_prev = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006712 case ')': ind_maxparen = n; break;
6713 case '*': ind_maxcomment = n; break;
6714 case 'g': ind_scopedecl = n; break;
6715 case 'h': ind_scopedecl_code = n; break;
6716 case 'j': ind_java = n; break;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006717 case 'J': ind_js = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006718 case 'l': ind_keep_case_label = n; break;
Bram Moolenaar39353fd2007-03-27 09:02:11 +00006719 case '#': ind_hash_comment = n; break;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02006720 case 'N': ind_cpp_namespace = n; break;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006721 case 'k': ind_if_for_while = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006722 }
Bram Moolenaardfdf3c42010-03-23 18:22:46 +01006723 if (*options == ',')
6724 ++options;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006725 }
6726
6727 /* remember where the cursor was when we started */
6728 cur_curpos = curwin->w_cursor;
6729
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006730 /* if we are at line 1 0 is fine, right? */
6731 if (cur_curpos.lnum == 1)
6732 return 0;
6733
Bram Moolenaar071d4272004-06-13 20:20:40 +00006734 /* Get a copy of the current contents of the line.
6735 * This is required, because only the most recent line obtained with
6736 * ml_get is valid! */
6737 linecopy = vim_strsave(ml_get(cur_curpos.lnum));
6738 if (linecopy == NULL)
6739 return 0;
6740
6741 /*
6742 * In insert mode and the cursor is on a ')' truncate the line at the
6743 * cursor position. We don't want to line up with the matching '(' when
6744 * inserting new stuff.
6745 * For unknown reasons the cursor might be past the end of the line, thus
6746 * check for that.
6747 */
6748 if ((State & INSERT)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006749 && curwin->w_cursor.col < (colnr_T)STRLEN(linecopy)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006750 && linecopy[curwin->w_cursor.col] == ')')
6751 linecopy[curwin->w_cursor.col] = NUL;
6752
6753 theline = skipwhite(linecopy);
6754
6755 /* move the cursor to the start of the line */
6756
6757 curwin->w_cursor.col = 0;
6758
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006759 original_line_islabel = cin_islabel(ind_maxcomment); /* XXX */
6760
Bram Moolenaar071d4272004-06-13 20:20:40 +00006761 /*
6762 * #defines and so on always go at the left when included in 'cinkeys'.
6763 */
6764 if (*theline == '#' && (*linecopy == '#' || in_cinkeys('#', ' ', TRUE)))
6765 {
6766 amount = 0;
6767 }
6768
6769 /*
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006770 * Is it a non-case label? Then that goes at the left margin too unless:
6771 * - JS flag is set.
6772 * - 'L' item has a positive value.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006773 */
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006774 else if (original_line_islabel && !ind_js && ind_jump_label < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006775 {
6776 amount = 0;
6777 }
6778
6779 /*
6780 * If we're inside a "//" comment and there is a "//" comment in a
6781 * previous line, lineup with that one.
6782 */
6783 else if (cin_islinecomment(theline)
6784 && (trypos = find_line_comment()) != NULL) /* XXX */
6785 {
6786 /* find how indented the line beginning the comment is */
6787 getvcol(curwin, trypos, &col, NULL, NULL);
6788 amount = col;
6789 }
6790
6791 /*
6792 * If we're inside a comment and not looking at the start of the
6793 * comment, try using the 'comments' option.
6794 */
6795 else if (!cin_iscomment(theline)
6796 && (trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
6797 {
6798 int lead_start_len = 2;
6799 int lead_middle_len = 1;
6800 char_u lead_start[COM_MAX_LEN]; /* start-comment string */
6801 char_u lead_middle[COM_MAX_LEN]; /* middle-comment string */
6802 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
6803 char_u *p;
6804 int start_align = 0;
6805 int start_off = 0;
6806 int done = FALSE;
6807
6808 /* find how indented the line beginning the comment is */
6809 getvcol(curwin, trypos, &col, NULL, NULL);
6810 amount = col;
Bram Moolenaar4aa97422011-04-11 14:27:38 +02006811 *lead_start = NUL;
6812 *lead_middle = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006813
6814 p = curbuf->b_p_com;
6815 while (*p != NUL)
6816 {
6817 int align = 0;
6818 int off = 0;
6819 int what = 0;
6820
6821 while (*p != NUL && *p != ':')
6822 {
6823 if (*p == COM_START || *p == COM_END || *p == COM_MIDDLE)
6824 what = *p++;
6825 else if (*p == COM_LEFT || *p == COM_RIGHT)
6826 align = *p++;
6827 else if (VIM_ISDIGIT(*p) || *p == '-')
6828 off = getdigits(&p);
6829 else
6830 ++p;
6831 }
6832
6833 if (*p == ':')
6834 ++p;
6835 (void)copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
6836 if (what == COM_START)
6837 {
6838 STRCPY(lead_start, lead_end);
6839 lead_start_len = (int)STRLEN(lead_start);
6840 start_off = off;
6841 start_align = align;
6842 }
6843 else if (what == COM_MIDDLE)
6844 {
6845 STRCPY(lead_middle, lead_end);
6846 lead_middle_len = (int)STRLEN(lead_middle);
6847 }
6848 else if (what == COM_END)
6849 {
6850 /* If our line starts with the middle comment string, line it
6851 * up with the comment opener per the 'comments' option. */
6852 if (STRNCMP(theline, lead_middle, lead_middle_len) == 0
6853 && STRNCMP(theline, lead_end, STRLEN(lead_end)) != 0)
6854 {
6855 done = TRUE;
6856 if (curwin->w_cursor.lnum > 1)
6857 {
6858 /* If the start comment string matches in the previous
Bram Moolenaare21877a2008-02-13 09:58:14 +00006859 * line, use the indent of that line plus offset. If
Bram Moolenaar071d4272004-06-13 20:20:40 +00006860 * the middle comment string matches in the previous
6861 * line, use the indent of that line. XXX */
6862 look = skipwhite(ml_get(curwin->w_cursor.lnum - 1));
6863 if (STRNCMP(look, lead_start, lead_start_len) == 0)
6864 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6865 else if (STRNCMP(look, lead_middle,
6866 lead_middle_len) == 0)
6867 {
6868 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6869 break;
6870 }
6871 /* If the start comment string doesn't match with the
6872 * start of the comment, skip this entry. XXX */
6873 else if (STRNCMP(ml_get(trypos->lnum) + trypos->col,
6874 lead_start, lead_start_len) != 0)
6875 continue;
6876 }
6877 if (start_off != 0)
6878 amount += start_off;
6879 else if (start_align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006880 amount += vim_strsize(lead_start)
6881 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006882 break;
6883 }
6884
6885 /* If our line starts with the end comment string, line it up
6886 * with the middle comment */
6887 if (STRNCMP(theline, lead_middle, lead_middle_len) != 0
6888 && STRNCMP(theline, lead_end, STRLEN(lead_end)) == 0)
6889 {
6890 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6891 /* XXX */
6892 if (off != 0)
6893 amount += off;
6894 else if (align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006895 amount += vim_strsize(lead_start)
6896 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006897 done = TRUE;
6898 break;
6899 }
6900 }
6901 }
6902
6903 /* If our line starts with an asterisk, line up with the
6904 * asterisk in the comment opener; otherwise, line up
6905 * with the first character of the comment text.
6906 */
6907 if (done)
6908 ;
6909 else if (theline[0] == '*')
6910 amount += 1;
6911 else
6912 {
6913 /*
6914 * If we are more than one line away from the comment opener, take
6915 * the indent of the previous non-empty line. If 'cino' has "CO"
6916 * and we are just below the comment opener and there are any
6917 * white characters after it line up with the text after it;
6918 * otherwise, add the amount specified by "c" in 'cino'
6919 */
6920 amount = -1;
6921 for (lnum = cur_curpos.lnum - 1; lnum > trypos->lnum; --lnum)
6922 {
6923 if (linewhite(lnum)) /* skip blank lines */
6924 continue;
6925 amount = get_indent_lnum(lnum); /* XXX */
6926 break;
6927 }
6928 if (amount == -1) /* use the comment opener */
6929 {
6930 if (!ind_in_comment2)
6931 {
6932 start = ml_get(trypos->lnum);
6933 look = start + trypos->col + 2; /* skip / and * */
6934 if (*look != NUL) /* if something after it */
6935 trypos->col = (colnr_T)(skipwhite(look) - start);
6936 }
6937 getvcol(curwin, trypos, &col, NULL, NULL);
6938 amount = col;
6939 if (ind_in_comment2 || *look == NUL)
6940 amount += ind_in_comment;
6941 }
6942 }
6943 }
6944
6945 /*
6946 * Are we inside parentheses or braces?
6947 */ /* XXX */
6948 else if (((trypos = find_match_paren(ind_maxparen, ind_maxcomment)) != NULL
6949 && ind_java == 0)
6950 || (tryposBrace = find_start_brace(ind_maxcomment)) != NULL
6951 || trypos != NULL)
6952 {
6953 if (trypos != NULL && tryposBrace != NULL)
6954 {
6955 /* Both an unmatched '(' and '{' is found. Use the one which is
6956 * closer to the current cursor position, set the other to NULL. */
6957 if (trypos->lnum != tryposBrace->lnum
6958 ? trypos->lnum < tryposBrace->lnum
6959 : trypos->col < tryposBrace->col)
6960 trypos = NULL;
6961 else
6962 tryposBrace = NULL;
6963 }
6964
6965 if (trypos != NULL)
6966 {
6967 /*
6968 * If the matching paren is more than one line away, use the indent of
6969 * a previous non-empty line that matches the same paren.
6970 */
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006971 if (theline[0] == ')' && ind_paren_prev)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006972 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006973 /* Line up with the start of the matching paren line. */
6974 amount = get_indent_lnum(curwin->w_cursor.lnum - 1); /* XXX */
6975 }
6976 else
6977 {
6978 amount = -1;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006979 our_paren_pos = *trypos;
6980 for (lnum = cur_curpos.lnum - 1; lnum > our_paren_pos.lnum; --lnum)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006981 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006982 l = skipwhite(ml_get(lnum));
6983 if (cin_nocode(l)) /* skip comment lines */
6984 continue;
6985 if (cin_ispreproc_cont(&l, &lnum))
6986 continue; /* ignore #define, #if, etc. */
6987 curwin->w_cursor.lnum = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006988
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006989 /* Skip a comment. XXX */
6990 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
6991 {
6992 lnum = trypos->lnum + 1;
6993 continue;
6994 }
6995
6996 /* XXX */
6997 if ((trypos = find_match_paren(
6998 corr_ind_maxparen(ind_maxparen, &cur_curpos),
Bram Moolenaar071d4272004-06-13 20:20:40 +00006999 ind_maxcomment)) != NULL
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007000 && trypos->lnum == our_paren_pos.lnum
7001 && trypos->col == our_paren_pos.col)
7002 {
7003 amount = get_indent_lnum(lnum); /* XXX */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007004
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007005 if (theline[0] == ')')
7006 {
7007 if (our_paren_pos.lnum != lnum
7008 && cur_amount > amount)
7009 cur_amount = amount;
7010 amount = -1;
7011 }
7012 break;
7013 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007014 }
7015 }
7016
7017 /*
7018 * Line up with line where the matching paren is. XXX
7019 * If the line starts with a '(' or the indent for unclosed
7020 * parentheses is zero, line up with the unclosed parentheses.
7021 */
7022 if (amount == -1)
7023 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007024 int ignore_paren_col = 0;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007025 int is_if_for_while = 0;
7026
7027 if (ind_if_for_while)
7028 {
7029 /* Look for the outermost opening parenthesis on this line
7030 * and check whether it belongs to an "if", "for" or "while". */
7031
7032 pos_T cursor_save = curwin->w_cursor;
7033 pos_T outermost;
7034 char_u *line;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007035
7036 trypos = &our_paren_pos;
7037 do {
7038 outermost = *trypos;
7039 curwin->w_cursor.lnum = outermost.lnum;
7040 curwin->w_cursor.col = outermost.col;
7041
7042 trypos = find_match_paren(ind_maxparen, ind_maxcomment);
7043 } while (trypos && trypos->lnum == outermost.lnum);
7044
7045 curwin->w_cursor = cursor_save;
7046
7047 line = ml_get(outermost.lnum);
7048
7049 is_if_for_while =
Bram Moolenaarb345d492012-04-09 20:42:26 +02007050 cin_is_if_for_while_before_offset(line, &outermost.col);
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007051 }
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007052
Bram Moolenaar071d4272004-06-13 20:20:40 +00007053 amount = skip_label(our_paren_pos.lnum, &look, ind_maxcomment);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007054 look = skipwhite(look);
7055 if (*look == '(')
7056 {
7057 linenr_T save_lnum = curwin->w_cursor.lnum;
7058 char_u *line;
7059 int look_col;
7060
7061 /* Ignore a '(' in front of the line that has a match before
7062 * our matching '('. */
7063 curwin->w_cursor.lnum = our_paren_pos.lnum;
7064 line = ml_get_curline();
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007065 look_col = (int)(look - line);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007066 curwin->w_cursor.col = look_col + 1;
7067 if ((trypos = findmatchlimit(NULL, ')', 0, ind_maxparen))
7068 != NULL
7069 && trypos->lnum == our_paren_pos.lnum
7070 && trypos->col < our_paren_pos.col)
7071 ignore_paren_col = trypos->col + 1;
7072
7073 curwin->w_cursor.lnum = save_lnum;
7074 look = ml_get(our_paren_pos.lnum) + look_col;
7075 }
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007076 if (theline[0] == ')' || (ind_unclosed == 0 && is_if_for_while == 0)
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007077 || (!ind_unclosed_noignore && *look == '('
7078 && ignore_paren_col == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007079 {
7080 /*
7081 * If we're looking at a close paren, line up right there;
7082 * otherwise, line up with the next (non-white) character.
7083 * When ind_unclosed_wrapped is set and the matching paren is
7084 * the last nonwhite character of the line, use either the
7085 * indent of the current line or the indentation of the next
7086 * outer paren and add ind_unclosed_wrapped (for very long
7087 * lines).
7088 */
7089 if (theline[0] != ')')
7090 {
7091 cur_amount = MAXCOL;
7092 l = ml_get(our_paren_pos.lnum);
7093 if (ind_unclosed_wrapped
7094 && cin_ends_in(l, (char_u *)"(", NULL))
7095 {
7096 /* look for opening unmatched paren, indent one level
7097 * for each additional level */
7098 n = 1;
7099 for (col = 0; col < our_paren_pos.col; ++col)
7100 {
7101 switch (l[col])
7102 {
7103 case '(':
7104 case '{': ++n;
7105 break;
7106
7107 case ')':
7108 case '}': if (n > 1)
7109 --n;
7110 break;
7111 }
7112 }
7113
7114 our_paren_pos.col = 0;
7115 amount += n * ind_unclosed_wrapped;
7116 }
7117 else if (ind_unclosed_whiteok)
7118 our_paren_pos.col++;
7119 else
7120 {
7121 col = our_paren_pos.col + 1;
7122 while (vim_iswhite(l[col]))
7123 col++;
7124 if (l[col] != NUL) /* In case of trailing space */
7125 our_paren_pos.col = col;
7126 else
7127 our_paren_pos.col++;
7128 }
7129 }
7130
7131 /*
7132 * Find how indented the paren is, or the character after it
7133 * if we did the above "if".
7134 */
7135 if (our_paren_pos.col > 0)
7136 {
7137 getvcol(curwin, &our_paren_pos, &col, NULL, NULL);
7138 if (cur_amount > (int)col)
7139 cur_amount = col;
7140 }
7141 }
7142
7143 if (theline[0] == ')' && ind_matching_paren)
7144 {
7145 /* Line up with the start of the matching paren line. */
7146 }
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007147 else if ((ind_unclosed == 0 && is_if_for_while == 0)
7148 || (!ind_unclosed_noignore
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007149 && *look == '(' && ignore_paren_col == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007150 {
7151 if (cur_amount != MAXCOL)
7152 amount = cur_amount;
7153 }
7154 else
7155 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007156 /* Add ind_unclosed2 for each '(' before our matching one, but
7157 * ignore (void) before the line (ignore_paren_col). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007158 col = our_paren_pos.col;
Bram Moolenaarb21e5842006-04-16 18:30:08 +00007159 while ((int)our_paren_pos.col > ignore_paren_col)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007160 {
7161 --our_paren_pos.col;
7162 switch (*ml_get_pos(&our_paren_pos))
7163 {
7164 case '(': amount += ind_unclosed2;
7165 col = our_paren_pos.col;
7166 break;
7167 case ')': amount -= ind_unclosed2;
7168 col = MAXCOL;
7169 break;
7170 }
7171 }
7172
7173 /* Use ind_unclosed once, when the first '(' is not inside
7174 * braces */
7175 if (col == MAXCOL)
7176 amount += ind_unclosed;
7177 else
7178 {
7179 curwin->w_cursor.lnum = our_paren_pos.lnum;
7180 curwin->w_cursor.col = col;
Bram Moolenaar367bec82011-04-11 14:26:19 +02007181 if (find_match_paren(ind_maxparen, ind_maxcomment) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007182 amount += ind_unclosed2;
7183 else
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007184 {
7185 if (is_if_for_while)
7186 amount += ind_if_for_while;
7187 else
7188 amount += ind_unclosed;
7189 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007190 }
7191 /*
7192 * For a line starting with ')' use the minimum of the two
7193 * positions, to avoid giving it more indent than the previous
7194 * lines:
7195 * func_long_name( if (x
7196 * arg && yy
7197 * ) ^ not here ) ^ not here
7198 */
7199 if (cur_amount < amount)
7200 amount = cur_amount;
7201 }
7202 }
7203
7204 /* add extra indent for a comment */
7205 if (cin_iscomment(theline))
7206 amount += ind_comment;
7207 }
7208
7209 /*
7210 * Are we at least inside braces, then?
7211 */
7212 else
7213 {
7214 trypos = tryposBrace;
7215
7216 ourscope = trypos->lnum;
7217 start = ml_get(ourscope);
7218
7219 /*
7220 * Now figure out how indented the line is in general.
7221 * If the brace was at the start of the line, we use that;
7222 * otherwise, check out the indentation of the line as
7223 * a whole and then add the "imaginary indent" to that.
7224 */
7225 look = skipwhite(start);
7226 if (*look == '{')
7227 {
7228 getvcol(curwin, trypos, &col, NULL, NULL);
7229 amount = col;
7230 if (*start == '{')
7231 start_brace = BRACE_IN_COL0;
7232 else
7233 start_brace = BRACE_AT_START;
7234 }
7235 else
7236 {
7237 /*
7238 * that opening brace might have been on a continuation
7239 * line. if so, find the start of the line.
7240 */
7241 curwin->w_cursor.lnum = ourscope;
7242
7243 /*
7244 * position the cursor over the rightmost paren, so that
7245 * matching it will take us back to the start of the line.
7246 */
7247 lnum = ourscope;
7248 if (find_last_paren(start, '(', ')')
7249 && (trypos = find_match_paren(ind_maxparen,
7250 ind_maxcomment)) != NULL)
7251 lnum = trypos->lnum;
7252
7253 /*
7254 * It could have been something like
7255 * case 1: if (asdf &&
7256 * ldfd) {
7257 * }
7258 */
Bram Moolenaar6ec154b2011-06-12 21:51:08 +02007259 if (ind_js || (ind_keep_case_label
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007260 && cin_iscase(skipwhite(ml_get_curline()), FALSE)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007261 amount = get_indent();
7262 else
7263 amount = skip_label(lnum, &l, ind_maxcomment);
7264
7265 start_brace = BRACE_AT_END;
7266 }
7267
7268 /*
7269 * if we're looking at a closing brace, that's where
7270 * we want to be. otherwise, add the amount of room
7271 * that an indent is supposed to be.
7272 */
7273 if (theline[0] == '}')
7274 {
7275 /*
7276 * they may want closing braces to line up with something
7277 * other than the open brace. indulge them, if so.
7278 */
7279 amount += ind_close_extra;
7280 }
7281 else
7282 {
7283 /*
7284 * If we're looking at an "else", try to find an "if"
7285 * to match it with.
7286 * If we're looking at a "while", try to find a "do"
7287 * to match it with.
7288 */
7289 lookfor = LOOKFOR_INITIAL;
7290 if (cin_iselse(theline))
7291 lookfor = LOOKFOR_IF;
7292 else if (cin_iswhileofdo(theline, cur_curpos.lnum, ind_maxparen))
7293 /* XXX */
7294 lookfor = LOOKFOR_DO;
7295 if (lookfor != LOOKFOR_INITIAL)
7296 {
7297 curwin->w_cursor.lnum = cur_curpos.lnum;
7298 if (find_match(lookfor, ourscope, ind_maxparen,
7299 ind_maxcomment) == OK)
7300 {
7301 amount = get_indent(); /* XXX */
7302 goto theend;
7303 }
7304 }
7305
7306 /*
7307 * We get here if we are not on an "while-of-do" or "else" (or
7308 * failed to find a matching "if").
7309 * Search backwards for something to line up with.
7310 * First set amount for when we don't find anything.
7311 */
7312
7313 /*
7314 * if the '{' is _really_ at the left margin, use the imaginary
7315 * location of a left-margin brace. Otherwise, correct the
7316 * location for ind_open_extra.
7317 */
7318
7319 if (start_brace == BRACE_IN_COL0) /* '{' is in column 0 */
7320 {
7321 amount = ind_open_left_imag;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007322 lookfor_cpp_namespace = TRUE;
7323 }
7324 else if (start_brace == BRACE_AT_START &&
7325 lookfor_cpp_namespace) /* '{' is at start */
7326 {
7327
7328 lookfor_cpp_namespace = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007329 }
7330 else
7331 {
7332 if (start_brace == BRACE_AT_END) /* '{' is at end of line */
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007333 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007334 amount += ind_open_imag;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007335
7336 l = skipwhite(ml_get_curline());
7337 if (cin_is_cpp_namespace(l))
7338 amount += ind_cpp_namespace;
7339 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007340 else
7341 {
7342 /* Compensate for adding ind_open_extra later. */
7343 amount -= ind_open_extra;
7344 if (amount < 0)
7345 amount = 0;
7346 }
7347 }
7348
7349 lookfor_break = FALSE;
7350
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007351 if (cin_iscase(theline, FALSE)) /* it's a switch() label */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007352 {
7353 lookfor = LOOKFOR_CASE; /* find a previous switch() label */
7354 amount += ind_case;
7355 }
7356 else if (cin_isscopedecl(theline)) /* private:, ... */
7357 {
7358 lookfor = LOOKFOR_SCOPEDECL; /* class decl is this block */
7359 amount += ind_scopedecl;
7360 }
7361 else
7362 {
7363 if (ind_case_break && cin_isbreak(theline)) /* break; ... */
7364 lookfor_break = TRUE;
7365
7366 lookfor = LOOKFOR_INITIAL;
7367 amount += ind_level; /* ind_level from start of block */
7368 }
7369 scope_amount = amount;
7370 whilelevel = 0;
7371
7372 /*
7373 * Search backwards. If we find something we recognize, line up
7374 * with that.
7375 *
7376 * if we're looking at an open brace, indent
7377 * the usual amount relative to the conditional
7378 * that opens the block.
7379 */
7380 curwin->w_cursor = cur_curpos;
7381 for (;;)
7382 {
7383 curwin->w_cursor.lnum--;
7384 curwin->w_cursor.col = 0;
7385
7386 /*
7387 * If we went all the way back to the start of our scope, line
7388 * up with it.
7389 */
7390 if (curwin->w_cursor.lnum <= ourscope)
7391 {
7392 /* we reached end of scope:
7393 * if looking for a enum or structure initialization
7394 * go further back:
7395 * if it is an initializer (enum xxx or xxx =), then
7396 * don't add ind_continuation, otherwise it is a variable
7397 * declaration:
7398 * int x,
7399 * here; <-- add ind_continuation
7400 */
7401 if (lookfor == LOOKFOR_ENUM_OR_INIT)
7402 {
7403 if (curwin->w_cursor.lnum == 0
7404 || curwin->w_cursor.lnum
7405 < ourscope - ind_maxparen)
7406 {
7407 /* nothing found (abuse ind_maxparen as limit)
7408 * assume terminated line (i.e. a variable
7409 * initialization) */
7410 if (cont_amount > 0)
7411 amount = cont_amount;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007412 else if (!ind_js)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007413 amount += ind_continuation;
7414 break;
7415 }
7416
7417 l = ml_get_curline();
7418
7419 /*
7420 * If we're in a comment now, skip to the start of the
7421 * comment.
7422 */
7423 trypos = find_start_comment(ind_maxcomment);
7424 if (trypos != NULL)
7425 {
7426 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007427 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007428 continue;
7429 }
7430
7431 /*
7432 * Skip preprocessor directives and blank lines.
7433 */
7434 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7435 continue;
7436
7437 if (cin_nocode(l))
7438 continue;
7439
7440 terminated = cin_isterminated(l, FALSE, TRUE);
7441
7442 /*
7443 * If we are at top level and the line looks like a
7444 * function declaration, we are done
7445 * (it's a variable declaration).
7446 */
7447 if (start_brace != BRACE_IN_COL0
Bram Moolenaarc367faa2011-12-14 20:21:35 +01007448 || !cin_isfuncdecl(&l, curwin->w_cursor.lnum,
7449 0, ind_maxparen, ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007450 {
7451 /* if the line is terminated with another ','
7452 * it is a continued variable initialization.
7453 * don't add extra indent.
7454 * TODO: does not work, if a function
7455 * declaration is split over multiple lines:
7456 * cin_isfuncdecl returns FALSE then.
7457 */
7458 if (terminated == ',')
7459 break;
7460
7461 /* if it es a enum declaration or an assignment,
7462 * we are done.
7463 */
7464 if (terminated != ';' && cin_isinit())
7465 break;
7466
7467 /* nothing useful found */
7468 if (terminated == 0 || terminated == '{')
7469 continue;
7470 }
7471
7472 if (terminated != ';')
7473 {
7474 /* Skip parens and braces. Position the cursor
7475 * over the rightmost paren, so that matching it
7476 * will take us back to the start of the line.
7477 */ /* XXX */
7478 trypos = NULL;
7479 if (find_last_paren(l, '(', ')'))
7480 trypos = find_match_paren(ind_maxparen,
7481 ind_maxcomment);
7482
7483 if (trypos == NULL && find_last_paren(l, '{', '}'))
7484 trypos = find_start_brace(ind_maxcomment);
7485
7486 if (trypos != NULL)
7487 {
7488 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007489 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007490 continue;
7491 }
7492 }
7493
7494 /* it's a variable declaration, add indentation
7495 * like in
7496 * int a,
7497 * b;
7498 */
7499 if (cont_amount > 0)
7500 amount = cont_amount;
7501 else
7502 amount += ind_continuation;
7503 }
7504 else if (lookfor == LOOKFOR_UNTERM)
7505 {
7506 if (cont_amount > 0)
7507 amount = cont_amount;
7508 else
7509 amount += ind_continuation;
7510 }
Bram Moolenaare79d1532011-10-04 18:03:47 +02007511 else
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007512 {
Bram Moolenaare79d1532011-10-04 18:03:47 +02007513 if (lookfor != LOOKFOR_TERM
Bram Moolenaar071d4272004-06-13 20:20:40 +00007514 && lookfor != LOOKFOR_CPP_BASECLASS)
Bram Moolenaare79d1532011-10-04 18:03:47 +02007515 {
7516 amount = scope_amount;
7517 if (theline[0] == '{')
7518 {
7519 amount += ind_open_extra;
7520 added_to_amount = ind_open_extra;
7521 }
7522 }
7523
7524 if (lookfor_cpp_namespace)
7525 {
7526 /*
7527 * Looking for C++ namespace, need to look further
7528 * back.
7529 */
7530 if (curwin->w_cursor.lnum == ourscope)
7531 continue;
7532
7533 if (curwin->w_cursor.lnum == 0
7534 || curwin->w_cursor.lnum
7535 < ourscope - FIND_NAMESPACE_LIM)
7536 break;
7537
7538 l = ml_get_curline();
7539
7540 /* If we're in a comment now, skip to the start of
7541 * the comment. */
7542 trypos = find_start_comment(ind_maxcomment);
7543 if (trypos != NULL)
7544 {
7545 curwin->w_cursor.lnum = trypos->lnum + 1;
7546 curwin->w_cursor.col = 0;
7547 continue;
7548 }
7549
7550 /* Skip preprocessor directives and blank lines. */
7551 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7552 continue;
7553
7554 /* Finally the actual check for "namespace". */
7555 if (cin_is_cpp_namespace(l))
7556 {
7557 amount += ind_cpp_namespace - added_to_amount;
7558 break;
7559 }
7560
7561 if (cin_nocode(l))
7562 continue;
7563 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007564 }
7565 break;
7566 }
7567
7568 /*
7569 * If we're in a comment now, skip to the start of the comment.
7570 */ /* XXX */
7571 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
7572 {
7573 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007574 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007575 continue;
7576 }
7577
7578 l = ml_get_curline();
7579
7580 /*
7581 * If this is a switch() label, may line up relative to that.
Bram Moolenaar18144c82006-04-12 21:52:12 +00007582 * If this is a C++ scope declaration, do the same.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007583 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007584 iscase = cin_iscase(l, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007585 if (iscase || cin_isscopedecl(l))
7586 {
7587 /* we are only looking for cpp base class
7588 * declaration/initialization any longer */
7589 if (lookfor == LOOKFOR_CPP_BASECLASS)
7590 break;
7591
7592 /* When looking for a "do" we are not interested in
7593 * labels. */
7594 if (whilelevel > 0)
7595 continue;
7596
7597 /*
7598 * case xx:
7599 * c = 99 + <- this indent plus continuation
7600 *-> here;
7601 */
7602 if (lookfor == LOOKFOR_UNTERM
7603 || lookfor == LOOKFOR_ENUM_OR_INIT)
7604 {
7605 if (cont_amount > 0)
7606 amount = cont_amount;
7607 else
7608 amount += ind_continuation;
7609 break;
7610 }
7611
7612 /*
7613 * case xx: <- line up with this case
7614 * x = 333;
7615 * case yy:
7616 */
7617 if ( (iscase && lookfor == LOOKFOR_CASE)
7618 || (iscase && lookfor_break)
7619 || (!iscase && lookfor == LOOKFOR_SCOPEDECL))
7620 {
7621 /*
7622 * Check that this case label is not for another
7623 * switch()
7624 */ /* XXX */
7625 if ((trypos = find_start_brace(ind_maxcomment)) ==
7626 NULL || trypos->lnum == ourscope)
7627 {
7628 amount = get_indent(); /* XXX */
7629 break;
7630 }
7631 continue;
7632 }
7633
7634 n = get_indent_nolabel(curwin->w_cursor.lnum); /* XXX */
7635
7636 /*
7637 * case xx: if (cond) <- line up with this if
7638 * y = y + 1;
7639 * -> s = 99;
7640 *
7641 * case xx:
7642 * if (cond) <- line up with this line
7643 * y = y + 1;
7644 * -> s = 99;
7645 */
7646 if (lookfor == LOOKFOR_TERM)
7647 {
7648 if (n)
7649 amount = n;
7650
7651 if (!lookfor_break)
7652 break;
7653 }
7654
7655 /*
7656 * case xx: x = x + 1; <- line up with this x
7657 * -> y = y + 1;
7658 *
7659 * case xx: if (cond) <- line up with this if
7660 * -> y = y + 1;
7661 */
7662 if (n)
7663 {
7664 amount = n;
7665 l = after_label(ml_get_curline());
7666 if (l != NULL && cin_is_cinword(l))
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007667 {
7668 if (theline[0] == '{')
7669 amount += ind_open_extra;
7670 else
7671 amount += ind_level + ind_no_brace;
7672 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007673 break;
7674 }
7675
7676 /*
7677 * Try to get the indent of a statement before the switch
7678 * label. If nothing is found, line up relative to the
7679 * switch label.
7680 * break; <- may line up with this line
7681 * case xx:
7682 * -> y = 1;
7683 */
7684 scope_amount = get_indent() + (iscase /* XXX */
7685 ? ind_case_code : ind_scopedecl_code);
7686 lookfor = ind_case_break ? LOOKFOR_NOBREAK : LOOKFOR_ANY;
7687 continue;
7688 }
7689
7690 /*
7691 * Looking for a switch() label or C++ scope declaration,
7692 * ignore other lines, skip {}-blocks.
7693 */
7694 if (lookfor == LOOKFOR_CASE || lookfor == LOOKFOR_SCOPEDECL)
7695 {
7696 if (find_last_paren(l, '{', '}') && (trypos =
7697 find_start_brace(ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007698 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007699 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007700 curwin->w_cursor.col = 0;
7701 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007702 continue;
7703 }
7704
7705 /*
7706 * Ignore jump labels with nothing after them.
7707 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007708 if (!ind_js && cin_islabel(ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007709 {
7710 l = after_label(ml_get_curline());
7711 if (l == NULL || cin_nocode(l))
7712 continue;
7713 }
7714
7715 /*
7716 * Ignore #defines, #if, etc.
7717 * Ignore comment and empty lines.
7718 * (need to get the line again, cin_islabel() may have
7719 * unlocked it)
7720 */
7721 l = ml_get_curline();
7722 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum)
7723 || cin_nocode(l))
7724 continue;
7725
7726 /*
7727 * Are we at the start of a cpp base class declaration or
7728 * constructor initialization?
7729 */ /* XXX */
Bram Moolenaar18144c82006-04-12 21:52:12 +00007730 n = FALSE;
7731 if (lookfor != LOOKFOR_TERM && ind_cpp_baseclass > 0)
7732 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00007733 n = cin_is_cpp_baseclass(&col);
Bram Moolenaar18144c82006-04-12 21:52:12 +00007734 l = ml_get_curline();
7735 }
7736 if (n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007737 {
7738 if (lookfor == LOOKFOR_UNTERM)
7739 {
7740 if (cont_amount > 0)
7741 amount = cont_amount;
7742 else
7743 amount += ind_continuation;
7744 }
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007745 else if (theline[0] == '{')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007746 {
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007747 /* Need to find start of the declaration. */
7748 lookfor = LOOKFOR_UNTERM;
7749 ind_continuation = 0;
7750 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007751 }
7752 else
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007753 /* XXX */
7754 amount = get_baseclass_amount(col, ind_maxparen,
7755 ind_maxcomment, ind_cpp_baseclass);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007756 break;
7757 }
7758 else if (lookfor == LOOKFOR_CPP_BASECLASS)
7759 {
7760 /* only look, whether there is a cpp base class
Bram Moolenaar18144c82006-04-12 21:52:12 +00007761 * declaration or initialization before the opening brace.
7762 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007763 if (cin_isterminated(l, TRUE, FALSE))
7764 break;
7765 else
7766 continue;
7767 }
7768
7769 /*
7770 * What happens next depends on the line being terminated.
7771 * If terminated with a ',' only consider it terminating if
Bram Moolenaar25394022007-05-10 19:06:20 +00007772 * there is another unterminated statement behind, eg:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007773 * 123,
7774 * sizeof
7775 * here
7776 * Otherwise check whether it is a enumeration or structure
7777 * initialisation (not indented) or a variable declaration
7778 * (indented).
7779 */
7780 terminated = cin_isterminated(l, FALSE, TRUE);
7781
7782 if (terminated == 0 || (lookfor != LOOKFOR_UNTERM
7783 && terminated == ','))
7784 {
7785 /*
7786 * if we're in the middle of a paren thing,
7787 * go back to the line that starts it so
7788 * we can get the right prevailing indent
7789 * if ( foo &&
7790 * bar )
7791 */
7792 /*
7793 * position the cursor over the rightmost paren, so that
7794 * matching it will take us back to the start of the line.
7795 */
7796 (void)find_last_paren(l, '(', ')');
7797 trypos = find_match_paren(
7798 corr_ind_maxparen(ind_maxparen, &cur_curpos),
7799 ind_maxcomment);
7800
7801 /*
7802 * If we are looking for ',', we also look for matching
7803 * braces.
7804 */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007805 if (trypos == NULL && terminated == ','
7806 && find_last_paren(l, '{', '}'))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007807 trypos = find_start_brace(ind_maxcomment);
7808
7809 if (trypos != NULL)
7810 {
7811 /*
7812 * Check if we are on a case label now. This is
7813 * handled above.
7814 * case xx: if ( asdf &&
7815 * asdf)
7816 */
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007817 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007818 l = ml_get_curline();
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007819 if (cin_iscase(l, FALSE) || cin_isscopedecl(l))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007820 {
7821 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007822 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007823 continue;
7824 }
7825 }
7826
7827 /*
7828 * Skip over continuation lines to find the one to get the
7829 * indent from
7830 * char *usethis = "bla\
7831 * bla",
7832 * here;
7833 */
7834 if (terminated == ',')
7835 {
7836 while (curwin->w_cursor.lnum > 1)
7837 {
7838 l = ml_get(curwin->w_cursor.lnum - 1);
7839 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
7840 break;
7841 --curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007842 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007843 }
7844 }
7845
7846 /*
7847 * Get indent and pointer to text for current line,
7848 * ignoring any jump label. XXX
7849 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007850 if (!ind_js)
7851 cur_amount = skip_label(curwin->w_cursor.lnum,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007852 &l, ind_maxcomment);
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007853 else
7854 cur_amount = get_indent();
Bram Moolenaar071d4272004-06-13 20:20:40 +00007855 /*
7856 * If this is just above the line we are indenting, and it
7857 * starts with a '{', line it up with this line.
7858 * while (not)
7859 * -> {
7860 * }
7861 */
7862 if (terminated != ',' && lookfor != LOOKFOR_TERM
7863 && theline[0] == '{')
7864 {
7865 amount = cur_amount;
7866 /*
7867 * Only add ind_open_extra when the current line
7868 * doesn't start with a '{', which must have a match
7869 * in the same line (scope is the same). Probably:
7870 * { 1, 2 },
7871 * -> { 3, 4 }
7872 */
7873 if (*skipwhite(l) != '{')
7874 amount += ind_open_extra;
7875
7876 if (ind_cpp_baseclass)
7877 {
7878 /* have to look back, whether it is a cpp base
7879 * class declaration or initialization */
7880 lookfor = LOOKFOR_CPP_BASECLASS;
7881 continue;
7882 }
7883 break;
7884 }
7885
7886 /*
7887 * Check if we are after an "if", "while", etc.
7888 * Also allow " } else".
7889 */
7890 if (cin_is_cinword(l) || cin_iselse(skipwhite(l)))
7891 {
7892 /*
7893 * Found an unterminated line after an if (), line up
7894 * with the last one.
7895 * if (cond)
7896 * 100 +
7897 * -> here;
7898 */
7899 if (lookfor == LOOKFOR_UNTERM
7900 || lookfor == LOOKFOR_ENUM_OR_INIT)
7901 {
7902 if (cont_amount > 0)
7903 amount = cont_amount;
7904 else
7905 amount += ind_continuation;
7906 break;
7907 }
7908
7909 /*
7910 * If this is just above the line we are indenting, we
7911 * are finished.
7912 * while (not)
7913 * -> here;
7914 * Otherwise this indent can be used when the line
7915 * before this is terminated.
7916 * yyy;
7917 * if (stat)
7918 * while (not)
7919 * xxx;
7920 * -> here;
7921 */
7922 amount = cur_amount;
7923 if (theline[0] == '{')
7924 amount += ind_open_extra;
7925 if (lookfor != LOOKFOR_TERM)
7926 {
7927 amount += ind_level + ind_no_brace;
7928 break;
7929 }
7930
7931 /*
7932 * Special trick: when expecting the while () after a
7933 * do, line up with the while()
7934 * do
7935 * x = 1;
7936 * -> here
7937 */
7938 l = skipwhite(ml_get_curline());
7939 if (cin_isdo(l))
7940 {
7941 if (whilelevel == 0)
7942 break;
7943 --whilelevel;
7944 }
7945
7946 /*
7947 * When searching for a terminated line, don't use the
Bram Moolenaar334adf02011-05-25 13:34:04 +02007948 * one between the "if" and the matching "else".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007949 * Need to use the scope of this "else". XXX
7950 * If whilelevel != 0 continue looking for a "do {".
7951 */
Bram Moolenaar334adf02011-05-25 13:34:04 +02007952 if (cin_iselse(l) && whilelevel == 0)
7953 {
7954 /* If we're looking at "} else", let's make sure we
7955 * find the opening brace of the enclosing scope,
7956 * not the one from "if () {". */
7957 if (*l == '}')
7958 curwin->w_cursor.col =
Bram Moolenaar9b83c2f2011-05-25 17:29:44 +02007959 (colnr_T)(l - ml_get_curline()) + 1;
Bram Moolenaar334adf02011-05-25 13:34:04 +02007960
7961 if ((trypos = find_start_brace(ind_maxcomment))
7962 == NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007963 || find_match(LOOKFOR_IF, trypos->lnum,
Bram Moolenaar334adf02011-05-25 13:34:04 +02007964 ind_maxparen, ind_maxcomment) == FAIL)
7965 break;
7966 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007967 }
7968
7969 /*
7970 * If we're below an unterminated line that is not an
7971 * "if" or something, we may line up with this line or
Bram Moolenaar25394022007-05-10 19:06:20 +00007972 * add something for a continuation line, depending on
Bram Moolenaar071d4272004-06-13 20:20:40 +00007973 * the line before this one.
7974 */
7975 else
7976 {
7977 /*
7978 * Found two unterminated lines on a row, line up with
7979 * the last one.
7980 * c = 99 +
7981 * 100 +
7982 * -> here;
7983 */
7984 if (lookfor == LOOKFOR_UNTERM)
7985 {
7986 /* When line ends in a comma add extra indent */
7987 if (terminated == ',')
7988 amount += ind_continuation;
7989 break;
7990 }
7991
7992 if (lookfor == LOOKFOR_ENUM_OR_INIT)
7993 {
7994 /* Found two lines ending in ',', lineup with the
7995 * lowest one, but check for cpp base class
7996 * declaration/initialization, if it is an
7997 * opening brace or we are looking just for
7998 * enumerations/initializations. */
7999 if (terminated == ',')
8000 {
8001 if (ind_cpp_baseclass == 0)
8002 break;
8003
8004 lookfor = LOOKFOR_CPP_BASECLASS;
8005 continue;
8006 }
8007
8008 /* Ignore unterminated lines in between, but
8009 * reduce indent. */
8010 if (amount > cur_amount)
8011 amount = cur_amount;
8012 }
8013 else
8014 {
8015 /*
8016 * Found first unterminated line on a row, may
8017 * line up with this line, remember its indent
8018 * 100 +
8019 * -> here;
8020 */
8021 amount = cur_amount;
8022
8023 /*
8024 * If previous line ends in ',', check whether we
8025 * are in an initialization or enum
8026 * struct xxx =
8027 * {
8028 * sizeof a,
8029 * 124 };
8030 * or a normal possible continuation line.
8031 * but only, of no other statement has been found
8032 * yet.
8033 */
8034 if (lookfor == LOOKFOR_INITIAL && terminated == ',')
8035 {
8036 lookfor = LOOKFOR_ENUM_OR_INIT;
8037 cont_amount = cin_first_id_amount();
8038 }
8039 else
8040 {
8041 if (lookfor == LOOKFOR_INITIAL
8042 && *l != NUL
8043 && l[STRLEN(l) - 1] == '\\')
8044 /* XXX */
8045 cont_amount = cin_get_equal_amount(
8046 curwin->w_cursor.lnum);
8047 if (lookfor != LOOKFOR_TERM)
8048 lookfor = LOOKFOR_UNTERM;
8049 }
8050 }
8051 }
8052 }
8053
8054 /*
8055 * Check if we are after a while (cond);
8056 * If so: Ignore until the matching "do".
8057 */
8058 /* XXX */
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00008059 else if (cin_iswhileofdo_end(terminated, ind_maxparen,
8060 ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008061 {
8062 /*
8063 * Found an unterminated line after a while ();, line up
8064 * with the last one.
8065 * while (cond);
8066 * 100 + <- line up with this one
8067 * -> here;
8068 */
8069 if (lookfor == LOOKFOR_UNTERM
8070 || lookfor == LOOKFOR_ENUM_OR_INIT)
8071 {
8072 if (cont_amount > 0)
8073 amount = cont_amount;
8074 else
8075 amount += ind_continuation;
8076 break;
8077 }
8078
8079 if (whilelevel == 0)
8080 {
8081 lookfor = LOOKFOR_TERM;
8082 amount = get_indent(); /* XXX */
8083 if (theline[0] == '{')
8084 amount += ind_open_extra;
8085 }
8086 ++whilelevel;
8087 }
8088
8089 /*
8090 * We are after a "normal" statement.
8091 * If we had another statement we can stop now and use the
8092 * indent of that other statement.
8093 * Otherwise the indent of the current statement may be used,
8094 * search backwards for the next "normal" statement.
8095 */
8096 else
8097 {
8098 /*
8099 * Skip single break line, if before a switch label. It
8100 * may be lined up with the case label.
8101 */
8102 if (lookfor == LOOKFOR_NOBREAK
8103 && cin_isbreak(skipwhite(ml_get_curline())))
8104 {
8105 lookfor = LOOKFOR_ANY;
8106 continue;
8107 }
8108
8109 /*
8110 * Handle "do {" line.
8111 */
8112 if (whilelevel > 0)
8113 {
8114 l = cin_skipcomment(ml_get_curline());
8115 if (cin_isdo(l))
8116 {
8117 amount = get_indent(); /* XXX */
8118 --whilelevel;
8119 continue;
8120 }
8121 }
8122
8123 /*
8124 * Found a terminated line above an unterminated line. Add
8125 * the amount for a continuation line.
8126 * x = 1;
8127 * y = foo +
8128 * -> here;
8129 * or
8130 * int x = 1;
8131 * int foo,
8132 * -> here;
8133 */
8134 if (lookfor == LOOKFOR_UNTERM
8135 || lookfor == LOOKFOR_ENUM_OR_INIT)
8136 {
8137 if (cont_amount > 0)
8138 amount = cont_amount;
8139 else
8140 amount += ind_continuation;
8141 break;
8142 }
8143
8144 /*
8145 * Found a terminated line above a terminated line or "if"
8146 * etc. line. Use the amount of the line below us.
8147 * x = 1; x = 1;
8148 * if (asdf) y = 2;
8149 * while (asdf) ->here;
8150 * here;
8151 * ->foo;
8152 */
8153 if (lookfor == LOOKFOR_TERM)
8154 {
8155 if (!lookfor_break && whilelevel == 0)
8156 break;
8157 }
8158
8159 /*
8160 * First line above the one we're indenting is terminated.
8161 * To know what needs to be done look further backward for
8162 * a terminated line.
8163 */
8164 else
8165 {
8166 /*
8167 * position the cursor over the rightmost paren, so
8168 * that matching it will take us back to the start of
8169 * the line. Helps for:
8170 * func(asdr,
8171 * asdfasdf);
8172 * here;
8173 */
8174term_again:
8175 l = ml_get_curline();
8176 if (find_last_paren(l, '(', ')')
8177 && (trypos = find_match_paren(ind_maxparen,
8178 ind_maxcomment)) != NULL)
8179 {
8180 /*
8181 * Check if we are on a case label now. This is
8182 * handled above.
8183 * case xx: if ( asdf &&
8184 * asdf)
8185 */
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008186 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008187 l = ml_get_curline();
Bram Moolenaar3acfc302010-07-11 17:23:02 +02008188 if (cin_iscase(l, FALSE) || cin_isscopedecl(l))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008189 {
8190 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008191 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008192 continue;
8193 }
8194 }
8195
8196 /* When aligning with the case statement, don't align
8197 * with a statement after it.
8198 * case 1: { <-- don't use this { position
8199 * stat;
8200 * }
8201 * case 2:
8202 * stat;
8203 * }
8204 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02008205 iscase = (ind_keep_case_label && cin_iscase(l, FALSE));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008206
8207 /*
8208 * Get indent and pointer to text for current line,
8209 * ignoring any jump label.
8210 */
8211 amount = skip_label(curwin->w_cursor.lnum,
8212 &l, ind_maxcomment);
8213
8214 if (theline[0] == '{')
8215 amount += ind_open_extra;
8216 /* See remark above: "Only add ind_open_extra.." */
Bram Moolenaar18144c82006-04-12 21:52:12 +00008217 l = skipwhite(l);
8218 if (*l == '{')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008219 amount -= ind_open_extra;
8220 lookfor = iscase ? LOOKFOR_ANY : LOOKFOR_TERM;
8221
8222 /*
Bram Moolenaar18144c82006-04-12 21:52:12 +00008223 * When a terminated line starts with "else" skip to
8224 * the matching "if":
8225 * else 3;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008226 * indent this;
Bram Moolenaar18144c82006-04-12 21:52:12 +00008227 * Need to use the scope of this "else". XXX
8228 * If whilelevel != 0 continue looking for a "do {".
8229 */
8230 if (lookfor == LOOKFOR_TERM
8231 && *l != '}'
8232 && cin_iselse(l)
8233 && whilelevel == 0)
8234 {
8235 if ((trypos = find_start_brace(ind_maxcomment))
8236 == NULL
8237 || find_match(LOOKFOR_IF, trypos->lnum,
8238 ind_maxparen, ind_maxcomment) == FAIL)
8239 break;
8240 continue;
8241 }
8242
8243 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008244 * If we're at the end of a block, skip to the start of
8245 * that block.
8246 */
Bram Moolenaar6d8f9c62011-11-30 13:03:28 +01008247 l = ml_get_curline();
Bram Moolenaar50f42ca2011-07-15 14:12:30 +02008248 if (find_last_paren(l, '{', '}')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008249 && (trypos = find_start_brace(ind_maxcomment))
8250 != NULL) /* XXX */
8251 {
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008252 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008253 /* if not "else {" check for terminated again */
8254 /* but skip block for "} else {" */
8255 l = cin_skipcomment(ml_get_curline());
8256 if (*l == '}' || !cin_iselse(l))
8257 goto term_again;
8258 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008259 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008260 }
8261 }
8262 }
8263 }
8264 }
8265 }
8266
8267 /* add extra indent for a comment */
8268 if (cin_iscomment(theline))
8269 amount += ind_comment;
Bram Moolenaar02c707a2010-07-17 17:12:06 +02008270
8271 /* subtract extra left-shift for jump labels */
8272 if (ind_jump_label > 0 && original_line_islabel)
8273 amount -= ind_jump_label;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008274 }
8275
8276 /*
8277 * ok -- we're not inside any sort of structure at all!
8278 *
8279 * this means we're at the top level, and everything should
8280 * basically just match where the previous line is, except
8281 * for the lines immediately following a function declaration,
8282 * which are K&R-style parameters and need to be indented.
8283 */
8284 else
8285 {
8286 /*
8287 * if our line starts with an open brace, forget about any
8288 * prevailing indent and make sure it looks like the start
8289 * of a function
8290 */
8291
8292 if (theline[0] == '{')
8293 {
8294 amount = ind_first_open;
8295 }
8296
8297 /*
8298 * If the NEXT line is a function declaration, the current
8299 * line needs to be indented as a function type spec.
Bram Moolenaar1a89bbe2010-03-02 12:38:22 +01008300 * Don't do this if the current line looks like a comment or if the
8301 * current line is terminated, ie. ends in ';', or if the current line
8302 * contains { or }: "void f() {\n if (1)"
Bram Moolenaar071d4272004-06-13 20:20:40 +00008303 */
8304 else if (cur_curpos.lnum < curbuf->b_ml.ml_line_count
8305 && !cin_nocode(theline)
Bram Moolenaar1a89bbe2010-03-02 12:38:22 +01008306 && vim_strchr(theline, '{') == NULL
8307 && vim_strchr(theline, '}') == NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00008308 && !cin_ends_in(theline, (char_u *)":", NULL)
8309 && !cin_ends_in(theline, (char_u *)",", NULL)
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008310 && cin_isfuncdecl(NULL, cur_curpos.lnum + 1,
8311 cur_curpos.lnum + 1,
8312 ind_maxparen, ind_maxcomment)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008313 && !cin_isterminated(theline, FALSE, TRUE))
8314 {
8315 amount = ind_func_type;
8316 }
8317 else
8318 {
8319 amount = 0;
8320 curwin->w_cursor = cur_curpos;
8321
8322 /* search backwards until we find something we recognize */
8323
8324 while (curwin->w_cursor.lnum > 1)
8325 {
8326 curwin->w_cursor.lnum--;
8327 curwin->w_cursor.col = 0;
8328
8329 l = ml_get_curline();
8330
8331 /*
8332 * If we're in a comment now, skip to the start of the comment.
8333 */ /* XXX */
8334 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
8335 {
8336 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008337 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008338 continue;
8339 }
8340
8341 /*
Bram Moolenaar18144c82006-04-12 21:52:12 +00008342 * Are we at the start of a cpp base class declaration or
8343 * constructor initialization?
Bram Moolenaar071d4272004-06-13 20:20:40 +00008344 */ /* XXX */
Bram Moolenaar18144c82006-04-12 21:52:12 +00008345 n = FALSE;
8346 if (ind_cpp_baseclass != 0 && theline[0] != '{')
8347 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00008348 n = cin_is_cpp_baseclass(&col);
Bram Moolenaar18144c82006-04-12 21:52:12 +00008349 l = ml_get_curline();
8350 }
8351 if (n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008352 {
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00008353 /* XXX */
8354 amount = get_baseclass_amount(col, ind_maxparen,
8355 ind_maxcomment, ind_cpp_baseclass);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008356 break;
8357 }
8358
8359 /*
8360 * Skip preprocessor directives and blank lines.
8361 */
8362 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
8363 continue;
8364
8365 if (cin_nocode(l))
8366 continue;
8367
8368 /*
8369 * If the previous line ends in ',', use one level of
8370 * indentation:
8371 * int foo,
8372 * bar;
8373 * do this before checking for '}' in case of eg.
8374 * enum foobar
8375 * {
8376 * ...
8377 * } foo,
8378 * bar;
8379 */
8380 n = 0;
8381 if (cin_ends_in(l, (char_u *)",", NULL)
8382 || (*l != NUL && (n = l[STRLEN(l) - 1]) == '\\'))
8383 {
8384 /* take us back to opening paren */
8385 if (find_last_paren(l, '(', ')')
8386 && (trypos = find_match_paren(ind_maxparen,
8387 ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008388 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008389
8390 /* For a line ending in ',' that is a continuation line go
8391 * back to the first line with a backslash:
8392 * char *foo = "bla\
8393 * bla",
8394 * here;
8395 */
8396 while (n == 0 && curwin->w_cursor.lnum > 1)
8397 {
8398 l = ml_get(curwin->w_cursor.lnum - 1);
8399 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
8400 break;
8401 --curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008402 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008403 }
8404
8405 amount = get_indent(); /* XXX */
8406
8407 if (amount == 0)
8408 amount = cin_first_id_amount();
8409 if (amount == 0)
8410 amount = ind_continuation;
8411 break;
8412 }
8413
8414 /*
8415 * If the line looks like a function declaration, and we're
8416 * not in a comment, put it the left margin.
8417 */
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008418 if (cin_isfuncdecl(NULL, cur_curpos.lnum, 0,
8419 ind_maxparen, ind_maxcomment)) /* XXX */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008420 break;
8421 l = ml_get_curline();
8422
8423 /*
8424 * Finding the closing '}' of a previous function. Put
8425 * current line at the left margin. For when 'cino' has "fs".
8426 */
8427 if (*skipwhite(l) == '}')
8428 break;
8429
8430 /* (matching {)
8431 * If the previous line ends on '};' (maybe followed by
8432 * comments) align at column 0. For example:
8433 * char *string_array[] = { "foo",
8434 * / * x * / "b};ar" }; / * foobar * /
8435 */
8436 if (cin_ends_in(l, (char_u *)"};", NULL))
8437 break;
8438
8439 /*
Bram Moolenaar3388bb42011-11-30 17:20:23 +01008440 * Find a line only has a semicolon that belongs to a previous
8441 * line ending in '}', e.g. before an #endif. Don't increase
8442 * indent then.
8443 */
8444 if (*(look = skipwhite(l)) == ';' && cin_nocode(look + 1))
8445 {
8446 pos_T curpos_save = curwin->w_cursor;
8447
8448 while (curwin->w_cursor.lnum > 1)
8449 {
8450 look = ml_get(--curwin->w_cursor.lnum);
8451 if (!(cin_nocode(look) || cin_ispreproc_cont(
8452 &look, &curwin->w_cursor.lnum)))
8453 break;
8454 }
8455 if (curwin->w_cursor.lnum > 0
8456 && cin_ends_in(look, (char_u *)"}", NULL))
8457 break;
8458
8459 curwin->w_cursor = curpos_save;
8460 }
8461
8462 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008463 * If the PREVIOUS line is a function declaration, the current
8464 * line (and the ones that follow) needs to be indented as
8465 * parameters.
8466 */
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008467 if (cin_isfuncdecl(&l, curwin->w_cursor.lnum, 0,
8468 ind_maxparen, ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008469 {
8470 amount = ind_param;
8471 break;
8472 }
8473
8474 /*
8475 * If the previous line ends in ';' and the line before the
8476 * previous line ends in ',' or '\', ident to column zero:
8477 * int foo,
8478 * bar;
8479 * indent_to_0 here;
8480 */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00008481 if (cin_ends_in(l, (char_u *)";", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008482 {
8483 l = ml_get(curwin->w_cursor.lnum - 1);
8484 if (cin_ends_in(l, (char_u *)",", NULL)
8485 || (*l != NUL && l[STRLEN(l) - 1] == '\\'))
8486 break;
8487 l = ml_get_curline();
8488 }
8489
8490 /*
8491 * Doesn't look like anything interesting -- so just
8492 * use the indent of this line.
8493 *
8494 * Position the cursor over the rightmost paren, so that
8495 * matching it will take us back to the start of the line.
8496 */
8497 find_last_paren(l, '(', ')');
8498
8499 if ((trypos = find_match_paren(ind_maxparen,
8500 ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008501 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008502 amount = get_indent(); /* XXX */
8503 break;
8504 }
8505
8506 /* add extra indent for a comment */
8507 if (cin_iscomment(theline))
8508 amount += ind_comment;
8509
8510 /* add extra indent if the previous line ended in a backslash:
8511 * "asdfasdf\
8512 * here";
8513 * char *foo = "asdf\
8514 * here";
8515 */
8516 if (cur_curpos.lnum > 1)
8517 {
8518 l = ml_get(cur_curpos.lnum - 1);
8519 if (*l != NUL && l[STRLEN(l) - 1] == '\\')
8520 {
8521 cur_amount = cin_get_equal_amount(cur_curpos.lnum - 1);
8522 if (cur_amount > 0)
8523 amount = cur_amount;
8524 else if (cur_amount == 0)
8525 amount += ind_continuation;
8526 }
8527 }
8528 }
8529 }
8530
8531theend:
8532 /* put the cursor back where it belongs */
8533 curwin->w_cursor = cur_curpos;
8534
8535 vim_free(linecopy);
8536
8537 if (amount < 0)
8538 return 0;
8539 return amount;
8540}
8541
8542 static int
8543find_match(lookfor, ourscope, ind_maxparen, ind_maxcomment)
8544 int lookfor;
8545 linenr_T ourscope;
8546 int ind_maxparen;
8547 int ind_maxcomment;
8548{
8549 char_u *look;
8550 pos_T *theirscope;
8551 char_u *mightbeif;
8552 int elselevel;
8553 int whilelevel;
8554
8555 if (lookfor == LOOKFOR_IF)
8556 {
8557 elselevel = 1;
8558 whilelevel = 0;
8559 }
8560 else
8561 {
8562 elselevel = 0;
8563 whilelevel = 1;
8564 }
8565
8566 curwin->w_cursor.col = 0;
8567
8568 while (curwin->w_cursor.lnum > ourscope + 1)
8569 {
8570 curwin->w_cursor.lnum--;
8571 curwin->w_cursor.col = 0;
8572
8573 look = cin_skipcomment(ml_get_curline());
8574 if (cin_iselse(look)
8575 || cin_isif(look)
8576 || cin_isdo(look) /* XXX */
8577 || cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
8578 {
8579 /*
8580 * if we've gone outside the braces entirely,
8581 * we must be out of scope...
8582 */
8583 theirscope = find_start_brace(ind_maxcomment); /* XXX */
8584 if (theirscope == NULL)
8585 break;
8586
8587 /*
8588 * and if the brace enclosing this is further
8589 * back than the one enclosing the else, we're
8590 * out of luck too.
8591 */
8592 if (theirscope->lnum < ourscope)
8593 break;
8594
8595 /*
8596 * and if they're enclosed in a *deeper* brace,
8597 * then we can ignore it because it's in a
8598 * different scope...
8599 */
8600 if (theirscope->lnum > ourscope)
8601 continue;
8602
8603 /*
8604 * if it was an "else" (that's not an "else if")
8605 * then we need to go back to another if, so
8606 * increment elselevel
8607 */
8608 look = cin_skipcomment(ml_get_curline());
8609 if (cin_iselse(look))
8610 {
8611 mightbeif = cin_skipcomment(look + 4);
8612 if (!cin_isif(mightbeif))
8613 ++elselevel;
8614 continue;
8615 }
8616
8617 /*
8618 * if it was a "while" then we need to go back to
8619 * another "do", so increment whilelevel. XXX
8620 */
8621 if (cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
8622 {
8623 ++whilelevel;
8624 continue;
8625 }
8626
8627 /* If it's an "if" decrement elselevel */
8628 look = cin_skipcomment(ml_get_curline());
8629 if (cin_isif(look))
8630 {
8631 elselevel--;
8632 /*
8633 * When looking for an "if" ignore "while"s that
8634 * get in the way.
8635 */
8636 if (elselevel == 0 && lookfor == LOOKFOR_IF)
8637 whilelevel = 0;
8638 }
8639
8640 /* If it's a "do" decrement whilelevel */
8641 if (cin_isdo(look))
8642 whilelevel--;
8643
8644 /*
8645 * if we've used up all the elses, then
8646 * this must be the if that we want!
8647 * match the indent level of that if.
8648 */
8649 if (elselevel <= 0 && whilelevel <= 0)
8650 {
8651 return OK;
8652 }
8653 }
8654 }
8655 return FAIL;
8656}
8657
8658# if defined(FEAT_EVAL) || defined(PROTO)
8659/*
8660 * Get indent level from 'indentexpr'.
8661 */
8662 int
8663get_expr_indent()
8664{
8665 int indent;
8666 pos_T pos;
8667 int save_State;
Bram Moolenaard1f56e62006-02-22 21:25:37 +00008668 int use_sandbox = was_set_insecurely((char_u *)"indentexpr",
8669 OPT_LOCAL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008670
8671 pos = curwin->w_cursor;
8672 set_vim_var_nr(VV_LNUM, curwin->w_cursor.lnum);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00008673 if (use_sandbox)
8674 ++sandbox;
8675 ++textlock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008676 indent = eval_to_number(curbuf->b_p_inde);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00008677 if (use_sandbox)
8678 --sandbox;
8679 --textlock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008680
8681 /* Restore the cursor position so that 'indentexpr' doesn't need to.
8682 * Pretend to be in Insert mode, allow cursor past end of line for "o"
8683 * command. */
8684 save_State = State;
8685 State = INSERT;
8686 curwin->w_cursor = pos;
8687 check_cursor();
8688 State = save_State;
8689
8690 /* If there is an error, just keep the current indent. */
8691 if (indent < 0)
8692 indent = get_indent();
8693
8694 return indent;
8695}
8696# endif
8697
8698#endif /* FEAT_CINDENT */
8699
8700#if defined(FEAT_LISP) || defined(PROTO)
8701
8702static int lisp_match __ARGS((char_u *p));
8703
8704 static int
8705lisp_match(p)
8706 char_u *p;
8707{
8708 char_u buf[LSIZE];
8709 int len;
8710 char_u *word = p_lispwords;
8711
8712 while (*word != NUL)
8713 {
8714 (void)copy_option_part(&word, buf, LSIZE, ",");
8715 len = (int)STRLEN(buf);
8716 if (STRNCMP(buf, p, len) == 0 && p[len] == ' ')
8717 return TRUE;
8718 }
8719 return FALSE;
8720}
8721
8722/*
8723 * When 'p' is present in 'cpoptions, a Vi compatible method is used.
8724 * The incompatible newer method is quite a bit better at indenting
8725 * code in lisp-like languages than the traditional one; it's still
8726 * mostly heuristics however -- Dirk van Deun, dirk@rave.org
8727 *
8728 * TODO:
8729 * Findmatch() should be adapted for lisp, also to make showmatch
8730 * work correctly: now (v5.3) it seems all C/C++ oriented:
8731 * - it does not recognize the #\( and #\) notations as character literals
8732 * - it doesn't know about comments starting with a semicolon
8733 * - it incorrectly interprets '(' as a character literal
8734 * All this messes up get_lisp_indent in some rare cases.
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008735 * Update from Sergey Khorev:
8736 * I tried to fix the first two issues.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008737 */
8738 int
8739get_lisp_indent()
8740{
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008741 pos_T *pos, realpos, paren;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008742 int amount;
8743 char_u *that;
8744 colnr_T col;
8745 colnr_T firsttry;
8746 int parencount, quotecount;
8747 int vi_lisp;
8748
8749 /* Set vi_lisp to use the vi-compatible method */
8750 vi_lisp = (vim_strchr(p_cpo, CPO_LISP) != NULL);
8751
8752 realpos = curwin->w_cursor;
8753 curwin->w_cursor.col = 0;
8754
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008755 if ((pos = findmatch(NULL, '(')) == NULL)
8756 pos = findmatch(NULL, '[');
8757 else
8758 {
8759 paren = *pos;
8760 pos = findmatch(NULL, '[');
8761 if (pos == NULL || ltp(pos, &paren))
8762 pos = &paren;
8763 }
8764 if (pos != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008765 {
8766 /* Extra trick: Take the indent of the first previous non-white
8767 * line that is at the same () level. */
8768 amount = -1;
8769 parencount = 0;
8770
8771 while (--curwin->w_cursor.lnum >= pos->lnum)
8772 {
8773 if (linewhite(curwin->w_cursor.lnum))
8774 continue;
8775 for (that = ml_get_curline(); *that != NUL; ++that)
8776 {
8777 if (*that == ';')
8778 {
8779 while (*(that + 1) != NUL)
8780 ++that;
8781 continue;
8782 }
8783 if (*that == '\\')
8784 {
8785 if (*(that + 1) != NUL)
8786 ++that;
8787 continue;
8788 }
8789 if (*that == '"' && *(that + 1) != NUL)
8790 {
Bram Moolenaar15ff6c12006-09-15 18:18:09 +00008791 while (*++that && *that != '"')
8792 {
8793 /* skipping escaped characters in the string */
8794 if (*that == '\\')
8795 {
8796 if (*++that == NUL)
8797 break;
8798 if (that[1] == NUL)
8799 {
8800 ++that;
8801 break;
8802 }
8803 }
8804 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008805 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008806 if (*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008807 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008808 else if (*that == ')' || *that == ']')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008809 --parencount;
8810 }
8811 if (parencount == 0)
8812 {
8813 amount = get_indent();
8814 break;
8815 }
8816 }
8817
8818 if (amount == -1)
8819 {
8820 curwin->w_cursor.lnum = pos->lnum;
8821 curwin->w_cursor.col = pos->col;
8822 col = pos->col;
8823
8824 that = ml_get_curline();
8825
8826 if (vi_lisp && get_indent() == 0)
8827 amount = 2;
8828 else
8829 {
8830 amount = 0;
8831 while (*that && col)
8832 {
8833 amount += lbr_chartabsize_adv(&that, (colnr_T)amount);
8834 col--;
8835 }
8836
8837 /*
8838 * Some keywords require "body" indenting rules (the
8839 * non-standard-lisp ones are Scheme special forms):
8840 *
8841 * (let ((a 1)) instead (let ((a 1))
8842 * (...)) of (...))
8843 */
8844
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008845 if (!vi_lisp && (*that == '(' || *that == '[')
8846 && lisp_match(that + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008847 amount += 2;
8848 else
8849 {
8850 that++;
8851 amount++;
8852 firsttry = amount;
8853
8854 while (vim_iswhite(*that))
8855 {
8856 amount += lbr_chartabsize(that, (colnr_T)amount);
8857 ++that;
8858 }
8859
8860 if (*that && *that != ';') /* not a comment line */
8861 {
Bram Moolenaare21877a2008-02-13 09:58:14 +00008862 /* test *that != '(' to accommodate first let/do
Bram Moolenaar071d4272004-06-13 20:20:40 +00008863 * argument if it is more than one line */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008864 if (!vi_lisp && *that != '(' && *that != '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008865 firsttry++;
8866
8867 parencount = 0;
8868 quotecount = 0;
8869
8870 if (vi_lisp
8871 || (*that != '"'
8872 && *that != '\''
8873 && *that != '#'
8874 && (*that < '0' || *that > '9')))
8875 {
8876 while (*that
8877 && (!vim_iswhite(*that)
8878 || quotecount
8879 || parencount)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008880 && (!((*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008881 && !quotecount
8882 && !parencount
8883 && vi_lisp)))
8884 {
8885 if (*that == '"')
8886 quotecount = !quotecount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008887 if ((*that == '(' || *that == '[')
8888 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008889 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008890 if ((*that == ')' || *that == ']')
8891 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008892 --parencount;
8893 if (*that == '\\' && *(that+1) != NUL)
8894 amount += lbr_chartabsize_adv(&that,
8895 (colnr_T)amount);
8896 amount += lbr_chartabsize_adv(&that,
8897 (colnr_T)amount);
8898 }
8899 }
8900 while (vim_iswhite(*that))
8901 {
8902 amount += lbr_chartabsize(that, (colnr_T)amount);
8903 that++;
8904 }
8905 if (!*that || *that == ';')
8906 amount = firsttry;
8907 }
8908 }
8909 }
8910 }
8911 }
8912 else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008913 amount = 0; /* no matching '(' or '[' found, use zero indent */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008914
8915 curwin->w_cursor = realpos;
8916
8917 return amount;
8918}
8919#endif /* FEAT_LISP */
8920
8921 void
8922prepare_to_exit()
8923{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00008924#if defined(SIGHUP) && defined(SIG_IGN)
8925 /* Ignore SIGHUP, because a dropped connection causes a read error, which
8926 * makes Vim exit and then handling SIGHUP causes various reentrance
8927 * problems. */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00008928 signal(SIGHUP, SIG_IGN);
8929#endif
8930
Bram Moolenaar071d4272004-06-13 20:20:40 +00008931#ifdef FEAT_GUI
8932 if (gui.in_use)
8933 {
8934 gui.dying = TRUE;
8935 out_trash(); /* trash any pending output */
8936 }
8937 else
8938#endif
8939 {
8940 windgoto((int)Rows - 1, 0);
8941
8942 /*
8943 * Switch terminal mode back now, so messages end up on the "normal"
8944 * screen (if there are two screens).
8945 */
8946 settmode(TMODE_COOK);
8947#ifdef WIN3264
8948 if (can_end_termcap_mode(FALSE) == TRUE)
8949#endif
8950 stoptermcap();
8951 out_flush();
8952 }
8953}
8954
8955/*
8956 * Preserve files and exit.
8957 * When called IObuff must contain a message.
8958 */
8959 void
8960preserve_exit()
8961{
8962 buf_T *buf;
8963
8964 prepare_to_exit();
8965
Bram Moolenaar4770d092006-01-12 23:22:24 +00008966 /* Setting this will prevent free() calls. That avoids calling free()
8967 * recursively when free() was invoked with a bad pointer. */
8968 really_exiting = TRUE;
8969
Bram Moolenaar071d4272004-06-13 20:20:40 +00008970 out_str(IObuff);
8971 screen_start(); /* don't know where cursor is now */
8972 out_flush();
8973
8974 ml_close_notmod(); /* close all not-modified buffers */
8975
8976 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8977 {
8978 if (buf->b_ml.ml_mfp != NULL && buf->b_ml.ml_mfp->mf_fname != NULL)
8979 {
8980 OUT_STR(_("Vim: preserving files...\n"));
8981 screen_start(); /* don't know where cursor is now */
8982 out_flush();
8983 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
8984 break;
8985 }
8986 }
8987
8988 ml_close_all(FALSE); /* close all memfiles, without deleting */
8989
8990 OUT_STR(_("Vim: Finished.\n"));
8991
8992 getout(1);
8993}
8994
8995/*
8996 * return TRUE if "fname" exists.
8997 */
8998 int
8999vim_fexists(fname)
9000 char_u *fname;
9001{
9002 struct stat st;
9003
9004 if (mch_stat((char *)fname, &st))
9005 return FALSE;
9006 return TRUE;
9007}
9008
9009/*
9010 * Check for CTRL-C pressed, but only once in a while.
9011 * Should be used instead of ui_breakcheck() for functions that check for
9012 * each line in the file. Calling ui_breakcheck() each time takes too much
9013 * time, because it can be a system call.
9014 */
9015
9016#ifndef BREAKCHECK_SKIP
9017# ifdef FEAT_GUI /* assume the GUI only runs on fast computers */
9018# define BREAKCHECK_SKIP 200
9019# else
9020# define BREAKCHECK_SKIP 32
9021# endif
9022#endif
9023
9024static int breakcheck_count = 0;
9025
9026 void
9027line_breakcheck()
9028{
9029 if (++breakcheck_count >= BREAKCHECK_SKIP)
9030 {
9031 breakcheck_count = 0;
9032 ui_breakcheck();
9033 }
9034}
9035
9036/*
9037 * Like line_breakcheck() but check 10 times less often.
9038 */
9039 void
9040fast_breakcheck()
9041{
9042 if (++breakcheck_count >= BREAKCHECK_SKIP * 10)
9043 {
9044 breakcheck_count = 0;
9045 ui_breakcheck();
9046 }
9047}
9048
9049/*
Bram Moolenaard7834d32009-12-02 16:14:36 +00009050 * Invoke expand_wildcards() for one pattern.
9051 * Expand items like "%:h" before the expansion.
9052 * Returns OK or FAIL.
9053 */
9054 int
9055expand_wildcards_eval(pat, num_file, file, flags)
9056 char_u **pat; /* pointer to input pattern */
9057 int *num_file; /* resulting number of files */
9058 char_u ***file; /* array of resulting files */
9059 int flags; /* EW_DIR, etc. */
9060{
9061 int ret = FAIL;
9062 char_u *eval_pat = NULL;
9063 char_u *exp_pat = *pat;
9064 char_u *ignored_msg;
9065 int usedlen;
9066
9067 if (*exp_pat == '%' || *exp_pat == '#' || *exp_pat == '<')
9068 {
9069 ++emsg_off;
9070 eval_pat = eval_vars(exp_pat, exp_pat, &usedlen,
9071 NULL, &ignored_msg, NULL);
9072 --emsg_off;
9073 if (eval_pat != NULL)
9074 exp_pat = concat_str(eval_pat, exp_pat + usedlen);
9075 }
9076
9077 if (exp_pat != NULL)
9078 ret = expand_wildcards(1, &exp_pat, num_file, file, flags);
9079
9080 if (eval_pat != NULL)
9081 {
9082 vim_free(exp_pat);
9083 vim_free(eval_pat);
9084 }
9085
9086 return ret;
9087}
9088
9089/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00009090 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching
9091 * 'wildignore'.
Bram Moolenaar9e193ac2010-07-19 23:11:27 +02009092 * Returns OK or FAIL. When FAIL then "num_file" won't be set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009093 */
9094 int
9095expand_wildcards(num_pat, pat, num_file, file, flags)
9096 int num_pat; /* number of input patterns */
9097 char_u **pat; /* array of input patterns */
9098 int *num_file; /* resulting number of files */
9099 char_u ***file; /* array of resulting files */
9100 int flags; /* EW_DIR, etc. */
9101{
9102 int retval;
9103 int i, j;
9104 char_u *p;
9105 int non_suf_match; /* number without matching suffix */
9106
9107 retval = gen_expand_wildcards(num_pat, pat, num_file, file, flags);
9108
9109 /* When keeping all matches, return here */
Bram Moolenaar9e193ac2010-07-19 23:11:27 +02009110 if ((flags & EW_KEEPALL) || retval == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009111 return retval;
9112
9113#ifdef FEAT_WILDIGN
9114 /*
9115 * Remove names that match 'wildignore'.
9116 */
9117 if (*p_wig)
9118 {
9119 char_u *ffname;
9120
9121 /* check all files in (*file)[] */
9122 for (i = 0; i < *num_file; ++i)
9123 {
9124 ffname = FullName_save((*file)[i], FALSE);
9125 if (ffname == NULL) /* out of memory */
9126 break;
9127# ifdef VMS
9128 vms_remove_version(ffname);
9129# endif
9130 if (match_file_list(p_wig, (*file)[i], ffname))
9131 {
9132 /* remove this matching file from the list */
9133 vim_free((*file)[i]);
9134 for (j = i; j + 1 < *num_file; ++j)
9135 (*file)[j] = (*file)[j + 1];
9136 --*num_file;
9137 --i;
9138 }
9139 vim_free(ffname);
9140 }
9141 }
9142#endif
9143
9144 /*
9145 * Move the names where 'suffixes' match to the end.
9146 */
9147 if (*num_file > 1)
9148 {
9149 non_suf_match = 0;
9150 for (i = 0; i < *num_file; ++i)
9151 {
9152 if (!match_suffix((*file)[i]))
9153 {
9154 /*
9155 * Move the name without matching suffix to the front
9156 * of the list.
9157 */
9158 p = (*file)[i];
9159 for (j = i; j > non_suf_match; --j)
9160 (*file)[j] = (*file)[j - 1];
9161 (*file)[non_suf_match++] = p;
9162 }
9163 }
9164 }
9165
9166 return retval;
9167}
9168
9169/*
9170 * Return TRUE if "fname" matches with an entry in 'suffixes'.
9171 */
9172 int
9173match_suffix(fname)
9174 char_u *fname;
9175{
9176 int fnamelen, setsuflen;
9177 char_u *setsuf;
9178#define MAXSUFLEN 30 /* maximum length of a file suffix */
9179 char_u suf_buf[MAXSUFLEN];
9180
9181 fnamelen = (int)STRLEN(fname);
9182 setsuflen = 0;
9183 for (setsuf = p_su; *setsuf; )
9184 {
9185 setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
Bram Moolenaar055a2ba2009-07-14 19:40:21 +00009186 if (setsuflen == 0)
9187 {
9188 char_u *tail = gettail(fname);
9189
9190 /* empty entry: match name without a '.' */
9191 if (vim_strchr(tail, '.') == NULL)
9192 {
9193 setsuflen = 1;
9194 break;
9195 }
9196 }
9197 else
9198 {
9199 if (fnamelen >= setsuflen
9200 && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
9201 (size_t)setsuflen) == 0)
9202 break;
9203 setsuflen = 0;
9204 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009205 }
9206 return (setsuflen != 0);
9207}
9208
9209#if !defined(NO_EXPANDPATH) || defined(PROTO)
9210
9211# ifdef VIM_BACKTICK
9212static int vim_backtick __ARGS((char_u *p));
9213static int expand_backtick __ARGS((garray_T *gap, char_u *pat, int flags));
9214# endif
9215
9216# if defined(MSDOS) || defined(FEAT_GUI_W16) || defined(WIN3264)
9217/*
9218 * File name expansion code for MS-DOS, Win16 and Win32. It's here because
9219 * it's shared between these systems.
9220 */
9221# if defined(DJGPP) || defined(PROTO)
9222# define _cdecl /* DJGPP doesn't have this */
9223# else
9224# ifdef __BORLANDC__
9225# define _cdecl _RTLENTRYF
9226# endif
9227# endif
9228
9229/*
9230 * comparison function for qsort in dos_expandpath()
9231 */
9232 static int _cdecl
9233pstrcmp(const void *a, const void *b)
9234{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00009235 return (pathcmp(*(char **)a, *(char **)b, -1));
Bram Moolenaar071d4272004-06-13 20:20:40 +00009236}
9237
9238# ifndef WIN3264
9239 static void
9240namelowcpy(
9241 char_u *d,
9242 char_u *s)
9243{
9244# ifdef DJGPP
9245 if (USE_LONG_FNAME) /* don't lower case on Windows 95/NT systems */
9246 while (*s)
9247 *d++ = *s++;
9248 else
9249# endif
9250 while (*s)
9251 *d++ = TOLOWER_LOC(*s++);
9252 *d = NUL;
9253}
9254# endif
9255
9256/*
Bram Moolenaar231334e2005-07-25 20:46:57 +00009257 * Recursively expand one path component into all matching files and/or
9258 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009259 * Return the number of matches found.
9260 * "path" has backslashes before chars that are not to be expanded, starting
9261 * at "path[wildoff]".
Bram Moolenaar231334e2005-07-25 20:46:57 +00009262 * Return the number of matches found.
9263 * NOTE: much of this is identical to unix_expandpath(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00009264 */
9265 static int
9266dos_expandpath(
9267 garray_T *gap,
9268 char_u *path,
9269 int wildoff,
Bram Moolenaar231334e2005-07-25 20:46:57 +00009270 int flags, /* EW_* flags */
Bram Moolenaar25394022007-05-10 19:06:20 +00009271 int didstar) /* expanded "**" once already */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009272{
Bram Moolenaar231334e2005-07-25 20:46:57 +00009273 char_u *buf;
9274 char_u *path_end;
9275 char_u *p, *s, *e;
9276 int start_len = gap->ga_len;
9277 char_u *pat;
9278 regmatch_T regmatch;
9279 int starts_with_dot;
9280 int matches;
9281 int len;
9282 int starstar = FALSE;
9283 static int stardepth = 0; /* depth for "**" expansion */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009284#ifdef WIN3264
9285 WIN32_FIND_DATA fb;
9286 HANDLE hFind = (HANDLE)0;
9287# ifdef FEAT_MBYTE
9288 WIN32_FIND_DATAW wfb;
9289 WCHAR *wn = NULL; /* UCS-2 name, NULL when not used. */
9290# endif
9291#else
9292 struct ffblk fb;
9293#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009294 char_u *matchname;
Bram Moolenaar231334e2005-07-25 20:46:57 +00009295 int ok;
9296
9297 /* Expanding "**" may take a long time, check for CTRL-C. */
9298 if (stardepth > 0)
9299 {
9300 ui_breakcheck();
9301 if (got_int)
9302 return 0;
9303 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009304
9305 /* make room for file name */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009306 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009307 if (buf == NULL)
9308 return 0;
9309
9310 /*
9311 * Find the first part in the path name that contains a wildcard or a ~1.
9312 * Copy it into buf, including the preceding characters.
9313 */
9314 p = buf;
9315 s = buf;
9316 e = NULL;
9317 path_end = path;
9318 while (*path_end != NUL)
9319 {
9320 /* May ignore a wildcard that has a backslash before it; it will
9321 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
9322 if (path_end >= path + wildoff && rem_backslash(path_end))
9323 *p++ = *path_end++;
9324 else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
9325 {
9326 if (e != NULL)
9327 break;
9328 s = p + 1;
9329 }
9330 else if (path_end >= path + wildoff
9331 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
9332 e = p;
9333#ifdef FEAT_MBYTE
9334 if (has_mbyte)
9335 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00009336 len = (*mb_ptr2len)(path_end);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009337 STRNCPY(p, path_end, len);
9338 p += len;
9339 path_end += len;
9340 }
9341 else
9342#endif
9343 *p++ = *path_end++;
9344 }
9345 e = p;
9346 *e = NUL;
9347
9348 /* now we have one wildcard component between s and e */
9349 /* Remove backslashes between "wildoff" and the start of the wildcard
9350 * component. */
9351 for (p = buf + wildoff; p < s; ++p)
9352 if (rem_backslash(p))
9353 {
Bram Moolenaar8c8de832008-06-24 22:58:06 +00009354 STRMOVE(p, p + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009355 --e;
9356 --s;
9357 }
9358
Bram Moolenaar231334e2005-07-25 20:46:57 +00009359 /* Check for "**" between "s" and "e". */
9360 for (p = s; p < e; ++p)
9361 if (p[0] == '*' && p[1] == '*')
9362 starstar = TRUE;
9363
Bram Moolenaar071d4272004-06-13 20:20:40 +00009364 starts_with_dot = (*s == '.');
9365 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
9366 if (pat == NULL)
9367 {
9368 vim_free(buf);
9369 return 0;
9370 }
9371
9372 /* compile the regexp into a program */
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009373 if (flags & (EW_NOERROR | EW_NOTWILD))
Bram Moolenaarb5609832011-07-20 15:04:58 +02009374 ++emsg_silent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009375 regmatch.rm_ic = TRUE; /* Always ignore case */
9376 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009377 if (flags & (EW_NOERROR | EW_NOTWILD))
Bram Moolenaarb5609832011-07-20 15:04:58 +02009378 --emsg_silent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009379 vim_free(pat);
9380
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009381 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009382 {
9383 vim_free(buf);
9384 return 0;
9385 }
9386
9387 /* remember the pattern or file name being looked for */
9388 matchname = vim_strsave(s);
9389
Bram Moolenaar231334e2005-07-25 20:46:57 +00009390 /* If "**" is by itself, this is the first time we encounter it and more
9391 * is following then find matches without any directory. */
9392 if (!didstar && stardepth < 100 && starstar && e - s == 2
9393 && *path_end == '/')
9394 {
9395 STRCPY(s, path_end + 1);
9396 ++stardepth;
9397 (void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
9398 --stardepth;
9399 }
9400
Bram Moolenaar071d4272004-06-13 20:20:40 +00009401 /* Scan all files in the directory with "dir/ *.*" */
9402 STRCPY(s, "*.*");
9403#ifdef WIN3264
9404# ifdef FEAT_MBYTE
9405 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
9406 {
9407 /* The active codepage differs from 'encoding'. Attempt using the
9408 * wide function. If it fails because it is not implemented fall back
9409 * to the non-wide version (for Windows 98) */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009410 wn = enc_to_utf16(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009411 if (wn != NULL)
9412 {
9413 hFind = FindFirstFileW(wn, &wfb);
9414 if (hFind == INVALID_HANDLE_VALUE
9415 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
9416 {
9417 vim_free(wn);
9418 wn = NULL;
9419 }
9420 }
9421 }
9422
9423 if (wn == NULL)
9424# endif
9425 hFind = FindFirstFile(buf, &fb);
9426 ok = (hFind != INVALID_HANDLE_VALUE);
9427#else
9428 /* If we are expanding wildcards we try both files and directories */
9429 ok = (findfirst((char *)buf, &fb,
9430 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
9431#endif
9432
9433 while (ok)
9434 {
9435#ifdef WIN3264
9436# ifdef FEAT_MBYTE
9437 if (wn != NULL)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009438 p = utf16_to_enc(wfb.cFileName, NULL); /* p is allocated here */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009439 else
9440# endif
9441 p = (char_u *)fb.cFileName;
9442#else
9443 p = (char_u *)fb.ff_name;
9444#endif
9445 /* Ignore entries starting with a dot, unless when asked for. Accept
9446 * all entries found with "matchname". */
9447 if ((p[0] != '.' || starts_with_dot)
9448 && (matchname == NULL
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009449 || (regmatch.regprog != NULL
9450 && vim_regexec(&regmatch, p, (colnr_T)0))
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009451 || ((flags & EW_NOTWILD)
9452 && fnamencmp(path + (s - buf), p, e - s) == 0)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009453 {
9454#ifdef WIN3264
9455 STRCPY(s, p);
9456#else
9457 namelowcpy(s, p);
9458#endif
9459 len = (int)STRLEN(buf);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009460
9461 if (starstar && stardepth < 100)
9462 {
9463 /* For "**" in the pattern first go deeper in the tree to
9464 * find matches. */
9465 STRCPY(buf + len, "/**");
9466 STRCPY(buf + len + 3, path_end);
9467 ++stardepth;
9468 (void)dos_expandpath(gap, buf, len + 1, flags, TRUE);
9469 --stardepth;
9470 }
9471
Bram Moolenaar071d4272004-06-13 20:20:40 +00009472 STRCPY(buf + len, path_end);
9473 if (mch_has_exp_wildcard(path_end))
9474 {
9475 /* need to expand another component of the path */
9476 /* remove backslashes for the remaining components only */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009477 (void)dos_expandpath(gap, buf, len + 1, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009478 }
9479 else
9480 {
9481 /* no more wildcards, check if there is a match */
9482 /* remove backslashes for the remaining components only */
9483 if (*path_end != 0)
9484 backslash_halve(buf + len + 1);
9485 if (mch_getperm(buf) >= 0) /* add existing file */
9486 addfile(gap, buf, flags);
9487 }
9488 }
9489
9490#ifdef WIN3264
9491# ifdef FEAT_MBYTE
9492 if (wn != NULL)
9493 {
9494 vim_free(p);
9495 ok = FindNextFileW(hFind, &wfb);
9496 }
9497 else
9498# endif
9499 ok = FindNextFile(hFind, &fb);
9500#else
9501 ok = (findnext(&fb) == 0);
9502#endif
9503
9504 /* If no more matches and no match was used, try expanding the name
9505 * itself. Finds the long name of a short filename. */
9506 if (!ok && matchname != NULL && gap->ga_len == start_len)
9507 {
9508 STRCPY(s, matchname);
9509#ifdef WIN3264
9510 FindClose(hFind);
9511# ifdef FEAT_MBYTE
9512 if (wn != NULL)
9513 {
9514 vim_free(wn);
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009515 wn = enc_to_utf16(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009516 if (wn != NULL)
9517 hFind = FindFirstFileW(wn, &wfb);
9518 }
9519 if (wn == NULL)
9520# endif
9521 hFind = FindFirstFile(buf, &fb);
9522 ok = (hFind != INVALID_HANDLE_VALUE);
9523#else
9524 ok = (findfirst((char *)buf, &fb,
9525 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
9526#endif
9527 vim_free(matchname);
9528 matchname = NULL;
9529 }
9530 }
9531
9532#ifdef WIN3264
9533 FindClose(hFind);
9534# ifdef FEAT_MBYTE
9535 vim_free(wn);
9536# endif
9537#endif
9538 vim_free(buf);
9539 vim_free(regmatch.regprog);
9540 vim_free(matchname);
9541
9542 matches = gap->ga_len - start_len;
9543 if (matches > 0)
9544 qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
9545 sizeof(char_u *), pstrcmp);
9546 return matches;
9547}
9548
9549 int
9550mch_expandpath(
9551 garray_T *gap,
9552 char_u *path,
9553 int flags) /* EW_* flags */
9554{
Bram Moolenaar231334e2005-07-25 20:46:57 +00009555 return dos_expandpath(gap, path, 0, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009556}
9557# endif /* MSDOS || FEAT_GUI_W16 || WIN3264 */
9558
Bram Moolenaar231334e2005-07-25 20:46:57 +00009559#if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
9560 || defined(PROTO)
9561/*
9562 * Unix style wildcard expansion code.
9563 * It's here because it's used both for Unix and Mac.
9564 */
9565static int pstrcmp __ARGS((const void *, const void *));
9566
9567 static int
9568pstrcmp(a, b)
9569 const void *a, *b;
9570{
9571 return (pathcmp(*(char **)a, *(char **)b, -1));
9572}
9573
9574/*
9575 * Recursively expand one path component into all matching files and/or
9576 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
9577 * "path" has backslashes before chars that are not to be expanded, starting
9578 * at "path + wildoff".
9579 * Return the number of matches found.
9580 * NOTE: much of this is identical to dos_expandpath(), keep in sync!
9581 */
9582 int
9583unix_expandpath(gap, path, wildoff, flags, didstar)
9584 garray_T *gap;
9585 char_u *path;
9586 int wildoff;
9587 int flags; /* EW_* flags */
9588 int didstar; /* expanded "**" once already */
9589{
9590 char_u *buf;
9591 char_u *path_end;
9592 char_u *p, *s, *e;
9593 int start_len = gap->ga_len;
9594 char_u *pat;
9595 regmatch_T regmatch;
9596 int starts_with_dot;
9597 int matches;
9598 int len;
9599 int starstar = FALSE;
9600 static int stardepth = 0; /* depth for "**" expansion */
9601
9602 DIR *dirp;
9603 struct dirent *dp;
9604
9605 /* Expanding "**" may take a long time, check for CTRL-C. */
9606 if (stardepth > 0)
9607 {
9608 ui_breakcheck();
9609 if (got_int)
9610 return 0;
9611 }
9612
9613 /* make room for file name */
9614 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
9615 if (buf == NULL)
9616 return 0;
9617
9618 /*
9619 * Find the first part in the path name that contains a wildcard.
Bram Moolenaar2d0b92f2012-04-30 21:09:43 +02009620 * When EW_ICASE is set every letter is considered to be a wildcard.
Bram Moolenaar231334e2005-07-25 20:46:57 +00009621 * Copy it into "buf", including the preceding characters.
9622 */
9623 p = buf;
9624 s = buf;
9625 e = NULL;
9626 path_end = path;
9627 while (*path_end != NUL)
9628 {
9629 /* May ignore a wildcard that has a backslash before it; it will
9630 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
9631 if (path_end >= path + wildoff && rem_backslash(path_end))
9632 *p++ = *path_end++;
9633 else if (*path_end == '/')
9634 {
9635 if (e != NULL)
9636 break;
9637 s = p + 1;
9638 }
9639 else if (path_end >= path + wildoff
Bram Moolenaar2d0b92f2012-04-30 21:09:43 +02009640 && (vim_strchr((char_u *)"*?[{~$", *path_end) != NULL
9641#ifndef CASE_INSENSITIVE_FILENAME
9642 || ((flags & EW_ICASE)
9643 && isalpha(PTR2CHAR(path_end)))
9644#endif
9645 ))
Bram Moolenaar231334e2005-07-25 20:46:57 +00009646 e = p;
9647#ifdef FEAT_MBYTE
9648 if (has_mbyte)
9649 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00009650 len = (*mb_ptr2len)(path_end);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009651 STRNCPY(p, path_end, len);
9652 p += len;
9653 path_end += len;
9654 }
9655 else
9656#endif
9657 *p++ = *path_end++;
9658 }
9659 e = p;
9660 *e = NUL;
9661
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009662 /* Now we have one wildcard component between "s" and "e". */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009663 /* Remove backslashes between "wildoff" and the start of the wildcard
9664 * component. */
9665 for (p = buf + wildoff; p < s; ++p)
9666 if (rem_backslash(p))
9667 {
Bram Moolenaar8c8de832008-06-24 22:58:06 +00009668 STRMOVE(p, p + 1);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009669 --e;
9670 --s;
9671 }
9672
9673 /* Check for "**" between "s" and "e". */
9674 for (p = s; p < e; ++p)
9675 if (p[0] == '*' && p[1] == '*')
9676 starstar = TRUE;
9677
9678 /* convert the file pattern to a regexp pattern */
9679 starts_with_dot = (*s == '.');
9680 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
9681 if (pat == NULL)
9682 {
9683 vim_free(buf);
9684 return 0;
9685 }
9686
9687 /* compile the regexp into a program */
Bram Moolenaarcc016f52005-12-10 20:23:46 +00009688#ifdef CASE_INSENSITIVE_FILENAME
Bram Moolenaar231334e2005-07-25 20:46:57 +00009689 regmatch.rm_ic = TRUE; /* Behave like Terminal.app */
9690#else
Bram Moolenaar94950a92010-12-02 16:01:29 +01009691 if (flags & EW_ICASE)
9692 regmatch.rm_ic = TRUE; /* 'wildignorecase' set */
9693 else
9694 regmatch.rm_ic = FALSE; /* Don't ignore case */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009695#endif
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009696 if (flags & (EW_NOERROR | EW_NOTWILD))
9697 ++emsg_silent;
Bram Moolenaar231334e2005-07-25 20:46:57 +00009698 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009699 if (flags & (EW_NOERROR | EW_NOTWILD))
9700 --emsg_silent;
Bram Moolenaar231334e2005-07-25 20:46:57 +00009701 vim_free(pat);
9702
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009703 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
Bram Moolenaar231334e2005-07-25 20:46:57 +00009704 {
9705 vim_free(buf);
9706 return 0;
9707 }
9708
9709 /* If "**" is by itself, this is the first time we encounter it and more
9710 * is following then find matches without any directory. */
9711 if (!didstar && stardepth < 100 && starstar && e - s == 2
9712 && *path_end == '/')
9713 {
9714 STRCPY(s, path_end + 1);
9715 ++stardepth;
9716 (void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
9717 --stardepth;
9718 }
9719
9720 /* open the directory for scanning */
9721 *s = NUL;
9722 dirp = opendir(*buf == NUL ? "." : (char *)buf);
9723
9724 /* Find all matching entries */
9725 if (dirp != NULL)
9726 {
9727 for (;;)
9728 {
9729 dp = readdir(dirp);
9730 if (dp == NULL)
9731 break;
9732 if ((dp->d_name[0] != '.' || starts_with_dot)
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009733 && ((regmatch.regprog != NULL && vim_regexec(&regmatch,
9734 (char_u *)dp->d_name, (colnr_T)0))
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009735 || ((flags & EW_NOTWILD)
9736 && fnamencmp(path + (s - buf), dp->d_name, e - s) == 0)))
Bram Moolenaar231334e2005-07-25 20:46:57 +00009737 {
9738 STRCPY(s, dp->d_name);
9739 len = STRLEN(buf);
9740
9741 if (starstar && stardepth < 100)
9742 {
9743 /* For "**" in the pattern first go deeper in the tree to
9744 * find matches. */
9745 STRCPY(buf + len, "/**");
9746 STRCPY(buf + len + 3, path_end);
9747 ++stardepth;
9748 (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
9749 --stardepth;
9750 }
9751
9752 STRCPY(buf + len, path_end);
9753 if (mch_has_exp_wildcard(path_end)) /* handle more wildcards */
9754 {
9755 /* need to expand another component of the path */
9756 /* remove backslashes for the remaining components only */
9757 (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
9758 }
9759 else
9760 {
9761 /* no more wildcards, check if there is a match */
9762 /* remove backslashes for the remaining components only */
9763 if (*path_end != NUL)
9764 backslash_halve(buf + len + 1);
9765 if (mch_getperm(buf) >= 0) /* add existing file */
9766 {
Bram Moolenaar95e9b492006-03-15 23:04:43 +00009767#ifdef MACOS_CONVERT
Bram Moolenaar231334e2005-07-25 20:46:57 +00009768 size_t precomp_len = STRLEN(buf)+1;
9769 char_u *precomp_buf =
9770 mac_precompose_path(buf, precomp_len, &precomp_len);
Bram Moolenaar95e9b492006-03-15 23:04:43 +00009771
Bram Moolenaar231334e2005-07-25 20:46:57 +00009772 if (precomp_buf)
9773 {
9774 mch_memmove(buf, precomp_buf, precomp_len);
9775 vim_free(precomp_buf);
9776 }
9777#endif
9778 addfile(gap, buf, flags);
9779 }
9780 }
9781 }
9782 }
9783
9784 closedir(dirp);
9785 }
9786
9787 vim_free(buf);
9788 vim_free(regmatch.regprog);
9789
9790 matches = gap->ga_len - start_len;
9791 if (matches > 0)
9792 qsort(((char_u **)gap->ga_data) + start_len, matches,
9793 sizeof(char_u *), pstrcmp);
9794 return matches;
9795}
9796#endif
9797
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009798#if defined(FEAT_SEARCHPATH)
9799static int find_previous_pathsep __ARGS((char_u *path, char_u **psep));
9800static int is_unique __ARGS((char_u *maybe_unique, garray_T *gap, int i));
Bram Moolenaar162bd912010-07-28 22:29:10 +02009801static void expand_path_option __ARGS((char_u *curdir, garray_T *gap));
9802static char_u *get_path_cutoff __ARGS((char_u *fname, garray_T *gap));
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009803static void uniquefy_paths __ARGS((garray_T *gap, char_u *pattern));
9804static int expand_in_path __ARGS((garray_T *gap, char_u *pattern, int flags));
9805
9806/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009807 * Moves "*psep" back to the previous path separator in "path".
9808 * Returns FAIL is "*psep" ends up at the beginning of "path".
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009809 */
9810 static int
9811find_previous_pathsep(path, psep)
9812 char_u *path;
9813 char_u **psep;
9814{
9815 /* skip the current separator */
9816 if (*psep > path && vim_ispathsep(**psep))
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009817 --*psep;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009818
9819 /* find the previous separator */
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009820 while (*psep > path)
9821 {
9822 if (vim_ispathsep(**psep))
9823 return OK;
9824 mb_ptr_back(path, *psep);
9825 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009826
9827 return FAIL;
9828}
9829
9830/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009831 * Returns TRUE if "maybe_unique" is unique wrt other_paths in "gap".
9832 * "maybe_unique" is the end portion of "((char_u **)gap->ga_data)[i]".
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009833 */
9834 static int
9835is_unique(maybe_unique, gap, i)
9836 char_u *maybe_unique;
9837 garray_T *gap;
9838 int i;
9839{
9840 int j;
9841 int candidate_len;
9842 int other_path_len;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009843 char_u **other_paths = (char_u **)gap->ga_data;
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009844 char_u *rival;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009845
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009846 for (j = 0; j < gap->ga_len; j++)
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009847 {
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009848 if (j == i)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009849 continue; /* don't compare it with itself */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009850
Bram Moolenaar624c7aa2010-07-16 20:38:52 +02009851 candidate_len = (int)STRLEN(maybe_unique);
9852 other_path_len = (int)STRLEN(other_paths[j]);
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009853 if (other_path_len < candidate_len)
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009854 continue; /* it's different when it's shorter */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009855
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009856 rival = other_paths[j] + other_path_len - candidate_len;
Bram Moolenaarda9836c2010-08-16 21:53:27 +02009857 if (fnamecmp(maybe_unique, rival) == 0
9858 && (rival == other_paths[j] || vim_ispathsep(*(rival - 1))))
Bram Moolenaar162bd912010-07-28 22:29:10 +02009859 return FALSE; /* match */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009860 }
9861
Bram Moolenaar162bd912010-07-28 22:29:10 +02009862 return TRUE; /* no match found */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009863}
9864
9865/*
Bram Moolenaar1a509df2010-08-01 17:59:57 +02009866 * Split the 'path' option into an array of strings in garray_T. Relative
Bram Moolenaar162bd912010-07-28 22:29:10 +02009867 * paths are expanded to their equivalent fullpath. This includes the "."
9868 * (relative to current buffer directory) and empty path (relative to current
9869 * directory) notations.
9870 *
9871 * TODO: handle upward search (;) and path limiter (**N) notations by
9872 * expanding each into their equivalent path(s).
9873 */
9874 static void
9875expand_path_option(curdir, gap)
9876 char_u *curdir;
9877 garray_T *gap;
9878{
9879 char_u *path_option = *curbuf->b_p_path == NUL
9880 ? p_path : curbuf->b_p_path;
9881 char_u *buf;
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009882 char_u *p;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009883 int len;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009884
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +02009885 if ((buf = alloc((int)MAXPATHL)) == NULL)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009886 return;
9887
9888 while (*path_option != NUL)
9889 {
9890 copy_option_part(&path_option, buf, MAXPATHL, " ,");
9891
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009892 if (buf[0] == '.' && (buf[1] == NUL || vim_ispathsep(buf[1])))
Bram Moolenaar162bd912010-07-28 22:29:10 +02009893 {
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009894 /* Relative to current buffer:
9895 * "/path/file" + "." -> "/path/"
9896 * "/path/file" + "./subdir" -> "/path/subdir" */
Bram Moolenaar162bd912010-07-28 22:29:10 +02009897 if (curbuf->b_ffname == NULL)
9898 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009899 p = gettail(curbuf->b_ffname);
9900 len = (int)(p - curbuf->b_ffname);
9901 if (len + (int)STRLEN(buf) >= MAXPATHL)
9902 continue;
9903 if (buf[1] == NUL)
9904 buf[len] = NUL;
9905 else
9906 STRMOVE(buf + len, buf + 2);
9907 mch_memmove(buf, curbuf->b_ffname, len);
9908 simplify_filename(buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009909 }
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009910 else if (buf[0] == NUL)
9911 /* relative to current directory */
Bram Moolenaar162bd912010-07-28 22:29:10 +02009912 STRCPY(buf, curdir);
Bram Moolenaar84f888a2010-08-05 21:40:16 +02009913 else if (path_with_url(buf))
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009914 /* URL can't be used here */
Bram Moolenaar84f888a2010-08-05 21:40:16 +02009915 continue;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009916 else if (!mch_isFullName(buf))
9917 {
9918 /* Expand relative path to their full path equivalent */
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009919 len = (int)STRLEN(curdir);
9920 if (len + (int)STRLEN(buf) + 3 > MAXPATHL)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009921 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009922 STRMOVE(buf + len + 1, buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009923 STRCPY(buf, curdir);
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009924 buf[len] = PATHSEP;
Bram Moolenaar57adda12010-08-03 22:11:29 +02009925 simplify_filename(buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009926 }
9927
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009928 if (ga_grow(gap, 1) == FAIL)
9929 break;
9930 p = vim_strsave(buf);
9931 if (p == NULL)
9932 break;
9933 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009934 }
9935
9936 vim_free(buf);
9937}
9938
9939/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009940 * Returns a pointer to the file or directory name in "fname" that matches the
9941 * longest path in "ga"p, or NULL if there is no match. For example:
Bram Moolenaar162bd912010-07-28 22:29:10 +02009942 *
9943 * path: /foo/bar/baz
9944 * fname: /foo/bar/baz/quux.txt
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009945 * returns: ^this
Bram Moolenaar162bd912010-07-28 22:29:10 +02009946 */
9947 static char_u *
9948get_path_cutoff(fname, gap)
9949 char_u *fname;
9950 garray_T *gap;
9951{
9952 int i;
9953 int maxlen = 0;
9954 char_u **path_part = (char_u **)gap->ga_data;
9955 char_u *cutoff = NULL;
9956
9957 for (i = 0; i < gap->ga_len; i++)
9958 {
9959 int j = 0;
9960
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009961 while ((fname[j] == path_part[i][j]
Bram Moolenaar2d7c47d2010-08-10 19:50:26 +02009962# if defined(MSWIN) || defined(MSDOS)
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009963 || (vim_ispathsep(fname[j]) && vim_ispathsep(path_part[i][j]))
9964#endif
9965 ) && fname[j] != NUL && path_part[i][j] != NUL)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009966 j++;
9967 if (j > maxlen)
9968 {
9969 maxlen = j;
9970 cutoff = &fname[j];
9971 }
9972 }
9973
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009974 /* skip to the file or directory name */
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009975 if (cutoff != NULL)
Bram Moolenaar31710262010-08-13 13:36:15 +02009976 while (vim_ispathsep(*cutoff))
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009977 mb_ptr_adv(cutoff);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009978
9979 return cutoff;
9980}
9981
9982/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009983 * Sorts, removes duplicates and modifies all the fullpath names in "gap" so
9984 * that they are unique with respect to each other while conserving the part
9985 * that matches the pattern. Beware, this is at least O(n^2) wrt "gap->ga_len".
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009986 */
9987 static void
9988uniquefy_paths(gap, pattern)
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +02009989 garray_T *gap;
9990 char_u *pattern;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009991{
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +02009992 int i;
9993 int len;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009994 char_u **fnames = (char_u **)gap->ga_data;
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009995 int sort_again = FALSE;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009996 char_u *pat;
9997 char_u *file_pattern;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009998 char_u *curdir;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009999 regmatch_T regmatch;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010000 garray_T path_ga;
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010001 char_u **in_curdir = NULL;
10002 char_u *short_name;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010003
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +020010004 remove_duplicates(gap);
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010005 ga_init2(&path_ga, (int)sizeof(char_u *), 1);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010006
10007 /*
10008 * We need to prepend a '*' at the beginning of file_pattern so that the
10009 * regex matches anywhere in the path. FIXME: is this valid for all
Bram Moolenaarb31e4382010-07-24 16:01:56 +020010010 * possible patterns?
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010011 */
Bram Moolenaar624c7aa2010-07-16 20:38:52 +020010012 len = (int)STRLEN(pattern);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010013 file_pattern = alloc(len + 2);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010014 if (file_pattern == NULL)
10015 return;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010016 file_pattern[0] = '*';
Bram Moolenaar162bd912010-07-28 22:29:10 +020010017 file_pattern[1] = NUL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010018 STRCAT(file_pattern, pattern);
10019 pat = file_pat_to_reg_pat(file_pattern, NULL, NULL, TRUE);
10020 vim_free(file_pattern);
Bram Moolenaarb31e4382010-07-24 16:01:56 +020010021 if (pat == NULL)
10022 return;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010023
Bram Moolenaarb31e4382010-07-24 16:01:56 +020010024 regmatch.rm_ic = TRUE; /* always ignore case */
10025 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
10026 vim_free(pat);
10027 if (regmatch.regprog == NULL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010028 return;
10029
Bram Moolenaar162bd912010-07-28 22:29:10 +020010030 if ((curdir = alloc((int)(MAXPATHL))) == NULL)
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010031 goto theend;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010032 mch_dirname(curdir, MAXPATHL);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010033 expand_path_option(curdir, &path_ga);
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010034
10035 in_curdir = (char_u **)alloc_clear(gap->ga_len * sizeof(char_u *));
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010036 if (in_curdir == NULL)
10037 goto theend;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010038
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010039 for (i = 0; i < gap->ga_len && !got_int; i++)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010040 {
Bram Moolenaar162bd912010-07-28 22:29:10 +020010041 char_u *path = fnames[i];
10042 int is_in_curdir;
Bram Moolenaar31710262010-08-13 13:36:15 +020010043 char_u *dir_end = gettail_dir(path);
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010044 char_u *pathsep_p;
10045 char_u *path_cutoff;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010046
Bram Moolenaar624c7aa2010-07-16 20:38:52 +020010047 len = (int)STRLEN(path);
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010048 is_in_curdir = fnamencmp(curdir, path, dir_end - path) == 0
Bram Moolenaar162bd912010-07-28 22:29:10 +020010049 && curdir[dir_end - path] == NUL;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010050 if (is_in_curdir)
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010051 in_curdir[i] = vim_strsave(path);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010052
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010053 /* Shorten the filename while maintaining its uniqueness */
10054 path_cutoff = get_path_cutoff(path, &path_ga);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010055
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010056 /* we start at the end of the path */
10057 pathsep_p = path + len - 1;
10058
10059 while (find_previous_pathsep(path, &pathsep_p))
10060 if (vim_regexec(&regmatch, pathsep_p + 1, (colnr_T)0)
10061 && is_unique(pathsep_p + 1, gap, i)
10062 && path_cutoff != NULL && pathsep_p + 1 >= path_cutoff)
10063 {
10064 sort_again = TRUE;
10065 mch_memmove(path, pathsep_p + 1, STRLEN(pathsep_p));
10066 break;
10067 }
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010068
10069 if (mch_isFullName(path))
10070 {
10071 /*
10072 * Last resort: shorten relative to curdir if possible.
10073 * 'possible' means:
10074 * 1. It is under the current directory.
10075 * 2. The result is actually shorter than the original.
10076 *
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010077 * Before curdir After
10078 * /foo/bar/file.txt /foo/bar ./file.txt
10079 * c:\foo\bar\file.txt c:\foo\bar .\file.txt
10080 * /file.txt / /file.txt
10081 * c:\file.txt c:\ .\file.txt
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010082 */
10083 short_name = shorten_fname(path, curdir);
Bram Moolenaar31710262010-08-13 13:36:15 +020010084 if (short_name != NULL && short_name > path + 1
10085#if defined(MSWIN) || defined(MSDOS)
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010086 /* On windows,
Bram Moolenaar31710262010-08-13 13:36:15 +020010087 * shorten_fname("c:\a\a.txt", "c:\a\b")
Bram Moolenaar31710262010-08-13 13:36:15 +020010088 * returns "\a\a.txt", which is not really the short
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010089 * name, hence: */
Bram Moolenaar31710262010-08-13 13:36:15 +020010090 && !vim_ispathsep(*short_name)
10091#endif
10092 )
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010093 {
10094 STRCPY(path, ".");
10095 add_pathsep(path);
Bram Moolenaarcda000e2010-08-14 13:34:39 +020010096 STRMOVE(path + STRLEN(path), short_name);
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010097 }
10098 }
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010099 ui_breakcheck();
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010100 }
10101
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010102 /* Shorten filenames in /in/current/directory/{filename} */
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010103 for (i = 0; i < gap->ga_len && !got_int; i++)
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010104 {
10105 char_u *rel_path;
10106 char_u *path = in_curdir[i];
10107
10108 if (path == NULL)
10109 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010110
10111 /* If the {filename} is not unique, change it to ./{filename}.
10112 * Else reduce it to {filename} */
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010113 short_name = shorten_fname(path, curdir);
10114 if (short_name == NULL)
10115 short_name = path;
10116 if (is_unique(short_name, gap, i))
10117 {
10118 STRCPY(fnames[i], short_name);
10119 continue;
10120 }
10121
10122 rel_path = alloc((int)(STRLEN(short_name) + STRLEN(PATHSEPSTR) + 2));
10123 if (rel_path == NULL)
10124 goto theend;
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010125 STRCPY(rel_path, ".");
10126 add_pathsep(rel_path);
10127 STRCAT(rel_path, short_name);
10128
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010129 vim_free(fnames[i]);
10130 fnames[i] = rel_path;
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010131 sort_again = TRUE;
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010132 ui_breakcheck();
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010133 }
10134
Bram Moolenaar162bd912010-07-28 22:29:10 +020010135theend:
10136 vim_free(curdir);
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010137 if (in_curdir != NULL)
10138 {
10139 for (i = 0; i < gap->ga_len; i++)
10140 vim_free(in_curdir[i]);
10141 vim_free(in_curdir);
10142 }
Bram Moolenaar162bd912010-07-28 22:29:10 +020010143 ga_clear_strings(&path_ga);
Bram Moolenaarb31e4382010-07-24 16:01:56 +020010144 vim_free(regmatch.regprog);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010145
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010146 if (sort_again)
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +020010147 remove_duplicates(gap);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010148}
10149
10150/*
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010151 * Calls globpath() with 'path' values for the given pattern and stores the
10152 * result in "gap".
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010153 * Returns the total number of matches.
10154 */
10155 static int
10156expand_in_path(gap, pattern, flags)
10157 garray_T *gap;
10158 char_u *pattern;
10159 int flags; /* EW_* flags */
10160{
Bram Moolenaar162bd912010-07-28 22:29:10 +020010161 char_u *curdir;
10162 garray_T path_ga;
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010163 char_u *files = NULL;
10164 char_u *s; /* start */
10165 char_u *e; /* end */
10166 char_u *paths = NULL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010167
Bram Moolenaar7f0f6212010-08-03 22:21:00 +020010168 if ((curdir = alloc((unsigned)MAXPATHL)) == NULL)
Bram Moolenaar162bd912010-07-28 22:29:10 +020010169 return 0;
10170 mch_dirname(curdir, MAXPATHL);
10171
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010172 ga_init2(&path_ga, (int)sizeof(char_u *), 1);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010173 expand_path_option(curdir, &path_ga);
10174 vim_free(curdir);
Bram Moolenaar006d2b02010-08-04 12:39:44 +020010175 if (path_ga.ga_len == 0)
10176 return 0;
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010177
10178 paths = ga_concat_strings(&path_ga);
10179 ga_clear_strings(&path_ga);
10180 if (paths == NULL)
Bram Moolenaar7f0f6212010-08-03 22:21:00 +020010181 return 0;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010182
Bram Moolenaar94950a92010-12-02 16:01:29 +010010183 files = globpath(paths, pattern, (flags & EW_ICASE) ? WILD_ICASE : 0);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010184 vim_free(paths);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010185 if (files == NULL)
10186 return 0;
10187
10188 /* Copy each path in files into gap */
10189 s = e = files;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010190 while (*s != NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010191 {
Bram Moolenaar162bd912010-07-28 22:29:10 +020010192 while (*e != '\n' && *e != NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010193 e++;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010194 if (*e == NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010195 {
10196 addfile(gap, s, flags);
10197 break;
10198 }
10199 else
10200 {
10201 /* *e is '\n' */
Bram Moolenaar162bd912010-07-28 22:29:10 +020010202 *e = NUL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010203 addfile(gap, s, flags);
10204 e++;
10205 s = e;
10206 }
10207 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010208 vim_free(files);
10209
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010210 return gap->ga_len;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010211}
10212#endif
10213
Bram Moolenaar1587a1e2010-07-29 20:59:59 +020010214#if defined(FEAT_SEARCHPATH) || defined(FEAT_CMDL_COMPL) || defined(PROTO)
10215/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010216 * Sort "gap" and remove duplicate entries. "gap" is expected to contain a
10217 * list of file names in allocated memory.
Bram Moolenaar1587a1e2010-07-29 20:59:59 +020010218 */
10219 void
10220remove_duplicates(gap)
10221 garray_T *gap;
10222{
10223 int i;
10224 int j;
10225 char_u **fnames = (char_u **)gap->ga_data;
10226
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010227 sort_strings(fnames, gap->ga_len);
Bram Moolenaar1587a1e2010-07-29 20:59:59 +020010228 for (i = gap->ga_len - 1; i > 0; --i)
10229 if (fnamecmp(fnames[i - 1], fnames[i]) == 0)
10230 {
10231 vim_free(fnames[i]);
10232 for (j = i + 1; j < gap->ga_len; ++j)
10233 fnames[j - 1] = fnames[j];
10234 --gap->ga_len;
10235 }
10236}
10237#endif
10238
Bram Moolenaar071d4272004-06-13 20:20:40 +000010239/*
10240 * Generic wildcard expansion code.
10241 *
10242 * Characters in "pat" that should not be expanded must be preceded with a
10243 * backslash. E.g., "/path\ with\ spaces/my\*star*"
10244 *
10245 * Return FAIL when no single file was found. In this case "num_file" is not
10246 * set, and "file" may contain an error message.
10247 * Return OK when some files found. "num_file" is set to the number of
10248 * matches, "file" to the array of matches. Call FreeWild() later.
10249 */
10250 int
10251gen_expand_wildcards(num_pat, pat, num_file, file, flags)
10252 int num_pat; /* number of input patterns */
10253 char_u **pat; /* array of input patterns */
10254 int *num_file; /* resulting number of files */
10255 char_u ***file; /* array of resulting files */
10256 int flags; /* EW_* flags */
10257{
10258 int i;
10259 garray_T ga;
10260 char_u *p;
10261 static int recursive = FALSE;
10262 int add_pat;
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010263#if defined(FEAT_SEARCHPATH)
10264 int did_expand_in_path = FALSE;
10265#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000010266
10267 /*
10268 * expand_env() is called to expand things like "~user". If this fails,
10269 * it calls ExpandOne(), which brings us back here. In this case, always
10270 * call the machine specific expansion function, if possible. Otherwise,
10271 * return FAIL.
10272 */
10273 if (recursive)
10274#ifdef SPECIAL_WILDCHAR
10275 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
10276#else
10277 return FAIL;
10278#endif
10279
10280#ifdef SPECIAL_WILDCHAR
10281 /*
10282 * If there are any special wildcard characters which we cannot handle
10283 * here, call machine specific function for all the expansion. This
10284 * avoids starting the shell for each argument separately.
10285 * For `=expr` do use the internal function.
10286 */
10287 for (i = 0; i < num_pat; i++)
10288 {
10289 if (vim_strpbrk(pat[i], (char_u *)SPECIAL_WILDCHAR) != NULL
10290# ifdef VIM_BACKTICK
10291 && !(vim_backtick(pat[i]) && pat[i][1] == '=')
10292# endif
10293 )
10294 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
10295 }
10296#endif
10297
10298 recursive = TRUE;
10299
10300 /*
10301 * The matching file names are stored in a growarray. Init it empty.
10302 */
10303 ga_init2(&ga, (int)sizeof(char_u *), 30);
10304
10305 for (i = 0; i < num_pat; ++i)
10306 {
10307 add_pat = -1;
10308 p = pat[i];
10309
10310#ifdef VIM_BACKTICK
10311 if (vim_backtick(p))
10312 add_pat = expand_backtick(&ga, p, flags);
10313 else
10314#endif
10315 {
10316 /*
10317 * First expand environment variables, "~/" and "~user/".
10318 */
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010319 if (vim_strchr(p, '$') != NULL || *p == '~')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010320 {
Bram Moolenaar9f0545d2007-09-26 20:36:32 +000010321 p = expand_env_save_opt(p, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010322 if (p == NULL)
10323 p = pat[i];
10324#ifdef UNIX
10325 /*
10326 * On Unix, if expand_env() can't expand an environment
10327 * variable, use the shell to do that. Discard previously
10328 * found file names and start all over again.
10329 */
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010330 else if (vim_strchr(p, '$') != NULL || *p == '~')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010331 {
10332 vim_free(p);
Bram Moolenaar782027e2009-06-24 14:25:49 +000010333 ga_clear_strings(&ga);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010334 i = mch_expand_wildcards(num_pat, pat, num_file, file,
10335 flags);
10336 recursive = FALSE;
10337 return i;
10338 }
10339#endif
10340 }
10341
10342 /*
10343 * If there are wildcards: Expand file names and add each match to
10344 * the list. If there is no match, and EW_NOTFOUND is given, add
10345 * the pattern.
10346 * If there are no wildcards: Add the file name if it exists or
10347 * when EW_NOTFOUND is given.
10348 */
10349 if (mch_has_exp_wildcard(p))
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010350 {
10351#if defined(FEAT_SEARCHPATH)
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010352 if ((flags & EW_PATH)
10353 && !mch_isFullName(p)
10354 && !(p[0] == '.'
10355 && (vim_ispathsep(p[1])
10356 || (p[1] == '.' && vim_ispathsep(p[2]))))
10357 )
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010358 {
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010359 /* :find completion where 'path' is used.
10360 * Recursiveness is OK here. */
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010361 recursive = FALSE;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010362 add_pat = expand_in_path(&ga, p, flags);
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010363 recursive = TRUE;
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010364 did_expand_in_path = TRUE;
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010365 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010366 else
10367#endif
10368 add_pat = mch_expandpath(&ga, p, flags);
10369 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010370 }
10371
10372 if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
10373 {
10374 char_u *t = backslash_halve_save(p);
10375
10376#if defined(MACOS_CLASSIC)
10377 slash_to_colon(t);
10378#endif
10379 /* When EW_NOTFOUND is used, always add files and dirs. Makes
10380 * "vim c:/" work. */
10381 if (flags & EW_NOTFOUND)
10382 addfile(&ga, t, flags | EW_DIR | EW_FILE);
10383 else if (mch_getperm(t) >= 0)
10384 addfile(&ga, t, flags);
10385 vim_free(t);
10386 }
10387
Bram Moolenaarb28ebbc2010-07-14 16:59:57 +020010388#if defined(FEAT_SEARCHPATH)
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010389 if (did_expand_in_path && ga.ga_len > 0 && (flags & EW_PATH))
Bram Moolenaarb28ebbc2010-07-14 16:59:57 +020010390 uniquefy_paths(&ga, p);
10391#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000010392 if (p != pat[i])
10393 vim_free(p);
10394 }
10395
10396 *num_file = ga.ga_len;
10397 *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data : (char_u **)"";
10398
10399 recursive = FALSE;
10400
10401 return (ga.ga_data != NULL) ? OK : FAIL;
10402}
10403
10404# ifdef VIM_BACKTICK
10405
10406/*
10407 * Return TRUE if we can expand this backtick thing here.
10408 */
10409 static int
10410vim_backtick(p)
10411 char_u *p;
10412{
10413 return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
10414}
10415
10416/*
10417 * Expand an item in `backticks` by executing it as a command.
10418 * Currently only works when pat[] starts and ends with a `.
10419 * Returns number of file names found.
10420 */
10421 static int
10422expand_backtick(gap, pat, flags)
10423 garray_T *gap;
10424 char_u *pat;
10425 int flags; /* EW_* flags */
10426{
10427 char_u *p;
10428 char_u *cmd;
10429 char_u *buffer;
10430 int cnt = 0;
10431 int i;
10432
10433 /* Create the command: lop off the backticks. */
10434 cmd = vim_strnsave(pat + 1, (int)STRLEN(pat) - 2);
10435 if (cmd == NULL)
10436 return 0;
10437
10438#ifdef FEAT_EVAL
10439 if (*cmd == '=') /* `={expr}`: Expand expression */
Bram Moolenaar362e1a32006-03-06 23:29:24 +000010440 buffer = eval_to_string(cmd + 1, &p, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010441 else
10442#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010443 buffer = get_cmd_output(cmd, NULL,
10444 (flags & EW_SILENT) ? SHELL_SILENT : 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010445 vim_free(cmd);
10446 if (buffer == NULL)
10447 return 0;
10448
10449 cmd = buffer;
10450 while (*cmd != NUL)
10451 {
10452 cmd = skipwhite(cmd); /* skip over white space */
10453 p = cmd;
10454 while (*p != NUL && *p != '\r' && *p != '\n') /* skip over entry */
10455 ++p;
10456 /* add an entry if it is not empty */
10457 if (p > cmd)
10458 {
10459 i = *p;
10460 *p = NUL;
10461 addfile(gap, cmd, flags);
10462 *p = i;
10463 ++cnt;
10464 }
10465 cmd = p;
10466 while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
10467 ++cmd;
10468 }
10469
10470 vim_free(buffer);
10471 return cnt;
10472}
10473# endif /* VIM_BACKTICK */
10474
10475/*
10476 * Add a file to a file list. Accepted flags:
10477 * EW_DIR add directories
10478 * EW_FILE add files
Bram Moolenaar1f35bf92006-03-07 22:38:47 +000010479 * EW_EXEC add executable files
Bram Moolenaar071d4272004-06-13 20:20:40 +000010480 * EW_NOTFOUND add even when it doesn't exist
10481 * EW_ADDSLASH add slash after directory name
10482 */
10483 void
10484addfile(gap, f, flags)
10485 garray_T *gap;
10486 char_u *f; /* filename */
10487 int flags;
10488{
10489 char_u *p;
10490 int isdir;
10491
10492 /* if the file/dir doesn't exist, may not add it */
10493 if (!(flags & EW_NOTFOUND) && mch_getperm(f) < 0)
10494 return;
10495
10496#ifdef FNAME_ILLEGAL
10497 /* if the file/dir contains illegal characters, don't add it */
10498 if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
10499 return;
10500#endif
10501
10502 isdir = mch_isdir(f);
10503 if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
10504 return;
10505
Bram Moolenaar1f35bf92006-03-07 22:38:47 +000010506 /* If the file isn't executable, may not add it. Do accept directories. */
10507 if (!isdir && (flags & EW_EXEC) && !mch_can_exe(f))
10508 return;
10509
Bram Moolenaar071d4272004-06-13 20:20:40 +000010510 /* Make room for another item in the file list. */
10511 if (ga_grow(gap, 1) == FAIL)
10512 return;
10513
10514 p = alloc((unsigned)(STRLEN(f) + 1 + isdir));
10515 if (p == NULL)
10516 return;
10517
10518 STRCPY(p, f);
10519#ifdef BACKSLASH_IN_FILENAME
10520 slash_adjust(p);
10521#endif
10522 /*
10523 * Append a slash or backslash after directory names if none is present.
10524 */
10525#ifndef DONT_ADD_PATHSEP_TO_DIR
10526 if (isdir && (flags & EW_ADDSLASH))
10527 add_pathsep(p);
10528#endif
10529 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010530}
10531#endif /* !NO_EXPANDPATH */
10532
10533#if defined(VIM_BACKTICK) || defined(FEAT_EVAL) || defined(PROTO)
10534
10535#ifndef SEEK_SET
10536# define SEEK_SET 0
10537#endif
10538#ifndef SEEK_END
10539# define SEEK_END 2
10540#endif
10541
10542/*
10543 * Get the stdout of an external command.
10544 * Returns an allocated string, or NULL for error.
10545 */
10546 char_u *
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010547get_cmd_output(cmd, infile, flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010548 char_u *cmd;
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010549 char_u *infile; /* optional input file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010550 int flags; /* can be SHELL_SILENT */
10551{
10552 char_u *tempname;
10553 char_u *command;
10554 char_u *buffer = NULL;
10555 int len;
10556 int i = 0;
10557 FILE *fd;
10558
10559 if (check_restricted() || check_secure())
10560 return NULL;
10561
10562 /* get a name for the temp file */
10563 if ((tempname = vim_tempname('o')) == NULL)
10564 {
10565 EMSG(_(e_notmp));
10566 return NULL;
10567 }
10568
10569 /* Add the redirection stuff */
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010570 command = make_filter_cmd(cmd, infile, tempname);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010571 if (command == NULL)
10572 goto done;
10573
10574 /*
10575 * Call the shell to execute the command (errors are ignored).
10576 * Don't check timestamps here.
10577 */
10578 ++no_check_timestamps;
10579 call_shell(command, SHELL_DOOUT | SHELL_EXPAND | flags);
10580 --no_check_timestamps;
10581
10582 vim_free(command);
10583
10584 /*
10585 * read the names from the file into memory
10586 */
10587# ifdef VMS
Bram Moolenaar25394022007-05-10 19:06:20 +000010588 /* created temporary file is not always readable as binary */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010589 fd = mch_fopen((char *)tempname, "r");
10590# else
10591 fd = mch_fopen((char *)tempname, READBIN);
10592# endif
10593
10594 if (fd == NULL)
10595 {
10596 EMSG2(_(e_notopen), tempname);
10597 goto done;
10598 }
10599
10600 fseek(fd, 0L, SEEK_END);
10601 len = ftell(fd); /* get size of temp file */
10602 fseek(fd, 0L, SEEK_SET);
10603
10604 buffer = alloc(len + 1);
10605 if (buffer != NULL)
10606 i = (int)fread((char *)buffer, (size_t)1, (size_t)len, fd);
10607 fclose(fd);
10608 mch_remove(tempname);
10609 if (buffer == NULL)
10610 goto done;
10611#ifdef VMS
10612 len = i; /* VMS doesn't give us what we asked for... */
10613#endif
10614 if (i != len)
10615 {
10616 EMSG2(_(e_notread), tempname);
10617 vim_free(buffer);
10618 buffer = NULL;
10619 }
10620 else
Bram Moolenaar162bd912010-07-28 22:29:10 +020010621 buffer[len] = NUL; /* make sure the buffer is terminated */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010622
10623done:
10624 vim_free(tempname);
10625 return buffer;
10626}
10627#endif
10628
10629/*
10630 * Free the list of files returned by expand_wildcards() or other expansion
10631 * functions.
10632 */
10633 void
10634FreeWild(count, files)
10635 int count;
10636 char_u **files;
10637{
Bram Moolenaarfc1421e2006-04-20 22:17:20 +000010638 if (count <= 0 || files == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010639 return;
10640#if defined(__EMX__) && defined(__ALWAYS_HAS_TRAILING_NULL_POINTER) /* XXX */
10641 /*
10642 * Is this still OK for when other functions than expand_wildcards() have
10643 * been used???
10644 */
10645 _fnexplodefree((char **)files);
10646#else
10647 while (count--)
10648 vim_free(files[count]);
10649 vim_free(files);
10650#endif
10651}
10652
10653/*
Bram Moolenaara9dc3752010-07-11 20:46:53 +020010654 * Return TRUE when need to go to Insert mode because of 'insertmode'.
Bram Moolenaar071d4272004-06-13 20:20:40 +000010655 * Don't do this when still processing a command or a mapping.
10656 * Don't do this when inside a ":normal" command.
10657 */
10658 int
10659goto_im()
10660{
10661 return (p_im && stuff_empty() && typebuf_typed());
10662}