blob: 7ba3972790df28b4ca994f93e3e27617e9212256 [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;
6638 int fraction = 0; /* init for GCC */
6639 int divider;
6640 int n;
6641 int iscase;
6642 int lookfor_break;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02006643 int lookfor_cpp_namespace = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006644 int cont_amount = 0; /* amount for continuation line */
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006645 int original_line_islabel;
Bram Moolenaare79d1532011-10-04 18:03:47 +02006646 int added_to_amount = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006647
6648 for (options = curbuf->b_p_cino; *options; )
6649 {
6650 l = options++;
6651 if (*options == '-')
6652 ++options;
6653 n = getdigits(&options);
6654 divider = 0;
6655 if (*options == '.') /* ".5s" means a fraction */
6656 {
6657 fraction = atol((char *)++options);
6658 while (VIM_ISDIGIT(*options))
6659 {
6660 ++options;
6661 if (divider)
6662 divider *= 10;
6663 else
6664 divider = 10;
6665 }
6666 }
6667 if (*options == 's') /* "2s" means two times 'shiftwidth' */
6668 {
6669 if (n == 0 && fraction == 0)
6670 n = curbuf->b_p_sw; /* just "s" is one 'shiftwidth' */
6671 else
6672 {
6673 n *= curbuf->b_p_sw;
6674 if (divider)
6675 n += (curbuf->b_p_sw * fraction + divider / 2) / divider;
6676 }
6677 ++options;
6678 }
6679 if (l[1] == '-')
6680 n = -n;
6681 /* When adding an entry here, also update the default 'cinoptions' in
Bram Moolenaar39353fd2007-03-27 09:02:11 +00006682 * doc/indent.txt, and add explanation for it! */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006683 switch (*l)
6684 {
6685 case '>': ind_level = n; break;
6686 case 'e': ind_open_imag = n; break;
6687 case 'n': ind_no_brace = n; break;
6688 case 'f': ind_first_open = n; break;
6689 case '{': ind_open_extra = n; break;
6690 case '}': ind_close_extra = n; break;
6691 case '^': ind_open_left_imag = n; break;
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006692 case 'L': ind_jump_label = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006693 case ':': ind_case = n; break;
6694 case '=': ind_case_code = n; break;
6695 case 'b': ind_case_break = n; break;
6696 case 'p': ind_param = n; break;
6697 case 't': ind_func_type = n; break;
6698 case '/': ind_comment = n; break;
6699 case 'c': ind_in_comment = n; break;
6700 case 'C': ind_in_comment2 = n; break;
6701 case 'i': ind_cpp_baseclass = n; break;
6702 case '+': ind_continuation = n; break;
6703 case '(': ind_unclosed = n; break;
6704 case 'u': ind_unclosed2 = n; break;
6705 case 'U': ind_unclosed_noignore = n; break;
6706 case 'W': ind_unclosed_wrapped = n; break;
6707 case 'w': ind_unclosed_whiteok = n; break;
6708 case 'm': ind_matching_paren = n; break;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006709 case 'M': ind_paren_prev = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006710 case ')': ind_maxparen = n; break;
6711 case '*': ind_maxcomment = n; break;
6712 case 'g': ind_scopedecl = n; break;
6713 case 'h': ind_scopedecl_code = n; break;
6714 case 'j': ind_java = n; break;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006715 case 'J': ind_js = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006716 case 'l': ind_keep_case_label = n; break;
Bram Moolenaar39353fd2007-03-27 09:02:11 +00006717 case '#': ind_hash_comment = n; break;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02006718 case 'N': ind_cpp_namespace = n; break;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006719 case 'k': ind_if_for_while = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006720 }
Bram Moolenaardfdf3c42010-03-23 18:22:46 +01006721 if (*options == ',')
6722 ++options;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006723 }
6724
6725 /* remember where the cursor was when we started */
6726 cur_curpos = curwin->w_cursor;
6727
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006728 /* if we are at line 1 0 is fine, right? */
6729 if (cur_curpos.lnum == 1)
6730 return 0;
6731
Bram Moolenaar071d4272004-06-13 20:20:40 +00006732 /* Get a copy of the current contents of the line.
6733 * This is required, because only the most recent line obtained with
6734 * ml_get is valid! */
6735 linecopy = vim_strsave(ml_get(cur_curpos.lnum));
6736 if (linecopy == NULL)
6737 return 0;
6738
6739 /*
6740 * In insert mode and the cursor is on a ')' truncate the line at the
6741 * cursor position. We don't want to line up with the matching '(' when
6742 * inserting new stuff.
6743 * For unknown reasons the cursor might be past the end of the line, thus
6744 * check for that.
6745 */
6746 if ((State & INSERT)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006747 && curwin->w_cursor.col < (colnr_T)STRLEN(linecopy)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006748 && linecopy[curwin->w_cursor.col] == ')')
6749 linecopy[curwin->w_cursor.col] = NUL;
6750
6751 theline = skipwhite(linecopy);
6752
6753 /* move the cursor to the start of the line */
6754
6755 curwin->w_cursor.col = 0;
6756
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006757 original_line_islabel = cin_islabel(ind_maxcomment); /* XXX */
6758
Bram Moolenaar071d4272004-06-13 20:20:40 +00006759 /*
6760 * #defines and so on always go at the left when included in 'cinkeys'.
6761 */
6762 if (*theline == '#' && (*linecopy == '#' || in_cinkeys('#', ' ', TRUE)))
6763 {
6764 amount = 0;
6765 }
6766
6767 /*
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006768 * Is it a non-case label? Then that goes at the left margin too unless:
6769 * - JS flag is set.
6770 * - 'L' item has a positive value.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006771 */
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006772 else if (original_line_islabel && !ind_js && ind_jump_label < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006773 {
6774 amount = 0;
6775 }
6776
6777 /*
6778 * If we're inside a "//" comment and there is a "//" comment in a
6779 * previous line, lineup with that one.
6780 */
6781 else if (cin_islinecomment(theline)
6782 && (trypos = find_line_comment()) != NULL) /* XXX */
6783 {
6784 /* find how indented the line beginning the comment is */
6785 getvcol(curwin, trypos, &col, NULL, NULL);
6786 amount = col;
6787 }
6788
6789 /*
6790 * If we're inside a comment and not looking at the start of the
6791 * comment, try using the 'comments' option.
6792 */
6793 else if (!cin_iscomment(theline)
6794 && (trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
6795 {
6796 int lead_start_len = 2;
6797 int lead_middle_len = 1;
6798 char_u lead_start[COM_MAX_LEN]; /* start-comment string */
6799 char_u lead_middle[COM_MAX_LEN]; /* middle-comment string */
6800 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
6801 char_u *p;
6802 int start_align = 0;
6803 int start_off = 0;
6804 int done = FALSE;
6805
6806 /* find how indented the line beginning the comment is */
6807 getvcol(curwin, trypos, &col, NULL, NULL);
6808 amount = col;
Bram Moolenaar4aa97422011-04-11 14:27:38 +02006809 *lead_start = NUL;
6810 *lead_middle = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006811
6812 p = curbuf->b_p_com;
6813 while (*p != NUL)
6814 {
6815 int align = 0;
6816 int off = 0;
6817 int what = 0;
6818
6819 while (*p != NUL && *p != ':')
6820 {
6821 if (*p == COM_START || *p == COM_END || *p == COM_MIDDLE)
6822 what = *p++;
6823 else if (*p == COM_LEFT || *p == COM_RIGHT)
6824 align = *p++;
6825 else if (VIM_ISDIGIT(*p) || *p == '-')
6826 off = getdigits(&p);
6827 else
6828 ++p;
6829 }
6830
6831 if (*p == ':')
6832 ++p;
6833 (void)copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
6834 if (what == COM_START)
6835 {
6836 STRCPY(lead_start, lead_end);
6837 lead_start_len = (int)STRLEN(lead_start);
6838 start_off = off;
6839 start_align = align;
6840 }
6841 else if (what == COM_MIDDLE)
6842 {
6843 STRCPY(lead_middle, lead_end);
6844 lead_middle_len = (int)STRLEN(lead_middle);
6845 }
6846 else if (what == COM_END)
6847 {
6848 /* If our line starts with the middle comment string, line it
6849 * up with the comment opener per the 'comments' option. */
6850 if (STRNCMP(theline, lead_middle, lead_middle_len) == 0
6851 && STRNCMP(theline, lead_end, STRLEN(lead_end)) != 0)
6852 {
6853 done = TRUE;
6854 if (curwin->w_cursor.lnum > 1)
6855 {
6856 /* If the start comment string matches in the previous
Bram Moolenaare21877a2008-02-13 09:58:14 +00006857 * line, use the indent of that line plus offset. If
Bram Moolenaar071d4272004-06-13 20:20:40 +00006858 * the middle comment string matches in the previous
6859 * line, use the indent of that line. XXX */
6860 look = skipwhite(ml_get(curwin->w_cursor.lnum - 1));
6861 if (STRNCMP(look, lead_start, lead_start_len) == 0)
6862 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6863 else if (STRNCMP(look, lead_middle,
6864 lead_middle_len) == 0)
6865 {
6866 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6867 break;
6868 }
6869 /* If the start comment string doesn't match with the
6870 * start of the comment, skip this entry. XXX */
6871 else if (STRNCMP(ml_get(trypos->lnum) + trypos->col,
6872 lead_start, lead_start_len) != 0)
6873 continue;
6874 }
6875 if (start_off != 0)
6876 amount += start_off;
6877 else if (start_align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006878 amount += vim_strsize(lead_start)
6879 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006880 break;
6881 }
6882
6883 /* If our line starts with the end comment string, line it up
6884 * with the middle comment */
6885 if (STRNCMP(theline, lead_middle, lead_middle_len) != 0
6886 && STRNCMP(theline, lead_end, STRLEN(lead_end)) == 0)
6887 {
6888 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6889 /* XXX */
6890 if (off != 0)
6891 amount += off;
6892 else if (align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006893 amount += vim_strsize(lead_start)
6894 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006895 done = TRUE;
6896 break;
6897 }
6898 }
6899 }
6900
6901 /* If our line starts with an asterisk, line up with the
6902 * asterisk in the comment opener; otherwise, line up
6903 * with the first character of the comment text.
6904 */
6905 if (done)
6906 ;
6907 else if (theline[0] == '*')
6908 amount += 1;
6909 else
6910 {
6911 /*
6912 * If we are more than one line away from the comment opener, take
6913 * the indent of the previous non-empty line. If 'cino' has "CO"
6914 * and we are just below the comment opener and there are any
6915 * white characters after it line up with the text after it;
6916 * otherwise, add the amount specified by "c" in 'cino'
6917 */
6918 amount = -1;
6919 for (lnum = cur_curpos.lnum - 1; lnum > trypos->lnum; --lnum)
6920 {
6921 if (linewhite(lnum)) /* skip blank lines */
6922 continue;
6923 amount = get_indent_lnum(lnum); /* XXX */
6924 break;
6925 }
6926 if (amount == -1) /* use the comment opener */
6927 {
6928 if (!ind_in_comment2)
6929 {
6930 start = ml_get(trypos->lnum);
6931 look = start + trypos->col + 2; /* skip / and * */
6932 if (*look != NUL) /* if something after it */
6933 trypos->col = (colnr_T)(skipwhite(look) - start);
6934 }
6935 getvcol(curwin, trypos, &col, NULL, NULL);
6936 amount = col;
6937 if (ind_in_comment2 || *look == NUL)
6938 amount += ind_in_comment;
6939 }
6940 }
6941 }
6942
6943 /*
6944 * Are we inside parentheses or braces?
6945 */ /* XXX */
6946 else if (((trypos = find_match_paren(ind_maxparen, ind_maxcomment)) != NULL
6947 && ind_java == 0)
6948 || (tryposBrace = find_start_brace(ind_maxcomment)) != NULL
6949 || trypos != NULL)
6950 {
6951 if (trypos != NULL && tryposBrace != NULL)
6952 {
6953 /* Both an unmatched '(' and '{' is found. Use the one which is
6954 * closer to the current cursor position, set the other to NULL. */
6955 if (trypos->lnum != tryposBrace->lnum
6956 ? trypos->lnum < tryposBrace->lnum
6957 : trypos->col < tryposBrace->col)
6958 trypos = NULL;
6959 else
6960 tryposBrace = NULL;
6961 }
6962
6963 if (trypos != NULL)
6964 {
6965 /*
6966 * If the matching paren is more than one line away, use the indent of
6967 * a previous non-empty line that matches the same paren.
6968 */
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006969 if (theline[0] == ')' && ind_paren_prev)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006970 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006971 /* Line up with the start of the matching paren line. */
6972 amount = get_indent_lnum(curwin->w_cursor.lnum - 1); /* XXX */
6973 }
6974 else
6975 {
6976 amount = -1;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006977 our_paren_pos = *trypos;
6978 for (lnum = cur_curpos.lnum - 1; lnum > our_paren_pos.lnum; --lnum)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006979 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006980 l = skipwhite(ml_get(lnum));
6981 if (cin_nocode(l)) /* skip comment lines */
6982 continue;
6983 if (cin_ispreproc_cont(&l, &lnum))
6984 continue; /* ignore #define, #if, etc. */
6985 curwin->w_cursor.lnum = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006986
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006987 /* Skip a comment. XXX */
6988 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
6989 {
6990 lnum = trypos->lnum + 1;
6991 continue;
6992 }
6993
6994 /* XXX */
6995 if ((trypos = find_match_paren(
6996 corr_ind_maxparen(ind_maxparen, &cur_curpos),
Bram Moolenaar071d4272004-06-13 20:20:40 +00006997 ind_maxcomment)) != NULL
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006998 && trypos->lnum == our_paren_pos.lnum
6999 && trypos->col == our_paren_pos.col)
7000 {
7001 amount = get_indent_lnum(lnum); /* XXX */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007002
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007003 if (theline[0] == ')')
7004 {
7005 if (our_paren_pos.lnum != lnum
7006 && cur_amount > amount)
7007 cur_amount = amount;
7008 amount = -1;
7009 }
7010 break;
7011 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007012 }
7013 }
7014
7015 /*
7016 * Line up with line where the matching paren is. XXX
7017 * If the line starts with a '(' or the indent for unclosed
7018 * parentheses is zero, line up with the unclosed parentheses.
7019 */
7020 if (amount == -1)
7021 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007022 int ignore_paren_col = 0;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007023 int is_if_for_while = 0;
7024
7025 if (ind_if_for_while)
7026 {
7027 /* Look for the outermost opening parenthesis on this line
7028 * and check whether it belongs to an "if", "for" or "while". */
7029
7030 pos_T cursor_save = curwin->w_cursor;
7031 pos_T outermost;
7032 char_u *line;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007033
7034 trypos = &our_paren_pos;
7035 do {
7036 outermost = *trypos;
7037 curwin->w_cursor.lnum = outermost.lnum;
7038 curwin->w_cursor.col = outermost.col;
7039
7040 trypos = find_match_paren(ind_maxparen, ind_maxcomment);
7041 } while (trypos && trypos->lnum == outermost.lnum);
7042
7043 curwin->w_cursor = cursor_save;
7044
7045 line = ml_get(outermost.lnum);
7046
7047 is_if_for_while =
Bram Moolenaarb345d492012-04-09 20:42:26 +02007048 cin_is_if_for_while_before_offset(line, &outermost.col);
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007049 }
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007050
Bram Moolenaar071d4272004-06-13 20:20:40 +00007051 amount = skip_label(our_paren_pos.lnum, &look, ind_maxcomment);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007052 look = skipwhite(look);
7053 if (*look == '(')
7054 {
7055 linenr_T save_lnum = curwin->w_cursor.lnum;
7056 char_u *line;
7057 int look_col;
7058
7059 /* Ignore a '(' in front of the line that has a match before
7060 * our matching '('. */
7061 curwin->w_cursor.lnum = our_paren_pos.lnum;
7062 line = ml_get_curline();
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007063 look_col = (int)(look - line);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007064 curwin->w_cursor.col = look_col + 1;
7065 if ((trypos = findmatchlimit(NULL, ')', 0, ind_maxparen))
7066 != NULL
7067 && trypos->lnum == our_paren_pos.lnum
7068 && trypos->col < our_paren_pos.col)
7069 ignore_paren_col = trypos->col + 1;
7070
7071 curwin->w_cursor.lnum = save_lnum;
7072 look = ml_get(our_paren_pos.lnum) + look_col;
7073 }
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007074 if (theline[0] == ')' || (ind_unclosed == 0 && is_if_for_while == 0)
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007075 || (!ind_unclosed_noignore && *look == '('
7076 && ignore_paren_col == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007077 {
7078 /*
7079 * If we're looking at a close paren, line up right there;
7080 * otherwise, line up with the next (non-white) character.
7081 * When ind_unclosed_wrapped is set and the matching paren is
7082 * the last nonwhite character of the line, use either the
7083 * indent of the current line or the indentation of the next
7084 * outer paren and add ind_unclosed_wrapped (for very long
7085 * lines).
7086 */
7087 if (theline[0] != ')')
7088 {
7089 cur_amount = MAXCOL;
7090 l = ml_get(our_paren_pos.lnum);
7091 if (ind_unclosed_wrapped
7092 && cin_ends_in(l, (char_u *)"(", NULL))
7093 {
7094 /* look for opening unmatched paren, indent one level
7095 * for each additional level */
7096 n = 1;
7097 for (col = 0; col < our_paren_pos.col; ++col)
7098 {
7099 switch (l[col])
7100 {
7101 case '(':
7102 case '{': ++n;
7103 break;
7104
7105 case ')':
7106 case '}': if (n > 1)
7107 --n;
7108 break;
7109 }
7110 }
7111
7112 our_paren_pos.col = 0;
7113 amount += n * ind_unclosed_wrapped;
7114 }
7115 else if (ind_unclosed_whiteok)
7116 our_paren_pos.col++;
7117 else
7118 {
7119 col = our_paren_pos.col + 1;
7120 while (vim_iswhite(l[col]))
7121 col++;
7122 if (l[col] != NUL) /* In case of trailing space */
7123 our_paren_pos.col = col;
7124 else
7125 our_paren_pos.col++;
7126 }
7127 }
7128
7129 /*
7130 * Find how indented the paren is, or the character after it
7131 * if we did the above "if".
7132 */
7133 if (our_paren_pos.col > 0)
7134 {
7135 getvcol(curwin, &our_paren_pos, &col, NULL, NULL);
7136 if (cur_amount > (int)col)
7137 cur_amount = col;
7138 }
7139 }
7140
7141 if (theline[0] == ')' && ind_matching_paren)
7142 {
7143 /* Line up with the start of the matching paren line. */
7144 }
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007145 else if ((ind_unclosed == 0 && is_if_for_while == 0)
7146 || (!ind_unclosed_noignore
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007147 && *look == '(' && ignore_paren_col == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007148 {
7149 if (cur_amount != MAXCOL)
7150 amount = cur_amount;
7151 }
7152 else
7153 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007154 /* Add ind_unclosed2 for each '(' before our matching one, but
7155 * ignore (void) before the line (ignore_paren_col). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007156 col = our_paren_pos.col;
Bram Moolenaarb21e5842006-04-16 18:30:08 +00007157 while ((int)our_paren_pos.col > ignore_paren_col)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007158 {
7159 --our_paren_pos.col;
7160 switch (*ml_get_pos(&our_paren_pos))
7161 {
7162 case '(': amount += ind_unclosed2;
7163 col = our_paren_pos.col;
7164 break;
7165 case ')': amount -= ind_unclosed2;
7166 col = MAXCOL;
7167 break;
7168 }
7169 }
7170
7171 /* Use ind_unclosed once, when the first '(' is not inside
7172 * braces */
7173 if (col == MAXCOL)
7174 amount += ind_unclosed;
7175 else
7176 {
7177 curwin->w_cursor.lnum = our_paren_pos.lnum;
7178 curwin->w_cursor.col = col;
Bram Moolenaar367bec82011-04-11 14:26:19 +02007179 if (find_match_paren(ind_maxparen, ind_maxcomment) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007180 amount += ind_unclosed2;
7181 else
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007182 {
7183 if (is_if_for_while)
7184 amount += ind_if_for_while;
7185 else
7186 amount += ind_unclosed;
7187 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007188 }
7189 /*
7190 * For a line starting with ')' use the minimum of the two
7191 * positions, to avoid giving it more indent than the previous
7192 * lines:
7193 * func_long_name( if (x
7194 * arg && yy
7195 * ) ^ not here ) ^ not here
7196 */
7197 if (cur_amount < amount)
7198 amount = cur_amount;
7199 }
7200 }
7201
7202 /* add extra indent for a comment */
7203 if (cin_iscomment(theline))
7204 amount += ind_comment;
7205 }
7206
7207 /*
7208 * Are we at least inside braces, then?
7209 */
7210 else
7211 {
7212 trypos = tryposBrace;
7213
7214 ourscope = trypos->lnum;
7215 start = ml_get(ourscope);
7216
7217 /*
7218 * Now figure out how indented the line is in general.
7219 * If the brace was at the start of the line, we use that;
7220 * otherwise, check out the indentation of the line as
7221 * a whole and then add the "imaginary indent" to that.
7222 */
7223 look = skipwhite(start);
7224 if (*look == '{')
7225 {
7226 getvcol(curwin, trypos, &col, NULL, NULL);
7227 amount = col;
7228 if (*start == '{')
7229 start_brace = BRACE_IN_COL0;
7230 else
7231 start_brace = BRACE_AT_START;
7232 }
7233 else
7234 {
7235 /*
7236 * that opening brace might have been on a continuation
7237 * line. if so, find the start of the line.
7238 */
7239 curwin->w_cursor.lnum = ourscope;
7240
7241 /*
7242 * position the cursor over the rightmost paren, so that
7243 * matching it will take us back to the start of the line.
7244 */
7245 lnum = ourscope;
7246 if (find_last_paren(start, '(', ')')
7247 && (trypos = find_match_paren(ind_maxparen,
7248 ind_maxcomment)) != NULL)
7249 lnum = trypos->lnum;
7250
7251 /*
7252 * It could have been something like
7253 * case 1: if (asdf &&
7254 * ldfd) {
7255 * }
7256 */
Bram Moolenaar6ec154b2011-06-12 21:51:08 +02007257 if (ind_js || (ind_keep_case_label
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007258 && cin_iscase(skipwhite(ml_get_curline()), FALSE)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007259 amount = get_indent();
7260 else
7261 amount = skip_label(lnum, &l, ind_maxcomment);
7262
7263 start_brace = BRACE_AT_END;
7264 }
7265
7266 /*
7267 * if we're looking at a closing brace, that's where
7268 * we want to be. otherwise, add the amount of room
7269 * that an indent is supposed to be.
7270 */
7271 if (theline[0] == '}')
7272 {
7273 /*
7274 * they may want closing braces to line up with something
7275 * other than the open brace. indulge them, if so.
7276 */
7277 amount += ind_close_extra;
7278 }
7279 else
7280 {
7281 /*
7282 * If we're looking at an "else", try to find an "if"
7283 * to match it with.
7284 * If we're looking at a "while", try to find a "do"
7285 * to match it with.
7286 */
7287 lookfor = LOOKFOR_INITIAL;
7288 if (cin_iselse(theline))
7289 lookfor = LOOKFOR_IF;
7290 else if (cin_iswhileofdo(theline, cur_curpos.lnum, ind_maxparen))
7291 /* XXX */
7292 lookfor = LOOKFOR_DO;
7293 if (lookfor != LOOKFOR_INITIAL)
7294 {
7295 curwin->w_cursor.lnum = cur_curpos.lnum;
7296 if (find_match(lookfor, ourscope, ind_maxparen,
7297 ind_maxcomment) == OK)
7298 {
7299 amount = get_indent(); /* XXX */
7300 goto theend;
7301 }
7302 }
7303
7304 /*
7305 * We get here if we are not on an "while-of-do" or "else" (or
7306 * failed to find a matching "if").
7307 * Search backwards for something to line up with.
7308 * First set amount for when we don't find anything.
7309 */
7310
7311 /*
7312 * if the '{' is _really_ at the left margin, use the imaginary
7313 * location of a left-margin brace. Otherwise, correct the
7314 * location for ind_open_extra.
7315 */
7316
7317 if (start_brace == BRACE_IN_COL0) /* '{' is in column 0 */
7318 {
7319 amount = ind_open_left_imag;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007320 lookfor_cpp_namespace = TRUE;
7321 }
7322 else if (start_brace == BRACE_AT_START &&
7323 lookfor_cpp_namespace) /* '{' is at start */
7324 {
7325
7326 lookfor_cpp_namespace = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007327 }
7328 else
7329 {
7330 if (start_brace == BRACE_AT_END) /* '{' is at end of line */
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007331 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007332 amount += ind_open_imag;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007333
7334 l = skipwhite(ml_get_curline());
7335 if (cin_is_cpp_namespace(l))
7336 amount += ind_cpp_namespace;
7337 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007338 else
7339 {
7340 /* Compensate for adding ind_open_extra later. */
7341 amount -= ind_open_extra;
7342 if (amount < 0)
7343 amount = 0;
7344 }
7345 }
7346
7347 lookfor_break = FALSE;
7348
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007349 if (cin_iscase(theline, FALSE)) /* it's a switch() label */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007350 {
7351 lookfor = LOOKFOR_CASE; /* find a previous switch() label */
7352 amount += ind_case;
7353 }
7354 else if (cin_isscopedecl(theline)) /* private:, ... */
7355 {
7356 lookfor = LOOKFOR_SCOPEDECL; /* class decl is this block */
7357 amount += ind_scopedecl;
7358 }
7359 else
7360 {
7361 if (ind_case_break && cin_isbreak(theline)) /* break; ... */
7362 lookfor_break = TRUE;
7363
7364 lookfor = LOOKFOR_INITIAL;
7365 amount += ind_level; /* ind_level from start of block */
7366 }
7367 scope_amount = amount;
7368 whilelevel = 0;
7369
7370 /*
7371 * Search backwards. If we find something we recognize, line up
7372 * with that.
7373 *
7374 * if we're looking at an open brace, indent
7375 * the usual amount relative to the conditional
7376 * that opens the block.
7377 */
7378 curwin->w_cursor = cur_curpos;
7379 for (;;)
7380 {
7381 curwin->w_cursor.lnum--;
7382 curwin->w_cursor.col = 0;
7383
7384 /*
7385 * If we went all the way back to the start of our scope, line
7386 * up with it.
7387 */
7388 if (curwin->w_cursor.lnum <= ourscope)
7389 {
7390 /* we reached end of scope:
7391 * if looking for a enum or structure initialization
7392 * go further back:
7393 * if it is an initializer (enum xxx or xxx =), then
7394 * don't add ind_continuation, otherwise it is a variable
7395 * declaration:
7396 * int x,
7397 * here; <-- add ind_continuation
7398 */
7399 if (lookfor == LOOKFOR_ENUM_OR_INIT)
7400 {
7401 if (curwin->w_cursor.lnum == 0
7402 || curwin->w_cursor.lnum
7403 < ourscope - ind_maxparen)
7404 {
7405 /* nothing found (abuse ind_maxparen as limit)
7406 * assume terminated line (i.e. a variable
7407 * initialization) */
7408 if (cont_amount > 0)
7409 amount = cont_amount;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007410 else if (!ind_js)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007411 amount += ind_continuation;
7412 break;
7413 }
7414
7415 l = ml_get_curline();
7416
7417 /*
7418 * If we're in a comment now, skip to the start of the
7419 * comment.
7420 */
7421 trypos = find_start_comment(ind_maxcomment);
7422 if (trypos != NULL)
7423 {
7424 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007425 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007426 continue;
7427 }
7428
7429 /*
7430 * Skip preprocessor directives and blank lines.
7431 */
7432 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7433 continue;
7434
7435 if (cin_nocode(l))
7436 continue;
7437
7438 terminated = cin_isterminated(l, FALSE, TRUE);
7439
7440 /*
7441 * If we are at top level and the line looks like a
7442 * function declaration, we are done
7443 * (it's a variable declaration).
7444 */
7445 if (start_brace != BRACE_IN_COL0
Bram Moolenaarc367faa2011-12-14 20:21:35 +01007446 || !cin_isfuncdecl(&l, curwin->w_cursor.lnum,
7447 0, ind_maxparen, ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007448 {
7449 /* if the line is terminated with another ','
7450 * it is a continued variable initialization.
7451 * don't add extra indent.
7452 * TODO: does not work, if a function
7453 * declaration is split over multiple lines:
7454 * cin_isfuncdecl returns FALSE then.
7455 */
7456 if (terminated == ',')
7457 break;
7458
7459 /* if it es a enum declaration or an assignment,
7460 * we are done.
7461 */
7462 if (terminated != ';' && cin_isinit())
7463 break;
7464
7465 /* nothing useful found */
7466 if (terminated == 0 || terminated == '{')
7467 continue;
7468 }
7469
7470 if (terminated != ';')
7471 {
7472 /* Skip parens and braces. Position the cursor
7473 * over the rightmost paren, so that matching it
7474 * will take us back to the start of the line.
7475 */ /* XXX */
7476 trypos = NULL;
7477 if (find_last_paren(l, '(', ')'))
7478 trypos = find_match_paren(ind_maxparen,
7479 ind_maxcomment);
7480
7481 if (trypos == NULL && find_last_paren(l, '{', '}'))
7482 trypos = find_start_brace(ind_maxcomment);
7483
7484 if (trypos != NULL)
7485 {
7486 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007487 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007488 continue;
7489 }
7490 }
7491
7492 /* it's a variable declaration, add indentation
7493 * like in
7494 * int a,
7495 * b;
7496 */
7497 if (cont_amount > 0)
7498 amount = cont_amount;
7499 else
7500 amount += ind_continuation;
7501 }
7502 else if (lookfor == LOOKFOR_UNTERM)
7503 {
7504 if (cont_amount > 0)
7505 amount = cont_amount;
7506 else
7507 amount += ind_continuation;
7508 }
Bram Moolenaare79d1532011-10-04 18:03:47 +02007509 else
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007510 {
Bram Moolenaare79d1532011-10-04 18:03:47 +02007511 if (lookfor != LOOKFOR_TERM
Bram Moolenaar071d4272004-06-13 20:20:40 +00007512 && lookfor != LOOKFOR_CPP_BASECLASS)
Bram Moolenaare79d1532011-10-04 18:03:47 +02007513 {
7514 amount = scope_amount;
7515 if (theline[0] == '{')
7516 {
7517 amount += ind_open_extra;
7518 added_to_amount = ind_open_extra;
7519 }
7520 }
7521
7522 if (lookfor_cpp_namespace)
7523 {
7524 /*
7525 * Looking for C++ namespace, need to look further
7526 * back.
7527 */
7528 if (curwin->w_cursor.lnum == ourscope)
7529 continue;
7530
7531 if (curwin->w_cursor.lnum == 0
7532 || curwin->w_cursor.lnum
7533 < ourscope - FIND_NAMESPACE_LIM)
7534 break;
7535
7536 l = ml_get_curline();
7537
7538 /* If we're in a comment now, skip to the start of
7539 * the comment. */
7540 trypos = find_start_comment(ind_maxcomment);
7541 if (trypos != NULL)
7542 {
7543 curwin->w_cursor.lnum = trypos->lnum + 1;
7544 curwin->w_cursor.col = 0;
7545 continue;
7546 }
7547
7548 /* Skip preprocessor directives and blank lines. */
7549 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7550 continue;
7551
7552 /* Finally the actual check for "namespace". */
7553 if (cin_is_cpp_namespace(l))
7554 {
7555 amount += ind_cpp_namespace - added_to_amount;
7556 break;
7557 }
7558
7559 if (cin_nocode(l))
7560 continue;
7561 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007562 }
7563 break;
7564 }
7565
7566 /*
7567 * If we're in a comment now, skip to the start of the comment.
7568 */ /* XXX */
7569 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
7570 {
7571 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007572 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007573 continue;
7574 }
7575
7576 l = ml_get_curline();
7577
7578 /*
7579 * If this is a switch() label, may line up relative to that.
Bram Moolenaar18144c82006-04-12 21:52:12 +00007580 * If this is a C++ scope declaration, do the same.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007581 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007582 iscase = cin_iscase(l, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007583 if (iscase || cin_isscopedecl(l))
7584 {
7585 /* we are only looking for cpp base class
7586 * declaration/initialization any longer */
7587 if (lookfor == LOOKFOR_CPP_BASECLASS)
7588 break;
7589
7590 /* When looking for a "do" we are not interested in
7591 * labels. */
7592 if (whilelevel > 0)
7593 continue;
7594
7595 /*
7596 * case xx:
7597 * c = 99 + <- this indent plus continuation
7598 *-> here;
7599 */
7600 if (lookfor == LOOKFOR_UNTERM
7601 || lookfor == LOOKFOR_ENUM_OR_INIT)
7602 {
7603 if (cont_amount > 0)
7604 amount = cont_amount;
7605 else
7606 amount += ind_continuation;
7607 break;
7608 }
7609
7610 /*
7611 * case xx: <- line up with this case
7612 * x = 333;
7613 * case yy:
7614 */
7615 if ( (iscase && lookfor == LOOKFOR_CASE)
7616 || (iscase && lookfor_break)
7617 || (!iscase && lookfor == LOOKFOR_SCOPEDECL))
7618 {
7619 /*
7620 * Check that this case label is not for another
7621 * switch()
7622 */ /* XXX */
7623 if ((trypos = find_start_brace(ind_maxcomment)) ==
7624 NULL || trypos->lnum == ourscope)
7625 {
7626 amount = get_indent(); /* XXX */
7627 break;
7628 }
7629 continue;
7630 }
7631
7632 n = get_indent_nolabel(curwin->w_cursor.lnum); /* XXX */
7633
7634 /*
7635 * case xx: if (cond) <- line up with this if
7636 * y = y + 1;
7637 * -> s = 99;
7638 *
7639 * case xx:
7640 * if (cond) <- line up with this line
7641 * y = y + 1;
7642 * -> s = 99;
7643 */
7644 if (lookfor == LOOKFOR_TERM)
7645 {
7646 if (n)
7647 amount = n;
7648
7649 if (!lookfor_break)
7650 break;
7651 }
7652
7653 /*
7654 * case xx: x = x + 1; <- line up with this x
7655 * -> y = y + 1;
7656 *
7657 * case xx: if (cond) <- line up with this if
7658 * -> y = y + 1;
7659 */
7660 if (n)
7661 {
7662 amount = n;
7663 l = after_label(ml_get_curline());
7664 if (l != NULL && cin_is_cinword(l))
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007665 {
7666 if (theline[0] == '{')
7667 amount += ind_open_extra;
7668 else
7669 amount += ind_level + ind_no_brace;
7670 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007671 break;
7672 }
7673
7674 /*
7675 * Try to get the indent of a statement before the switch
7676 * label. If nothing is found, line up relative to the
7677 * switch label.
7678 * break; <- may line up with this line
7679 * case xx:
7680 * -> y = 1;
7681 */
7682 scope_amount = get_indent() + (iscase /* XXX */
7683 ? ind_case_code : ind_scopedecl_code);
7684 lookfor = ind_case_break ? LOOKFOR_NOBREAK : LOOKFOR_ANY;
7685 continue;
7686 }
7687
7688 /*
7689 * Looking for a switch() label or C++ scope declaration,
7690 * ignore other lines, skip {}-blocks.
7691 */
7692 if (lookfor == LOOKFOR_CASE || lookfor == LOOKFOR_SCOPEDECL)
7693 {
7694 if (find_last_paren(l, '{', '}') && (trypos =
7695 find_start_brace(ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007696 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007697 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007698 curwin->w_cursor.col = 0;
7699 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007700 continue;
7701 }
7702
7703 /*
7704 * Ignore jump labels with nothing after them.
7705 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007706 if (!ind_js && cin_islabel(ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007707 {
7708 l = after_label(ml_get_curline());
7709 if (l == NULL || cin_nocode(l))
7710 continue;
7711 }
7712
7713 /*
7714 * Ignore #defines, #if, etc.
7715 * Ignore comment and empty lines.
7716 * (need to get the line again, cin_islabel() may have
7717 * unlocked it)
7718 */
7719 l = ml_get_curline();
7720 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum)
7721 || cin_nocode(l))
7722 continue;
7723
7724 /*
7725 * Are we at the start of a cpp base class declaration or
7726 * constructor initialization?
7727 */ /* XXX */
Bram Moolenaar18144c82006-04-12 21:52:12 +00007728 n = FALSE;
7729 if (lookfor != LOOKFOR_TERM && ind_cpp_baseclass > 0)
7730 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00007731 n = cin_is_cpp_baseclass(&col);
Bram Moolenaar18144c82006-04-12 21:52:12 +00007732 l = ml_get_curline();
7733 }
7734 if (n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007735 {
7736 if (lookfor == LOOKFOR_UNTERM)
7737 {
7738 if (cont_amount > 0)
7739 amount = cont_amount;
7740 else
7741 amount += ind_continuation;
7742 }
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007743 else if (theline[0] == '{')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007744 {
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007745 /* Need to find start of the declaration. */
7746 lookfor = LOOKFOR_UNTERM;
7747 ind_continuation = 0;
7748 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007749 }
7750 else
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007751 /* XXX */
7752 amount = get_baseclass_amount(col, ind_maxparen,
7753 ind_maxcomment, ind_cpp_baseclass);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007754 break;
7755 }
7756 else if (lookfor == LOOKFOR_CPP_BASECLASS)
7757 {
7758 /* only look, whether there is a cpp base class
Bram Moolenaar18144c82006-04-12 21:52:12 +00007759 * declaration or initialization before the opening brace.
7760 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007761 if (cin_isterminated(l, TRUE, FALSE))
7762 break;
7763 else
7764 continue;
7765 }
7766
7767 /*
7768 * What happens next depends on the line being terminated.
7769 * If terminated with a ',' only consider it terminating if
Bram Moolenaar25394022007-05-10 19:06:20 +00007770 * there is another unterminated statement behind, eg:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007771 * 123,
7772 * sizeof
7773 * here
7774 * Otherwise check whether it is a enumeration or structure
7775 * initialisation (not indented) or a variable declaration
7776 * (indented).
7777 */
7778 terminated = cin_isterminated(l, FALSE, TRUE);
7779
7780 if (terminated == 0 || (lookfor != LOOKFOR_UNTERM
7781 && terminated == ','))
7782 {
7783 /*
7784 * if we're in the middle of a paren thing,
7785 * go back to the line that starts it so
7786 * we can get the right prevailing indent
7787 * if ( foo &&
7788 * bar )
7789 */
7790 /*
7791 * position the cursor over the rightmost paren, so that
7792 * matching it will take us back to the start of the line.
7793 */
7794 (void)find_last_paren(l, '(', ')');
7795 trypos = find_match_paren(
7796 corr_ind_maxparen(ind_maxparen, &cur_curpos),
7797 ind_maxcomment);
7798
7799 /*
7800 * If we are looking for ',', we also look for matching
7801 * braces.
7802 */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007803 if (trypos == NULL && terminated == ','
7804 && find_last_paren(l, '{', '}'))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007805 trypos = find_start_brace(ind_maxcomment);
7806
7807 if (trypos != NULL)
7808 {
7809 /*
7810 * Check if we are on a case label now. This is
7811 * handled above.
7812 * case xx: if ( asdf &&
7813 * asdf)
7814 */
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007815 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007816 l = ml_get_curline();
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007817 if (cin_iscase(l, FALSE) || cin_isscopedecl(l))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007818 {
7819 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007820 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007821 continue;
7822 }
7823 }
7824
7825 /*
7826 * Skip over continuation lines to find the one to get the
7827 * indent from
7828 * char *usethis = "bla\
7829 * bla",
7830 * here;
7831 */
7832 if (terminated == ',')
7833 {
7834 while (curwin->w_cursor.lnum > 1)
7835 {
7836 l = ml_get(curwin->w_cursor.lnum - 1);
7837 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
7838 break;
7839 --curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007840 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007841 }
7842 }
7843
7844 /*
7845 * Get indent and pointer to text for current line,
7846 * ignoring any jump label. XXX
7847 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007848 if (!ind_js)
7849 cur_amount = skip_label(curwin->w_cursor.lnum,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007850 &l, ind_maxcomment);
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007851 else
7852 cur_amount = get_indent();
Bram Moolenaar071d4272004-06-13 20:20:40 +00007853 /*
7854 * If this is just above the line we are indenting, and it
7855 * starts with a '{', line it up with this line.
7856 * while (not)
7857 * -> {
7858 * }
7859 */
7860 if (terminated != ',' && lookfor != LOOKFOR_TERM
7861 && theline[0] == '{')
7862 {
7863 amount = cur_amount;
7864 /*
7865 * Only add ind_open_extra when the current line
7866 * doesn't start with a '{', which must have a match
7867 * in the same line (scope is the same). Probably:
7868 * { 1, 2 },
7869 * -> { 3, 4 }
7870 */
7871 if (*skipwhite(l) != '{')
7872 amount += ind_open_extra;
7873
7874 if (ind_cpp_baseclass)
7875 {
7876 /* have to look back, whether it is a cpp base
7877 * class declaration or initialization */
7878 lookfor = LOOKFOR_CPP_BASECLASS;
7879 continue;
7880 }
7881 break;
7882 }
7883
7884 /*
7885 * Check if we are after an "if", "while", etc.
7886 * Also allow " } else".
7887 */
7888 if (cin_is_cinword(l) || cin_iselse(skipwhite(l)))
7889 {
7890 /*
7891 * Found an unterminated line after an if (), line up
7892 * with the last one.
7893 * if (cond)
7894 * 100 +
7895 * -> here;
7896 */
7897 if (lookfor == LOOKFOR_UNTERM
7898 || lookfor == LOOKFOR_ENUM_OR_INIT)
7899 {
7900 if (cont_amount > 0)
7901 amount = cont_amount;
7902 else
7903 amount += ind_continuation;
7904 break;
7905 }
7906
7907 /*
7908 * If this is just above the line we are indenting, we
7909 * are finished.
7910 * while (not)
7911 * -> here;
7912 * Otherwise this indent can be used when the line
7913 * before this is terminated.
7914 * yyy;
7915 * if (stat)
7916 * while (not)
7917 * xxx;
7918 * -> here;
7919 */
7920 amount = cur_amount;
7921 if (theline[0] == '{')
7922 amount += ind_open_extra;
7923 if (lookfor != LOOKFOR_TERM)
7924 {
7925 amount += ind_level + ind_no_brace;
7926 break;
7927 }
7928
7929 /*
7930 * Special trick: when expecting the while () after a
7931 * do, line up with the while()
7932 * do
7933 * x = 1;
7934 * -> here
7935 */
7936 l = skipwhite(ml_get_curline());
7937 if (cin_isdo(l))
7938 {
7939 if (whilelevel == 0)
7940 break;
7941 --whilelevel;
7942 }
7943
7944 /*
7945 * When searching for a terminated line, don't use the
Bram Moolenaar334adf02011-05-25 13:34:04 +02007946 * one between the "if" and the matching "else".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007947 * Need to use the scope of this "else". XXX
7948 * If whilelevel != 0 continue looking for a "do {".
7949 */
Bram Moolenaar334adf02011-05-25 13:34:04 +02007950 if (cin_iselse(l) && whilelevel == 0)
7951 {
7952 /* If we're looking at "} else", let's make sure we
7953 * find the opening brace of the enclosing scope,
7954 * not the one from "if () {". */
7955 if (*l == '}')
7956 curwin->w_cursor.col =
Bram Moolenaar9b83c2f2011-05-25 17:29:44 +02007957 (colnr_T)(l - ml_get_curline()) + 1;
Bram Moolenaar334adf02011-05-25 13:34:04 +02007958
7959 if ((trypos = find_start_brace(ind_maxcomment))
7960 == NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007961 || find_match(LOOKFOR_IF, trypos->lnum,
Bram Moolenaar334adf02011-05-25 13:34:04 +02007962 ind_maxparen, ind_maxcomment) == FAIL)
7963 break;
7964 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007965 }
7966
7967 /*
7968 * If we're below an unterminated line that is not an
7969 * "if" or something, we may line up with this line or
Bram Moolenaar25394022007-05-10 19:06:20 +00007970 * add something for a continuation line, depending on
Bram Moolenaar071d4272004-06-13 20:20:40 +00007971 * the line before this one.
7972 */
7973 else
7974 {
7975 /*
7976 * Found two unterminated lines on a row, line up with
7977 * the last one.
7978 * c = 99 +
7979 * 100 +
7980 * -> here;
7981 */
7982 if (lookfor == LOOKFOR_UNTERM)
7983 {
7984 /* When line ends in a comma add extra indent */
7985 if (terminated == ',')
7986 amount += ind_continuation;
7987 break;
7988 }
7989
7990 if (lookfor == LOOKFOR_ENUM_OR_INIT)
7991 {
7992 /* Found two lines ending in ',', lineup with the
7993 * lowest one, but check for cpp base class
7994 * declaration/initialization, if it is an
7995 * opening brace or we are looking just for
7996 * enumerations/initializations. */
7997 if (terminated == ',')
7998 {
7999 if (ind_cpp_baseclass == 0)
8000 break;
8001
8002 lookfor = LOOKFOR_CPP_BASECLASS;
8003 continue;
8004 }
8005
8006 /* Ignore unterminated lines in between, but
8007 * reduce indent. */
8008 if (amount > cur_amount)
8009 amount = cur_amount;
8010 }
8011 else
8012 {
8013 /*
8014 * Found first unterminated line on a row, may
8015 * line up with this line, remember its indent
8016 * 100 +
8017 * -> here;
8018 */
8019 amount = cur_amount;
8020
8021 /*
8022 * If previous line ends in ',', check whether we
8023 * are in an initialization or enum
8024 * struct xxx =
8025 * {
8026 * sizeof a,
8027 * 124 };
8028 * or a normal possible continuation line.
8029 * but only, of no other statement has been found
8030 * yet.
8031 */
8032 if (lookfor == LOOKFOR_INITIAL && terminated == ',')
8033 {
8034 lookfor = LOOKFOR_ENUM_OR_INIT;
8035 cont_amount = cin_first_id_amount();
8036 }
8037 else
8038 {
8039 if (lookfor == LOOKFOR_INITIAL
8040 && *l != NUL
8041 && l[STRLEN(l) - 1] == '\\')
8042 /* XXX */
8043 cont_amount = cin_get_equal_amount(
8044 curwin->w_cursor.lnum);
8045 if (lookfor != LOOKFOR_TERM)
8046 lookfor = LOOKFOR_UNTERM;
8047 }
8048 }
8049 }
8050 }
8051
8052 /*
8053 * Check if we are after a while (cond);
8054 * If so: Ignore until the matching "do".
8055 */
8056 /* XXX */
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00008057 else if (cin_iswhileofdo_end(terminated, ind_maxparen,
8058 ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008059 {
8060 /*
8061 * Found an unterminated line after a while ();, line up
8062 * with the last one.
8063 * while (cond);
8064 * 100 + <- line up with this one
8065 * -> here;
8066 */
8067 if (lookfor == LOOKFOR_UNTERM
8068 || lookfor == LOOKFOR_ENUM_OR_INIT)
8069 {
8070 if (cont_amount > 0)
8071 amount = cont_amount;
8072 else
8073 amount += ind_continuation;
8074 break;
8075 }
8076
8077 if (whilelevel == 0)
8078 {
8079 lookfor = LOOKFOR_TERM;
8080 amount = get_indent(); /* XXX */
8081 if (theline[0] == '{')
8082 amount += ind_open_extra;
8083 }
8084 ++whilelevel;
8085 }
8086
8087 /*
8088 * We are after a "normal" statement.
8089 * If we had another statement we can stop now and use the
8090 * indent of that other statement.
8091 * Otherwise the indent of the current statement may be used,
8092 * search backwards for the next "normal" statement.
8093 */
8094 else
8095 {
8096 /*
8097 * Skip single break line, if before a switch label. It
8098 * may be lined up with the case label.
8099 */
8100 if (lookfor == LOOKFOR_NOBREAK
8101 && cin_isbreak(skipwhite(ml_get_curline())))
8102 {
8103 lookfor = LOOKFOR_ANY;
8104 continue;
8105 }
8106
8107 /*
8108 * Handle "do {" line.
8109 */
8110 if (whilelevel > 0)
8111 {
8112 l = cin_skipcomment(ml_get_curline());
8113 if (cin_isdo(l))
8114 {
8115 amount = get_indent(); /* XXX */
8116 --whilelevel;
8117 continue;
8118 }
8119 }
8120
8121 /*
8122 * Found a terminated line above an unterminated line. Add
8123 * the amount for a continuation line.
8124 * x = 1;
8125 * y = foo +
8126 * -> here;
8127 * or
8128 * int x = 1;
8129 * int foo,
8130 * -> here;
8131 */
8132 if (lookfor == LOOKFOR_UNTERM
8133 || lookfor == LOOKFOR_ENUM_OR_INIT)
8134 {
8135 if (cont_amount > 0)
8136 amount = cont_amount;
8137 else
8138 amount += ind_continuation;
8139 break;
8140 }
8141
8142 /*
8143 * Found a terminated line above a terminated line or "if"
8144 * etc. line. Use the amount of the line below us.
8145 * x = 1; x = 1;
8146 * if (asdf) y = 2;
8147 * while (asdf) ->here;
8148 * here;
8149 * ->foo;
8150 */
8151 if (lookfor == LOOKFOR_TERM)
8152 {
8153 if (!lookfor_break && whilelevel == 0)
8154 break;
8155 }
8156
8157 /*
8158 * First line above the one we're indenting is terminated.
8159 * To know what needs to be done look further backward for
8160 * a terminated line.
8161 */
8162 else
8163 {
8164 /*
8165 * position the cursor over the rightmost paren, so
8166 * that matching it will take us back to the start of
8167 * the line. Helps for:
8168 * func(asdr,
8169 * asdfasdf);
8170 * here;
8171 */
8172term_again:
8173 l = ml_get_curline();
8174 if (find_last_paren(l, '(', ')')
8175 && (trypos = find_match_paren(ind_maxparen,
8176 ind_maxcomment)) != NULL)
8177 {
8178 /*
8179 * Check if we are on a case label now. This is
8180 * handled above.
8181 * case xx: if ( asdf &&
8182 * asdf)
8183 */
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008184 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008185 l = ml_get_curline();
Bram Moolenaar3acfc302010-07-11 17:23:02 +02008186 if (cin_iscase(l, FALSE) || cin_isscopedecl(l))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008187 {
8188 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008189 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008190 continue;
8191 }
8192 }
8193
8194 /* When aligning with the case statement, don't align
8195 * with a statement after it.
8196 * case 1: { <-- don't use this { position
8197 * stat;
8198 * }
8199 * case 2:
8200 * stat;
8201 * }
8202 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02008203 iscase = (ind_keep_case_label && cin_iscase(l, FALSE));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008204
8205 /*
8206 * Get indent and pointer to text for current line,
8207 * ignoring any jump label.
8208 */
8209 amount = skip_label(curwin->w_cursor.lnum,
8210 &l, ind_maxcomment);
8211
8212 if (theline[0] == '{')
8213 amount += ind_open_extra;
8214 /* See remark above: "Only add ind_open_extra.." */
Bram Moolenaar18144c82006-04-12 21:52:12 +00008215 l = skipwhite(l);
8216 if (*l == '{')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008217 amount -= ind_open_extra;
8218 lookfor = iscase ? LOOKFOR_ANY : LOOKFOR_TERM;
8219
8220 /*
Bram Moolenaar18144c82006-04-12 21:52:12 +00008221 * When a terminated line starts with "else" skip to
8222 * the matching "if":
8223 * else 3;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008224 * indent this;
Bram Moolenaar18144c82006-04-12 21:52:12 +00008225 * Need to use the scope of this "else". XXX
8226 * If whilelevel != 0 continue looking for a "do {".
8227 */
8228 if (lookfor == LOOKFOR_TERM
8229 && *l != '}'
8230 && cin_iselse(l)
8231 && whilelevel == 0)
8232 {
8233 if ((trypos = find_start_brace(ind_maxcomment))
8234 == NULL
8235 || find_match(LOOKFOR_IF, trypos->lnum,
8236 ind_maxparen, ind_maxcomment) == FAIL)
8237 break;
8238 continue;
8239 }
8240
8241 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008242 * If we're at the end of a block, skip to the start of
8243 * that block.
8244 */
Bram Moolenaar6d8f9c62011-11-30 13:03:28 +01008245 l = ml_get_curline();
Bram Moolenaar50f42ca2011-07-15 14:12:30 +02008246 if (find_last_paren(l, '{', '}')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008247 && (trypos = find_start_brace(ind_maxcomment))
8248 != NULL) /* XXX */
8249 {
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008250 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008251 /* if not "else {" check for terminated again */
8252 /* but skip block for "} else {" */
8253 l = cin_skipcomment(ml_get_curline());
8254 if (*l == '}' || !cin_iselse(l))
8255 goto term_again;
8256 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008257 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008258 }
8259 }
8260 }
8261 }
8262 }
8263 }
8264
8265 /* add extra indent for a comment */
8266 if (cin_iscomment(theline))
8267 amount += ind_comment;
Bram Moolenaar02c707a2010-07-17 17:12:06 +02008268
8269 /* subtract extra left-shift for jump labels */
8270 if (ind_jump_label > 0 && original_line_islabel)
8271 amount -= ind_jump_label;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008272 }
8273
8274 /*
8275 * ok -- we're not inside any sort of structure at all!
8276 *
8277 * this means we're at the top level, and everything should
8278 * basically just match where the previous line is, except
8279 * for the lines immediately following a function declaration,
8280 * which are K&R-style parameters and need to be indented.
8281 */
8282 else
8283 {
8284 /*
8285 * if our line starts with an open brace, forget about any
8286 * prevailing indent and make sure it looks like the start
8287 * of a function
8288 */
8289
8290 if (theline[0] == '{')
8291 {
8292 amount = ind_first_open;
8293 }
8294
8295 /*
8296 * If the NEXT line is a function declaration, the current
8297 * line needs to be indented as a function type spec.
Bram Moolenaar1a89bbe2010-03-02 12:38:22 +01008298 * Don't do this if the current line looks like a comment or if the
8299 * current line is terminated, ie. ends in ';', or if the current line
8300 * contains { or }: "void f() {\n if (1)"
Bram Moolenaar071d4272004-06-13 20:20:40 +00008301 */
8302 else if (cur_curpos.lnum < curbuf->b_ml.ml_line_count
8303 && !cin_nocode(theline)
Bram Moolenaar1a89bbe2010-03-02 12:38:22 +01008304 && vim_strchr(theline, '{') == NULL
8305 && vim_strchr(theline, '}') == NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00008306 && !cin_ends_in(theline, (char_u *)":", NULL)
8307 && !cin_ends_in(theline, (char_u *)",", NULL)
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008308 && cin_isfuncdecl(NULL, cur_curpos.lnum + 1,
8309 cur_curpos.lnum + 1,
8310 ind_maxparen, ind_maxcomment)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008311 && !cin_isterminated(theline, FALSE, TRUE))
8312 {
8313 amount = ind_func_type;
8314 }
8315 else
8316 {
8317 amount = 0;
8318 curwin->w_cursor = cur_curpos;
8319
8320 /* search backwards until we find something we recognize */
8321
8322 while (curwin->w_cursor.lnum > 1)
8323 {
8324 curwin->w_cursor.lnum--;
8325 curwin->w_cursor.col = 0;
8326
8327 l = ml_get_curline();
8328
8329 /*
8330 * If we're in a comment now, skip to the start of the comment.
8331 */ /* XXX */
8332 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
8333 {
8334 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008335 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008336 continue;
8337 }
8338
8339 /*
Bram Moolenaar18144c82006-04-12 21:52:12 +00008340 * Are we at the start of a cpp base class declaration or
8341 * constructor initialization?
Bram Moolenaar071d4272004-06-13 20:20:40 +00008342 */ /* XXX */
Bram Moolenaar18144c82006-04-12 21:52:12 +00008343 n = FALSE;
8344 if (ind_cpp_baseclass != 0 && theline[0] != '{')
8345 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00008346 n = cin_is_cpp_baseclass(&col);
Bram Moolenaar18144c82006-04-12 21:52:12 +00008347 l = ml_get_curline();
8348 }
8349 if (n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008350 {
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00008351 /* XXX */
8352 amount = get_baseclass_amount(col, ind_maxparen,
8353 ind_maxcomment, ind_cpp_baseclass);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008354 break;
8355 }
8356
8357 /*
8358 * Skip preprocessor directives and blank lines.
8359 */
8360 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
8361 continue;
8362
8363 if (cin_nocode(l))
8364 continue;
8365
8366 /*
8367 * If the previous line ends in ',', use one level of
8368 * indentation:
8369 * int foo,
8370 * bar;
8371 * do this before checking for '}' in case of eg.
8372 * enum foobar
8373 * {
8374 * ...
8375 * } foo,
8376 * bar;
8377 */
8378 n = 0;
8379 if (cin_ends_in(l, (char_u *)",", NULL)
8380 || (*l != NUL && (n = l[STRLEN(l) - 1]) == '\\'))
8381 {
8382 /* take us back to opening paren */
8383 if (find_last_paren(l, '(', ')')
8384 && (trypos = find_match_paren(ind_maxparen,
8385 ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008386 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008387
8388 /* For a line ending in ',' that is a continuation line go
8389 * back to the first line with a backslash:
8390 * char *foo = "bla\
8391 * bla",
8392 * here;
8393 */
8394 while (n == 0 && curwin->w_cursor.lnum > 1)
8395 {
8396 l = ml_get(curwin->w_cursor.lnum - 1);
8397 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
8398 break;
8399 --curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008400 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008401 }
8402
8403 amount = get_indent(); /* XXX */
8404
8405 if (amount == 0)
8406 amount = cin_first_id_amount();
8407 if (amount == 0)
8408 amount = ind_continuation;
8409 break;
8410 }
8411
8412 /*
8413 * If the line looks like a function declaration, and we're
8414 * not in a comment, put it the left margin.
8415 */
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008416 if (cin_isfuncdecl(NULL, cur_curpos.lnum, 0,
8417 ind_maxparen, ind_maxcomment)) /* XXX */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008418 break;
8419 l = ml_get_curline();
8420
8421 /*
8422 * Finding the closing '}' of a previous function. Put
8423 * current line at the left margin. For when 'cino' has "fs".
8424 */
8425 if (*skipwhite(l) == '}')
8426 break;
8427
8428 /* (matching {)
8429 * If the previous line ends on '};' (maybe followed by
8430 * comments) align at column 0. For example:
8431 * char *string_array[] = { "foo",
8432 * / * x * / "b};ar" }; / * foobar * /
8433 */
8434 if (cin_ends_in(l, (char_u *)"};", NULL))
8435 break;
8436
8437 /*
Bram Moolenaar3388bb42011-11-30 17:20:23 +01008438 * Find a line only has a semicolon that belongs to a previous
8439 * line ending in '}', e.g. before an #endif. Don't increase
8440 * indent then.
8441 */
8442 if (*(look = skipwhite(l)) == ';' && cin_nocode(look + 1))
8443 {
8444 pos_T curpos_save = curwin->w_cursor;
8445
8446 while (curwin->w_cursor.lnum > 1)
8447 {
8448 look = ml_get(--curwin->w_cursor.lnum);
8449 if (!(cin_nocode(look) || cin_ispreproc_cont(
8450 &look, &curwin->w_cursor.lnum)))
8451 break;
8452 }
8453 if (curwin->w_cursor.lnum > 0
8454 && cin_ends_in(look, (char_u *)"}", NULL))
8455 break;
8456
8457 curwin->w_cursor = curpos_save;
8458 }
8459
8460 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008461 * If the PREVIOUS line is a function declaration, the current
8462 * line (and the ones that follow) needs to be indented as
8463 * parameters.
8464 */
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008465 if (cin_isfuncdecl(&l, curwin->w_cursor.lnum, 0,
8466 ind_maxparen, ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008467 {
8468 amount = ind_param;
8469 break;
8470 }
8471
8472 /*
8473 * If the previous line ends in ';' and the line before the
8474 * previous line ends in ',' or '\', ident to column zero:
8475 * int foo,
8476 * bar;
8477 * indent_to_0 here;
8478 */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00008479 if (cin_ends_in(l, (char_u *)";", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008480 {
8481 l = ml_get(curwin->w_cursor.lnum - 1);
8482 if (cin_ends_in(l, (char_u *)",", NULL)
8483 || (*l != NUL && l[STRLEN(l) - 1] == '\\'))
8484 break;
8485 l = ml_get_curline();
8486 }
8487
8488 /*
8489 * Doesn't look like anything interesting -- so just
8490 * use the indent of this line.
8491 *
8492 * Position the cursor over the rightmost paren, so that
8493 * matching it will take us back to the start of the line.
8494 */
8495 find_last_paren(l, '(', ')');
8496
8497 if ((trypos = find_match_paren(ind_maxparen,
8498 ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008499 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008500 amount = get_indent(); /* XXX */
8501 break;
8502 }
8503
8504 /* add extra indent for a comment */
8505 if (cin_iscomment(theline))
8506 amount += ind_comment;
8507
8508 /* add extra indent if the previous line ended in a backslash:
8509 * "asdfasdf\
8510 * here";
8511 * char *foo = "asdf\
8512 * here";
8513 */
8514 if (cur_curpos.lnum > 1)
8515 {
8516 l = ml_get(cur_curpos.lnum - 1);
8517 if (*l != NUL && l[STRLEN(l) - 1] == '\\')
8518 {
8519 cur_amount = cin_get_equal_amount(cur_curpos.lnum - 1);
8520 if (cur_amount > 0)
8521 amount = cur_amount;
8522 else if (cur_amount == 0)
8523 amount += ind_continuation;
8524 }
8525 }
8526 }
8527 }
8528
8529theend:
8530 /* put the cursor back where it belongs */
8531 curwin->w_cursor = cur_curpos;
8532
8533 vim_free(linecopy);
8534
8535 if (amount < 0)
8536 return 0;
8537 return amount;
8538}
8539
8540 static int
8541find_match(lookfor, ourscope, ind_maxparen, ind_maxcomment)
8542 int lookfor;
8543 linenr_T ourscope;
8544 int ind_maxparen;
8545 int ind_maxcomment;
8546{
8547 char_u *look;
8548 pos_T *theirscope;
8549 char_u *mightbeif;
8550 int elselevel;
8551 int whilelevel;
8552
8553 if (lookfor == LOOKFOR_IF)
8554 {
8555 elselevel = 1;
8556 whilelevel = 0;
8557 }
8558 else
8559 {
8560 elselevel = 0;
8561 whilelevel = 1;
8562 }
8563
8564 curwin->w_cursor.col = 0;
8565
8566 while (curwin->w_cursor.lnum > ourscope + 1)
8567 {
8568 curwin->w_cursor.lnum--;
8569 curwin->w_cursor.col = 0;
8570
8571 look = cin_skipcomment(ml_get_curline());
8572 if (cin_iselse(look)
8573 || cin_isif(look)
8574 || cin_isdo(look) /* XXX */
8575 || cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
8576 {
8577 /*
8578 * if we've gone outside the braces entirely,
8579 * we must be out of scope...
8580 */
8581 theirscope = find_start_brace(ind_maxcomment); /* XXX */
8582 if (theirscope == NULL)
8583 break;
8584
8585 /*
8586 * and if the brace enclosing this is further
8587 * back than the one enclosing the else, we're
8588 * out of luck too.
8589 */
8590 if (theirscope->lnum < ourscope)
8591 break;
8592
8593 /*
8594 * and if they're enclosed in a *deeper* brace,
8595 * then we can ignore it because it's in a
8596 * different scope...
8597 */
8598 if (theirscope->lnum > ourscope)
8599 continue;
8600
8601 /*
8602 * if it was an "else" (that's not an "else if")
8603 * then we need to go back to another if, so
8604 * increment elselevel
8605 */
8606 look = cin_skipcomment(ml_get_curline());
8607 if (cin_iselse(look))
8608 {
8609 mightbeif = cin_skipcomment(look + 4);
8610 if (!cin_isif(mightbeif))
8611 ++elselevel;
8612 continue;
8613 }
8614
8615 /*
8616 * if it was a "while" then we need to go back to
8617 * another "do", so increment whilelevel. XXX
8618 */
8619 if (cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
8620 {
8621 ++whilelevel;
8622 continue;
8623 }
8624
8625 /* If it's an "if" decrement elselevel */
8626 look = cin_skipcomment(ml_get_curline());
8627 if (cin_isif(look))
8628 {
8629 elselevel--;
8630 /*
8631 * When looking for an "if" ignore "while"s that
8632 * get in the way.
8633 */
8634 if (elselevel == 0 && lookfor == LOOKFOR_IF)
8635 whilelevel = 0;
8636 }
8637
8638 /* If it's a "do" decrement whilelevel */
8639 if (cin_isdo(look))
8640 whilelevel--;
8641
8642 /*
8643 * if we've used up all the elses, then
8644 * this must be the if that we want!
8645 * match the indent level of that if.
8646 */
8647 if (elselevel <= 0 && whilelevel <= 0)
8648 {
8649 return OK;
8650 }
8651 }
8652 }
8653 return FAIL;
8654}
8655
8656# if defined(FEAT_EVAL) || defined(PROTO)
8657/*
8658 * Get indent level from 'indentexpr'.
8659 */
8660 int
8661get_expr_indent()
8662{
8663 int indent;
8664 pos_T pos;
8665 int save_State;
Bram Moolenaard1f56e62006-02-22 21:25:37 +00008666 int use_sandbox = was_set_insecurely((char_u *)"indentexpr",
8667 OPT_LOCAL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008668
8669 pos = curwin->w_cursor;
8670 set_vim_var_nr(VV_LNUM, curwin->w_cursor.lnum);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00008671 if (use_sandbox)
8672 ++sandbox;
8673 ++textlock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008674 indent = eval_to_number(curbuf->b_p_inde);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00008675 if (use_sandbox)
8676 --sandbox;
8677 --textlock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008678
8679 /* Restore the cursor position so that 'indentexpr' doesn't need to.
8680 * Pretend to be in Insert mode, allow cursor past end of line for "o"
8681 * command. */
8682 save_State = State;
8683 State = INSERT;
8684 curwin->w_cursor = pos;
8685 check_cursor();
8686 State = save_State;
8687
8688 /* If there is an error, just keep the current indent. */
8689 if (indent < 0)
8690 indent = get_indent();
8691
8692 return indent;
8693}
8694# endif
8695
8696#endif /* FEAT_CINDENT */
8697
8698#if defined(FEAT_LISP) || defined(PROTO)
8699
8700static int lisp_match __ARGS((char_u *p));
8701
8702 static int
8703lisp_match(p)
8704 char_u *p;
8705{
8706 char_u buf[LSIZE];
8707 int len;
8708 char_u *word = p_lispwords;
8709
8710 while (*word != NUL)
8711 {
8712 (void)copy_option_part(&word, buf, LSIZE, ",");
8713 len = (int)STRLEN(buf);
8714 if (STRNCMP(buf, p, len) == 0 && p[len] == ' ')
8715 return TRUE;
8716 }
8717 return FALSE;
8718}
8719
8720/*
8721 * When 'p' is present in 'cpoptions, a Vi compatible method is used.
8722 * The incompatible newer method is quite a bit better at indenting
8723 * code in lisp-like languages than the traditional one; it's still
8724 * mostly heuristics however -- Dirk van Deun, dirk@rave.org
8725 *
8726 * TODO:
8727 * Findmatch() should be adapted for lisp, also to make showmatch
8728 * work correctly: now (v5.3) it seems all C/C++ oriented:
8729 * - it does not recognize the #\( and #\) notations as character literals
8730 * - it doesn't know about comments starting with a semicolon
8731 * - it incorrectly interprets '(' as a character literal
8732 * All this messes up get_lisp_indent in some rare cases.
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008733 * Update from Sergey Khorev:
8734 * I tried to fix the first two issues.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008735 */
8736 int
8737get_lisp_indent()
8738{
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008739 pos_T *pos, realpos, paren;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008740 int amount;
8741 char_u *that;
8742 colnr_T col;
8743 colnr_T firsttry;
8744 int parencount, quotecount;
8745 int vi_lisp;
8746
8747 /* Set vi_lisp to use the vi-compatible method */
8748 vi_lisp = (vim_strchr(p_cpo, CPO_LISP) != NULL);
8749
8750 realpos = curwin->w_cursor;
8751 curwin->w_cursor.col = 0;
8752
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008753 if ((pos = findmatch(NULL, '(')) == NULL)
8754 pos = findmatch(NULL, '[');
8755 else
8756 {
8757 paren = *pos;
8758 pos = findmatch(NULL, '[');
8759 if (pos == NULL || ltp(pos, &paren))
8760 pos = &paren;
8761 }
8762 if (pos != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008763 {
8764 /* Extra trick: Take the indent of the first previous non-white
8765 * line that is at the same () level. */
8766 amount = -1;
8767 parencount = 0;
8768
8769 while (--curwin->w_cursor.lnum >= pos->lnum)
8770 {
8771 if (linewhite(curwin->w_cursor.lnum))
8772 continue;
8773 for (that = ml_get_curline(); *that != NUL; ++that)
8774 {
8775 if (*that == ';')
8776 {
8777 while (*(that + 1) != NUL)
8778 ++that;
8779 continue;
8780 }
8781 if (*that == '\\')
8782 {
8783 if (*(that + 1) != NUL)
8784 ++that;
8785 continue;
8786 }
8787 if (*that == '"' && *(that + 1) != NUL)
8788 {
Bram Moolenaar15ff6c12006-09-15 18:18:09 +00008789 while (*++that && *that != '"')
8790 {
8791 /* skipping escaped characters in the string */
8792 if (*that == '\\')
8793 {
8794 if (*++that == NUL)
8795 break;
8796 if (that[1] == NUL)
8797 {
8798 ++that;
8799 break;
8800 }
8801 }
8802 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008803 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008804 if (*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008805 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008806 else if (*that == ')' || *that == ']')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008807 --parencount;
8808 }
8809 if (parencount == 0)
8810 {
8811 amount = get_indent();
8812 break;
8813 }
8814 }
8815
8816 if (amount == -1)
8817 {
8818 curwin->w_cursor.lnum = pos->lnum;
8819 curwin->w_cursor.col = pos->col;
8820 col = pos->col;
8821
8822 that = ml_get_curline();
8823
8824 if (vi_lisp && get_indent() == 0)
8825 amount = 2;
8826 else
8827 {
8828 amount = 0;
8829 while (*that && col)
8830 {
8831 amount += lbr_chartabsize_adv(&that, (colnr_T)amount);
8832 col--;
8833 }
8834
8835 /*
8836 * Some keywords require "body" indenting rules (the
8837 * non-standard-lisp ones are Scheme special forms):
8838 *
8839 * (let ((a 1)) instead (let ((a 1))
8840 * (...)) of (...))
8841 */
8842
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008843 if (!vi_lisp && (*that == '(' || *that == '[')
8844 && lisp_match(that + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008845 amount += 2;
8846 else
8847 {
8848 that++;
8849 amount++;
8850 firsttry = amount;
8851
8852 while (vim_iswhite(*that))
8853 {
8854 amount += lbr_chartabsize(that, (colnr_T)amount);
8855 ++that;
8856 }
8857
8858 if (*that && *that != ';') /* not a comment line */
8859 {
Bram Moolenaare21877a2008-02-13 09:58:14 +00008860 /* test *that != '(' to accommodate first let/do
Bram Moolenaar071d4272004-06-13 20:20:40 +00008861 * argument if it is more than one line */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008862 if (!vi_lisp && *that != '(' && *that != '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008863 firsttry++;
8864
8865 parencount = 0;
8866 quotecount = 0;
8867
8868 if (vi_lisp
8869 || (*that != '"'
8870 && *that != '\''
8871 && *that != '#'
8872 && (*that < '0' || *that > '9')))
8873 {
8874 while (*that
8875 && (!vim_iswhite(*that)
8876 || quotecount
8877 || parencount)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008878 && (!((*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008879 && !quotecount
8880 && !parencount
8881 && vi_lisp)))
8882 {
8883 if (*that == '"')
8884 quotecount = !quotecount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008885 if ((*that == '(' || *that == '[')
8886 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008887 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008888 if ((*that == ')' || *that == ']')
8889 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008890 --parencount;
8891 if (*that == '\\' && *(that+1) != NUL)
8892 amount += lbr_chartabsize_adv(&that,
8893 (colnr_T)amount);
8894 amount += lbr_chartabsize_adv(&that,
8895 (colnr_T)amount);
8896 }
8897 }
8898 while (vim_iswhite(*that))
8899 {
8900 amount += lbr_chartabsize(that, (colnr_T)amount);
8901 that++;
8902 }
8903 if (!*that || *that == ';')
8904 amount = firsttry;
8905 }
8906 }
8907 }
8908 }
8909 }
8910 else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008911 amount = 0; /* no matching '(' or '[' found, use zero indent */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008912
8913 curwin->w_cursor = realpos;
8914
8915 return amount;
8916}
8917#endif /* FEAT_LISP */
8918
8919 void
8920prepare_to_exit()
8921{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00008922#if defined(SIGHUP) && defined(SIG_IGN)
8923 /* Ignore SIGHUP, because a dropped connection causes a read error, which
8924 * makes Vim exit and then handling SIGHUP causes various reentrance
8925 * problems. */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00008926 signal(SIGHUP, SIG_IGN);
8927#endif
8928
Bram Moolenaar071d4272004-06-13 20:20:40 +00008929#ifdef FEAT_GUI
8930 if (gui.in_use)
8931 {
8932 gui.dying = TRUE;
8933 out_trash(); /* trash any pending output */
8934 }
8935 else
8936#endif
8937 {
8938 windgoto((int)Rows - 1, 0);
8939
8940 /*
8941 * Switch terminal mode back now, so messages end up on the "normal"
8942 * screen (if there are two screens).
8943 */
8944 settmode(TMODE_COOK);
8945#ifdef WIN3264
8946 if (can_end_termcap_mode(FALSE) == TRUE)
8947#endif
8948 stoptermcap();
8949 out_flush();
8950 }
8951}
8952
8953/*
8954 * Preserve files and exit.
8955 * When called IObuff must contain a message.
8956 */
8957 void
8958preserve_exit()
8959{
8960 buf_T *buf;
8961
8962 prepare_to_exit();
8963
Bram Moolenaar4770d092006-01-12 23:22:24 +00008964 /* Setting this will prevent free() calls. That avoids calling free()
8965 * recursively when free() was invoked with a bad pointer. */
8966 really_exiting = TRUE;
8967
Bram Moolenaar071d4272004-06-13 20:20:40 +00008968 out_str(IObuff);
8969 screen_start(); /* don't know where cursor is now */
8970 out_flush();
8971
8972 ml_close_notmod(); /* close all not-modified buffers */
8973
8974 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8975 {
8976 if (buf->b_ml.ml_mfp != NULL && buf->b_ml.ml_mfp->mf_fname != NULL)
8977 {
8978 OUT_STR(_("Vim: preserving files...\n"));
8979 screen_start(); /* don't know where cursor is now */
8980 out_flush();
8981 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
8982 break;
8983 }
8984 }
8985
8986 ml_close_all(FALSE); /* close all memfiles, without deleting */
8987
8988 OUT_STR(_("Vim: Finished.\n"));
8989
8990 getout(1);
8991}
8992
8993/*
8994 * return TRUE if "fname" exists.
8995 */
8996 int
8997vim_fexists(fname)
8998 char_u *fname;
8999{
9000 struct stat st;
9001
9002 if (mch_stat((char *)fname, &st))
9003 return FALSE;
9004 return TRUE;
9005}
9006
9007/*
9008 * Check for CTRL-C pressed, but only once in a while.
9009 * Should be used instead of ui_breakcheck() for functions that check for
9010 * each line in the file. Calling ui_breakcheck() each time takes too much
9011 * time, because it can be a system call.
9012 */
9013
9014#ifndef BREAKCHECK_SKIP
9015# ifdef FEAT_GUI /* assume the GUI only runs on fast computers */
9016# define BREAKCHECK_SKIP 200
9017# else
9018# define BREAKCHECK_SKIP 32
9019# endif
9020#endif
9021
9022static int breakcheck_count = 0;
9023
9024 void
9025line_breakcheck()
9026{
9027 if (++breakcheck_count >= BREAKCHECK_SKIP)
9028 {
9029 breakcheck_count = 0;
9030 ui_breakcheck();
9031 }
9032}
9033
9034/*
9035 * Like line_breakcheck() but check 10 times less often.
9036 */
9037 void
9038fast_breakcheck()
9039{
9040 if (++breakcheck_count >= BREAKCHECK_SKIP * 10)
9041 {
9042 breakcheck_count = 0;
9043 ui_breakcheck();
9044 }
9045}
9046
9047/*
Bram Moolenaard7834d32009-12-02 16:14:36 +00009048 * Invoke expand_wildcards() for one pattern.
9049 * Expand items like "%:h" before the expansion.
9050 * Returns OK or FAIL.
9051 */
9052 int
9053expand_wildcards_eval(pat, num_file, file, flags)
9054 char_u **pat; /* pointer to input pattern */
9055 int *num_file; /* resulting number of files */
9056 char_u ***file; /* array of resulting files */
9057 int flags; /* EW_DIR, etc. */
9058{
9059 int ret = FAIL;
9060 char_u *eval_pat = NULL;
9061 char_u *exp_pat = *pat;
9062 char_u *ignored_msg;
9063 int usedlen;
9064
9065 if (*exp_pat == '%' || *exp_pat == '#' || *exp_pat == '<')
9066 {
9067 ++emsg_off;
9068 eval_pat = eval_vars(exp_pat, exp_pat, &usedlen,
9069 NULL, &ignored_msg, NULL);
9070 --emsg_off;
9071 if (eval_pat != NULL)
9072 exp_pat = concat_str(eval_pat, exp_pat + usedlen);
9073 }
9074
9075 if (exp_pat != NULL)
9076 ret = expand_wildcards(1, &exp_pat, num_file, file, flags);
9077
9078 if (eval_pat != NULL)
9079 {
9080 vim_free(exp_pat);
9081 vim_free(eval_pat);
9082 }
9083
9084 return ret;
9085}
9086
9087/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00009088 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching
9089 * 'wildignore'.
Bram Moolenaar9e193ac2010-07-19 23:11:27 +02009090 * Returns OK or FAIL. When FAIL then "num_file" won't be set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009091 */
9092 int
9093expand_wildcards(num_pat, pat, num_file, file, flags)
9094 int num_pat; /* number of input patterns */
9095 char_u **pat; /* array of input patterns */
9096 int *num_file; /* resulting number of files */
9097 char_u ***file; /* array of resulting files */
9098 int flags; /* EW_DIR, etc. */
9099{
9100 int retval;
9101 int i, j;
9102 char_u *p;
9103 int non_suf_match; /* number without matching suffix */
9104
9105 retval = gen_expand_wildcards(num_pat, pat, num_file, file, flags);
9106
9107 /* When keeping all matches, return here */
Bram Moolenaar9e193ac2010-07-19 23:11:27 +02009108 if ((flags & EW_KEEPALL) || retval == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009109 return retval;
9110
9111#ifdef FEAT_WILDIGN
9112 /*
9113 * Remove names that match 'wildignore'.
9114 */
9115 if (*p_wig)
9116 {
9117 char_u *ffname;
9118
9119 /* check all files in (*file)[] */
9120 for (i = 0; i < *num_file; ++i)
9121 {
9122 ffname = FullName_save((*file)[i], FALSE);
9123 if (ffname == NULL) /* out of memory */
9124 break;
9125# ifdef VMS
9126 vms_remove_version(ffname);
9127# endif
9128 if (match_file_list(p_wig, (*file)[i], ffname))
9129 {
9130 /* remove this matching file from the list */
9131 vim_free((*file)[i]);
9132 for (j = i; j + 1 < *num_file; ++j)
9133 (*file)[j] = (*file)[j + 1];
9134 --*num_file;
9135 --i;
9136 }
9137 vim_free(ffname);
9138 }
9139 }
9140#endif
9141
9142 /*
9143 * Move the names where 'suffixes' match to the end.
9144 */
9145 if (*num_file > 1)
9146 {
9147 non_suf_match = 0;
9148 for (i = 0; i < *num_file; ++i)
9149 {
9150 if (!match_suffix((*file)[i]))
9151 {
9152 /*
9153 * Move the name without matching suffix to the front
9154 * of the list.
9155 */
9156 p = (*file)[i];
9157 for (j = i; j > non_suf_match; --j)
9158 (*file)[j] = (*file)[j - 1];
9159 (*file)[non_suf_match++] = p;
9160 }
9161 }
9162 }
9163
9164 return retval;
9165}
9166
9167/*
9168 * Return TRUE if "fname" matches with an entry in 'suffixes'.
9169 */
9170 int
9171match_suffix(fname)
9172 char_u *fname;
9173{
9174 int fnamelen, setsuflen;
9175 char_u *setsuf;
9176#define MAXSUFLEN 30 /* maximum length of a file suffix */
9177 char_u suf_buf[MAXSUFLEN];
9178
9179 fnamelen = (int)STRLEN(fname);
9180 setsuflen = 0;
9181 for (setsuf = p_su; *setsuf; )
9182 {
9183 setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
Bram Moolenaar055a2ba2009-07-14 19:40:21 +00009184 if (setsuflen == 0)
9185 {
9186 char_u *tail = gettail(fname);
9187
9188 /* empty entry: match name without a '.' */
9189 if (vim_strchr(tail, '.') == NULL)
9190 {
9191 setsuflen = 1;
9192 break;
9193 }
9194 }
9195 else
9196 {
9197 if (fnamelen >= setsuflen
9198 && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
9199 (size_t)setsuflen) == 0)
9200 break;
9201 setsuflen = 0;
9202 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009203 }
9204 return (setsuflen != 0);
9205}
9206
9207#if !defined(NO_EXPANDPATH) || defined(PROTO)
9208
9209# ifdef VIM_BACKTICK
9210static int vim_backtick __ARGS((char_u *p));
9211static int expand_backtick __ARGS((garray_T *gap, char_u *pat, int flags));
9212# endif
9213
9214# if defined(MSDOS) || defined(FEAT_GUI_W16) || defined(WIN3264)
9215/*
9216 * File name expansion code for MS-DOS, Win16 and Win32. It's here because
9217 * it's shared between these systems.
9218 */
9219# if defined(DJGPP) || defined(PROTO)
9220# define _cdecl /* DJGPP doesn't have this */
9221# else
9222# ifdef __BORLANDC__
9223# define _cdecl _RTLENTRYF
9224# endif
9225# endif
9226
9227/*
9228 * comparison function for qsort in dos_expandpath()
9229 */
9230 static int _cdecl
9231pstrcmp(const void *a, const void *b)
9232{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00009233 return (pathcmp(*(char **)a, *(char **)b, -1));
Bram Moolenaar071d4272004-06-13 20:20:40 +00009234}
9235
9236# ifndef WIN3264
9237 static void
9238namelowcpy(
9239 char_u *d,
9240 char_u *s)
9241{
9242# ifdef DJGPP
9243 if (USE_LONG_FNAME) /* don't lower case on Windows 95/NT systems */
9244 while (*s)
9245 *d++ = *s++;
9246 else
9247# endif
9248 while (*s)
9249 *d++ = TOLOWER_LOC(*s++);
9250 *d = NUL;
9251}
9252# endif
9253
9254/*
Bram Moolenaar231334e2005-07-25 20:46:57 +00009255 * Recursively expand one path component into all matching files and/or
9256 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009257 * Return the number of matches found.
9258 * "path" has backslashes before chars that are not to be expanded, starting
9259 * at "path[wildoff]".
Bram Moolenaar231334e2005-07-25 20:46:57 +00009260 * Return the number of matches found.
9261 * NOTE: much of this is identical to unix_expandpath(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00009262 */
9263 static int
9264dos_expandpath(
9265 garray_T *gap,
9266 char_u *path,
9267 int wildoff,
Bram Moolenaar231334e2005-07-25 20:46:57 +00009268 int flags, /* EW_* flags */
Bram Moolenaar25394022007-05-10 19:06:20 +00009269 int didstar) /* expanded "**" once already */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009270{
Bram Moolenaar231334e2005-07-25 20:46:57 +00009271 char_u *buf;
9272 char_u *path_end;
9273 char_u *p, *s, *e;
9274 int start_len = gap->ga_len;
9275 char_u *pat;
9276 regmatch_T regmatch;
9277 int starts_with_dot;
9278 int matches;
9279 int len;
9280 int starstar = FALSE;
9281 static int stardepth = 0; /* depth for "**" expansion */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009282#ifdef WIN3264
9283 WIN32_FIND_DATA fb;
9284 HANDLE hFind = (HANDLE)0;
9285# ifdef FEAT_MBYTE
9286 WIN32_FIND_DATAW wfb;
9287 WCHAR *wn = NULL; /* UCS-2 name, NULL when not used. */
9288# endif
9289#else
9290 struct ffblk fb;
9291#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009292 char_u *matchname;
Bram Moolenaar231334e2005-07-25 20:46:57 +00009293 int ok;
9294
9295 /* Expanding "**" may take a long time, check for CTRL-C. */
9296 if (stardepth > 0)
9297 {
9298 ui_breakcheck();
9299 if (got_int)
9300 return 0;
9301 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009302
9303 /* make room for file name */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009304 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009305 if (buf == NULL)
9306 return 0;
9307
9308 /*
9309 * Find the first part in the path name that contains a wildcard or a ~1.
9310 * Copy it into buf, including the preceding characters.
9311 */
9312 p = buf;
9313 s = buf;
9314 e = NULL;
9315 path_end = path;
9316 while (*path_end != NUL)
9317 {
9318 /* May ignore a wildcard that has a backslash before it; it will
9319 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
9320 if (path_end >= path + wildoff && rem_backslash(path_end))
9321 *p++ = *path_end++;
9322 else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
9323 {
9324 if (e != NULL)
9325 break;
9326 s = p + 1;
9327 }
9328 else if (path_end >= path + wildoff
9329 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
9330 e = p;
9331#ifdef FEAT_MBYTE
9332 if (has_mbyte)
9333 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00009334 len = (*mb_ptr2len)(path_end);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009335 STRNCPY(p, path_end, len);
9336 p += len;
9337 path_end += len;
9338 }
9339 else
9340#endif
9341 *p++ = *path_end++;
9342 }
9343 e = p;
9344 *e = NUL;
9345
9346 /* now we have one wildcard component between s and e */
9347 /* Remove backslashes between "wildoff" and the start of the wildcard
9348 * component. */
9349 for (p = buf + wildoff; p < s; ++p)
9350 if (rem_backslash(p))
9351 {
Bram Moolenaar8c8de832008-06-24 22:58:06 +00009352 STRMOVE(p, p + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009353 --e;
9354 --s;
9355 }
9356
Bram Moolenaar231334e2005-07-25 20:46:57 +00009357 /* Check for "**" between "s" and "e". */
9358 for (p = s; p < e; ++p)
9359 if (p[0] == '*' && p[1] == '*')
9360 starstar = TRUE;
9361
Bram Moolenaar071d4272004-06-13 20:20:40 +00009362 starts_with_dot = (*s == '.');
9363 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
9364 if (pat == NULL)
9365 {
9366 vim_free(buf);
9367 return 0;
9368 }
9369
9370 /* compile the regexp into a program */
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009371 if (flags & (EW_NOERROR | EW_NOTWILD))
Bram Moolenaarb5609832011-07-20 15:04:58 +02009372 ++emsg_silent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009373 regmatch.rm_ic = TRUE; /* Always ignore case */
9374 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009375 if (flags & (EW_NOERROR | EW_NOTWILD))
Bram Moolenaarb5609832011-07-20 15:04:58 +02009376 --emsg_silent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009377 vim_free(pat);
9378
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009379 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009380 {
9381 vim_free(buf);
9382 return 0;
9383 }
9384
9385 /* remember the pattern or file name being looked for */
9386 matchname = vim_strsave(s);
9387
Bram Moolenaar231334e2005-07-25 20:46:57 +00009388 /* If "**" is by itself, this is the first time we encounter it and more
9389 * is following then find matches without any directory. */
9390 if (!didstar && stardepth < 100 && starstar && e - s == 2
9391 && *path_end == '/')
9392 {
9393 STRCPY(s, path_end + 1);
9394 ++stardepth;
9395 (void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
9396 --stardepth;
9397 }
9398
Bram Moolenaar071d4272004-06-13 20:20:40 +00009399 /* Scan all files in the directory with "dir/ *.*" */
9400 STRCPY(s, "*.*");
9401#ifdef WIN3264
9402# ifdef FEAT_MBYTE
9403 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
9404 {
9405 /* The active codepage differs from 'encoding'. Attempt using the
9406 * wide function. If it fails because it is not implemented fall back
9407 * to the non-wide version (for Windows 98) */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009408 wn = enc_to_utf16(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009409 if (wn != NULL)
9410 {
9411 hFind = FindFirstFileW(wn, &wfb);
9412 if (hFind == INVALID_HANDLE_VALUE
9413 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
9414 {
9415 vim_free(wn);
9416 wn = NULL;
9417 }
9418 }
9419 }
9420
9421 if (wn == NULL)
9422# endif
9423 hFind = FindFirstFile(buf, &fb);
9424 ok = (hFind != INVALID_HANDLE_VALUE);
9425#else
9426 /* If we are expanding wildcards we try both files and directories */
9427 ok = (findfirst((char *)buf, &fb,
9428 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
9429#endif
9430
9431 while (ok)
9432 {
9433#ifdef WIN3264
9434# ifdef FEAT_MBYTE
9435 if (wn != NULL)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009436 p = utf16_to_enc(wfb.cFileName, NULL); /* p is allocated here */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009437 else
9438# endif
9439 p = (char_u *)fb.cFileName;
9440#else
9441 p = (char_u *)fb.ff_name;
9442#endif
9443 /* Ignore entries starting with a dot, unless when asked for. Accept
9444 * all entries found with "matchname". */
9445 if ((p[0] != '.' || starts_with_dot)
9446 && (matchname == NULL
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009447 || (regmatch.regprog != NULL
9448 && vim_regexec(&regmatch, p, (colnr_T)0))
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009449 || ((flags & EW_NOTWILD)
9450 && fnamencmp(path + (s - buf), p, e - s) == 0)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009451 {
9452#ifdef WIN3264
9453 STRCPY(s, p);
9454#else
9455 namelowcpy(s, p);
9456#endif
9457 len = (int)STRLEN(buf);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009458
9459 if (starstar && stardepth < 100)
9460 {
9461 /* For "**" in the pattern first go deeper in the tree to
9462 * find matches. */
9463 STRCPY(buf + len, "/**");
9464 STRCPY(buf + len + 3, path_end);
9465 ++stardepth;
9466 (void)dos_expandpath(gap, buf, len + 1, flags, TRUE);
9467 --stardepth;
9468 }
9469
Bram Moolenaar071d4272004-06-13 20:20:40 +00009470 STRCPY(buf + len, path_end);
9471 if (mch_has_exp_wildcard(path_end))
9472 {
9473 /* need to expand another component of the path */
9474 /* remove backslashes for the remaining components only */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009475 (void)dos_expandpath(gap, buf, len + 1, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009476 }
9477 else
9478 {
9479 /* no more wildcards, check if there is a match */
9480 /* remove backslashes for the remaining components only */
9481 if (*path_end != 0)
9482 backslash_halve(buf + len + 1);
9483 if (mch_getperm(buf) >= 0) /* add existing file */
9484 addfile(gap, buf, flags);
9485 }
9486 }
9487
9488#ifdef WIN3264
9489# ifdef FEAT_MBYTE
9490 if (wn != NULL)
9491 {
9492 vim_free(p);
9493 ok = FindNextFileW(hFind, &wfb);
9494 }
9495 else
9496# endif
9497 ok = FindNextFile(hFind, &fb);
9498#else
9499 ok = (findnext(&fb) == 0);
9500#endif
9501
9502 /* If no more matches and no match was used, try expanding the name
9503 * itself. Finds the long name of a short filename. */
9504 if (!ok && matchname != NULL && gap->ga_len == start_len)
9505 {
9506 STRCPY(s, matchname);
9507#ifdef WIN3264
9508 FindClose(hFind);
9509# ifdef FEAT_MBYTE
9510 if (wn != NULL)
9511 {
9512 vim_free(wn);
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009513 wn = enc_to_utf16(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009514 if (wn != NULL)
9515 hFind = FindFirstFileW(wn, &wfb);
9516 }
9517 if (wn == NULL)
9518# endif
9519 hFind = FindFirstFile(buf, &fb);
9520 ok = (hFind != INVALID_HANDLE_VALUE);
9521#else
9522 ok = (findfirst((char *)buf, &fb,
9523 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
9524#endif
9525 vim_free(matchname);
9526 matchname = NULL;
9527 }
9528 }
9529
9530#ifdef WIN3264
9531 FindClose(hFind);
9532# ifdef FEAT_MBYTE
9533 vim_free(wn);
9534# endif
9535#endif
9536 vim_free(buf);
9537 vim_free(regmatch.regprog);
9538 vim_free(matchname);
9539
9540 matches = gap->ga_len - start_len;
9541 if (matches > 0)
9542 qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
9543 sizeof(char_u *), pstrcmp);
9544 return matches;
9545}
9546
9547 int
9548mch_expandpath(
9549 garray_T *gap,
9550 char_u *path,
9551 int flags) /* EW_* flags */
9552{
Bram Moolenaar231334e2005-07-25 20:46:57 +00009553 return dos_expandpath(gap, path, 0, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009554}
9555# endif /* MSDOS || FEAT_GUI_W16 || WIN3264 */
9556
Bram Moolenaar231334e2005-07-25 20:46:57 +00009557#if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
9558 || defined(PROTO)
9559/*
9560 * Unix style wildcard expansion code.
9561 * It's here because it's used both for Unix and Mac.
9562 */
9563static int pstrcmp __ARGS((const void *, const void *));
9564
9565 static int
9566pstrcmp(a, b)
9567 const void *a, *b;
9568{
9569 return (pathcmp(*(char **)a, *(char **)b, -1));
9570}
9571
9572/*
9573 * Recursively expand one path component into all matching files and/or
9574 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
9575 * "path" has backslashes before chars that are not to be expanded, starting
9576 * at "path + wildoff".
9577 * Return the number of matches found.
9578 * NOTE: much of this is identical to dos_expandpath(), keep in sync!
9579 */
9580 int
9581unix_expandpath(gap, path, wildoff, flags, didstar)
9582 garray_T *gap;
9583 char_u *path;
9584 int wildoff;
9585 int flags; /* EW_* flags */
9586 int didstar; /* expanded "**" once already */
9587{
9588 char_u *buf;
9589 char_u *path_end;
9590 char_u *p, *s, *e;
9591 int start_len = gap->ga_len;
9592 char_u *pat;
9593 regmatch_T regmatch;
9594 int starts_with_dot;
9595 int matches;
9596 int len;
9597 int starstar = FALSE;
9598 static int stardepth = 0; /* depth for "**" expansion */
9599
9600 DIR *dirp;
9601 struct dirent *dp;
9602
9603 /* Expanding "**" may take a long time, check for CTRL-C. */
9604 if (stardepth > 0)
9605 {
9606 ui_breakcheck();
9607 if (got_int)
9608 return 0;
9609 }
9610
9611 /* make room for file name */
9612 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
9613 if (buf == NULL)
9614 return 0;
9615
9616 /*
9617 * Find the first part in the path name that contains a wildcard.
Bram Moolenaar2d0b92f2012-04-30 21:09:43 +02009618 * When EW_ICASE is set every letter is considered to be a wildcard.
Bram Moolenaar231334e2005-07-25 20:46:57 +00009619 * Copy it into "buf", including the preceding characters.
9620 */
9621 p = buf;
9622 s = buf;
9623 e = NULL;
9624 path_end = path;
9625 while (*path_end != NUL)
9626 {
9627 /* May ignore a wildcard that has a backslash before it; it will
9628 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
9629 if (path_end >= path + wildoff && rem_backslash(path_end))
9630 *p++ = *path_end++;
9631 else if (*path_end == '/')
9632 {
9633 if (e != NULL)
9634 break;
9635 s = p + 1;
9636 }
9637 else if (path_end >= path + wildoff
Bram Moolenaar2d0b92f2012-04-30 21:09:43 +02009638 && (vim_strchr((char_u *)"*?[{~$", *path_end) != NULL
9639#ifndef CASE_INSENSITIVE_FILENAME
9640 || ((flags & EW_ICASE)
9641 && isalpha(PTR2CHAR(path_end)))
9642#endif
9643 ))
Bram Moolenaar231334e2005-07-25 20:46:57 +00009644 e = p;
9645#ifdef FEAT_MBYTE
9646 if (has_mbyte)
9647 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00009648 len = (*mb_ptr2len)(path_end);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009649 STRNCPY(p, path_end, len);
9650 p += len;
9651 path_end += len;
9652 }
9653 else
9654#endif
9655 *p++ = *path_end++;
9656 }
9657 e = p;
9658 *e = NUL;
9659
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009660 /* Now we have one wildcard component between "s" and "e". */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009661 /* Remove backslashes between "wildoff" and the start of the wildcard
9662 * component. */
9663 for (p = buf + wildoff; p < s; ++p)
9664 if (rem_backslash(p))
9665 {
Bram Moolenaar8c8de832008-06-24 22:58:06 +00009666 STRMOVE(p, p + 1);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009667 --e;
9668 --s;
9669 }
9670
9671 /* Check for "**" between "s" and "e". */
9672 for (p = s; p < e; ++p)
9673 if (p[0] == '*' && p[1] == '*')
9674 starstar = TRUE;
9675
9676 /* convert the file pattern to a regexp pattern */
9677 starts_with_dot = (*s == '.');
9678 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
9679 if (pat == NULL)
9680 {
9681 vim_free(buf);
9682 return 0;
9683 }
9684
9685 /* compile the regexp into a program */
Bram Moolenaarcc016f52005-12-10 20:23:46 +00009686#ifdef CASE_INSENSITIVE_FILENAME
Bram Moolenaar231334e2005-07-25 20:46:57 +00009687 regmatch.rm_ic = TRUE; /* Behave like Terminal.app */
9688#else
Bram Moolenaar94950a92010-12-02 16:01:29 +01009689 if (flags & EW_ICASE)
9690 regmatch.rm_ic = TRUE; /* 'wildignorecase' set */
9691 else
9692 regmatch.rm_ic = FALSE; /* Don't ignore case */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009693#endif
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009694 if (flags & (EW_NOERROR | EW_NOTWILD))
9695 ++emsg_silent;
Bram Moolenaar231334e2005-07-25 20:46:57 +00009696 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009697 if (flags & (EW_NOERROR | EW_NOTWILD))
9698 --emsg_silent;
Bram Moolenaar231334e2005-07-25 20:46:57 +00009699 vim_free(pat);
9700
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009701 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
Bram Moolenaar231334e2005-07-25 20:46:57 +00009702 {
9703 vim_free(buf);
9704 return 0;
9705 }
9706
9707 /* If "**" is by itself, this is the first time we encounter it and more
9708 * is following then find matches without any directory. */
9709 if (!didstar && stardepth < 100 && starstar && e - s == 2
9710 && *path_end == '/')
9711 {
9712 STRCPY(s, path_end + 1);
9713 ++stardepth;
9714 (void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
9715 --stardepth;
9716 }
9717
9718 /* open the directory for scanning */
9719 *s = NUL;
9720 dirp = opendir(*buf == NUL ? "." : (char *)buf);
9721
9722 /* Find all matching entries */
9723 if (dirp != NULL)
9724 {
9725 for (;;)
9726 {
9727 dp = readdir(dirp);
9728 if (dp == NULL)
9729 break;
9730 if ((dp->d_name[0] != '.' || starts_with_dot)
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009731 && ((regmatch.regprog != NULL && vim_regexec(&regmatch,
9732 (char_u *)dp->d_name, (colnr_T)0))
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009733 || ((flags & EW_NOTWILD)
9734 && fnamencmp(path + (s - buf), dp->d_name, e - s) == 0)))
Bram Moolenaar231334e2005-07-25 20:46:57 +00009735 {
9736 STRCPY(s, dp->d_name);
9737 len = STRLEN(buf);
9738
9739 if (starstar && stardepth < 100)
9740 {
9741 /* For "**" in the pattern first go deeper in the tree to
9742 * find matches. */
9743 STRCPY(buf + len, "/**");
9744 STRCPY(buf + len + 3, path_end);
9745 ++stardepth;
9746 (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
9747 --stardepth;
9748 }
9749
9750 STRCPY(buf + len, path_end);
9751 if (mch_has_exp_wildcard(path_end)) /* handle more wildcards */
9752 {
9753 /* need to expand another component of the path */
9754 /* remove backslashes for the remaining components only */
9755 (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
9756 }
9757 else
9758 {
9759 /* no more wildcards, check if there is a match */
9760 /* remove backslashes for the remaining components only */
9761 if (*path_end != NUL)
9762 backslash_halve(buf + len + 1);
9763 if (mch_getperm(buf) >= 0) /* add existing file */
9764 {
Bram Moolenaar95e9b492006-03-15 23:04:43 +00009765#ifdef MACOS_CONVERT
Bram Moolenaar231334e2005-07-25 20:46:57 +00009766 size_t precomp_len = STRLEN(buf)+1;
9767 char_u *precomp_buf =
9768 mac_precompose_path(buf, precomp_len, &precomp_len);
Bram Moolenaar95e9b492006-03-15 23:04:43 +00009769
Bram Moolenaar231334e2005-07-25 20:46:57 +00009770 if (precomp_buf)
9771 {
9772 mch_memmove(buf, precomp_buf, precomp_len);
9773 vim_free(precomp_buf);
9774 }
9775#endif
9776 addfile(gap, buf, flags);
9777 }
9778 }
9779 }
9780 }
9781
9782 closedir(dirp);
9783 }
9784
9785 vim_free(buf);
9786 vim_free(regmatch.regprog);
9787
9788 matches = gap->ga_len - start_len;
9789 if (matches > 0)
9790 qsort(((char_u **)gap->ga_data) + start_len, matches,
9791 sizeof(char_u *), pstrcmp);
9792 return matches;
9793}
9794#endif
9795
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009796#if defined(FEAT_SEARCHPATH)
9797static int find_previous_pathsep __ARGS((char_u *path, char_u **psep));
9798static int is_unique __ARGS((char_u *maybe_unique, garray_T *gap, int i));
Bram Moolenaar162bd912010-07-28 22:29:10 +02009799static void expand_path_option __ARGS((char_u *curdir, garray_T *gap));
9800static char_u *get_path_cutoff __ARGS((char_u *fname, garray_T *gap));
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009801static void uniquefy_paths __ARGS((garray_T *gap, char_u *pattern));
9802static int expand_in_path __ARGS((garray_T *gap, char_u *pattern, int flags));
9803
9804/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009805 * Moves "*psep" back to the previous path separator in "path".
9806 * Returns FAIL is "*psep" ends up at the beginning of "path".
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009807 */
9808 static int
9809find_previous_pathsep(path, psep)
9810 char_u *path;
9811 char_u **psep;
9812{
9813 /* skip the current separator */
9814 if (*psep > path && vim_ispathsep(**psep))
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009815 --*psep;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009816
9817 /* find the previous separator */
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009818 while (*psep > path)
9819 {
9820 if (vim_ispathsep(**psep))
9821 return OK;
9822 mb_ptr_back(path, *psep);
9823 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009824
9825 return FAIL;
9826}
9827
9828/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009829 * Returns TRUE if "maybe_unique" is unique wrt other_paths in "gap".
9830 * "maybe_unique" is the end portion of "((char_u **)gap->ga_data)[i]".
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009831 */
9832 static int
9833is_unique(maybe_unique, gap, i)
9834 char_u *maybe_unique;
9835 garray_T *gap;
9836 int i;
9837{
9838 int j;
9839 int candidate_len;
9840 int other_path_len;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009841 char_u **other_paths = (char_u **)gap->ga_data;
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009842 char_u *rival;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009843
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009844 for (j = 0; j < gap->ga_len; j++)
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009845 {
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009846 if (j == i)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009847 continue; /* don't compare it with itself */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009848
Bram Moolenaar624c7aa2010-07-16 20:38:52 +02009849 candidate_len = (int)STRLEN(maybe_unique);
9850 other_path_len = (int)STRLEN(other_paths[j]);
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009851 if (other_path_len < candidate_len)
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009852 continue; /* it's different when it's shorter */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009853
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009854 rival = other_paths[j] + other_path_len - candidate_len;
Bram Moolenaarda9836c2010-08-16 21:53:27 +02009855 if (fnamecmp(maybe_unique, rival) == 0
9856 && (rival == other_paths[j] || vim_ispathsep(*(rival - 1))))
Bram Moolenaar162bd912010-07-28 22:29:10 +02009857 return FALSE; /* match */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009858 }
9859
Bram Moolenaar162bd912010-07-28 22:29:10 +02009860 return TRUE; /* no match found */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009861}
9862
9863/*
Bram Moolenaar1a509df2010-08-01 17:59:57 +02009864 * Split the 'path' option into an array of strings in garray_T. Relative
Bram Moolenaar162bd912010-07-28 22:29:10 +02009865 * paths are expanded to their equivalent fullpath. This includes the "."
9866 * (relative to current buffer directory) and empty path (relative to current
9867 * directory) notations.
9868 *
9869 * TODO: handle upward search (;) and path limiter (**N) notations by
9870 * expanding each into their equivalent path(s).
9871 */
9872 static void
9873expand_path_option(curdir, gap)
9874 char_u *curdir;
9875 garray_T *gap;
9876{
9877 char_u *path_option = *curbuf->b_p_path == NUL
9878 ? p_path : curbuf->b_p_path;
9879 char_u *buf;
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009880 char_u *p;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009881 int len;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009882
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +02009883 if ((buf = alloc((int)MAXPATHL)) == NULL)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009884 return;
9885
9886 while (*path_option != NUL)
9887 {
9888 copy_option_part(&path_option, buf, MAXPATHL, " ,");
9889
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009890 if (buf[0] == '.' && (buf[1] == NUL || vim_ispathsep(buf[1])))
Bram Moolenaar162bd912010-07-28 22:29:10 +02009891 {
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009892 /* Relative to current buffer:
9893 * "/path/file" + "." -> "/path/"
9894 * "/path/file" + "./subdir" -> "/path/subdir" */
Bram Moolenaar162bd912010-07-28 22:29:10 +02009895 if (curbuf->b_ffname == NULL)
9896 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009897 p = gettail(curbuf->b_ffname);
9898 len = (int)(p - curbuf->b_ffname);
9899 if (len + (int)STRLEN(buf) >= MAXPATHL)
9900 continue;
9901 if (buf[1] == NUL)
9902 buf[len] = NUL;
9903 else
9904 STRMOVE(buf + len, buf + 2);
9905 mch_memmove(buf, curbuf->b_ffname, len);
9906 simplify_filename(buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009907 }
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009908 else if (buf[0] == NUL)
9909 /* relative to current directory */
Bram Moolenaar162bd912010-07-28 22:29:10 +02009910 STRCPY(buf, curdir);
Bram Moolenaar84f888a2010-08-05 21:40:16 +02009911 else if (path_with_url(buf))
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009912 /* URL can't be used here */
Bram Moolenaar84f888a2010-08-05 21:40:16 +02009913 continue;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009914 else if (!mch_isFullName(buf))
9915 {
9916 /* Expand relative path to their full path equivalent */
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009917 len = (int)STRLEN(curdir);
9918 if (len + (int)STRLEN(buf) + 3 > MAXPATHL)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009919 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009920 STRMOVE(buf + len + 1, buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009921 STRCPY(buf, curdir);
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009922 buf[len] = PATHSEP;
Bram Moolenaar57adda12010-08-03 22:11:29 +02009923 simplify_filename(buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009924 }
9925
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009926 if (ga_grow(gap, 1) == FAIL)
9927 break;
9928 p = vim_strsave(buf);
9929 if (p == NULL)
9930 break;
9931 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009932 }
9933
9934 vim_free(buf);
9935}
9936
9937/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009938 * Returns a pointer to the file or directory name in "fname" that matches the
9939 * longest path in "ga"p, or NULL if there is no match. For example:
Bram Moolenaar162bd912010-07-28 22:29:10 +02009940 *
9941 * path: /foo/bar/baz
9942 * fname: /foo/bar/baz/quux.txt
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009943 * returns: ^this
Bram Moolenaar162bd912010-07-28 22:29:10 +02009944 */
9945 static char_u *
9946get_path_cutoff(fname, gap)
9947 char_u *fname;
9948 garray_T *gap;
9949{
9950 int i;
9951 int maxlen = 0;
9952 char_u **path_part = (char_u **)gap->ga_data;
9953 char_u *cutoff = NULL;
9954
9955 for (i = 0; i < gap->ga_len; i++)
9956 {
9957 int j = 0;
9958
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009959 while ((fname[j] == path_part[i][j]
Bram Moolenaar2d7c47d2010-08-10 19:50:26 +02009960# if defined(MSWIN) || defined(MSDOS)
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009961 || (vim_ispathsep(fname[j]) && vim_ispathsep(path_part[i][j]))
9962#endif
9963 ) && fname[j] != NUL && path_part[i][j] != NUL)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009964 j++;
9965 if (j > maxlen)
9966 {
9967 maxlen = j;
9968 cutoff = &fname[j];
9969 }
9970 }
9971
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009972 /* skip to the file or directory name */
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009973 if (cutoff != NULL)
Bram Moolenaar31710262010-08-13 13:36:15 +02009974 while (vim_ispathsep(*cutoff))
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009975 mb_ptr_adv(cutoff);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009976
9977 return cutoff;
9978}
9979
9980/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009981 * Sorts, removes duplicates and modifies all the fullpath names in "gap" so
9982 * that they are unique with respect to each other while conserving the part
9983 * that matches the pattern. Beware, this is at least O(n^2) wrt "gap->ga_len".
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009984 */
9985 static void
9986uniquefy_paths(gap, pattern)
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +02009987 garray_T *gap;
9988 char_u *pattern;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009989{
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +02009990 int i;
9991 int len;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009992 char_u **fnames = (char_u **)gap->ga_data;
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009993 int sort_again = FALSE;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009994 char_u *pat;
9995 char_u *file_pattern;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009996 char_u *curdir;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009997 regmatch_T regmatch;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009998 garray_T path_ga;
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009999 char_u **in_curdir = NULL;
10000 char_u *short_name;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010001
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +020010002 remove_duplicates(gap);
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010003 ga_init2(&path_ga, (int)sizeof(char_u *), 1);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010004
10005 /*
10006 * We need to prepend a '*' at the beginning of file_pattern so that the
10007 * regex matches anywhere in the path. FIXME: is this valid for all
Bram Moolenaarb31e4382010-07-24 16:01:56 +020010008 * possible patterns?
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010009 */
Bram Moolenaar624c7aa2010-07-16 20:38:52 +020010010 len = (int)STRLEN(pattern);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010011 file_pattern = alloc(len + 2);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010012 if (file_pattern == NULL)
10013 return;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010014 file_pattern[0] = '*';
Bram Moolenaar162bd912010-07-28 22:29:10 +020010015 file_pattern[1] = NUL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010016 STRCAT(file_pattern, pattern);
10017 pat = file_pat_to_reg_pat(file_pattern, NULL, NULL, TRUE);
10018 vim_free(file_pattern);
Bram Moolenaarb31e4382010-07-24 16:01:56 +020010019 if (pat == NULL)
10020 return;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010021
Bram Moolenaarb31e4382010-07-24 16:01:56 +020010022 regmatch.rm_ic = TRUE; /* always ignore case */
10023 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
10024 vim_free(pat);
10025 if (regmatch.regprog == NULL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010026 return;
10027
Bram Moolenaar162bd912010-07-28 22:29:10 +020010028 if ((curdir = alloc((int)(MAXPATHL))) == NULL)
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010029 goto theend;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010030 mch_dirname(curdir, MAXPATHL);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010031 expand_path_option(curdir, &path_ga);
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010032
10033 in_curdir = (char_u **)alloc_clear(gap->ga_len * sizeof(char_u *));
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010034 if (in_curdir == NULL)
10035 goto theend;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010036
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010037 for (i = 0; i < gap->ga_len && !got_int; i++)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010038 {
Bram Moolenaar162bd912010-07-28 22:29:10 +020010039 char_u *path = fnames[i];
10040 int is_in_curdir;
Bram Moolenaar31710262010-08-13 13:36:15 +020010041 char_u *dir_end = gettail_dir(path);
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010042 char_u *pathsep_p;
10043 char_u *path_cutoff;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010044
Bram Moolenaar624c7aa2010-07-16 20:38:52 +020010045 len = (int)STRLEN(path);
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010046 is_in_curdir = fnamencmp(curdir, path, dir_end - path) == 0
Bram Moolenaar162bd912010-07-28 22:29:10 +020010047 && curdir[dir_end - path] == NUL;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010048 if (is_in_curdir)
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010049 in_curdir[i] = vim_strsave(path);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010050
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010051 /* Shorten the filename while maintaining its uniqueness */
10052 path_cutoff = get_path_cutoff(path, &path_ga);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010053
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010054 /* we start at the end of the path */
10055 pathsep_p = path + len - 1;
10056
10057 while (find_previous_pathsep(path, &pathsep_p))
10058 if (vim_regexec(&regmatch, pathsep_p + 1, (colnr_T)0)
10059 && is_unique(pathsep_p + 1, gap, i)
10060 && path_cutoff != NULL && pathsep_p + 1 >= path_cutoff)
10061 {
10062 sort_again = TRUE;
10063 mch_memmove(path, pathsep_p + 1, STRLEN(pathsep_p));
10064 break;
10065 }
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010066
10067 if (mch_isFullName(path))
10068 {
10069 /*
10070 * Last resort: shorten relative to curdir if possible.
10071 * 'possible' means:
10072 * 1. It is under the current directory.
10073 * 2. The result is actually shorter than the original.
10074 *
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010075 * Before curdir After
10076 * /foo/bar/file.txt /foo/bar ./file.txt
10077 * c:\foo\bar\file.txt c:\foo\bar .\file.txt
10078 * /file.txt / /file.txt
10079 * c:\file.txt c:\ .\file.txt
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010080 */
10081 short_name = shorten_fname(path, curdir);
Bram Moolenaar31710262010-08-13 13:36:15 +020010082 if (short_name != NULL && short_name > path + 1
10083#if defined(MSWIN) || defined(MSDOS)
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010084 /* On windows,
Bram Moolenaar31710262010-08-13 13:36:15 +020010085 * shorten_fname("c:\a\a.txt", "c:\a\b")
Bram Moolenaar31710262010-08-13 13:36:15 +020010086 * returns "\a\a.txt", which is not really the short
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010087 * name, hence: */
Bram Moolenaar31710262010-08-13 13:36:15 +020010088 && !vim_ispathsep(*short_name)
10089#endif
10090 )
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010091 {
10092 STRCPY(path, ".");
10093 add_pathsep(path);
Bram Moolenaarcda000e2010-08-14 13:34:39 +020010094 STRMOVE(path + STRLEN(path), short_name);
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010095 }
10096 }
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010097 ui_breakcheck();
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010098 }
10099
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010100 /* Shorten filenames in /in/current/directory/{filename} */
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010101 for (i = 0; i < gap->ga_len && !got_int; i++)
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010102 {
10103 char_u *rel_path;
10104 char_u *path = in_curdir[i];
10105
10106 if (path == NULL)
10107 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010108
10109 /* If the {filename} is not unique, change it to ./{filename}.
10110 * Else reduce it to {filename} */
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010111 short_name = shorten_fname(path, curdir);
10112 if (short_name == NULL)
10113 short_name = path;
10114 if (is_unique(short_name, gap, i))
10115 {
10116 STRCPY(fnames[i], short_name);
10117 continue;
10118 }
10119
10120 rel_path = alloc((int)(STRLEN(short_name) + STRLEN(PATHSEPSTR) + 2));
10121 if (rel_path == NULL)
10122 goto theend;
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010123 STRCPY(rel_path, ".");
10124 add_pathsep(rel_path);
10125 STRCAT(rel_path, short_name);
10126
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010127 vim_free(fnames[i]);
10128 fnames[i] = rel_path;
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010129 sort_again = TRUE;
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010130 ui_breakcheck();
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010131 }
10132
Bram Moolenaar162bd912010-07-28 22:29:10 +020010133theend:
10134 vim_free(curdir);
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010135 if (in_curdir != NULL)
10136 {
10137 for (i = 0; i < gap->ga_len; i++)
10138 vim_free(in_curdir[i]);
10139 vim_free(in_curdir);
10140 }
Bram Moolenaar162bd912010-07-28 22:29:10 +020010141 ga_clear_strings(&path_ga);
Bram Moolenaarb31e4382010-07-24 16:01:56 +020010142 vim_free(regmatch.regprog);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010143
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010144 if (sort_again)
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +020010145 remove_duplicates(gap);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010146}
10147
10148/*
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010149 * Calls globpath() with 'path' values for the given pattern and stores the
10150 * result in "gap".
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010151 * Returns the total number of matches.
10152 */
10153 static int
10154expand_in_path(gap, pattern, flags)
10155 garray_T *gap;
10156 char_u *pattern;
10157 int flags; /* EW_* flags */
10158{
Bram Moolenaar162bd912010-07-28 22:29:10 +020010159 char_u *curdir;
10160 garray_T path_ga;
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010161 char_u *files = NULL;
10162 char_u *s; /* start */
10163 char_u *e; /* end */
10164 char_u *paths = NULL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010165
Bram Moolenaar7f0f6212010-08-03 22:21:00 +020010166 if ((curdir = alloc((unsigned)MAXPATHL)) == NULL)
Bram Moolenaar162bd912010-07-28 22:29:10 +020010167 return 0;
10168 mch_dirname(curdir, MAXPATHL);
10169
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010170 ga_init2(&path_ga, (int)sizeof(char_u *), 1);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010171 expand_path_option(curdir, &path_ga);
10172 vim_free(curdir);
Bram Moolenaar006d2b02010-08-04 12:39:44 +020010173 if (path_ga.ga_len == 0)
10174 return 0;
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010175
10176 paths = ga_concat_strings(&path_ga);
10177 ga_clear_strings(&path_ga);
10178 if (paths == NULL)
Bram Moolenaar7f0f6212010-08-03 22:21:00 +020010179 return 0;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010180
Bram Moolenaar94950a92010-12-02 16:01:29 +010010181 files = globpath(paths, pattern, (flags & EW_ICASE) ? WILD_ICASE : 0);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010182 vim_free(paths);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010183 if (files == NULL)
10184 return 0;
10185
10186 /* Copy each path in files into gap */
10187 s = e = files;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010188 while (*s != NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010189 {
Bram Moolenaar162bd912010-07-28 22:29:10 +020010190 while (*e != '\n' && *e != NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010191 e++;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010192 if (*e == NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010193 {
10194 addfile(gap, s, flags);
10195 break;
10196 }
10197 else
10198 {
10199 /* *e is '\n' */
Bram Moolenaar162bd912010-07-28 22:29:10 +020010200 *e = NUL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010201 addfile(gap, s, flags);
10202 e++;
10203 s = e;
10204 }
10205 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010206 vim_free(files);
10207
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010208 return gap->ga_len;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010209}
10210#endif
10211
Bram Moolenaar1587a1e2010-07-29 20:59:59 +020010212#if defined(FEAT_SEARCHPATH) || defined(FEAT_CMDL_COMPL) || defined(PROTO)
10213/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010214 * Sort "gap" and remove duplicate entries. "gap" is expected to contain a
10215 * list of file names in allocated memory.
Bram Moolenaar1587a1e2010-07-29 20:59:59 +020010216 */
10217 void
10218remove_duplicates(gap)
10219 garray_T *gap;
10220{
10221 int i;
10222 int j;
10223 char_u **fnames = (char_u **)gap->ga_data;
10224
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010225 sort_strings(fnames, gap->ga_len);
Bram Moolenaar1587a1e2010-07-29 20:59:59 +020010226 for (i = gap->ga_len - 1; i > 0; --i)
10227 if (fnamecmp(fnames[i - 1], fnames[i]) == 0)
10228 {
10229 vim_free(fnames[i]);
10230 for (j = i + 1; j < gap->ga_len; ++j)
10231 fnames[j - 1] = fnames[j];
10232 --gap->ga_len;
10233 }
10234}
10235#endif
10236
Bram Moolenaar071d4272004-06-13 20:20:40 +000010237/*
10238 * Generic wildcard expansion code.
10239 *
10240 * Characters in "pat" that should not be expanded must be preceded with a
10241 * backslash. E.g., "/path\ with\ spaces/my\*star*"
10242 *
10243 * Return FAIL when no single file was found. In this case "num_file" is not
10244 * set, and "file" may contain an error message.
10245 * Return OK when some files found. "num_file" is set to the number of
10246 * matches, "file" to the array of matches. Call FreeWild() later.
10247 */
10248 int
10249gen_expand_wildcards(num_pat, pat, num_file, file, flags)
10250 int num_pat; /* number of input patterns */
10251 char_u **pat; /* array of input patterns */
10252 int *num_file; /* resulting number of files */
10253 char_u ***file; /* array of resulting files */
10254 int flags; /* EW_* flags */
10255{
10256 int i;
10257 garray_T ga;
10258 char_u *p;
10259 static int recursive = FALSE;
10260 int add_pat;
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010261#if defined(FEAT_SEARCHPATH)
10262 int did_expand_in_path = FALSE;
10263#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000010264
10265 /*
10266 * expand_env() is called to expand things like "~user". If this fails,
10267 * it calls ExpandOne(), which brings us back here. In this case, always
10268 * call the machine specific expansion function, if possible. Otherwise,
10269 * return FAIL.
10270 */
10271 if (recursive)
10272#ifdef SPECIAL_WILDCHAR
10273 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
10274#else
10275 return FAIL;
10276#endif
10277
10278#ifdef SPECIAL_WILDCHAR
10279 /*
10280 * If there are any special wildcard characters which we cannot handle
10281 * here, call machine specific function for all the expansion. This
10282 * avoids starting the shell for each argument separately.
10283 * For `=expr` do use the internal function.
10284 */
10285 for (i = 0; i < num_pat; i++)
10286 {
10287 if (vim_strpbrk(pat[i], (char_u *)SPECIAL_WILDCHAR) != NULL
10288# ifdef VIM_BACKTICK
10289 && !(vim_backtick(pat[i]) && pat[i][1] == '=')
10290# endif
10291 )
10292 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
10293 }
10294#endif
10295
10296 recursive = TRUE;
10297
10298 /*
10299 * The matching file names are stored in a growarray. Init it empty.
10300 */
10301 ga_init2(&ga, (int)sizeof(char_u *), 30);
10302
10303 for (i = 0; i < num_pat; ++i)
10304 {
10305 add_pat = -1;
10306 p = pat[i];
10307
10308#ifdef VIM_BACKTICK
10309 if (vim_backtick(p))
10310 add_pat = expand_backtick(&ga, p, flags);
10311 else
10312#endif
10313 {
10314 /*
10315 * First expand environment variables, "~/" and "~user/".
10316 */
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010317 if (vim_strchr(p, '$') != NULL || *p == '~')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010318 {
Bram Moolenaar9f0545d2007-09-26 20:36:32 +000010319 p = expand_env_save_opt(p, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010320 if (p == NULL)
10321 p = pat[i];
10322#ifdef UNIX
10323 /*
10324 * On Unix, if expand_env() can't expand an environment
10325 * variable, use the shell to do that. Discard previously
10326 * found file names and start all over again.
10327 */
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010328 else if (vim_strchr(p, '$') != NULL || *p == '~')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010329 {
10330 vim_free(p);
Bram Moolenaar782027e2009-06-24 14:25:49 +000010331 ga_clear_strings(&ga);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010332 i = mch_expand_wildcards(num_pat, pat, num_file, file,
10333 flags);
10334 recursive = FALSE;
10335 return i;
10336 }
10337#endif
10338 }
10339
10340 /*
10341 * If there are wildcards: Expand file names and add each match to
10342 * the list. If there is no match, and EW_NOTFOUND is given, add
10343 * the pattern.
10344 * If there are no wildcards: Add the file name if it exists or
10345 * when EW_NOTFOUND is given.
10346 */
10347 if (mch_has_exp_wildcard(p))
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010348 {
10349#if defined(FEAT_SEARCHPATH)
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010350 if ((flags & EW_PATH)
10351 && !mch_isFullName(p)
10352 && !(p[0] == '.'
10353 && (vim_ispathsep(p[1])
10354 || (p[1] == '.' && vim_ispathsep(p[2]))))
10355 )
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010356 {
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010357 /* :find completion where 'path' is used.
10358 * Recursiveness is OK here. */
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010359 recursive = FALSE;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010360 add_pat = expand_in_path(&ga, p, flags);
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010361 recursive = TRUE;
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010362 did_expand_in_path = TRUE;
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010363 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010364 else
10365#endif
10366 add_pat = mch_expandpath(&ga, p, flags);
10367 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010368 }
10369
10370 if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
10371 {
10372 char_u *t = backslash_halve_save(p);
10373
10374#if defined(MACOS_CLASSIC)
10375 slash_to_colon(t);
10376#endif
10377 /* When EW_NOTFOUND is used, always add files and dirs. Makes
10378 * "vim c:/" work. */
10379 if (flags & EW_NOTFOUND)
10380 addfile(&ga, t, flags | EW_DIR | EW_FILE);
10381 else if (mch_getperm(t) >= 0)
10382 addfile(&ga, t, flags);
10383 vim_free(t);
10384 }
10385
Bram Moolenaarb28ebbc2010-07-14 16:59:57 +020010386#if defined(FEAT_SEARCHPATH)
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010387 if (did_expand_in_path && ga.ga_len > 0 && (flags & EW_PATH))
Bram Moolenaarb28ebbc2010-07-14 16:59:57 +020010388 uniquefy_paths(&ga, p);
10389#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000010390 if (p != pat[i])
10391 vim_free(p);
10392 }
10393
10394 *num_file = ga.ga_len;
10395 *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data : (char_u **)"";
10396
10397 recursive = FALSE;
10398
10399 return (ga.ga_data != NULL) ? OK : FAIL;
10400}
10401
10402# ifdef VIM_BACKTICK
10403
10404/*
10405 * Return TRUE if we can expand this backtick thing here.
10406 */
10407 static int
10408vim_backtick(p)
10409 char_u *p;
10410{
10411 return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
10412}
10413
10414/*
10415 * Expand an item in `backticks` by executing it as a command.
10416 * Currently only works when pat[] starts and ends with a `.
10417 * Returns number of file names found.
10418 */
10419 static int
10420expand_backtick(gap, pat, flags)
10421 garray_T *gap;
10422 char_u *pat;
10423 int flags; /* EW_* flags */
10424{
10425 char_u *p;
10426 char_u *cmd;
10427 char_u *buffer;
10428 int cnt = 0;
10429 int i;
10430
10431 /* Create the command: lop off the backticks. */
10432 cmd = vim_strnsave(pat + 1, (int)STRLEN(pat) - 2);
10433 if (cmd == NULL)
10434 return 0;
10435
10436#ifdef FEAT_EVAL
10437 if (*cmd == '=') /* `={expr}`: Expand expression */
Bram Moolenaar362e1a32006-03-06 23:29:24 +000010438 buffer = eval_to_string(cmd + 1, &p, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010439 else
10440#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010441 buffer = get_cmd_output(cmd, NULL,
10442 (flags & EW_SILENT) ? SHELL_SILENT : 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010443 vim_free(cmd);
10444 if (buffer == NULL)
10445 return 0;
10446
10447 cmd = buffer;
10448 while (*cmd != NUL)
10449 {
10450 cmd = skipwhite(cmd); /* skip over white space */
10451 p = cmd;
10452 while (*p != NUL && *p != '\r' && *p != '\n') /* skip over entry */
10453 ++p;
10454 /* add an entry if it is not empty */
10455 if (p > cmd)
10456 {
10457 i = *p;
10458 *p = NUL;
10459 addfile(gap, cmd, flags);
10460 *p = i;
10461 ++cnt;
10462 }
10463 cmd = p;
10464 while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
10465 ++cmd;
10466 }
10467
10468 vim_free(buffer);
10469 return cnt;
10470}
10471# endif /* VIM_BACKTICK */
10472
10473/*
10474 * Add a file to a file list. Accepted flags:
10475 * EW_DIR add directories
10476 * EW_FILE add files
Bram Moolenaar1f35bf92006-03-07 22:38:47 +000010477 * EW_EXEC add executable files
Bram Moolenaar071d4272004-06-13 20:20:40 +000010478 * EW_NOTFOUND add even when it doesn't exist
10479 * EW_ADDSLASH add slash after directory name
10480 */
10481 void
10482addfile(gap, f, flags)
10483 garray_T *gap;
10484 char_u *f; /* filename */
10485 int flags;
10486{
10487 char_u *p;
10488 int isdir;
10489
10490 /* if the file/dir doesn't exist, may not add it */
10491 if (!(flags & EW_NOTFOUND) && mch_getperm(f) < 0)
10492 return;
10493
10494#ifdef FNAME_ILLEGAL
10495 /* if the file/dir contains illegal characters, don't add it */
10496 if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
10497 return;
10498#endif
10499
10500 isdir = mch_isdir(f);
10501 if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
10502 return;
10503
Bram Moolenaar1f35bf92006-03-07 22:38:47 +000010504 /* If the file isn't executable, may not add it. Do accept directories. */
10505 if (!isdir && (flags & EW_EXEC) && !mch_can_exe(f))
10506 return;
10507
Bram Moolenaar071d4272004-06-13 20:20:40 +000010508 /* Make room for another item in the file list. */
10509 if (ga_grow(gap, 1) == FAIL)
10510 return;
10511
10512 p = alloc((unsigned)(STRLEN(f) + 1 + isdir));
10513 if (p == NULL)
10514 return;
10515
10516 STRCPY(p, f);
10517#ifdef BACKSLASH_IN_FILENAME
10518 slash_adjust(p);
10519#endif
10520 /*
10521 * Append a slash or backslash after directory names if none is present.
10522 */
10523#ifndef DONT_ADD_PATHSEP_TO_DIR
10524 if (isdir && (flags & EW_ADDSLASH))
10525 add_pathsep(p);
10526#endif
10527 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010528}
10529#endif /* !NO_EXPANDPATH */
10530
10531#if defined(VIM_BACKTICK) || defined(FEAT_EVAL) || defined(PROTO)
10532
10533#ifndef SEEK_SET
10534# define SEEK_SET 0
10535#endif
10536#ifndef SEEK_END
10537# define SEEK_END 2
10538#endif
10539
10540/*
10541 * Get the stdout of an external command.
10542 * Returns an allocated string, or NULL for error.
10543 */
10544 char_u *
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010545get_cmd_output(cmd, infile, flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010546 char_u *cmd;
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010547 char_u *infile; /* optional input file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010548 int flags; /* can be SHELL_SILENT */
10549{
10550 char_u *tempname;
10551 char_u *command;
10552 char_u *buffer = NULL;
10553 int len;
10554 int i = 0;
10555 FILE *fd;
10556
10557 if (check_restricted() || check_secure())
10558 return NULL;
10559
10560 /* get a name for the temp file */
10561 if ((tempname = vim_tempname('o')) == NULL)
10562 {
10563 EMSG(_(e_notmp));
10564 return NULL;
10565 }
10566
10567 /* Add the redirection stuff */
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010568 command = make_filter_cmd(cmd, infile, tempname);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010569 if (command == NULL)
10570 goto done;
10571
10572 /*
10573 * Call the shell to execute the command (errors are ignored).
10574 * Don't check timestamps here.
10575 */
10576 ++no_check_timestamps;
10577 call_shell(command, SHELL_DOOUT | SHELL_EXPAND | flags);
10578 --no_check_timestamps;
10579
10580 vim_free(command);
10581
10582 /*
10583 * read the names from the file into memory
10584 */
10585# ifdef VMS
Bram Moolenaar25394022007-05-10 19:06:20 +000010586 /* created temporary file is not always readable as binary */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010587 fd = mch_fopen((char *)tempname, "r");
10588# else
10589 fd = mch_fopen((char *)tempname, READBIN);
10590# endif
10591
10592 if (fd == NULL)
10593 {
10594 EMSG2(_(e_notopen), tempname);
10595 goto done;
10596 }
10597
10598 fseek(fd, 0L, SEEK_END);
10599 len = ftell(fd); /* get size of temp file */
10600 fseek(fd, 0L, SEEK_SET);
10601
10602 buffer = alloc(len + 1);
10603 if (buffer != NULL)
10604 i = (int)fread((char *)buffer, (size_t)1, (size_t)len, fd);
10605 fclose(fd);
10606 mch_remove(tempname);
10607 if (buffer == NULL)
10608 goto done;
10609#ifdef VMS
10610 len = i; /* VMS doesn't give us what we asked for... */
10611#endif
10612 if (i != len)
10613 {
10614 EMSG2(_(e_notread), tempname);
10615 vim_free(buffer);
10616 buffer = NULL;
10617 }
10618 else
Bram Moolenaar162bd912010-07-28 22:29:10 +020010619 buffer[len] = NUL; /* make sure the buffer is terminated */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010620
10621done:
10622 vim_free(tempname);
10623 return buffer;
10624}
10625#endif
10626
10627/*
10628 * Free the list of files returned by expand_wildcards() or other expansion
10629 * functions.
10630 */
10631 void
10632FreeWild(count, files)
10633 int count;
10634 char_u **files;
10635{
Bram Moolenaarfc1421e2006-04-20 22:17:20 +000010636 if (count <= 0 || files == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010637 return;
10638#if defined(__EMX__) && defined(__ALWAYS_HAS_TRAILING_NULL_POINTER) /* XXX */
10639 /*
10640 * Is this still OK for when other functions than expand_wildcards() have
10641 * been used???
10642 */
10643 _fnexplodefree((char **)files);
10644#else
10645 while (count--)
10646 vim_free(files[count]);
10647 vim_free(files);
10648#endif
10649}
10650
10651/*
Bram Moolenaara9dc3752010-07-11 20:46:53 +020010652 * Return TRUE when need to go to Insert mode because of 'insertmode'.
Bram Moolenaar071d4272004-06-13 20:20:40 +000010653 * Don't do this when still processing a command or a mapping.
10654 * Don't do this when inside a ":normal" command.
10655 */
10656 int
10657goto_im()
10658{
10659 return (p_im && stuff_empty() && typebuf_typed());
10660}