blob: a5a3ad31474f4ad9942fce1361ca8c264e0c129c [file] [log] [blame]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001/* vi:set ts=8 sts=4 sw=4:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * misc1.c: functions that didn't seem to fit elsewhere
12 */
13
14#include "vim.h"
15#include "version.h"
16
Bram Moolenaar071d4272004-06-13 20:20:40 +000017static char_u *vim_version_dir __ARGS((char_u *vimdir));
18static char_u *remove_tail __ARGS((char_u *p, char_u *pend, char_u *name));
Bram Moolenaar071d4272004-06-13 20:20:40 +000019static int copy_indent __ARGS((int size, char_u *src));
20
21/*
22 * Count the size (in window cells) of the indent in the current line.
23 */
24 int
25get_indent()
26{
27 return get_indent_str(ml_get_curline(), (int)curbuf->b_p_ts);
28}
29
30/*
31 * Count the size (in window cells) of the indent in line "lnum".
32 */
33 int
34get_indent_lnum(lnum)
35 linenr_T lnum;
36{
37 return get_indent_str(ml_get(lnum), (int)curbuf->b_p_ts);
38}
39
40#if defined(FEAT_FOLDING) || defined(PROTO)
41/*
42 * Count the size (in window cells) of the indent in line "lnum" of buffer
43 * "buf".
44 */
45 int
46get_indent_buf(buf, lnum)
47 buf_T *buf;
48 linenr_T lnum;
49{
50 return get_indent_str(ml_get_buf(buf, lnum, FALSE), (int)buf->b_p_ts);
51}
52#endif
53
54/*
55 * count the size (in window cells) of the indent in line "ptr", with
56 * 'tabstop' at "ts"
57 */
Bram Moolenaar4399ef42005-02-12 14:29:27 +000058 int
Bram Moolenaar071d4272004-06-13 20:20:40 +000059get_indent_str(ptr, ts)
60 char_u *ptr;
61 int ts;
62{
63 int count = 0;
64
65 for ( ; *ptr; ++ptr)
66 {
67 if (*ptr == TAB) /* count a tab for what it is worth */
68 count += ts - (count % ts);
69 else if (*ptr == ' ')
70 ++count; /* count a space for one */
71 else
72 break;
73 }
Bram Moolenaar4399ef42005-02-12 14:29:27 +000074 return count;
Bram Moolenaar071d4272004-06-13 20:20:40 +000075}
76
77/*
78 * Set the indent of the current line.
79 * Leaves the cursor on the first non-blank in the line.
80 * Caller must take care of undo.
81 * "flags":
82 * SIN_CHANGED: call changed_bytes() if the line was changed.
83 * SIN_INSERT: insert the indent in front of the line.
84 * SIN_UNDO: save line for undo before changing it.
85 * Returns TRUE if the line was changed.
86 */
87 int
88set_indent(size, flags)
Bram Moolenaar5002c292007-07-24 13:26:15 +000089 int size; /* measured in spaces */
Bram Moolenaar071d4272004-06-13 20:20:40 +000090 int flags;
91{
92 char_u *p;
93 char_u *newline;
94 char_u *oldline;
95 char_u *s;
96 int todo;
Bram Moolenaar5002c292007-07-24 13:26:15 +000097 int ind_len; /* measured in characters */
Bram Moolenaar071d4272004-06-13 20:20:40 +000098 int line_len;
99 int doit = FALSE;
Bram Moolenaar5002c292007-07-24 13:26:15 +0000100 int ind_done = 0; /* measured in spaces */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000101 int tab_pad;
Bram Moolenaar5409c052005-03-18 20:27:04 +0000102 int retval = FALSE;
Bram Moolenaar4d64b782007-08-14 20:16:42 +0000103 int orig_char_len = -1; /* number of initial whitespace chars when
Bram Moolenaar5002c292007-07-24 13:26:15 +0000104 'et' and 'pi' are both set */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000105
106 /*
107 * First check if there is anything to do and compute the number of
108 * characters needed for the indent.
109 */
110 todo = size;
111 ind_len = 0;
112 p = oldline = ml_get_curline();
113
114 /* Calculate the buffer size for the new indent, and check to see if it
115 * isn't already set */
116
Bram Moolenaar5002c292007-07-24 13:26:15 +0000117 /* if 'expandtab' isn't set: use TABs; if both 'expandtab' and
118 * 'preserveindent' are set count the number of characters at the
119 * beginning of the line to be copied */
120 if (!curbuf->b_p_et || (!(flags & SIN_INSERT) && curbuf->b_p_pi))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000121 {
122 /* If 'preserveindent' is set then reuse as much as possible of
123 * the existing indent structure for the new indent */
124 if (!(flags & SIN_INSERT) && curbuf->b_p_pi)
125 {
126 ind_done = 0;
127
128 /* count as many characters as we can use */
129 while (todo > 0 && vim_iswhite(*p))
130 {
131 if (*p == TAB)
132 {
133 tab_pad = (int)curbuf->b_p_ts
134 - (ind_done % (int)curbuf->b_p_ts);
135 /* stop if this tab will overshoot the target */
136 if (todo < tab_pad)
137 break;
138 todo -= tab_pad;
139 ++ind_len;
140 ind_done += tab_pad;
141 }
142 else
143 {
144 --todo;
145 ++ind_len;
146 ++ind_done;
147 }
148 ++p;
149 }
150
Bram Moolenaar5002c292007-07-24 13:26:15 +0000151 /* Set initial number of whitespace chars to copy if we are
152 * preserving indent but expandtab is set */
153 if (curbuf->b_p_et)
154 orig_char_len = ind_len;
155
Bram Moolenaar071d4272004-06-13 20:20:40 +0000156 /* Fill to next tabstop with a tab, if possible */
157 tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
Bram Moolenaar4d64b782007-08-14 20:16:42 +0000158 if (todo >= tab_pad && orig_char_len == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000159 {
160 doit = TRUE;
161 todo -= tab_pad;
162 ++ind_len;
163 /* ind_done += tab_pad; */
164 }
165 }
166
167 /* count tabs required for indent */
168 while (todo >= (int)curbuf->b_p_ts)
169 {
170 if (*p != TAB)
171 doit = TRUE;
172 else
173 ++p;
174 todo -= (int)curbuf->b_p_ts;
175 ++ind_len;
176 /* ind_done += (int)curbuf->b_p_ts; */
177 }
178 }
179 /* count spaces required for indent */
180 while (todo > 0)
181 {
182 if (*p != ' ')
183 doit = TRUE;
184 else
185 ++p;
186 --todo;
187 ++ind_len;
188 /* ++ind_done; */
189 }
190
191 /* Return if the indent is OK already. */
192 if (!doit && !vim_iswhite(*p) && !(flags & SIN_INSERT))
193 return FALSE;
194
195 /* Allocate memory for the new line. */
196 if (flags & SIN_INSERT)
197 p = oldline;
198 else
199 p = skipwhite(p);
200 line_len = (int)STRLEN(p) + 1;
Bram Moolenaar5002c292007-07-24 13:26:15 +0000201
202 /* If 'preserveindent' and 'expandtab' are both set keep the original
203 * characters and allocate accordingly. We will fill the rest with spaces
204 * after the if (!curbuf->b_p_et) below. */
Bram Moolenaar4d64b782007-08-14 20:16:42 +0000205 if (orig_char_len != -1)
Bram Moolenaar5002c292007-07-24 13:26:15 +0000206 {
207 newline = alloc(orig_char_len + size - ind_done + line_len);
208 if (newline == NULL)
209 return FALSE;
Bram Moolenaar4d64b782007-08-14 20:16:42 +0000210 todo = size - ind_done;
211 ind_len = orig_char_len + todo; /* Set total length of indent in
212 * characters, which may have been
213 * undercounted until now */
Bram Moolenaar5002c292007-07-24 13:26:15 +0000214 p = oldline;
215 s = newline;
216 while (orig_char_len > 0)
217 {
218 *s++ = *p++;
219 orig_char_len--;
220 }
Bram Moolenaar913626c2008-01-03 11:43:42 +0000221
Bram Moolenaar5002c292007-07-24 13:26:15 +0000222 /* Skip over any additional white space (useful when newindent is less
223 * than old) */
224 while (vim_iswhite(*p))
Bram Moolenaar913626c2008-01-03 11:43:42 +0000225 ++p;
Bram Moolenaarcc00b952007-08-11 12:32:57 +0000226
Bram Moolenaar5002c292007-07-24 13:26:15 +0000227 }
228 else
229 {
230 todo = size;
231 newline = alloc(ind_len + line_len);
232 if (newline == NULL)
233 return FALSE;
234 s = newline;
235 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000236
237 /* Put the characters in the new line. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000238 /* if 'expandtab' isn't set: use TABs */
239 if (!curbuf->b_p_et)
240 {
241 /* If 'preserveindent' is set then reuse as much as possible of
242 * the existing indent structure for the new indent */
243 if (!(flags & SIN_INSERT) && curbuf->b_p_pi)
244 {
245 p = oldline;
246 ind_done = 0;
247
248 while (todo > 0 && vim_iswhite(*p))
249 {
250 if (*p == TAB)
251 {
252 tab_pad = (int)curbuf->b_p_ts
253 - (ind_done % (int)curbuf->b_p_ts);
254 /* stop if this tab will overshoot the target */
255 if (todo < tab_pad)
256 break;
257 todo -= tab_pad;
258 ind_done += tab_pad;
259 }
260 else
261 {
262 --todo;
263 ++ind_done;
264 }
265 *s++ = *p++;
266 }
267
268 /* Fill to next tabstop with a tab, if possible */
269 tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
270 if (todo >= tab_pad)
271 {
272 *s++ = TAB;
273 todo -= tab_pad;
274 }
275
276 p = skipwhite(p);
277 }
278
279 while (todo >= (int)curbuf->b_p_ts)
280 {
281 *s++ = TAB;
282 todo -= (int)curbuf->b_p_ts;
283 }
284 }
285 while (todo > 0)
286 {
287 *s++ = ' ';
288 --todo;
289 }
290 mch_memmove(s, p, (size_t)line_len);
291
292 /* Replace the line (unless undo fails). */
293 if (!(flags & SIN_UNDO) || u_savesub(curwin->w_cursor.lnum) == OK)
294 {
295 ml_replace(curwin->w_cursor.lnum, newline, FALSE);
296 if (flags & SIN_CHANGED)
297 changed_bytes(curwin->w_cursor.lnum, 0);
298 /* Correct saved cursor position if it's after the indent. */
299 if (saved_cursor.lnum == curwin->w_cursor.lnum
300 && saved_cursor.col >= (colnr_T)(p - oldline))
Bram Moolenaara93fa7e2006-04-17 22:14:47 +0000301 saved_cursor.col += ind_len - (colnr_T)(p - oldline);
Bram Moolenaar5409c052005-03-18 20:27:04 +0000302 retval = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000303 }
304 else
305 vim_free(newline);
306
307 curwin->w_cursor.col = ind_len;
Bram Moolenaar5409c052005-03-18 20:27:04 +0000308 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000309}
310
311/*
312 * Copy the indent from ptr to the current line (and fill to size)
313 * Leaves the cursor on the first non-blank in the line.
314 * Returns TRUE if the line was changed.
315 */
316 static int
317copy_indent(size, src)
318 int size;
319 char_u *src;
320{
321 char_u *p = NULL;
322 char_u *line = NULL;
323 char_u *s;
324 int todo;
325 int ind_len;
326 int line_len = 0;
327 int tab_pad;
328 int ind_done;
329 int round;
330
331 /* Round 1: compute the number of characters needed for the indent
332 * Round 2: copy the characters. */
333 for (round = 1; round <= 2; ++round)
334 {
335 todo = size;
336 ind_len = 0;
337 ind_done = 0;
338 s = src;
339
340 /* Count/copy the usable portion of the source line */
341 while (todo > 0 && vim_iswhite(*s))
342 {
343 if (*s == TAB)
344 {
345 tab_pad = (int)curbuf->b_p_ts
346 - (ind_done % (int)curbuf->b_p_ts);
347 /* Stop if this tab will overshoot the target */
348 if (todo < tab_pad)
349 break;
350 todo -= tab_pad;
351 ind_done += tab_pad;
352 }
353 else
354 {
355 --todo;
356 ++ind_done;
357 }
358 ++ind_len;
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000359 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000360 *p++ = *s;
361 ++s;
362 }
363
364 /* Fill to next tabstop with a tab, if possible */
365 tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
Bram Moolenaarc42e7ed2011-09-07 19:58:09 +0200366 if (todo >= tab_pad && !curbuf->b_p_et)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000367 {
368 todo -= tab_pad;
369 ++ind_len;
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000370 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000371 *p++ = TAB;
372 }
373
374 /* Add tabs required for indent */
Bram Moolenaarc42e7ed2011-09-07 19:58:09 +0200375 while (todo >= (int)curbuf->b_p_ts && !curbuf->b_p_et)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000376 {
377 todo -= (int)curbuf->b_p_ts;
378 ++ind_len;
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000379 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000380 *p++ = TAB;
381 }
382
383 /* Count/add spaces required for indent */
384 while (todo > 0)
385 {
386 --todo;
387 ++ind_len;
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000388 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000389 *p++ = ' ';
390 }
391
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000392 if (p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000393 {
394 /* Allocate memory for the result: the copied indent, new indent
395 * and the rest of the line. */
396 line_len = (int)STRLEN(ml_get_curline()) + 1;
397 line = alloc(ind_len + line_len);
398 if (line == NULL)
399 return FALSE;
400 p = line;
401 }
402 }
403
404 /* Append the original line */
405 mch_memmove(p, ml_get_curline(), (size_t)line_len);
406
407 /* Replace the line */
408 ml_replace(curwin->w_cursor.lnum, line, FALSE);
409
410 /* Put the cursor after the indent. */
411 curwin->w_cursor.col = ind_len;
412 return TRUE;
413}
414
415/*
416 * Return the indent of the current line after a number. Return -1 if no
417 * number was found. Used for 'n' in 'formatoptions': numbered list.
Bram Moolenaar86b68352004-12-27 21:59:20 +0000418 * Since a pattern is used it can actually handle more than numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000419 */
420 int
421get_number_indent(lnum)
422 linenr_T lnum;
423{
Bram Moolenaar071d4272004-06-13 20:20:40 +0000424 colnr_T col;
425 pos_T pos;
Bram Moolenaar86b68352004-12-27 21:59:20 +0000426 regmmatch_T regmatch;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000427
428 if (lnum > curbuf->b_ml.ml_line_count)
429 return -1;
Bram Moolenaar86b68352004-12-27 21:59:20 +0000430 pos.lnum = 0;
431 regmatch.regprog = vim_regcomp(curbuf->b_p_flp, RE_MAGIC);
432 if (regmatch.regprog != NULL)
433 {
434 regmatch.rmm_ic = FALSE;
Bram Moolenaar3b56eb32005-07-11 22:40:32 +0000435 regmatch.rmm_maxcol = 0;
Bram Moolenaar91a4e822008-01-19 14:59:58 +0000436 if (vim_regexec_multi(&regmatch, curwin, curbuf, lnum,
437 (colnr_T)0, NULL))
Bram Moolenaar86b68352004-12-27 21:59:20 +0000438 {
439 pos.lnum = regmatch.endpos[0].lnum + lnum;
440 pos.col = regmatch.endpos[0].col;
441#ifdef FEAT_VIRTUALEDIT
442 pos.coladd = 0;
443#endif
444 }
445 vim_free(regmatch.regprog);
446 }
447
448 if (pos.lnum == 0 || *ml_get_pos(&pos) == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000449 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000450 getvcol(curwin, &pos, &col, NULL, NULL);
451 return (int)col;
452}
453
454#if defined(FEAT_CINDENT) || defined(FEAT_SMARTINDENT)
455
456static int cin_is_cinword __ARGS((char_u *line));
457
458/*
459 * Return TRUE if the string "line" starts with a word from 'cinwords'.
460 */
461 static int
462cin_is_cinword(line)
463 char_u *line;
464{
465 char_u *cinw;
466 char_u *cinw_buf;
467 int cinw_len;
468 int retval = FALSE;
469 int len;
470
471 cinw_len = (int)STRLEN(curbuf->b_p_cinw) + 1;
472 cinw_buf = alloc((unsigned)cinw_len);
473 if (cinw_buf != NULL)
474 {
475 line = skipwhite(line);
476 for (cinw = curbuf->b_p_cinw; *cinw; )
477 {
478 len = copy_option_part(&cinw, cinw_buf, cinw_len, ",");
479 if (STRNCMP(line, cinw_buf, len) == 0
480 && (!vim_iswordc(line[len]) || !vim_iswordc(line[len - 1])))
481 {
482 retval = TRUE;
483 break;
484 }
485 }
486 vim_free(cinw_buf);
487 }
488 return retval;
489}
490#endif
491
492/*
493 * open_line: Add a new line below or above the current line.
494 *
495 * For VREPLACE mode, we only add a new line when we get to the end of the
496 * file, otherwise we just start replacing the next line.
497 *
498 * Caller must take care of undo. Since VREPLACE may affect any number of
499 * lines however, it may call u_save_cursor() again when starting to change a
500 * new line.
501 * "flags": OPENLINE_DELSPACES delete spaces after cursor
502 * OPENLINE_DO_COM format comments
503 * OPENLINE_KEEPTRAIL keep trailing spaces
504 * OPENLINE_MARKFIX adjust mark positions after the line break
505 *
506 * Return TRUE for success, FALSE for failure
507 */
508 int
509open_line(dir, flags, old_indent)
510 int dir; /* FORWARD or BACKWARD */
511 int flags;
512 int old_indent; /* indent for after ^^D in Insert mode */
513{
514 char_u *saved_line; /* copy of the original line */
515 char_u *next_line = NULL; /* copy of the next line */
516 char_u *p_extra = NULL; /* what goes to next line */
517 int less_cols = 0; /* less columns for mark in new line */
518 int less_cols_off = 0; /* columns to skip for mark adjust */
519 pos_T old_cursor; /* old cursor position */
520 int newcol = 0; /* new cursor column */
521 int newindent = 0; /* auto-indent of the new line */
522 int n;
523 int trunc_line = FALSE; /* truncate current line afterwards */
524 int retval = FALSE; /* return value, default is FAIL */
525#ifdef FEAT_COMMENTS
526 int extra_len = 0; /* length of p_extra string */
527 int lead_len; /* length of comment leader */
528 char_u *lead_flags; /* position in 'comments' for comment leader */
529 char_u *leader = NULL; /* copy of comment leader */
530#endif
531 char_u *allocated = NULL; /* allocated memory */
532#if defined(FEAT_SMARTINDENT) || defined(FEAT_VREPLACE) || defined(FEAT_LISP) \
533 || defined(FEAT_CINDENT) || defined(FEAT_COMMENTS)
534 char_u *p;
535#endif
536 int saved_char = NUL; /* init for GCC */
537#if defined(FEAT_SMARTINDENT) || defined(FEAT_COMMENTS)
538 pos_T *pos;
539#endif
540#ifdef FEAT_SMARTINDENT
541 int do_si = (!p_paste && curbuf->b_p_si
542# ifdef FEAT_CINDENT
543 && !curbuf->b_p_cin
544# endif
545 );
546 int no_si = FALSE; /* reset did_si afterwards */
547 int first_char = NUL; /* init for GCC */
548#endif
549#if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
550 int vreplace_mode;
551#endif
552 int did_append; /* appended a new line */
553 int saved_pi = curbuf->b_p_pi; /* copy of preserveindent setting */
554
555 /*
556 * make a copy of the current line so we can mess with it
557 */
558 saved_line = vim_strsave(ml_get_curline());
559 if (saved_line == NULL) /* out of memory! */
560 return FALSE;
561
562#ifdef FEAT_VREPLACE
563 if (State & VREPLACE_FLAG)
564 {
565 /*
566 * With VREPLACE we make a copy of the next line, which we will be
567 * starting to replace. First make the new line empty and let vim play
568 * with the indenting and comment leader to its heart's content. Then
569 * we grab what it ended up putting on the new line, put back the
570 * original line, and call ins_char() to put each new character onto
571 * the line, replacing what was there before and pushing the right
572 * stuff onto the replace stack. -- webb.
573 */
574 if (curwin->w_cursor.lnum < orig_line_count)
575 next_line = vim_strsave(ml_get(curwin->w_cursor.lnum + 1));
576 else
577 next_line = vim_strsave((char_u *)"");
578 if (next_line == NULL) /* out of memory! */
579 goto theend;
580
581 /*
582 * In VREPLACE mode, a NL replaces the rest of the line, and starts
583 * replacing the next line, so push all of the characters left on the
584 * line onto the replace stack. We'll push any other characters that
585 * might be replaced at the start of the next line (due to autoindent
586 * etc) a bit later.
587 */
588 replace_push(NUL); /* Call twice because BS over NL expects it */
589 replace_push(NUL);
590 p = saved_line + curwin->w_cursor.col;
591 while (*p != NUL)
Bram Moolenaar2c994e82008-01-02 16:49:36 +0000592 {
593#ifdef FEAT_MBYTE
594 if (has_mbyte)
595 p += replace_push_mb(p);
596 else
597#endif
598 replace_push(*p++);
599 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000600 saved_line[curwin->w_cursor.col] = NUL;
601 }
602#endif
603
604 if ((State & INSERT)
605#ifdef FEAT_VREPLACE
606 && !(State & VREPLACE_FLAG)
607#endif
608 )
609 {
610 p_extra = saved_line + curwin->w_cursor.col;
611#ifdef FEAT_SMARTINDENT
612 if (do_si) /* need first char after new line break */
613 {
614 p = skipwhite(p_extra);
615 first_char = *p;
616 }
617#endif
618#ifdef FEAT_COMMENTS
619 extra_len = (int)STRLEN(p_extra);
620#endif
621 saved_char = *p_extra;
622 *p_extra = NUL;
623 }
624
625 u_clearline(); /* cannot do "U" command when adding lines */
626#ifdef FEAT_SMARTINDENT
627 did_si = FALSE;
628#endif
629 ai_col = 0;
630
631 /*
632 * If we just did an auto-indent, then we didn't type anything on
633 * the prior line, and it should be truncated. Do this even if 'ai' is not
634 * set because automatically inserting a comment leader also sets did_ai.
635 */
636 if (dir == FORWARD && did_ai)
637 trunc_line = TRUE;
638
639 /*
640 * If 'autoindent' and/or 'smartindent' is set, try to figure out what
641 * indent to use for the new line.
642 */
643 if (curbuf->b_p_ai
644#ifdef FEAT_SMARTINDENT
645 || do_si
646#endif
647 )
648 {
649 /*
650 * count white space on current line
651 */
652 newindent = get_indent_str(saved_line, (int)curbuf->b_p_ts);
653 if (newindent == 0)
654 newindent = old_indent; /* for ^^D command in insert mode */
655
656#ifdef FEAT_SMARTINDENT
657 /*
658 * Do smart indenting.
659 * In insert/replace mode (only when dir == FORWARD)
660 * we may move some text to the next line. If it starts with '{'
661 * don't add an indent. Fixes inserting a NL before '{' in line
662 * "if (condition) {"
663 */
664 if (!trunc_line && do_si && *saved_line != NUL
665 && (p_extra == NULL || first_char != '{'))
666 {
667 char_u *ptr;
668 char_u last_char;
669
670 old_cursor = curwin->w_cursor;
671 ptr = saved_line;
672# ifdef FEAT_COMMENTS
673 if (flags & OPENLINE_DO_COM)
674 lead_len = get_leader_len(ptr, NULL, FALSE);
675 else
676 lead_len = 0;
677# endif
678 if (dir == FORWARD)
679 {
680 /*
681 * Skip preprocessor directives, unless they are
682 * recognised as comments.
683 */
684 if (
685# ifdef FEAT_COMMENTS
686 lead_len == 0 &&
687# endif
688 ptr[0] == '#')
689 {
690 while (ptr[0] == '#' && curwin->w_cursor.lnum > 1)
691 ptr = ml_get(--curwin->w_cursor.lnum);
692 newindent = get_indent();
693 }
694# ifdef FEAT_COMMENTS
695 if (flags & OPENLINE_DO_COM)
696 lead_len = get_leader_len(ptr, NULL, FALSE);
697 else
698 lead_len = 0;
699 if (lead_len > 0)
700 {
701 /*
702 * This case gets the following right:
703 * \*
704 * * A comment (read '\' as '/').
705 * *\
706 * #define IN_THE_WAY
707 * This should line up here;
708 */
709 p = skipwhite(ptr);
710 if (p[0] == '/' && p[1] == '*')
711 p++;
712 if (p[0] == '*')
713 {
714 for (p++; *p; p++)
715 {
716 if (p[0] == '/' && p[-1] == '*')
717 {
718 /*
719 * End of C comment, indent should line up
720 * with the line containing the start of
721 * the comment
722 */
723 curwin->w_cursor.col = (colnr_T)(p - ptr);
724 if ((pos = findmatch(NULL, NUL)) != NULL)
725 {
726 curwin->w_cursor.lnum = pos->lnum;
727 newindent = get_indent();
728 }
729 }
730 }
731 }
732 }
733 else /* Not a comment line */
734# endif
735 {
736 /* Find last non-blank in line */
737 p = ptr + STRLEN(ptr) - 1;
738 while (p > ptr && vim_iswhite(*p))
739 --p;
740 last_char = *p;
741
742 /*
743 * find the character just before the '{' or ';'
744 */
745 if (last_char == '{' || last_char == ';')
746 {
747 if (p > ptr)
748 --p;
749 while (p > ptr && vim_iswhite(*p))
750 --p;
751 }
752 /*
753 * Try to catch lines that are split over multiple
754 * lines. eg:
755 * if (condition &&
756 * condition) {
757 * Should line up here!
758 * }
759 */
760 if (*p == ')')
761 {
762 curwin->w_cursor.col = (colnr_T)(p - ptr);
763 if ((pos = findmatch(NULL, '(')) != NULL)
764 {
765 curwin->w_cursor.lnum = pos->lnum;
766 newindent = get_indent();
767 ptr = ml_get_curline();
768 }
769 }
770 /*
771 * If last character is '{' do indent, without
772 * checking for "if" and the like.
773 */
774 if (last_char == '{')
775 {
776 did_si = TRUE; /* do indent */
777 no_si = TRUE; /* don't delete it when '{' typed */
778 }
779 /*
780 * Look for "if" and the like, use 'cinwords'.
781 * Don't do this if the previous line ended in ';' or
782 * '}'.
783 */
784 else if (last_char != ';' && last_char != '}'
785 && cin_is_cinword(ptr))
786 did_si = TRUE;
787 }
788 }
789 else /* dir == BACKWARD */
790 {
791 /*
792 * Skip preprocessor directives, unless they are
793 * recognised as comments.
794 */
795 if (
796# ifdef FEAT_COMMENTS
797 lead_len == 0 &&
798# endif
799 ptr[0] == '#')
800 {
801 int was_backslashed = FALSE;
802
803 while ((ptr[0] == '#' || was_backslashed) &&
804 curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
805 {
806 if (*ptr && ptr[STRLEN(ptr) - 1] == '\\')
807 was_backslashed = TRUE;
808 else
809 was_backslashed = FALSE;
810 ptr = ml_get(++curwin->w_cursor.lnum);
811 }
812 if (was_backslashed)
813 newindent = 0; /* Got to end of file */
814 else
815 newindent = get_indent();
816 }
817 p = skipwhite(ptr);
818 if (*p == '}') /* if line starts with '}': do indent */
819 did_si = TRUE;
820 else /* can delete indent when '{' typed */
821 can_si_back = TRUE;
822 }
823 curwin->w_cursor = old_cursor;
824 }
825 if (do_si)
826 can_si = TRUE;
827#endif /* FEAT_SMARTINDENT */
828
829 did_ai = TRUE;
830 }
831
832#ifdef FEAT_COMMENTS
833 /*
834 * Find out if the current line starts with a comment leader.
835 * This may then be inserted in front of the new line.
836 */
837 end_comment_pending = NUL;
838 if (flags & OPENLINE_DO_COM)
839 lead_len = get_leader_len(saved_line, &lead_flags, dir == BACKWARD);
840 else
841 lead_len = 0;
842 if (lead_len > 0)
843 {
844 char_u *lead_repl = NULL; /* replaces comment leader */
845 int lead_repl_len = 0; /* length of *lead_repl */
846 char_u lead_middle[COM_MAX_LEN]; /* middle-comment string */
847 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
848 char_u *comment_end = NULL; /* where lead_end has been found */
849 int extra_space = FALSE; /* append extra space */
850 int current_flag;
851 int require_blank = FALSE; /* requires blank after middle */
852 char_u *p2;
853
854 /*
855 * If the comment leader has the start, middle or end flag, it may not
856 * be used or may be replaced with the middle leader.
857 */
858 for (p = lead_flags; *p && *p != ':'; ++p)
859 {
860 if (*p == COM_BLANK)
861 {
862 require_blank = TRUE;
863 continue;
864 }
865 if (*p == COM_START || *p == COM_MIDDLE)
866 {
867 current_flag = *p;
868 if (*p == COM_START)
869 {
870 /*
871 * Doing "O" on a start of comment does not insert leader.
872 */
873 if (dir == BACKWARD)
874 {
875 lead_len = 0;
876 break;
877 }
878
879 /* find start of middle part */
880 (void)copy_option_part(&p, lead_middle, COM_MAX_LEN, ",");
881 require_blank = FALSE;
882 }
883
884 /*
885 * Isolate the strings of the middle and end leader.
886 */
887 while (*p && p[-1] != ':') /* find end of middle flags */
888 {
889 if (*p == COM_BLANK)
890 require_blank = TRUE;
891 ++p;
892 }
893 (void)copy_option_part(&p, lead_middle, COM_MAX_LEN, ",");
894
895 while (*p && p[-1] != ':') /* find end of end flags */
896 {
897 /* Check whether we allow automatic ending of comments */
898 if (*p == COM_AUTO_END)
899 end_comment_pending = -1; /* means we want to set it */
900 ++p;
901 }
902 n = copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
903
904 if (end_comment_pending == -1) /* we can set it now */
905 end_comment_pending = lead_end[n - 1];
906
907 /*
908 * If the end of the comment is in the same line, don't use
909 * the comment leader.
910 */
911 if (dir == FORWARD)
912 {
913 for (p = saved_line + lead_len; *p; ++p)
914 if (STRNCMP(p, lead_end, n) == 0)
915 {
916 comment_end = p;
917 lead_len = 0;
918 break;
919 }
920 }
921
922 /*
923 * Doing "o" on a start of comment inserts the middle leader.
924 */
925 if (lead_len > 0)
926 {
927 if (current_flag == COM_START)
928 {
929 lead_repl = lead_middle;
930 lead_repl_len = (int)STRLEN(lead_middle);
931 }
932
933 /*
934 * If we have hit RETURN immediately after the start
935 * comment leader, then put a space after the middle
936 * comment leader on the next line.
937 */
938 if (!vim_iswhite(saved_line[lead_len - 1])
939 && ((p_extra != NULL
940 && (int)curwin->w_cursor.col == lead_len)
941 || (p_extra == NULL
942 && saved_line[lead_len] == NUL)
943 || require_blank))
944 extra_space = TRUE;
945 }
946 break;
947 }
948 if (*p == COM_END)
949 {
950 /*
951 * Doing "o" on the end of a comment does not insert leader.
952 * Remember where the end is, might want to use it to find the
953 * start (for C-comments).
954 */
955 if (dir == FORWARD)
956 {
957 comment_end = skipwhite(saved_line);
958 lead_len = 0;
959 break;
960 }
961
962 /*
963 * Doing "O" on the end of a comment inserts the middle leader.
964 * Find the string for the middle leader, searching backwards.
965 */
966 while (p > curbuf->b_p_com && *p != ',')
967 --p;
968 for (lead_repl = p; lead_repl > curbuf->b_p_com
969 && lead_repl[-1] != ':'; --lead_repl)
970 ;
971 lead_repl_len = (int)(p - lead_repl);
972
973 /* We can probably always add an extra space when doing "O" on
974 * the comment-end */
975 extra_space = TRUE;
976
977 /* Check whether we allow automatic ending of comments */
978 for (p2 = p; *p2 && *p2 != ':'; p2++)
979 {
980 if (*p2 == COM_AUTO_END)
981 end_comment_pending = -1; /* means we want to set it */
982 }
983 if (end_comment_pending == -1)
984 {
985 /* Find last character in end-comment string */
986 while (*p2 && *p2 != ',')
987 p2++;
988 end_comment_pending = p2[-1];
989 }
990 break;
991 }
992 if (*p == COM_FIRST)
993 {
994 /*
995 * Comment leader for first line only: Don't repeat leader
996 * when using "O", blank out leader when using "o".
997 */
998 if (dir == BACKWARD)
999 lead_len = 0;
1000 else
1001 {
1002 lead_repl = (char_u *)"";
1003 lead_repl_len = 0;
1004 }
1005 break;
1006 }
1007 }
1008 if (lead_len)
1009 {
1010 /* allocate buffer (may concatenate p_exta later) */
1011 leader = alloc(lead_len + lead_repl_len + extra_space +
1012 extra_len + 1);
1013 allocated = leader; /* remember to free it later */
1014
1015 if (leader == NULL)
1016 lead_len = 0;
1017 else
1018 {
Bram Moolenaarce0842a2005-07-18 21:58:11 +00001019 vim_strncpy(leader, saved_line, lead_len);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001020
1021 /*
1022 * Replace leader with lead_repl, right or left adjusted
1023 */
1024 if (lead_repl != NULL)
1025 {
1026 int c = 0;
1027 int off = 0;
1028
Bram Moolenaard7d5b472009-11-11 16:30:08 +00001029 for (p = lead_flags; *p != NUL && *p != ':'; )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001030 {
1031 if (*p == COM_RIGHT || *p == COM_LEFT)
Bram Moolenaard7d5b472009-11-11 16:30:08 +00001032 c = *p++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001033 else if (VIM_ISDIGIT(*p) || *p == '-')
1034 off = getdigits(&p);
Bram Moolenaard7d5b472009-11-11 16:30:08 +00001035 else
1036 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001037 }
1038 if (c == COM_RIGHT) /* right adjusted leader */
1039 {
1040 /* find last non-white in the leader to line up with */
1041 for (p = leader + lead_len - 1; p > leader
1042 && vim_iswhite(*p); --p)
1043 ;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001044 ++p;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001045
1046#ifdef FEAT_MBYTE
1047 /* Compute the length of the replaced characters in
1048 * screen characters, not bytes. */
1049 {
1050 int repl_size = vim_strnsize(lead_repl,
1051 lead_repl_len);
1052 int old_size = 0;
1053 char_u *endp = p;
1054 int l;
1055
1056 while (old_size < repl_size && p > leader)
1057 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001058 mb_ptr_back(leader, p);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001059 old_size += ptr2cells(p);
1060 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001061 l = lead_repl_len - (int)(endp - p);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001062 if (l != 0)
1063 mch_memmove(endp + l, endp,
1064 (size_t)((leader + lead_len) - endp));
1065 lead_len += l;
1066 }
1067#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001068 if (p < leader + lead_repl_len)
1069 p = leader;
1070 else
1071 p -= lead_repl_len;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001072#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001073 mch_memmove(p, lead_repl, (size_t)lead_repl_len);
1074 if (p + lead_repl_len > leader + lead_len)
1075 p[lead_repl_len] = NUL;
1076
1077 /* blank-out any other chars from the old leader. */
1078 while (--p >= leader)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001079 {
1080#ifdef FEAT_MBYTE
1081 int l = mb_head_off(leader, p);
1082
1083 if (l > 1)
1084 {
1085 p -= l;
1086 if (ptr2cells(p) > 1)
1087 {
1088 p[1] = ' ';
1089 --l;
1090 }
1091 mch_memmove(p + 1, p + l + 1,
1092 (size_t)((leader + lead_len) - (p + l + 1)));
1093 lead_len -= l;
1094 *p = ' ';
1095 }
1096 else
1097#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001098 if (!vim_iswhite(*p))
1099 *p = ' ';
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001100 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001101 }
1102 else /* left adjusted leader */
1103 {
1104 p = skipwhite(leader);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001105#ifdef FEAT_MBYTE
1106 /* Compute the length of the replaced characters in
1107 * screen characters, not bytes. Move the part that is
1108 * not to be overwritten. */
1109 {
1110 int repl_size = vim_strnsize(lead_repl,
1111 lead_repl_len);
1112 int i;
1113 int l;
1114
1115 for (i = 0; p[i] != NUL && i < lead_len; i += l)
1116 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00001117 l = (*mb_ptr2len)(p + i);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001118 if (vim_strnsize(p, i + l) > repl_size)
1119 break;
1120 }
1121 if (i != lead_repl_len)
1122 {
1123 mch_memmove(p + lead_repl_len, p + i,
Bram Moolenaar2d7ff052009-11-17 15:08:26 +00001124 (size_t)(lead_len - i - (p - leader)));
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001125 lead_len += lead_repl_len - i;
1126 }
1127 }
1128#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001129 mch_memmove(p, lead_repl, (size_t)lead_repl_len);
1130
1131 /* Replace any remaining non-white chars in the old
1132 * leader by spaces. Keep Tabs, the indent must
1133 * remain the same. */
1134 for (p += lead_repl_len; p < leader + lead_len; ++p)
1135 if (!vim_iswhite(*p))
1136 {
1137 /* Don't put a space before a TAB. */
1138 if (p + 1 < leader + lead_len && p[1] == TAB)
1139 {
1140 --lead_len;
1141 mch_memmove(p, p + 1,
1142 (leader + lead_len) - p);
1143 }
1144 else
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001145 {
1146#ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00001147 int l = (*mb_ptr2len)(p);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001148
1149 if (l > 1)
1150 {
1151 if (ptr2cells(p) > 1)
1152 {
1153 /* Replace a double-wide char with
1154 * two spaces */
1155 --l;
1156 *p++ = ' ';
1157 }
1158 mch_memmove(p + 1, p + l,
1159 (leader + lead_len) - p);
1160 lead_len -= l - 1;
1161 }
1162#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001163 *p = ' ';
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001164 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001165 }
1166 *p = NUL;
1167 }
1168
1169 /* Recompute the indent, it may have changed. */
1170 if (curbuf->b_p_ai
1171#ifdef FEAT_SMARTINDENT
1172 || do_si
1173#endif
1174 )
1175 newindent = get_indent_str(leader, (int)curbuf->b_p_ts);
1176
1177 /* Add the indent offset */
1178 if (newindent + off < 0)
1179 {
1180 off = -newindent;
1181 newindent = 0;
1182 }
1183 else
1184 newindent += off;
1185
1186 /* Correct trailing spaces for the shift, so that
1187 * alignment remains equal. */
1188 while (off > 0 && lead_len > 0
1189 && leader[lead_len - 1] == ' ')
1190 {
1191 /* Don't do it when there is a tab before the space */
1192 if (vim_strchr(skipwhite(leader), '\t') != NULL)
1193 break;
1194 --lead_len;
1195 --off;
1196 }
1197
1198 /* If the leader ends in white space, don't add an
1199 * extra space */
1200 if (lead_len > 0 && vim_iswhite(leader[lead_len - 1]))
1201 extra_space = FALSE;
1202 leader[lead_len] = NUL;
1203 }
1204
1205 if (extra_space)
1206 {
1207 leader[lead_len++] = ' ';
1208 leader[lead_len] = NUL;
1209 }
1210
1211 newcol = lead_len;
1212
1213 /*
1214 * if a new indent will be set below, remove the indent that
1215 * is in the comment leader
1216 */
1217 if (newindent
1218#ifdef FEAT_SMARTINDENT
1219 || did_si
1220#endif
1221 )
1222 {
1223 while (lead_len && vim_iswhite(*leader))
1224 {
1225 --lead_len;
1226 --newcol;
1227 ++leader;
1228 }
1229 }
1230
1231 }
1232#ifdef FEAT_SMARTINDENT
1233 did_si = can_si = FALSE;
1234#endif
1235 }
1236 else if (comment_end != NULL)
1237 {
1238 /*
1239 * We have finished a comment, so we don't use the leader.
1240 * If this was a C-comment and 'ai' or 'si' is set do a normal
1241 * indent to align with the line containing the start of the
1242 * comment.
1243 */
1244 if (comment_end[0] == '*' && comment_end[1] == '/' &&
1245 (curbuf->b_p_ai
1246#ifdef FEAT_SMARTINDENT
1247 || do_si
1248#endif
1249 ))
1250 {
1251 old_cursor = curwin->w_cursor;
1252 curwin->w_cursor.col = (colnr_T)(comment_end - saved_line);
1253 if ((pos = findmatch(NULL, NUL)) != NULL)
1254 {
1255 curwin->w_cursor.lnum = pos->lnum;
1256 newindent = get_indent();
1257 }
1258 curwin->w_cursor = old_cursor;
1259 }
1260 }
1261 }
1262#endif
1263
1264 /* (State == INSERT || State == REPLACE), only when dir == FORWARD */
1265 if (p_extra != NULL)
1266 {
1267 *p_extra = saved_char; /* restore char that NUL replaced */
1268
1269 /*
1270 * When 'ai' set or "flags" has OPENLINE_DELSPACES, skip to the first
1271 * non-blank.
1272 *
1273 * When in REPLACE mode, put the deleted blanks on the replace stack,
1274 * preceded by a NUL, so they can be put back when a BS is entered.
1275 */
1276 if (REPLACE_NORMAL(State))
1277 replace_push(NUL); /* end of extra blanks */
1278 if (curbuf->b_p_ai || (flags & OPENLINE_DELSPACES))
1279 {
1280 while ((*p_extra == ' ' || *p_extra == '\t')
1281#ifdef FEAT_MBYTE
1282 && (!enc_utf8
1283 || !utf_iscomposing(utf_ptr2char(p_extra + 1)))
1284#endif
1285 )
1286 {
1287 if (REPLACE_NORMAL(State))
1288 replace_push(*p_extra);
1289 ++p_extra;
1290 ++less_cols_off;
1291 }
1292 }
1293 if (*p_extra != NUL)
1294 did_ai = FALSE; /* append some text, don't truncate now */
1295
1296 /* columns for marks adjusted for removed columns */
1297 less_cols = (int)(p_extra - saved_line);
1298 }
1299
1300 if (p_extra == NULL)
1301 p_extra = (char_u *)""; /* append empty line */
1302
1303#ifdef FEAT_COMMENTS
1304 /* concatenate leader and p_extra, if there is a leader */
1305 if (lead_len)
1306 {
1307 STRCAT(leader, p_extra);
1308 p_extra = leader;
1309 did_ai = TRUE; /* So truncating blanks works with comments */
1310 less_cols -= lead_len;
1311 }
1312 else
1313 end_comment_pending = NUL; /* turns out there was no leader */
1314#endif
1315
1316 old_cursor = curwin->w_cursor;
1317 if (dir == BACKWARD)
1318 --curwin->w_cursor.lnum;
1319#ifdef FEAT_VREPLACE
1320 if (!(State & VREPLACE_FLAG) || old_cursor.lnum >= orig_line_count)
1321#endif
1322 {
1323 if (ml_append(curwin->w_cursor.lnum, p_extra, (colnr_T)0, FALSE)
1324 == FAIL)
1325 goto theend;
1326 /* Postpone calling changed_lines(), because it would mess up folding
1327 * with markers. */
1328 mark_adjust(curwin->w_cursor.lnum + 1, (linenr_T)MAXLNUM, 1L, 0L);
1329 did_append = TRUE;
1330 }
1331#ifdef FEAT_VREPLACE
1332 else
1333 {
1334 /*
1335 * In VREPLACE mode we are starting to replace the next line.
1336 */
1337 curwin->w_cursor.lnum++;
1338 if (curwin->w_cursor.lnum >= Insstart.lnum + vr_lines_changed)
1339 {
1340 /* In case we NL to a new line, BS to the previous one, and NL
1341 * again, we don't want to save the new line for undo twice.
1342 */
1343 (void)u_save_cursor(); /* errors are ignored! */
1344 vr_lines_changed++;
1345 }
1346 ml_replace(curwin->w_cursor.lnum, p_extra, TRUE);
1347 changed_bytes(curwin->w_cursor.lnum, 0);
1348 curwin->w_cursor.lnum--;
1349 did_append = FALSE;
1350 }
1351#endif
1352
1353 if (newindent
1354#ifdef FEAT_SMARTINDENT
1355 || did_si
1356#endif
1357 )
1358 {
1359 ++curwin->w_cursor.lnum;
1360#ifdef FEAT_SMARTINDENT
1361 if (did_si)
1362 {
1363 if (p_sr)
1364 newindent -= newindent % (int)curbuf->b_p_sw;
1365 newindent += (int)curbuf->b_p_sw;
1366 }
1367#endif
Bram Moolenaar5002c292007-07-24 13:26:15 +00001368 /* Copy the indent */
1369 if (curbuf->b_p_ci)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001370 {
1371 (void)copy_indent(newindent, saved_line);
1372
1373 /*
1374 * Set the 'preserveindent' option so that any further screwing
1375 * with the line doesn't entirely destroy our efforts to preserve
1376 * it. It gets restored at the function end.
1377 */
1378 curbuf->b_p_pi = TRUE;
1379 }
1380 else
1381 (void)set_indent(newindent, SIN_INSERT);
1382 less_cols -= curwin->w_cursor.col;
1383
1384 ai_col = curwin->w_cursor.col;
1385
1386 /*
1387 * In REPLACE mode, for each character in the new indent, there must
1388 * be a NUL on the replace stack, for when it is deleted with BS
1389 */
1390 if (REPLACE_NORMAL(State))
1391 for (n = 0; n < (int)curwin->w_cursor.col; ++n)
1392 replace_push(NUL);
1393 newcol += curwin->w_cursor.col;
1394#ifdef FEAT_SMARTINDENT
1395 if (no_si)
1396 did_si = FALSE;
1397#endif
1398 }
1399
1400#ifdef FEAT_COMMENTS
1401 /*
1402 * In REPLACE mode, for each character in the extra leader, there must be
1403 * a NUL on the replace stack, for when it is deleted with BS.
1404 */
1405 if (REPLACE_NORMAL(State))
1406 while (lead_len-- > 0)
1407 replace_push(NUL);
1408#endif
1409
1410 curwin->w_cursor = old_cursor;
1411
1412 if (dir == FORWARD)
1413 {
1414 if (trunc_line || (State & INSERT))
1415 {
1416 /* truncate current line at cursor */
1417 saved_line[curwin->w_cursor.col] = NUL;
1418 /* Remove trailing white space, unless OPENLINE_KEEPTRAIL used. */
1419 if (trunc_line && !(flags & OPENLINE_KEEPTRAIL))
1420 truncate_spaces(saved_line);
1421 ml_replace(curwin->w_cursor.lnum, saved_line, FALSE);
1422 saved_line = NULL;
1423 if (did_append)
1424 {
1425 changed_lines(curwin->w_cursor.lnum, curwin->w_cursor.col,
1426 curwin->w_cursor.lnum + 1, 1L);
1427 did_append = FALSE;
1428
1429 /* Move marks after the line break to the new line. */
1430 if (flags & OPENLINE_MARKFIX)
1431 mark_col_adjust(curwin->w_cursor.lnum,
1432 curwin->w_cursor.col + less_cols_off,
1433 1L, (long)-less_cols);
1434 }
1435 else
1436 changed_bytes(curwin->w_cursor.lnum, curwin->w_cursor.col);
1437 }
1438
1439 /*
1440 * Put the cursor on the new line. Careful: the scrollup() above may
1441 * have moved w_cursor, we must use old_cursor.
1442 */
1443 curwin->w_cursor.lnum = old_cursor.lnum + 1;
1444 }
1445 if (did_append)
1446 changed_lines(curwin->w_cursor.lnum, 0, curwin->w_cursor.lnum, 1L);
1447
1448 curwin->w_cursor.col = newcol;
1449#ifdef FEAT_VIRTUALEDIT
1450 curwin->w_cursor.coladd = 0;
1451#endif
1452
1453#if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
1454 /*
1455 * In VREPLACE mode, we are handling the replace stack ourselves, so stop
1456 * fixthisline() from doing it (via change_indent()) by telling it we're in
1457 * normal INSERT mode.
1458 */
1459 if (State & VREPLACE_FLAG)
1460 {
1461 vreplace_mode = State; /* So we know to put things right later */
1462 State = INSERT;
1463 }
1464 else
1465 vreplace_mode = 0;
1466#endif
1467#ifdef FEAT_LISP
1468 /*
1469 * May do lisp indenting.
1470 */
1471 if (!p_paste
1472# ifdef FEAT_COMMENTS
1473 && leader == NULL
1474# endif
1475 && curbuf->b_p_lisp
1476 && curbuf->b_p_ai)
1477 {
1478 fixthisline(get_lisp_indent);
1479 p = ml_get_curline();
1480 ai_col = (colnr_T)(skipwhite(p) - p);
1481 }
1482#endif
1483#ifdef FEAT_CINDENT
1484 /*
1485 * May do indenting after opening a new line.
1486 */
1487 if (!p_paste
1488 && (curbuf->b_p_cin
1489# ifdef FEAT_EVAL
1490 || *curbuf->b_p_inde != NUL
1491# endif
1492 )
1493 && in_cinkeys(dir == FORWARD
1494 ? KEY_OPEN_FORW
1495 : KEY_OPEN_BACK, ' ', linewhite(curwin->w_cursor.lnum)))
1496 {
1497 do_c_expr_indent();
1498 p = ml_get_curline();
1499 ai_col = (colnr_T)(skipwhite(p) - p);
1500 }
1501#endif
1502#if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
1503 if (vreplace_mode != 0)
1504 State = vreplace_mode;
1505#endif
1506
1507#ifdef FEAT_VREPLACE
1508 /*
1509 * Finally, VREPLACE gets the stuff on the new line, then puts back the
1510 * original line, and inserts the new stuff char by char, pushing old stuff
1511 * onto the replace stack (via ins_char()).
1512 */
1513 if (State & VREPLACE_FLAG)
1514 {
1515 /* Put new line in p_extra */
1516 p_extra = vim_strsave(ml_get_curline());
1517 if (p_extra == NULL)
1518 goto theend;
1519
1520 /* Put back original line */
1521 ml_replace(curwin->w_cursor.lnum, next_line, FALSE);
1522
1523 /* Insert new stuff into line again */
1524 curwin->w_cursor.col = 0;
1525#ifdef FEAT_VIRTUALEDIT
1526 curwin->w_cursor.coladd = 0;
1527#endif
1528 ins_bytes(p_extra); /* will call changed_bytes() */
1529 vim_free(p_extra);
1530 next_line = NULL;
1531 }
1532#endif
1533
1534 retval = TRUE; /* success! */
1535theend:
1536 curbuf->b_p_pi = saved_pi;
1537 vim_free(saved_line);
1538 vim_free(next_line);
1539 vim_free(allocated);
1540 return retval;
1541}
1542
1543#if defined(FEAT_COMMENTS) || defined(PROTO)
1544/*
1545 * get_leader_len() returns the length of the prefix of the given string
1546 * which introduces a comment. If this string is not a comment then 0 is
1547 * returned.
1548 * When "flags" is not NULL, it is set to point to the flags of the recognized
1549 * comment leader.
1550 * "backward" must be true for the "O" command.
1551 */
1552 int
1553get_leader_len(line, flags, backward)
1554 char_u *line;
1555 char_u **flags;
1556 int backward;
1557{
1558 int i, j;
1559 int got_com = FALSE;
1560 int found_one;
1561 char_u part_buf[COM_MAX_LEN]; /* buffer for one option part */
1562 char_u *string; /* pointer to comment string */
1563 char_u *list;
Bram Moolenaara4271d52011-05-10 13:38:27 +02001564 int middle_match_len = 0;
1565 char_u *prev_list;
Bram Moolenaar05da4282011-05-10 14:44:11 +02001566 char_u *saved_flags = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001567
1568 i = 0;
1569 while (vim_iswhite(line[i])) /* leading white space is ignored */
1570 ++i;
1571
1572 /*
1573 * Repeat to match several nested comment strings.
1574 */
Bram Moolenaara4271d52011-05-10 13:38:27 +02001575 while (line[i] != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001576 {
1577 /*
1578 * scan through the 'comments' option for a match
1579 */
1580 found_one = FALSE;
1581 for (list = curbuf->b_p_com; *list; )
1582 {
Bram Moolenaara4271d52011-05-10 13:38:27 +02001583 /* Get one option part into part_buf[]. Advance "list" to next
1584 * one. Put "string" at start of string. */
1585 if (!got_com && flags != NULL)
1586 *flags = list; /* remember where flags started */
1587 prev_list = list;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001588 (void)copy_option_part(&list, part_buf, COM_MAX_LEN, ",");
1589 string = vim_strchr(part_buf, ':');
1590 if (string == NULL) /* missing ':', ignore this part */
1591 continue;
1592 *string++ = NUL; /* isolate flags from string */
1593
Bram Moolenaara4271d52011-05-10 13:38:27 +02001594 /* If we found a middle match previously, use that match when this
1595 * is not a middle or end. */
1596 if (middle_match_len != 0
1597 && vim_strchr(part_buf, COM_MIDDLE) == NULL
1598 && vim_strchr(part_buf, COM_END) == NULL)
1599 break;
1600
1601 /* When we already found a nested comment, only accept further
1602 * nested comments. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001603 if (got_com && vim_strchr(part_buf, COM_NEST) == NULL)
1604 continue;
1605
Bram Moolenaara4271d52011-05-10 13:38:27 +02001606 /* When 'O' flag present and using "O" command skip this one. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001607 if (backward && vim_strchr(part_buf, COM_NOBACK) != NULL)
1608 continue;
1609
Bram Moolenaara4271d52011-05-10 13:38:27 +02001610 /* Line contents and string must match.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001611 * When string starts with white space, must have some white space
1612 * (but the amount does not need to match, there might be a mix of
Bram Moolenaara4271d52011-05-10 13:38:27 +02001613 * TABs and spaces). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001614 if (vim_iswhite(string[0]))
1615 {
1616 if (i == 0 || !vim_iswhite(line[i - 1]))
Bram Moolenaara4271d52011-05-10 13:38:27 +02001617 continue; /* missing shite space */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001618 while (vim_iswhite(string[0]))
1619 ++string;
1620 }
1621 for (j = 0; string[j] != NUL && string[j] == line[i + j]; ++j)
1622 ;
1623 if (string[j] != NUL)
Bram Moolenaara4271d52011-05-10 13:38:27 +02001624 continue; /* string doesn't match */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001625
Bram Moolenaara4271d52011-05-10 13:38:27 +02001626 /* When 'b' flag used, there must be white space or an
1627 * end-of-line after the string in the line. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001628 if (vim_strchr(part_buf, COM_BLANK) != NULL
1629 && !vim_iswhite(line[i + j]) && line[i + j] != NUL)
1630 continue;
1631
Bram Moolenaara4271d52011-05-10 13:38:27 +02001632 /* We have found a match, stop searching unless this is a middle
1633 * comment. The middle comment can be a substring of the end
1634 * comment in which case it's better to return the length of the
1635 * end comment and its flags. Thus we keep searching with middle
1636 * and end matches and use an end match if it matches better. */
1637 if (vim_strchr(part_buf, COM_MIDDLE) != NULL)
1638 {
1639 if (middle_match_len == 0)
1640 {
1641 middle_match_len = j;
1642 saved_flags = prev_list;
1643 }
1644 continue;
1645 }
1646 if (middle_match_len != 0 && j > middle_match_len)
1647 /* Use this match instead of the middle match, since it's a
1648 * longer thus better match. */
1649 middle_match_len = 0;
1650
1651 if (middle_match_len == 0)
1652 i += j;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001653 found_one = TRUE;
1654 break;
1655 }
1656
Bram Moolenaara4271d52011-05-10 13:38:27 +02001657 if (middle_match_len != 0)
1658 {
1659 /* Use the previously found middle match after failing to find a
1660 * match with an end. */
1661 if (!got_com && flags != NULL)
1662 *flags = saved_flags;
1663 i += middle_match_len;
1664 found_one = TRUE;
1665 }
1666
1667 /* No match found, stop scanning. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001668 if (!found_one)
1669 break;
1670
Bram Moolenaara4271d52011-05-10 13:38:27 +02001671 /* Include any trailing white space. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001672 while (vim_iswhite(line[i]))
1673 ++i;
1674
Bram Moolenaara4271d52011-05-10 13:38:27 +02001675 /* If this comment doesn't nest, stop here. */
1676 got_com = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001677 if (vim_strchr(part_buf, COM_NEST) == NULL)
1678 break;
1679 }
Bram Moolenaara4271d52011-05-10 13:38:27 +02001680
Bram Moolenaar071d4272004-06-13 20:20:40 +00001681 return (got_com ? i : 0);
1682}
1683#endif
1684
1685/*
1686 * Return the number of window lines occupied by buffer line "lnum".
1687 */
1688 int
1689plines(lnum)
1690 linenr_T lnum;
1691{
1692 return plines_win(curwin, lnum, TRUE);
1693}
1694
1695 int
1696plines_win(wp, lnum, winheight)
1697 win_T *wp;
1698 linenr_T lnum;
1699 int winheight; /* when TRUE limit to window height */
1700{
1701#if defined(FEAT_DIFF) || defined(PROTO)
1702 /* Check for filler lines above this buffer line. When folded the result
1703 * is one line anyway. */
1704 return plines_win_nofill(wp, lnum, winheight) + diff_check_fill(wp, lnum);
1705}
1706
1707 int
1708plines_nofill(lnum)
1709 linenr_T lnum;
1710{
1711 return plines_win_nofill(curwin, lnum, TRUE);
1712}
1713
1714 int
1715plines_win_nofill(wp, lnum, winheight)
1716 win_T *wp;
1717 linenr_T lnum;
1718 int winheight; /* when TRUE limit to window height */
1719{
1720#endif
1721 int lines;
1722
1723 if (!wp->w_p_wrap)
1724 return 1;
1725
1726#ifdef FEAT_VERTSPLIT
1727 if (wp->w_width == 0)
1728 return 1;
1729#endif
1730
1731#ifdef FEAT_FOLDING
1732 /* A folded lines is handled just like an empty line. */
1733 /* NOTE: Caller must handle lines that are MAYBE folded. */
1734 if (lineFolded(wp, lnum) == TRUE)
1735 return 1;
1736#endif
1737
1738 lines = plines_win_nofold(wp, lnum);
1739 if (winheight > 0 && lines > wp->w_height)
1740 return (int)wp->w_height;
1741 return lines;
1742}
1743
1744/*
1745 * Return number of window lines physical line "lnum" will occupy in window
1746 * "wp". Does not care about folding, 'wrap' or 'diff'.
1747 */
1748 int
1749plines_win_nofold(wp, lnum)
1750 win_T *wp;
1751 linenr_T lnum;
1752{
1753 char_u *s;
1754 long col;
1755 int width;
1756
1757 s = ml_get_buf(wp->w_buffer, lnum, FALSE);
1758 if (*s == NUL) /* empty line */
1759 return 1;
1760 col = win_linetabsize(wp, s, (colnr_T)MAXCOL);
1761
1762 /*
1763 * If list mode is on, then the '$' at the end of the line may take up one
1764 * extra column.
1765 */
1766 if (wp->w_p_list && lcs_eol != NUL)
1767 col += 1;
1768
1769 /*
Bram Moolenaar64486672010-05-16 15:46:46 +02001770 * Add column offset for 'number', 'relativenumber' and 'foldcolumn'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001771 */
1772 width = W_WIDTH(wp) - win_col_off(wp);
1773 if (width <= 0)
1774 return 32000;
1775 if (col <= width)
1776 return 1;
1777 col -= width;
1778 width += win_col_off2(wp);
1779 return (col + (width - 1)) / width + 1;
1780}
1781
1782/*
1783 * Like plines_win(), but only reports the number of physical screen lines
1784 * used from the start of the line to the given column number.
1785 */
1786 int
1787plines_win_col(wp, lnum, column)
1788 win_T *wp;
1789 linenr_T lnum;
1790 long column;
1791{
1792 long col;
1793 char_u *s;
1794 int lines = 0;
1795 int width;
1796
1797#ifdef FEAT_DIFF
1798 /* Check for filler lines above this buffer line. When folded the result
1799 * is one line anyway. */
1800 lines = diff_check_fill(wp, lnum);
1801#endif
1802
1803 if (!wp->w_p_wrap)
1804 return lines + 1;
1805
1806#ifdef FEAT_VERTSPLIT
1807 if (wp->w_width == 0)
1808 return lines + 1;
1809#endif
1810
1811 s = ml_get_buf(wp->w_buffer, lnum, FALSE);
1812
1813 col = 0;
1814 while (*s != NUL && --column >= 0)
1815 {
1816 col += win_lbr_chartabsize(wp, s, (colnr_T)col, NULL);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001817 mb_ptr_adv(s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001818 }
1819
1820 /*
1821 * If *s is a TAB, and the TAB is not displayed as ^I, and we're not in
1822 * INSERT mode, then col must be adjusted so that it represents the last
1823 * screen position of the TAB. This only fixes an error when the TAB wraps
1824 * from one screen line to the next (when 'columns' is not a multiple of
1825 * 'ts') -- webb.
1826 */
1827 if (*s == TAB && (State & NORMAL) && (!wp->w_p_list || lcs_tab1))
1828 col += win_lbr_chartabsize(wp, s, (colnr_T)col, NULL) - 1;
1829
1830 /*
Bram Moolenaar64486672010-05-16 15:46:46 +02001831 * Add column offset for 'number', 'relativenumber', 'foldcolumn', etc.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001832 */
1833 width = W_WIDTH(wp) - win_col_off(wp);
Bram Moolenaar26470632006-10-24 19:12:40 +00001834 if (width <= 0)
1835 return 9999;
1836
1837 lines += 1;
1838 if (col > width)
1839 lines += (col - width) / (width + win_col_off2(wp)) + 1;
1840 return lines;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001841}
1842
1843 int
1844plines_m_win(wp, first, last)
1845 win_T *wp;
1846 linenr_T first, last;
1847{
1848 int count = 0;
1849
1850 while (first <= last)
1851 {
1852#ifdef FEAT_FOLDING
1853 int x;
1854
1855 /* Check if there are any really folded lines, but also included lines
1856 * that are maybe folded. */
1857 x = foldedCount(wp, first, NULL);
1858 if (x > 0)
1859 {
1860 ++count; /* count 1 for "+-- folded" line */
1861 first += x;
1862 }
1863 else
1864#endif
1865 {
1866#ifdef FEAT_DIFF
1867 if (first == wp->w_topline)
1868 count += plines_win_nofill(wp, first, TRUE) + wp->w_topfill;
1869 else
1870#endif
1871 count += plines_win(wp, first, TRUE);
1872 ++first;
1873 }
1874 }
1875 return (count);
1876}
1877
1878#if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) || defined(PROTO)
1879/*
1880 * Insert string "p" at the cursor position. Stops at a NUL byte.
1881 * Handles Replace mode and multi-byte characters.
1882 */
1883 void
1884ins_bytes(p)
1885 char_u *p;
1886{
1887 ins_bytes_len(p, (int)STRLEN(p));
1888}
1889#endif
1890
1891#if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) \
1892 || defined(FEAT_COMMENTS) || defined(FEAT_MBYTE) || defined(PROTO)
1893/*
1894 * Insert string "p" with length "len" at the cursor position.
1895 * Handles Replace mode and multi-byte characters.
1896 */
1897 void
1898ins_bytes_len(p, len)
1899 char_u *p;
1900 int len;
1901{
1902 int i;
1903# ifdef FEAT_MBYTE
1904 int n;
1905
Bram Moolenaar176dd1e2008-06-21 14:30:28 +00001906 if (has_mbyte)
1907 for (i = 0; i < len; i += n)
1908 {
1909 if (enc_utf8)
1910 /* avoid reading past p[len] */
1911 n = utfc_ptr2len_len(p + i, len - i);
1912 else
1913 n = (*mb_ptr2len)(p + i);
1914 ins_char_bytes(p + i, n);
1915 }
1916 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001917# endif
Bram Moolenaar176dd1e2008-06-21 14:30:28 +00001918 for (i = 0; i < len; ++i)
1919 ins_char(p[i]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001920}
1921#endif
1922
1923/*
1924 * Insert or replace a single character at the cursor position.
1925 * When in REPLACE or VREPLACE mode, replace any existing character.
1926 * Caller must have prepared for undo.
1927 * For multi-byte characters we get the whole character, the caller must
1928 * convert bytes to a character.
1929 */
1930 void
1931ins_char(c)
1932 int c;
1933{
1934#if defined(FEAT_MBYTE) || defined(PROTO)
1935 char_u buf[MB_MAXBYTES];
1936 int n;
1937
1938 n = (*mb_char2bytes)(c, buf);
1939
1940 /* When "c" is 0x100, 0x200, etc. we don't want to insert a NUL byte.
1941 * Happens for CTRL-Vu9900. */
1942 if (buf[0] == 0)
1943 buf[0] = '\n';
1944
1945 ins_char_bytes(buf, n);
1946}
1947
1948 void
1949ins_char_bytes(buf, charlen)
1950 char_u *buf;
1951 int charlen;
1952{
1953 int c = buf[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001954#endif
1955 int newlen; /* nr of bytes inserted */
1956 int oldlen; /* nr of bytes deleted (0 when not replacing) */
1957 char_u *p;
1958 char_u *newp;
1959 char_u *oldp;
1960 int linelen; /* length of old line including NUL */
1961 colnr_T col;
1962 linenr_T lnum = curwin->w_cursor.lnum;
1963 int i;
1964
1965#ifdef FEAT_VIRTUALEDIT
1966 /* Break tabs if needed. */
1967 if (virtual_active() && curwin->w_cursor.coladd > 0)
1968 coladvance_force(getviscol());
1969#endif
1970
1971 col = curwin->w_cursor.col;
1972 oldp = ml_get(lnum);
1973 linelen = (int)STRLEN(oldp) + 1;
1974
1975 /* The lengths default to the values for when not replacing. */
1976 oldlen = 0;
1977#ifdef FEAT_MBYTE
1978 newlen = charlen;
1979#else
1980 newlen = 1;
1981#endif
1982
1983 if (State & REPLACE_FLAG)
1984 {
1985#ifdef FEAT_VREPLACE
1986 if (State & VREPLACE_FLAG)
1987 {
1988 colnr_T new_vcol = 0; /* init for GCC */
1989 colnr_T vcol;
1990 int old_list;
1991#ifndef FEAT_MBYTE
1992 char_u buf[2];
1993#endif
1994
1995 /*
1996 * Disable 'list' temporarily, unless 'cpo' contains the 'L' flag.
1997 * Returns the old value of list, so when finished,
1998 * curwin->w_p_list should be set back to this.
1999 */
2000 old_list = curwin->w_p_list;
2001 if (old_list && vim_strchr(p_cpo, CPO_LISTWM) == NULL)
2002 curwin->w_p_list = FALSE;
2003
2004 /*
2005 * In virtual replace mode each character may replace one or more
2006 * characters (zero if it's a TAB). Count the number of bytes to
2007 * be deleted to make room for the new character, counting screen
2008 * cells. May result in adding spaces to fill a gap.
2009 */
2010 getvcol(curwin, &curwin->w_cursor, NULL, &vcol, NULL);
2011#ifndef FEAT_MBYTE
2012 buf[0] = c;
2013 buf[1] = NUL;
2014#endif
2015 new_vcol = vcol + chartabsize(buf, vcol);
2016 while (oldp[col + oldlen] != NUL && vcol < new_vcol)
2017 {
2018 vcol += chartabsize(oldp + col + oldlen, vcol);
2019 /* Don't need to remove a TAB that takes us to the right
2020 * position. */
2021 if (vcol > new_vcol && oldp[col + oldlen] == TAB)
2022 break;
2023#ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002024 oldlen += (*mb_ptr2len)(oldp + col + oldlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002025#else
2026 ++oldlen;
2027#endif
2028 /* Deleted a bit too much, insert spaces. */
2029 if (vcol > new_vcol)
2030 newlen += vcol - new_vcol;
2031 }
2032 curwin->w_p_list = old_list;
2033 }
2034 else
2035#endif
2036 if (oldp[col] != NUL)
2037 {
2038 /* normal replace */
2039#ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002040 oldlen = (*mb_ptr2len)(oldp + col);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002041#else
2042 oldlen = 1;
2043#endif
2044 }
2045
2046
2047 /* Push the replaced bytes onto the replace stack, so that they can be
2048 * put back when BS is used. The bytes of a multi-byte character are
2049 * done the other way around, so that the first byte is popped off
2050 * first (it tells the byte length of the character). */
2051 replace_push(NUL);
2052 for (i = 0; i < oldlen; ++i)
2053 {
2054#ifdef FEAT_MBYTE
Bram Moolenaar2c994e82008-01-02 16:49:36 +00002055 if (has_mbyte)
2056 i += replace_push_mb(oldp + col + i) - 1;
2057 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002058#endif
Bram Moolenaar2c994e82008-01-02 16:49:36 +00002059 replace_push(oldp[col + i]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002060 }
2061 }
2062
2063 newp = alloc_check((unsigned)(linelen + newlen - oldlen));
2064 if (newp == NULL)
2065 return;
2066
2067 /* Copy bytes before the cursor. */
2068 if (col > 0)
2069 mch_memmove(newp, oldp, (size_t)col);
2070
2071 /* Copy bytes after the changed character(s). */
2072 p = newp + col;
2073 mch_memmove(p + newlen, oldp + col + oldlen,
2074 (size_t)(linelen - col - oldlen));
2075
2076 /* Insert or overwrite the new character. */
2077#ifdef FEAT_MBYTE
2078 mch_memmove(p, buf, charlen);
2079 i = charlen;
2080#else
2081 *p = c;
2082 i = 1;
2083#endif
2084
2085 /* Fill with spaces when necessary. */
2086 while (i < newlen)
2087 p[i++] = ' ';
2088
2089 /* Replace the line in the buffer. */
2090 ml_replace(lnum, newp, FALSE);
2091
2092 /* mark the buffer as changed and prepare for displaying */
2093 changed_bytes(lnum, col);
2094
2095 /*
2096 * If we're in Insert or Replace mode and 'showmatch' is set, then briefly
2097 * show the match for right parens and braces.
2098 */
2099 if (p_sm && (State & INSERT)
2100 && msg_silent == 0
2101#ifdef FEAT_MBYTE
2102 && charlen == 1
2103#endif
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00002104#ifdef FEAT_INS_EXPAND
2105 && !ins_compl_active()
2106#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002107 )
2108 showmatch(c);
2109
2110#ifdef FEAT_RIGHTLEFT
2111 if (!p_ri || (State & REPLACE_FLAG))
2112#endif
2113 {
2114 /* Normal insert: move cursor right */
2115#ifdef FEAT_MBYTE
2116 curwin->w_cursor.col += charlen;
2117#else
2118 ++curwin->w_cursor.col;
2119#endif
2120 }
2121 /*
2122 * TODO: should try to update w_row here, to avoid recomputing it later.
2123 */
2124}
2125
2126/*
2127 * Insert a string at the cursor position.
2128 * Note: Does NOT handle Replace mode.
2129 * Caller must have prepared for undo.
2130 */
2131 void
2132ins_str(s)
2133 char_u *s;
2134{
2135 char_u *oldp, *newp;
2136 int newlen = (int)STRLEN(s);
2137 int oldlen;
2138 colnr_T col;
2139 linenr_T lnum = curwin->w_cursor.lnum;
2140
2141#ifdef FEAT_VIRTUALEDIT
2142 if (virtual_active() && curwin->w_cursor.coladd > 0)
2143 coladvance_force(getviscol());
2144#endif
2145
2146 col = curwin->w_cursor.col;
2147 oldp = ml_get(lnum);
2148 oldlen = (int)STRLEN(oldp);
2149
2150 newp = alloc_check((unsigned)(oldlen + newlen + 1));
2151 if (newp == NULL)
2152 return;
2153 if (col > 0)
2154 mch_memmove(newp, oldp, (size_t)col);
2155 mch_memmove(newp + col, s, (size_t)newlen);
2156 mch_memmove(newp + col + newlen, oldp + col, (size_t)(oldlen - col + 1));
2157 ml_replace(lnum, newp, FALSE);
2158 changed_bytes(lnum, col);
2159 curwin->w_cursor.col += newlen;
2160}
2161
2162/*
2163 * Delete one character under the cursor.
2164 * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
2165 * Caller must have prepared for undo.
2166 *
2167 * return FAIL for failure, OK otherwise
2168 */
2169 int
2170del_char(fixpos)
2171 int fixpos;
2172{
2173#ifdef FEAT_MBYTE
2174 if (has_mbyte)
2175 {
2176 /* Make sure the cursor is at the start of a character. */
2177 mb_adjust_cursor();
2178 if (*ml_get_cursor() == NUL)
2179 return FAIL;
2180 return del_chars(1L, fixpos);
2181 }
2182#endif
Bram Moolenaare3226be2005-12-18 22:10:00 +00002183 return del_bytes(1L, fixpos, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002184}
2185
2186#if defined(FEAT_MBYTE) || defined(PROTO)
2187/*
2188 * Like del_bytes(), but delete characters instead of bytes.
2189 */
2190 int
2191del_chars(count, fixpos)
2192 long count;
2193 int fixpos;
2194{
2195 long bytes = 0;
2196 long i;
2197 char_u *p;
2198 int l;
2199
2200 p = ml_get_cursor();
2201 for (i = 0; i < count && *p != NUL; ++i)
2202 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002203 l = (*mb_ptr2len)(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002204 bytes += l;
2205 p += l;
2206 }
Bram Moolenaare3226be2005-12-18 22:10:00 +00002207 return del_bytes(bytes, fixpos, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002208}
2209#endif
2210
2211/*
2212 * Delete "count" bytes under the cursor.
2213 * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
2214 * Caller must have prepared for undo.
2215 *
2216 * return FAIL for failure, OK otherwise
2217 */
2218 int
Bram Moolenaarca003e12006-03-17 23:19:38 +00002219del_bytes(count, fixpos_arg, use_delcombine)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002220 long count;
Bram Moolenaarca003e12006-03-17 23:19:38 +00002221 int fixpos_arg;
Bram Moolenaar78a15312009-05-15 19:33:18 +00002222 int use_delcombine UNUSED; /* 'delcombine' option applies */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002223{
2224 char_u *oldp, *newp;
2225 colnr_T oldlen;
2226 linenr_T lnum = curwin->w_cursor.lnum;
2227 colnr_T col = curwin->w_cursor.col;
2228 int was_alloced;
2229 long movelen;
Bram Moolenaarca003e12006-03-17 23:19:38 +00002230 int fixpos = fixpos_arg;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002231
2232 oldp = ml_get(lnum);
2233 oldlen = (int)STRLEN(oldp);
2234
2235 /*
2236 * Can't do anything when the cursor is on the NUL after the line.
2237 */
2238 if (col >= oldlen)
2239 return FAIL;
2240
2241#ifdef FEAT_MBYTE
2242 /* If 'delcombine' is set and deleting (less than) one character, only
2243 * delete the last combining character. */
Bram Moolenaare3226be2005-12-18 22:10:00 +00002244 if (p_deco && use_delcombine && enc_utf8
2245 && utfc_ptr2len(oldp + col) >= count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002246 {
Bram Moolenaar362e1a32006-03-06 23:29:24 +00002247 int cc[MAX_MCO];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002248 int n;
2249
Bram Moolenaar362e1a32006-03-06 23:29:24 +00002250 (void)utfc_ptr2char(oldp + col, cc);
2251 if (cc[0] != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002252 {
2253 /* Find the last composing char, there can be several. */
2254 n = col;
2255 do
2256 {
2257 col = n;
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002258 count = utf_ptr2len(oldp + n);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002259 n += count;
2260 } while (UTF_COMPOSINGLIKE(oldp + col, oldp + n));
2261 fixpos = 0;
2262 }
2263 }
2264#endif
2265
2266 /*
2267 * When count is too big, reduce it.
2268 */
2269 movelen = (long)oldlen - (long)col - count + 1; /* includes trailing NUL */
2270 if (movelen <= 1)
2271 {
2272 /*
2273 * If we just took off the last character of a non-blank line, and
Bram Moolenaarca003e12006-03-17 23:19:38 +00002274 * fixpos is TRUE, we don't want to end up positioned at the NUL,
2275 * unless "restart_edit" is set or 'virtualedit' contains "onemore".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002276 */
Bram Moolenaarca003e12006-03-17 23:19:38 +00002277 if (col > 0 && fixpos && restart_edit == 0
2278#ifdef FEAT_VIRTUALEDIT
2279 && (ve_flags & VE_ONEMORE) == 0
2280#endif
2281 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00002282 {
2283 --curwin->w_cursor.col;
2284#ifdef FEAT_VIRTUALEDIT
2285 curwin->w_cursor.coladd = 0;
2286#endif
2287#ifdef FEAT_MBYTE
2288 if (has_mbyte)
2289 curwin->w_cursor.col -=
2290 (*mb_head_off)(oldp, oldp + curwin->w_cursor.col);
2291#endif
2292 }
2293 count = oldlen - col;
2294 movelen = 1;
2295 }
2296
2297 /*
2298 * If the old line has been allocated the deletion can be done in the
2299 * existing line. Otherwise a new line has to be allocated
Bram Moolenaare21877a2008-02-13 09:58:14 +00002300 * Can't do this when using Netbeans, because we would need to invoke
2301 * netbeans_removed(), which deallocates the line. Let ml_replace() take
Bram Moolenaar1a509df2010-08-01 17:59:57 +02002302 * care of notifying Netbeans.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002303 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002304#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02002305 if (netbeans_active())
Bram Moolenaare21877a2008-02-13 09:58:14 +00002306 was_alloced = FALSE;
2307 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002308#endif
Bram Moolenaare21877a2008-02-13 09:58:14 +00002309 was_alloced = ml_line_alloced(); /* check if oldp was allocated */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002310 if (was_alloced)
2311 newp = oldp; /* use same allocated memory */
2312 else
2313 { /* need to allocate a new line */
2314 newp = alloc((unsigned)(oldlen + 1 - count));
2315 if (newp == NULL)
2316 return FAIL;
2317 mch_memmove(newp, oldp, (size_t)col);
2318 }
2319 mch_memmove(newp + col, oldp + col + count, (size_t)movelen);
2320 if (!was_alloced)
2321 ml_replace(lnum, newp, FALSE);
2322
2323 /* mark the buffer as changed and prepare for displaying */
2324 changed_bytes(lnum, curwin->w_cursor.col);
2325
2326 return OK;
2327}
2328
2329/*
2330 * Delete from cursor to end of line.
2331 * Caller must have prepared for undo.
2332 *
2333 * return FAIL for failure, OK otherwise
2334 */
2335 int
2336truncate_line(fixpos)
2337 int fixpos; /* if TRUE fix the cursor position when done */
2338{
2339 char_u *newp;
2340 linenr_T lnum = curwin->w_cursor.lnum;
2341 colnr_T col = curwin->w_cursor.col;
2342
2343 if (col == 0)
2344 newp = vim_strsave((char_u *)"");
2345 else
2346 newp = vim_strnsave(ml_get(lnum), col);
2347
2348 if (newp == NULL)
2349 return FAIL;
2350
2351 ml_replace(lnum, newp, FALSE);
2352
2353 /* mark the buffer as changed and prepare for displaying */
2354 changed_bytes(lnum, curwin->w_cursor.col);
2355
2356 /*
2357 * If "fixpos" is TRUE we don't want to end up positioned at the NUL.
2358 */
2359 if (fixpos && curwin->w_cursor.col > 0)
2360 --curwin->w_cursor.col;
2361
2362 return OK;
2363}
2364
2365/*
2366 * Delete "nlines" lines at the cursor.
2367 * Saves the lines for undo first if "undo" is TRUE.
2368 */
2369 void
2370del_lines(nlines, undo)
2371 long nlines; /* number of lines to delete */
2372 int undo; /* if TRUE, prepare for undo */
2373{
2374 long n;
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002375 linenr_T first = curwin->w_cursor.lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002376
2377 if (nlines <= 0)
2378 return;
2379
2380 /* save the deleted lines for undo */
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002381 if (undo && u_savedel(first, nlines) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002382 return;
2383
2384 for (n = 0; n < nlines; )
2385 {
2386 if (curbuf->b_ml.ml_flags & ML_EMPTY) /* nothing to delete */
2387 break;
2388
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002389 ml_delete(first, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002390 ++n;
2391
2392 /* If we delete the last line in the file, stop */
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002393 if (first > curbuf->b_ml.ml_line_count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002394 break;
2395 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002396
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002397 /* Correct the cursor position before calling deleted_lines_mark(), it may
2398 * trigger a callback to display the cursor. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002399 curwin->w_cursor.col = 0;
2400 check_cursor_lnum();
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002401
2402 /* adjust marks, mark the buffer as changed and prepare for displaying */
2403 deleted_lines_mark(first, n);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002404}
2405
2406 int
2407gchar_pos(pos)
2408 pos_T *pos;
2409{
2410 char_u *ptr = ml_get_pos(pos);
2411
2412#ifdef FEAT_MBYTE
2413 if (has_mbyte)
2414 return (*mb_ptr2char)(ptr);
2415#endif
2416 return (int)*ptr;
2417}
2418
2419 int
2420gchar_cursor()
2421{
2422#ifdef FEAT_MBYTE
2423 if (has_mbyte)
2424 return (*mb_ptr2char)(ml_get_cursor());
2425#endif
2426 return (int)*ml_get_cursor();
2427}
2428
2429/*
2430 * Write a character at the current cursor position.
2431 * It is directly written into the block.
2432 */
2433 void
2434pchar_cursor(c)
2435 int c;
2436{
2437 *(ml_get_buf(curbuf, curwin->w_cursor.lnum, TRUE)
2438 + curwin->w_cursor.col) = c;
2439}
2440
Bram Moolenaar071d4272004-06-13 20:20:40 +00002441/*
2442 * When extra == 0: Return TRUE if the cursor is before or on the first
2443 * non-blank in the line.
2444 * When extra == 1: Return TRUE if the cursor is before the first non-blank in
2445 * the line.
2446 */
2447 int
2448inindent(extra)
2449 int extra;
2450{
2451 char_u *ptr;
2452 colnr_T col;
2453
2454 for (col = 0, ptr = ml_get_curline(); vim_iswhite(*ptr); ++col)
2455 ++ptr;
2456 if (col >= curwin->w_cursor.col + extra)
2457 return TRUE;
2458 else
2459 return FALSE;
2460}
2461
2462/*
2463 * Skip to next part of an option argument: Skip space and comma.
2464 */
2465 char_u *
2466skip_to_option_part(p)
2467 char_u *p;
2468{
2469 if (*p == ',')
2470 ++p;
2471 while (*p == ' ')
2472 ++p;
2473 return p;
2474}
2475
2476/*
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002477 * Call this function when something in the current buffer is changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002478 *
2479 * Most often called through changed_bytes() and changed_lines(), which also
2480 * mark the area of the display to be redrawn.
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002481 *
2482 * Careful: may trigger autocommands that reload the buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002483 */
2484 void
2485changed()
2486{
2487#if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
2488 /* The text of the preediting area is inserted, but this doesn't
2489 * mean a change of the buffer yet. That is delayed until the
2490 * text is committed. (this means preedit becomes empty) */
2491 if (im_is_preediting() && !xim_changed_while_preediting)
2492 return;
2493 xim_changed_while_preediting = FALSE;
2494#endif
2495
2496 if (!curbuf->b_changed)
2497 {
2498 int save_msg_scroll = msg_scroll;
2499
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002500 /* Give a warning about changing a read-only file. This may also
2501 * check-out the file, thus change "curbuf"! */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002502 change_warning(0);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002503
Bram Moolenaar071d4272004-06-13 20:20:40 +00002504 /* Create a swap file if that is wanted.
2505 * Don't do this for "nofile" and "nowrite" buffer types. */
2506 if (curbuf->b_may_swap
2507#ifdef FEAT_QUICKFIX
2508 && !bt_dontwrite(curbuf)
2509#endif
2510 )
2511 {
2512 ml_open_file(curbuf);
2513
2514 /* The ml_open_file() can cause an ATTENTION message.
2515 * Wait two seconds, to make sure the user reads this unexpected
2516 * message. Since we could be anywhere, call wait_return() now,
2517 * and don't let the emsg() set msg_scroll. */
2518 if (need_wait_return && emsg_silent == 0)
2519 {
2520 out_flush();
2521 ui_delay(2000L, TRUE);
2522 wait_return(TRUE);
2523 msg_scroll = save_msg_scroll;
2524 }
2525 }
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02002526 changed_int();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002527 }
2528 ++curbuf->b_changedtick;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002529}
2530
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02002531/*
2532 * Internal part of changed(), no user interaction.
2533 */
2534 void
2535changed_int()
2536{
2537 curbuf->b_changed = TRUE;
2538 ml_setflags(curbuf);
2539#ifdef FEAT_WINDOWS
2540 check_status(curbuf);
2541 redraw_tabline = TRUE;
2542#endif
2543#ifdef FEAT_TITLE
2544 need_maketitle = TRUE; /* set window title later */
2545#endif
2546}
2547
Bram Moolenaardba8a912005-04-24 22:08:39 +00002548static void changedOneline __ARGS((buf_T *buf, linenr_T lnum));
2549static void changed_lines_buf __ARGS((buf_T *buf, linenr_T lnum, linenr_T lnume, long xtra));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002550static void changed_common __ARGS((linenr_T lnum, colnr_T col, linenr_T lnume, long xtra));
2551
2552/*
2553 * Changed bytes within a single line for the current buffer.
2554 * - marks the windows on this buffer to be redisplayed
2555 * - marks the buffer changed by calling changed()
2556 * - invalidates cached values
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002557 * Careful: may trigger autocommands that reload the buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002558 */
2559 void
2560changed_bytes(lnum, col)
2561 linenr_T lnum;
2562 colnr_T col;
2563{
Bram Moolenaardba8a912005-04-24 22:08:39 +00002564 changedOneline(curbuf, lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002565 changed_common(lnum, col, lnum + 1, 0L);
Bram Moolenaardba8a912005-04-24 22:08:39 +00002566
2567#ifdef FEAT_DIFF
2568 /* Diff highlighting in other diff windows may need to be updated too. */
2569 if (curwin->w_p_diff)
2570 {
2571 win_T *wp;
2572 linenr_T wlnum;
2573
2574 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2575 if (wp->w_p_diff && wp != curwin)
2576 {
2577 redraw_win_later(wp, VALID);
2578 wlnum = diff_lnum_win(lnum, wp);
2579 if (wlnum > 0)
2580 changedOneline(wp->w_buffer, wlnum);
2581 }
2582 }
2583#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002584}
2585
2586 static void
Bram Moolenaardba8a912005-04-24 22:08:39 +00002587changedOneline(buf, lnum)
2588 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002589 linenr_T lnum;
2590{
Bram Moolenaardba8a912005-04-24 22:08:39 +00002591 if (buf->b_mod_set)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002592 {
2593 /* find the maximum area that must be redisplayed */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002594 if (lnum < buf->b_mod_top)
2595 buf->b_mod_top = lnum;
2596 else if (lnum >= buf->b_mod_bot)
2597 buf->b_mod_bot = lnum + 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002598 }
2599 else
2600 {
2601 /* set the area that must be redisplayed to one line */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002602 buf->b_mod_set = TRUE;
2603 buf->b_mod_top = lnum;
2604 buf->b_mod_bot = lnum + 1;
2605 buf->b_mod_xlines = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002606 }
2607}
2608
2609/*
2610 * Appended "count" lines below line "lnum" in the current buffer.
2611 * Must be called AFTER the change and after mark_adjust().
2612 * Takes care of marking the buffer to be redrawn and sets the changed flag.
2613 */
2614 void
2615appended_lines(lnum, count)
2616 linenr_T lnum;
2617 long count;
2618{
2619 changed_lines(lnum + 1, 0, lnum + 1, count);
2620}
2621
2622/*
2623 * Like appended_lines(), but adjust marks first.
2624 */
2625 void
2626appended_lines_mark(lnum, count)
2627 linenr_T lnum;
2628 long count;
2629{
2630 mark_adjust(lnum + 1, (linenr_T)MAXLNUM, count, 0L);
2631 changed_lines(lnum + 1, 0, lnum + 1, count);
2632}
2633
2634/*
2635 * Deleted "count" lines at line "lnum" in the current buffer.
2636 * Must be called AFTER the change and after mark_adjust().
2637 * Takes care of marking the buffer to be redrawn and sets the changed flag.
2638 */
2639 void
2640deleted_lines(lnum, count)
2641 linenr_T lnum;
2642 long count;
2643{
2644 changed_lines(lnum, 0, lnum + count, -count);
2645}
2646
2647/*
2648 * Like deleted_lines(), but adjust marks first.
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002649 * Make sure the cursor is on a valid line before calling, a GUI callback may
2650 * be triggered to display the cursor.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002651 */
2652 void
2653deleted_lines_mark(lnum, count)
2654 linenr_T lnum;
2655 long count;
2656{
2657 mark_adjust(lnum, (linenr_T)(lnum + count - 1), (long)MAXLNUM, -count);
2658 changed_lines(lnum, 0, lnum + count, -count);
2659}
2660
2661/*
2662 * Changed lines for the current buffer.
2663 * Must be called AFTER the change and after mark_adjust().
2664 * - mark the buffer changed by calling changed()
2665 * - mark the windows on this buffer to be redisplayed
2666 * - invalidate cached values
2667 * "lnum" is the first line that needs displaying, "lnume" the first line
2668 * below the changed lines (BEFORE the change).
2669 * When only inserting lines, "lnum" and "lnume" are equal.
2670 * Takes care of calling changed() and updating b_mod_*.
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002671 * Careful: may trigger autocommands that reload the buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002672 */
2673 void
2674changed_lines(lnum, col, lnume, xtra)
2675 linenr_T lnum; /* first line with change */
2676 colnr_T col; /* column in first line with change */
2677 linenr_T lnume; /* line below last changed line */
2678 long xtra; /* number of extra lines (negative when deleting) */
2679{
Bram Moolenaardba8a912005-04-24 22:08:39 +00002680 changed_lines_buf(curbuf, lnum, lnume, xtra);
2681
2682#ifdef FEAT_DIFF
2683 if (xtra == 0 && curwin->w_p_diff)
2684 {
2685 /* When the number of lines doesn't change then mark_adjust() isn't
2686 * called and other diff buffers still need to be marked for
2687 * displaying. */
2688 win_T *wp;
2689 linenr_T wlnum;
2690
2691 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2692 if (wp->w_p_diff && wp != curwin)
2693 {
2694 redraw_win_later(wp, VALID);
2695 wlnum = diff_lnum_win(lnum, wp);
2696 if (wlnum > 0)
2697 changed_lines_buf(wp->w_buffer, wlnum,
2698 lnume - lnum + wlnum, 0L);
2699 }
2700 }
2701#endif
2702
2703 changed_common(lnum, col, lnume, xtra);
2704}
2705
2706 static void
2707changed_lines_buf(buf, lnum, lnume, xtra)
2708 buf_T *buf;
2709 linenr_T lnum; /* first line with change */
2710 linenr_T lnume; /* line below last changed line */
2711 long xtra; /* number of extra lines (negative when deleting) */
2712{
2713 if (buf->b_mod_set)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002714 {
2715 /* find the maximum area that must be redisplayed */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002716 if (lnum < buf->b_mod_top)
2717 buf->b_mod_top = lnum;
2718 if (lnum < buf->b_mod_bot)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002719 {
2720 /* adjust old bot position for xtra lines */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002721 buf->b_mod_bot += xtra;
2722 if (buf->b_mod_bot < lnum)
2723 buf->b_mod_bot = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002724 }
Bram Moolenaardba8a912005-04-24 22:08:39 +00002725 if (lnume + xtra > buf->b_mod_bot)
2726 buf->b_mod_bot = lnume + xtra;
2727 buf->b_mod_xlines += xtra;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002728 }
2729 else
2730 {
2731 /* set the area that must be redisplayed */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002732 buf->b_mod_set = TRUE;
2733 buf->b_mod_top = lnum;
2734 buf->b_mod_bot = lnume + xtra;
2735 buf->b_mod_xlines = xtra;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002736 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002737}
2738
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002739/*
2740 * Common code for when a change is was made.
2741 * See changed_lines() for the arguments.
2742 * Careful: may trigger autocommands that reload the buffer.
2743 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002744 static void
2745changed_common(lnum, col, lnume, xtra)
2746 linenr_T lnum;
2747 colnr_T col;
2748 linenr_T lnume;
2749 long xtra;
2750{
2751 win_T *wp;
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00002752#ifdef FEAT_WINDOWS
2753 tabpage_T *tp;
2754#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002755 int i;
2756#ifdef FEAT_JUMPLIST
2757 int cols;
2758 pos_T *p;
2759 int add;
2760#endif
2761
2762 /* mark the buffer as modified */
2763 changed();
2764
2765 /* set the '. mark */
2766 if (!cmdmod.keepjumps)
2767 {
2768 curbuf->b_last_change.lnum = lnum;
2769 curbuf->b_last_change.col = col;
2770
2771#ifdef FEAT_JUMPLIST
2772 /* Create a new entry if a new undo-able change was started or we
2773 * don't have an entry yet. */
2774 if (curbuf->b_new_change || curbuf->b_changelistlen == 0)
2775 {
2776 if (curbuf->b_changelistlen == 0)
2777 add = TRUE;
2778 else
2779 {
2780 /* Don't create a new entry when the line number is the same
2781 * as the last one and the column is not too far away. Avoids
2782 * creating many entries for typing "xxxxx". */
2783 p = &curbuf->b_changelist[curbuf->b_changelistlen - 1];
2784 if (p->lnum != lnum)
2785 add = TRUE;
2786 else
2787 {
2788 cols = comp_textwidth(FALSE);
2789 if (cols == 0)
2790 cols = 79;
2791 add = (p->col + cols < col || col + cols < p->col);
2792 }
2793 }
2794 if (add)
2795 {
2796 /* This is the first of a new sequence of undo-able changes
2797 * and it's at some distance of the last change. Use a new
2798 * position in the changelist. */
2799 curbuf->b_new_change = FALSE;
2800
2801 if (curbuf->b_changelistlen == JUMPLISTSIZE)
2802 {
2803 /* changelist is full: remove oldest entry */
2804 curbuf->b_changelistlen = JUMPLISTSIZE - 1;
2805 mch_memmove(curbuf->b_changelist, curbuf->b_changelist + 1,
2806 sizeof(pos_T) * (JUMPLISTSIZE - 1));
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00002807 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002808 {
2809 /* Correct position in changelist for other windows on
2810 * this buffer. */
2811 if (wp->w_buffer == curbuf && wp->w_changelistidx > 0)
2812 --wp->w_changelistidx;
2813 }
2814 }
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00002815 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002816 {
2817 /* For other windows, if the position in the changelist is
2818 * at the end it stays at the end. */
2819 if (wp->w_buffer == curbuf
2820 && wp->w_changelistidx == curbuf->b_changelistlen)
2821 ++wp->w_changelistidx;
2822 }
2823 ++curbuf->b_changelistlen;
2824 }
2825 }
2826 curbuf->b_changelist[curbuf->b_changelistlen - 1] =
2827 curbuf->b_last_change;
2828 /* The current window is always after the last change, so that "g,"
2829 * takes you back to it. */
2830 curwin->w_changelistidx = curbuf->b_changelistlen;
2831#endif
2832 }
2833
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00002834 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002835 {
2836 if (wp->w_buffer == curbuf)
2837 {
2838 /* Mark this window to be redrawn later. */
2839 if (wp->w_redr_type < VALID)
2840 wp->w_redr_type = VALID;
2841
2842 /* Check if a change in the buffer has invalidated the cached
2843 * values for the cursor. */
2844#ifdef FEAT_FOLDING
2845 /*
2846 * Update the folds for this window. Can't postpone this, because
2847 * a following operator might work on the whole fold: ">>dd".
2848 */
2849 foldUpdate(wp, lnum, lnume + xtra - 1);
2850
2851 /* The change may cause lines above or below the change to become
2852 * included in a fold. Set lnum/lnume to the first/last line that
2853 * might be displayed differently.
2854 * Set w_cline_folded here as an efficient way to update it when
2855 * inserting lines just above a closed fold. */
2856 i = hasFoldingWin(wp, lnum, &lnum, NULL, FALSE, NULL);
2857 if (wp->w_cursor.lnum == lnum)
2858 wp->w_cline_folded = i;
2859 i = hasFoldingWin(wp, lnume, NULL, &lnume, FALSE, NULL);
2860 if (wp->w_cursor.lnum == lnume)
2861 wp->w_cline_folded = i;
2862
2863 /* If the changed line is in a range of previously folded lines,
2864 * compare with the first line in that range. */
2865 if (wp->w_cursor.lnum <= lnum)
2866 {
2867 i = find_wl_entry(wp, lnum);
2868 if (i >= 0 && wp->w_cursor.lnum > wp->w_lines[i].wl_lnum)
2869 changed_line_abv_curs_win(wp);
2870 }
2871#endif
2872
2873 if (wp->w_cursor.lnum > lnum)
2874 changed_line_abv_curs_win(wp);
2875 else if (wp->w_cursor.lnum == lnum && wp->w_cursor.col >= col)
2876 changed_cline_bef_curs_win(wp);
2877 if (wp->w_botline >= lnum)
2878 {
2879 /* Assume that botline doesn't change (inserted lines make
2880 * other lines scroll down below botline). */
2881 approximate_botline_win(wp);
2882 }
2883
2884 /* Check if any w_lines[] entries have become invalid.
2885 * For entries below the change: Correct the lnums for
2886 * inserted/deleted lines. Makes it possible to stop displaying
2887 * after the change. */
2888 for (i = 0; i < wp->w_lines_valid; ++i)
2889 if (wp->w_lines[i].wl_valid)
2890 {
2891 if (wp->w_lines[i].wl_lnum >= lnum)
2892 {
2893 if (wp->w_lines[i].wl_lnum < lnume)
2894 {
2895 /* line included in change */
2896 wp->w_lines[i].wl_valid = FALSE;
2897 }
2898 else if (xtra != 0)
2899 {
2900 /* line below change */
2901 wp->w_lines[i].wl_lnum += xtra;
2902#ifdef FEAT_FOLDING
2903 wp->w_lines[i].wl_lastlnum += xtra;
2904#endif
2905 }
2906 }
2907#ifdef FEAT_FOLDING
2908 else if (wp->w_lines[i].wl_lastlnum >= lnum)
2909 {
2910 /* change somewhere inside this range of folded lines,
2911 * may need to be redrawn */
2912 wp->w_lines[i].wl_valid = FALSE;
2913 }
2914#endif
2915 }
Bram Moolenaar3234cc62009-11-03 17:47:12 +00002916
2917#ifdef FEAT_FOLDING
2918 /* Take care of side effects for setting w_topline when folds have
2919 * changed. Esp. when the buffer was changed in another window. */
2920 if (hasAnyFolding(wp))
2921 set_topline(wp, wp->w_topline);
2922#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002923 }
2924 }
2925
2926 /* Call update_screen() later, which checks out what needs to be redrawn,
2927 * since it notices b_mod_set and then uses b_mod_*. */
2928 if (must_redraw < VALID)
2929 must_redraw = VALID;
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002930
2931#ifdef FEAT_AUTOCMD
2932 /* when the cursor line is changed always trigger CursorMoved */
Bram Moolenaare163f1c2006-10-17 09:12:21 +00002933 if (lnum <= curwin->w_cursor.lnum
2934 && lnume + (xtra < 0 ? -xtra : xtra) > curwin->w_cursor.lnum)
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002935 last_cursormoved.lnum = 0;
2936#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002937}
2938
2939/*
2940 * unchanged() is called when the changed flag must be reset for buffer 'buf'
2941 */
2942 void
2943unchanged(buf, ff)
2944 buf_T *buf;
2945 int ff; /* also reset 'fileformat' */
2946{
Bram Moolenaar164c60f2011-01-22 00:11:50 +01002947 if (buf->b_changed || (ff && file_ff_differs(buf, FALSE)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002948 {
2949 buf->b_changed = 0;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002950 ml_setflags(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002951 if (ff)
2952 save_file_ff(buf);
2953#ifdef FEAT_WINDOWS
2954 check_status(buf);
Bram Moolenaar997fb4b2006-02-17 21:53:23 +00002955 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002956#endif
2957#ifdef FEAT_TITLE
2958 need_maketitle = TRUE; /* set window title later */
2959#endif
2960 }
2961 ++buf->b_changedtick;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002962#ifdef FEAT_NETBEANS_INTG
2963 netbeans_unmodified(buf);
2964#endif
2965}
2966
2967#if defined(FEAT_WINDOWS) || defined(PROTO)
2968/*
2969 * check_status: called when the status bars for the buffer 'buf'
2970 * need to be updated
2971 */
2972 void
2973check_status(buf)
2974 buf_T *buf;
2975{
2976 win_T *wp;
2977
2978 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2979 if (wp->w_buffer == buf && wp->w_status_height)
2980 {
2981 wp->w_redr_status = TRUE;
2982 if (must_redraw < VALID)
2983 must_redraw = VALID;
2984 }
2985}
2986#endif
2987
2988/*
2989 * If the file is readonly, give a warning message with the first change.
2990 * Don't do this for autocommands.
2991 * Don't use emsg(), because it flushes the macro buffer.
Bram Moolenaard5cdbeb2005-10-10 20:59:28 +00002992 * If we have undone all changes b_changed will be FALSE, but "b_did_warn"
Bram Moolenaar071d4272004-06-13 20:20:40 +00002993 * will be TRUE.
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002994 * Careful: may trigger autocommands that reload the buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002995 */
2996 void
2997change_warning(col)
2998 int col; /* column for message; non-zero when in insert
2999 mode and 'showmode' is on */
3000{
Bram Moolenaar496c5262009-03-18 14:42:00 +00003001 static char *w_readonly = N_("W10: Warning: Changing a readonly file");
3002
Bram Moolenaar071d4272004-06-13 20:20:40 +00003003 if (curbuf->b_did_warn == FALSE
3004 && curbufIsChanged() == 0
3005#ifdef FEAT_AUTOCMD
3006 && !autocmd_busy
3007#endif
3008 && curbuf->b_p_ro)
3009 {
3010#ifdef FEAT_AUTOCMD
Bram Moolenaar910f66f2006-04-05 20:41:53 +00003011 ++curbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003012 apply_autocmds(EVENT_FILECHANGEDRO, NULL, NULL, FALSE, curbuf);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00003013 --curbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003014 if (!curbuf->b_p_ro)
3015 return;
3016#endif
3017 /*
3018 * Do what msg() does, but with a column offset if the warning should
3019 * be after the mode message.
3020 */
3021 msg_start();
3022 if (msg_row == Rows - 1)
3023 msg_col = col;
Bram Moolenaar2df6dcc2004-07-12 15:53:54 +00003024 msg_source(hl_attr(HLF_W));
Bram Moolenaar496c5262009-03-18 14:42:00 +00003025 MSG_PUTS_ATTR(_(w_readonly), hl_attr(HLF_W) | MSG_HIST);
3026#ifdef FEAT_EVAL
3027 set_vim_var_string(VV_WARNINGMSG, (char_u *)_(w_readonly), -1);
3028#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003029 msg_clr_eos();
3030 (void)msg_end();
3031 if (msg_silent == 0 && !silent_mode)
3032 {
3033 out_flush();
3034 ui_delay(1000L, TRUE); /* give the user time to think about it */
3035 }
3036 curbuf->b_did_warn = TRUE;
3037 redraw_cmdline = FALSE; /* don't redraw and erase the message */
3038 if (msg_row < Rows - 1)
3039 showmode();
3040 }
3041}
3042
3043/*
3044 * Ask for a reply from the user, a 'y' or a 'n'.
3045 * No other characters are accepted, the message is repeated until a valid
3046 * reply is entered or CTRL-C is hit.
3047 * If direct is TRUE, don't use vgetc() but ui_inchar(), don't get characters
3048 * from any buffers but directly from the user.
3049 *
3050 * return the 'y' or 'n'
3051 */
3052 int
3053ask_yesno(str, direct)
3054 char_u *str;
3055 int direct;
3056{
3057 int r = ' ';
3058 int save_State = State;
3059
3060 if (exiting) /* put terminal in raw mode for this question */
3061 settmode(TMODE_RAW);
3062 ++no_wait_return;
3063#ifdef USE_ON_FLY_SCROLL
3064 dont_scroll = TRUE; /* disallow scrolling here */
3065#endif
3066 State = CONFIRM; /* mouse behaves like with :confirm */
3067#ifdef FEAT_MOUSE
3068 setmouse(); /* disables mouse for xterm */
3069#endif
3070 ++no_mapping;
3071 ++allow_keys; /* no mapping here, but recognize keys */
3072
3073 while (r != 'y' && r != 'n')
3074 {
3075 /* same highlighting as for wait_return */
3076 smsg_attr(hl_attr(HLF_R), (char_u *)"%s (y/n)?", str);
3077 if (direct)
3078 r = get_keystroke();
3079 else
Bram Moolenaar913626c2008-01-03 11:43:42 +00003080 r = plain_vgetc();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003081 if (r == Ctrl_C || r == ESC)
3082 r = 'n';
3083 msg_putchar(r); /* show what you typed */
3084 out_flush();
3085 }
3086 --no_wait_return;
3087 State = save_State;
3088#ifdef FEAT_MOUSE
3089 setmouse();
3090#endif
3091 --no_mapping;
3092 --allow_keys;
3093
3094 return r;
3095}
3096
3097/*
3098 * Get a key stroke directly from the user.
3099 * Ignores mouse clicks and scrollbar events, except a click for the left
3100 * button (used at the more prompt).
3101 * Doesn't use vgetc(), because it syncs undo and eats mapped characters.
3102 * Disadvantage: typeahead is ignored.
3103 * Translates the interrupt character for unix to ESC.
3104 */
3105 int
3106get_keystroke()
3107{
3108#define CBUFLEN 151
3109 char_u buf[CBUFLEN];
3110 int len = 0;
3111 int n;
3112 int save_mapped_ctrl_c = mapped_ctrl_c;
Bram Moolenaar4395a712006-09-05 18:57:57 +00003113 int waited = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003114
3115 mapped_ctrl_c = FALSE; /* mappings are not used here */
3116 for (;;)
3117 {
3118 cursor_on();
3119 out_flush();
3120
3121 /* First time: blocking wait. Second time: wait up to 100ms for a
3122 * terminal code to complete. Leave some room for check_termcode() to
3123 * insert a key code into (max 5 chars plus NUL). And
3124 * fix_input_buffer() can triple the number of bytes. */
3125 n = ui_inchar(buf + len, (CBUFLEN - 6 - len) / 3,
3126 len == 0 ? -1L : 100L, 0);
3127 if (n > 0)
3128 {
3129 /* Replace zero and CSI by a special key code. */
3130 n = fix_input_buffer(buf + len, n, FALSE);
3131 len += n;
Bram Moolenaar4395a712006-09-05 18:57:57 +00003132 waited = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003133 }
Bram Moolenaar4395a712006-09-05 18:57:57 +00003134 else if (len > 0)
3135 ++waited; /* keep track of the waiting time */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003136
Bram Moolenaar4395a712006-09-05 18:57:57 +00003137 /* Incomplete termcode and not timed out yet: get more characters */
3138 if ((n = check_termcode(1, buf, len)) < 0
3139 && (!p_ttimeout || waited * 100L < (p_ttm < 0 ? p_tm : p_ttm)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003140 continue;
Bram Moolenaar4395a712006-09-05 18:57:57 +00003141
Bram Moolenaar946ffd42010-12-30 12:30:31 +01003142 if (n == KEYLEN_REMOVED) /* key code removed */
Bram Moolenaar6eb634e2011-03-03 15:04:08 +01003143 {
Bram Moolenaarfd30cd42011-03-22 13:07:26 +01003144 if (must_redraw != 0 && !need_wait_return && (State & CMDLINE) == 0)
Bram Moolenaar6eb634e2011-03-03 15:04:08 +01003145 {
3146 /* Redrawing was postponed, do it now. */
3147 update_screen(0);
3148 setcursor(); /* put cursor back where it belongs */
3149 }
Bram Moolenaar946ffd42010-12-30 12:30:31 +01003150 continue;
Bram Moolenaar6eb634e2011-03-03 15:04:08 +01003151 }
Bram Moolenaar946ffd42010-12-30 12:30:31 +01003152 if (n > 0) /* found a termcode: adjust length */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003153 len = n;
Bram Moolenaar946ffd42010-12-30 12:30:31 +01003154 if (len == 0) /* nothing typed yet */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003155 continue;
3156
3157 /* Handle modifier and/or special key code. */
3158 n = buf[0];
3159 if (n == K_SPECIAL)
3160 {
3161 n = TO_SPECIAL(buf[1], buf[2]);
3162 if (buf[1] == KS_MODIFIER
3163 || n == K_IGNORE
3164#ifdef FEAT_MOUSE
3165 || n == K_LEFTMOUSE_NM
3166 || n == K_LEFTDRAG
3167 || n == K_LEFTRELEASE
3168 || n == K_LEFTRELEASE_NM
3169 || n == K_MIDDLEMOUSE
3170 || n == K_MIDDLEDRAG
3171 || n == K_MIDDLERELEASE
3172 || n == K_RIGHTMOUSE
3173 || n == K_RIGHTDRAG
3174 || n == K_RIGHTRELEASE
3175 || n == K_MOUSEDOWN
3176 || n == K_MOUSEUP
Bram Moolenaar8d9b40e2010-07-25 15:49:07 +02003177 || n == K_MOUSELEFT
3178 || n == K_MOUSERIGHT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003179 || n == K_X1MOUSE
3180 || n == K_X1DRAG
3181 || n == K_X1RELEASE
3182 || n == K_X2MOUSE
3183 || n == K_X2DRAG
3184 || n == K_X2RELEASE
3185# ifdef FEAT_GUI
3186 || n == K_VER_SCROLLBAR
3187 || n == K_HOR_SCROLLBAR
3188# endif
3189#endif
3190 )
3191 {
3192 if (buf[1] == KS_MODIFIER)
3193 mod_mask = buf[2];
3194 len -= 3;
3195 if (len > 0)
3196 mch_memmove(buf, buf + 3, (size_t)len);
3197 continue;
3198 }
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00003199 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003200 }
3201#ifdef FEAT_MBYTE
3202 if (has_mbyte)
3203 {
3204 if (MB_BYTE2LEN(n) > len)
3205 continue; /* more bytes to get */
3206 buf[len >= CBUFLEN ? CBUFLEN - 1 : len] = NUL;
3207 n = (*mb_ptr2char)(buf);
3208 }
3209#endif
3210#ifdef UNIX
3211 if (n == intr_char)
3212 n = ESC;
3213#endif
3214 break;
3215 }
3216
3217 mapped_ctrl_c = save_mapped_ctrl_c;
3218 return n;
3219}
3220
3221/*
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003222 * Get a number from the user.
3223 * When "mouse_used" is not NULL allow using the mouse.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003224 */
3225 int
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003226get_number(colon, mouse_used)
3227 int colon; /* allow colon to abort */
3228 int *mouse_used;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003229{
3230 int n = 0;
3231 int c;
Bram Moolenaar3991dab2006-03-27 17:01:56 +00003232 int typed = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003233
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003234 if (mouse_used != NULL)
3235 *mouse_used = FALSE;
3236
Bram Moolenaar071d4272004-06-13 20:20:40 +00003237 /* When not printing messages, the user won't know what to type, return a
3238 * zero (as if CR was hit). */
3239 if (msg_silent != 0)
3240 return 0;
3241
3242#ifdef USE_ON_FLY_SCROLL
3243 dont_scroll = TRUE; /* disallow scrolling here */
3244#endif
3245 ++no_mapping;
3246 ++allow_keys; /* no mapping here, but recognize keys */
3247 for (;;)
3248 {
3249 windgoto(msg_row, msg_col);
3250 c = safe_vgetc();
3251 if (VIM_ISDIGIT(c))
3252 {
3253 n = n * 10 + c - '0';
3254 msg_putchar(c);
Bram Moolenaar3991dab2006-03-27 17:01:56 +00003255 ++typed;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003256 }
3257 else if (c == K_DEL || c == K_KDEL || c == K_BS || c == Ctrl_H)
3258 {
Bram Moolenaar3991dab2006-03-27 17:01:56 +00003259 if (typed > 0)
3260 {
3261 MSG_PUTS("\b \b");
3262 --typed;
3263 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003264 n /= 10;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003265 }
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003266#ifdef FEAT_MOUSE
3267 else if (mouse_used != NULL && c == K_LEFTMOUSE)
3268 {
3269 *mouse_used = TRUE;
3270 n = mouse_row + 1;
3271 break;
3272 }
3273#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003274 else if (n == 0 && c == ':' && colon)
3275 {
3276 stuffcharReadbuff(':');
3277 if (!exmode_active)
3278 cmdline_row = msg_row;
3279 skip_redraw = TRUE; /* skip redraw once */
3280 do_redraw = FALSE;
3281 break;
3282 }
3283 else if (c == CAR || c == NL || c == Ctrl_C || c == ESC)
3284 break;
3285 }
3286 --no_mapping;
3287 --allow_keys;
3288 return n;
3289}
3290
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003291/*
3292 * Ask the user to enter a number.
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003293 * When "mouse_used" is not NULL allow using the mouse and in that case return
3294 * the line number.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003295 */
3296 int
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003297prompt_for_number(mouse_used)
3298 int *mouse_used;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003299{
3300 int i;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003301 int save_cmdline_row;
3302 int save_State;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003303
3304 /* When using ":silent" assume that <CR> was entered. */
Bram Moolenaar42eeac32005-06-29 22:40:58 +00003305 if (mouse_used != NULL)
Bram Moolenaard812df62008-11-09 12:46:09 +00003306 MSG_PUTS(_("Type number and <Enter> or click with mouse (empty cancels): "));
Bram Moolenaar42eeac32005-06-29 22:40:58 +00003307 else
Bram Moolenaard812df62008-11-09 12:46:09 +00003308 MSG_PUTS(_("Type number and <Enter> (empty cancels): "));
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003309
Bram Moolenaar203335e2006-09-03 14:35:42 +00003310 /* Set the state such that text can be selected/copied/pasted and we still
3311 * get mouse events. */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003312 save_cmdline_row = cmdline_row;
Bram Moolenaar203335e2006-09-03 14:35:42 +00003313 cmdline_row = 0;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003314 save_State = State;
Bram Moolenaar203335e2006-09-03 14:35:42 +00003315 State = CMDLINE;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003316
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003317 i = get_number(TRUE, mouse_used);
3318 if (KeyTyped)
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003319 {
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003320 /* don't call wait_return() now */
3321 /* msg_putchar('\n'); */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003322 cmdline_row = msg_row - 1;
3323 need_wait_return = FALSE;
3324 msg_didany = FALSE;
Bram Moolenaarb2450162009-07-22 09:04:20 +00003325 msg_didout = FALSE;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003326 }
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003327 else
3328 cmdline_row = save_cmdline_row;
3329 State = save_State;
3330
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003331 return i;
3332}
3333
Bram Moolenaar071d4272004-06-13 20:20:40 +00003334 void
3335msgmore(n)
3336 long n;
3337{
3338 long pn;
3339
3340 if (global_busy /* no messages now, wait until global is finished */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003341 || !messaging()) /* 'lazyredraw' set, don't do messages now */
3342 return;
3343
Bram Moolenaar7df2d662005-01-25 22:18:08 +00003344 /* We don't want to overwrite another important message, but do overwrite
3345 * a previous "more lines" or "fewer lines" message, so that "5dd" and
3346 * then "put" reports the last action. */
3347 if (keep_msg != NULL && !keep_msg_more)
3348 return;
3349
Bram Moolenaar071d4272004-06-13 20:20:40 +00003350 if (n > 0)
3351 pn = n;
3352 else
3353 pn = -n;
3354
3355 if (pn > p_report)
3356 {
3357 if (pn == 1)
3358 {
3359 if (n > 0)
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003360 vim_strncpy(msg_buf, (char_u *)_("1 more line"),
3361 MSG_BUF_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003362 else
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003363 vim_strncpy(msg_buf, (char_u *)_("1 line less"),
3364 MSG_BUF_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003365 }
3366 else
3367 {
3368 if (n > 0)
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003369 vim_snprintf((char *)msg_buf, MSG_BUF_LEN,
3370 _("%ld more lines"), pn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003371 else
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003372 vim_snprintf((char *)msg_buf, MSG_BUF_LEN,
3373 _("%ld fewer lines"), pn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003374 }
3375 if (got_int)
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003376 vim_strcat(msg_buf, (char_u *)_(" (Interrupted)"), MSG_BUF_LEN);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003377 if (msg(msg_buf))
3378 {
Bram Moolenaar238a5642006-02-21 22:12:05 +00003379 set_keep_msg(msg_buf, 0);
Bram Moolenaar7df2d662005-01-25 22:18:08 +00003380 keep_msg_more = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003381 }
3382 }
3383}
3384
3385/*
3386 * flush map and typeahead buffers and give a warning for an error
3387 */
3388 void
3389beep_flush()
3390{
3391 if (emsg_silent == 0)
3392 {
3393 flush_buffers(FALSE);
3394 vim_beep();
3395 }
3396}
3397
3398/*
3399 * give a warning for an error
3400 */
3401 void
3402vim_beep()
3403{
3404 if (emsg_silent == 0)
3405 {
3406 if (p_vb
3407#ifdef FEAT_GUI
3408 /* While the GUI is starting up the termcap is set for the GUI
3409 * but the output still goes to a terminal. */
3410 && !(gui.in_use && gui.starting)
3411#endif
3412 )
3413 {
3414 out_str(T_VB);
3415 }
3416 else
3417 {
3418#ifdef MSDOS
3419 /*
3420 * The number of beeps outputted is reduced to avoid having to wait
3421 * for all the beeps to finish. This is only a problem on systems
3422 * where the beeps don't overlap.
3423 */
3424 if (beep_count == 0 || beep_count == 10)
3425 {
3426 out_char(BELL);
3427 beep_count = 1;
3428 }
3429 else
3430 ++beep_count;
3431#else
3432 out_char(BELL);
3433#endif
3434 }
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003435
3436 /* When 'verbose' is set and we are sourcing a script or executing a
3437 * function give the user a hint where the beep comes from. */
3438 if (vim_strchr(p_debug, 'e') != NULL)
3439 {
3440 msg_source(hl_attr(HLF_W));
3441 msg_attr((char_u *)_("Beep!"), hl_attr(HLF_W));
3442 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003443 }
3444}
3445
3446/*
3447 * To get the "real" home directory:
3448 * - get value of $HOME
3449 * For Unix:
3450 * - go to that directory
3451 * - do mch_dirname() to get the real name of that directory.
3452 * This also works with mounts and links.
3453 * Don't do this for MS-DOS, it will change the "current dir" for a drive.
3454 */
3455static char_u *homedir = NULL;
3456
3457 void
3458init_homedir()
3459{
3460 char_u *var;
3461
Bram Moolenaar05159a02005-02-26 23:04:13 +00003462 /* In case we are called a second time (when 'encoding' changes). */
3463 vim_free(homedir);
3464 homedir = NULL;
3465
Bram Moolenaar071d4272004-06-13 20:20:40 +00003466#ifdef VMS
3467 var = mch_getenv((char_u *)"SYS$LOGIN");
3468#else
3469 var = mch_getenv((char_u *)"HOME");
3470#endif
3471
3472 if (var != NULL && *var == NUL) /* empty is same as not set */
3473 var = NULL;
3474
3475#ifdef WIN3264
3476 /*
3477 * Weird but true: $HOME may contain an indirect reference to another
3478 * variable, esp. "%USERPROFILE%". Happens when $USERPROFILE isn't set
3479 * when $HOME is being set.
3480 */
3481 if (var != NULL && *var == '%')
3482 {
3483 char_u *p;
3484 char_u *exp;
3485
3486 p = vim_strchr(var + 1, '%');
3487 if (p != NULL)
3488 {
Bram Moolenaarce0842a2005-07-18 21:58:11 +00003489 vim_strncpy(NameBuff, var + 1, p - (var + 1));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003490 exp = mch_getenv(NameBuff);
3491 if (exp != NULL && *exp != NUL
3492 && STRLEN(exp) + STRLEN(p) < MAXPATHL)
3493 {
Bram Moolenaar555b2802005-05-19 21:08:39 +00003494 vim_snprintf((char *)NameBuff, MAXPATHL, "%s%s", exp, p + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003495 var = NameBuff;
3496 /* Also set $HOME, it's needed for _viminfo. */
3497 vim_setenv((char_u *)"HOME", NameBuff);
3498 }
3499 }
3500 }
3501
3502 /*
3503 * Typically, $HOME is not defined on Windows, unless the user has
3504 * specifically defined it for Vim's sake. However, on Windows NT
3505 * platforms, $HOMEDRIVE and $HOMEPATH are automatically defined for
3506 * each user. Try constructing $HOME from these.
3507 */
3508 if (var == NULL)
3509 {
3510 char_u *homedrive, *homepath;
3511
3512 homedrive = mch_getenv((char_u *)"HOMEDRIVE");
3513 homepath = mch_getenv((char_u *)"HOMEPATH");
Bram Moolenaar6f977012010-01-06 17:53:38 +01003514 if (homepath == NULL || *homepath == NUL)
3515 homepath = "\\";
3516 if (homedrive != NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00003517 && STRLEN(homedrive) + STRLEN(homepath) < MAXPATHL)
3518 {
3519 sprintf((char *)NameBuff, "%s%s", homedrive, homepath);
3520 if (NameBuff[0] != NUL)
3521 {
3522 var = NameBuff;
3523 /* Also set $HOME, it's needed for _viminfo. */
3524 vim_setenv((char_u *)"HOME", NameBuff);
3525 }
3526 }
3527 }
Bram Moolenaar05159a02005-02-26 23:04:13 +00003528
3529# if defined(FEAT_MBYTE)
3530 if (enc_utf8 && var != NULL)
3531 {
3532 int len;
Bram Moolenaarb453a532011-04-28 17:48:44 +02003533 char_u *pp = NULL;
Bram Moolenaar05159a02005-02-26 23:04:13 +00003534
3535 /* Convert from active codepage to UTF-8. Other conversions are
3536 * not done, because they would fail for non-ASCII characters. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003537 acp_to_enc(var, (int)STRLEN(var), &pp, &len);
Bram Moolenaar05159a02005-02-26 23:04:13 +00003538 if (pp != NULL)
3539 {
3540 homedir = pp;
3541 return;
3542 }
3543 }
3544# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003545#endif
3546
3547#if defined(OS2) || defined(MSDOS) || defined(MSWIN)
3548 /*
3549 * Default home dir is C:/
3550 * Best assumption we can make in such a situation.
3551 */
3552 if (var == NULL)
3553 var = "C:/";
3554#endif
3555 if (var != NULL)
3556 {
3557#ifdef UNIX
3558 /*
3559 * Change to the directory and get the actual path. This resolves
3560 * links. Don't do it when we can't return.
3561 */
3562 if (mch_dirname(NameBuff, MAXPATHL) == OK
3563 && mch_chdir((char *)NameBuff) == 0)
3564 {
3565 if (!mch_chdir((char *)var) && mch_dirname(IObuff, IOSIZE) == OK)
3566 var = IObuff;
3567 if (mch_chdir((char *)NameBuff) != 0)
3568 EMSG(_(e_prev_dir));
3569 }
3570#endif
3571 homedir = vim_strsave(var);
3572 }
3573}
3574
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003575#if defined(EXITFREE) || defined(PROTO)
3576 void
3577free_homedir()
3578{
3579 vim_free(homedir);
3580}
3581#endif
3582
Bram Moolenaar071d4272004-06-13 20:20:40 +00003583/*
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003584 * Call expand_env() and store the result in an allocated string.
3585 * This is not very memory efficient, this expects the result to be freed
3586 * again soon.
3587 */
3588 char_u *
3589expand_env_save(src)
3590 char_u *src;
3591{
3592 return expand_env_save_opt(src, FALSE);
3593}
3594
3595/*
3596 * Idem, but when "one" is TRUE handle the string as one file name, only
3597 * expand "~" at the start.
3598 */
3599 char_u *
3600expand_env_save_opt(src, one)
3601 char_u *src;
3602 int one;
3603{
3604 char_u *p;
3605
3606 p = alloc(MAXPATHL);
3607 if (p != NULL)
3608 expand_env_esc(src, p, MAXPATHL, FALSE, one, NULL);
3609 return p;
3610}
3611
3612/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003613 * Expand environment variable with path name.
3614 * "~/" is also expanded, using $HOME. For Unix "~user/" is expanded.
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003615 * Skips over "\ ", "\~" and "\$" (not for Win32 though).
Bram Moolenaar071d4272004-06-13 20:20:40 +00003616 * If anything fails no expansion is done and dst equals src.
3617 */
3618 void
3619expand_env(src, dst, dstlen)
3620 char_u *src; /* input string e.g. "$HOME/vim.hlp" */
3621 char_u *dst; /* where to put the result */
3622 int dstlen; /* maximum length of the result */
3623{
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003624 expand_env_esc(src, dst, dstlen, FALSE, FALSE, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003625}
3626
3627 void
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003628expand_env_esc(srcp, dst, dstlen, esc, one, startstr)
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003629 char_u *srcp; /* input string e.g. "$HOME/vim.hlp" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003630 char_u *dst; /* where to put the result */
3631 int dstlen; /* maximum length of the result */
3632 int esc; /* escape spaces in expanded variables */
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003633 int one; /* "srcp" is one file name */
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003634 char_u *startstr; /* start again after this (can be NULL) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003635{
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003636 char_u *src;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003637 char_u *tail;
3638 int c;
3639 char_u *var;
3640 int copy_char;
3641 int mustfree; /* var was allocated, need to free it later */
3642 int at_start = TRUE; /* at start of a name */
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003643 int startstr_len = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003644
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003645 if (startstr != NULL)
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003646 startstr_len = (int)STRLEN(startstr);
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003647
3648 src = skipwhite(srcp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003649 --dstlen; /* leave one char space for "\," */
3650 while (*src && dstlen > 0)
3651 {
3652 copy_char = TRUE;
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003653 if ((*src == '$'
3654#ifdef VMS
3655 && at_start
3656#endif
3657 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003658#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3659 || *src == '%'
3660#endif
3661 || (*src == '~' && at_start))
3662 {
3663 mustfree = FALSE;
3664
3665 /*
3666 * The variable name is copied into dst temporarily, because it may
3667 * be a string in read-only memory and a NUL needs to be appended.
3668 */
3669 if (*src != '~') /* environment var */
3670 {
3671 tail = src + 1;
3672 var = dst;
3673 c = dstlen - 1;
3674
3675#ifdef UNIX
3676 /* Unix has ${var-name} type environment vars */
3677 if (*tail == '{' && !vim_isIDc('{'))
3678 {
3679 tail++; /* ignore '{' */
3680 while (c-- > 0 && *tail && *tail != '}')
3681 *var++ = *tail++;
3682 }
3683 else
3684#endif
3685 {
3686 while (c-- > 0 && *tail != NUL && ((vim_isIDc(*tail))
3687#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3688 || (*src == '%' && *tail != '%')
3689#endif
3690 ))
3691 {
3692#ifdef OS2 /* env vars only in uppercase */
3693 *var++ = TOUPPER_LOC(*tail);
3694 tail++; /* toupper() may be a macro! */
3695#else
3696 *var++ = *tail++;
3697#endif
3698 }
3699 }
3700
3701#if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
3702# ifdef UNIX
3703 if (src[1] == '{' && *tail != '}')
3704# else
3705 if (*src == '%' && *tail != '%')
3706# endif
3707 var = NULL;
3708 else
3709 {
3710# ifdef UNIX
3711 if (src[1] == '{')
3712# else
3713 if (*src == '%')
3714#endif
3715 ++tail;
3716#endif
3717 *var = NUL;
3718 var = vim_getenv(dst, &mustfree);
3719#if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
3720 }
3721#endif
3722 }
3723 /* home directory */
3724 else if ( src[1] == NUL
3725 || vim_ispathsep(src[1])
3726 || vim_strchr((char_u *)" ,\t\n", src[1]) != NULL)
3727 {
3728 var = homedir;
3729 tail = src + 1;
3730 }
3731 else /* user directory */
3732 {
3733#if defined(UNIX) || (defined(VMS) && defined(USER_HOME))
3734 /*
3735 * Copy ~user to dst[], so we can put a NUL after it.
3736 */
3737 tail = src;
3738 var = dst;
3739 c = dstlen - 1;
3740 while ( c-- > 0
3741 && *tail
3742 && vim_isfilec(*tail)
3743 && !vim_ispathsep(*tail))
3744 *var++ = *tail++;
3745 *var = NUL;
3746# ifdef UNIX
3747 /*
3748 * If the system supports getpwnam(), use it.
3749 * Otherwise, or if getpwnam() fails, the shell is used to
3750 * expand ~user. This is slower and may fail if the shell
3751 * does not support ~user (old versions of /bin/sh).
3752 */
3753# if defined(HAVE_GETPWNAM) && defined(HAVE_PWD_H)
3754 {
3755 struct passwd *pw;
3756
Bram Moolenaara40ceaf2006-01-13 22:35:40 +00003757 /* Note: memory allocated by getpwnam() is never freed.
3758 * Calling endpwent() apparently doesn't help. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003759 pw = getpwnam((char *)dst + 1);
3760 if (pw != NULL)
3761 var = (char_u *)pw->pw_dir;
3762 else
3763 var = NULL;
3764 }
3765 if (var == NULL)
3766# endif
3767 {
3768 expand_T xpc;
3769
3770 ExpandInit(&xpc);
3771 xpc.xp_context = EXPAND_FILES;
3772 var = ExpandOne(&xpc, dst, NULL,
3773 WILD_ADD_SLASH|WILD_SILENT, WILD_EXPAND_FREE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003774 mustfree = TRUE;
3775 }
3776
3777# else /* !UNIX, thus VMS */
3778 /*
3779 * USER_HOME is a comma-separated list of
3780 * directories to search for the user account in.
3781 */
3782 {
3783 char_u test[MAXPATHL], paths[MAXPATHL];
3784 char_u *path, *next_path, *ptr;
3785 struct stat st;
3786
3787 STRCPY(paths, USER_HOME);
3788 next_path = paths;
3789 while (*next_path)
3790 {
3791 for (path = next_path; *next_path && *next_path != ',';
3792 next_path++);
3793 if (*next_path)
3794 *next_path++ = NUL;
3795 STRCPY(test, path);
3796 STRCAT(test, "/");
3797 STRCAT(test, dst + 1);
3798 if (mch_stat(test, &st) == 0)
3799 {
3800 var = alloc(STRLEN(test) + 1);
3801 STRCPY(var, test);
3802 mustfree = TRUE;
3803 break;
3804 }
3805 }
3806 }
3807# endif /* UNIX */
3808#else
3809 /* cannot expand user's home directory, so don't try */
3810 var = NULL;
3811 tail = (char_u *)""; /* for gcc */
3812#endif /* UNIX || VMS */
3813 }
3814
3815#ifdef BACKSLASH_IN_FILENAME
3816 /* If 'shellslash' is set change backslashes to forward slashes.
3817 * Can't use slash_adjust(), p_ssl may be set temporarily. */
3818 if (p_ssl && var != NULL && vim_strchr(var, '\\') != NULL)
3819 {
3820 char_u *p = vim_strsave(var);
3821
3822 if (p != NULL)
3823 {
3824 if (mustfree)
3825 vim_free(var);
3826 var = p;
3827 mustfree = TRUE;
3828 forward_slash(var);
3829 }
3830 }
3831#endif
3832
3833 /* If "var" contains white space, escape it with a backslash.
3834 * Required for ":e ~/tt" when $HOME includes a space. */
3835 if (esc && var != NULL && vim_strpbrk(var, (char_u *)" \t") != NULL)
3836 {
3837 char_u *p = vim_strsave_escaped(var, (char_u *)" \t");
3838
3839 if (p != NULL)
3840 {
3841 if (mustfree)
3842 vim_free(var);
3843 var = p;
3844 mustfree = TRUE;
3845 }
3846 }
3847
3848 if (var != NULL && *var != NUL
3849 && (STRLEN(var) + STRLEN(tail) + 1 < (unsigned)dstlen))
3850 {
3851 STRCPY(dst, var);
3852 dstlen -= (int)STRLEN(var);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003853 c = (int)STRLEN(var);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003854 /* if var[] ends in a path separator and tail[] starts
3855 * with it, skip a character */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003856 if (*var != NUL && after_pathsep(dst, dst + c)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003857#if defined(BACKSLASH_IN_FILENAME) || defined(AMIGA)
3858 && dst[-1] != ':'
3859#endif
3860 && vim_ispathsep(*tail))
3861 ++tail;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003862 dst += c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003863 src = tail;
3864 copy_char = FALSE;
3865 }
3866 if (mustfree)
3867 vim_free(var);
3868 }
3869
3870 if (copy_char) /* copy at least one char */
3871 {
3872 /*
Bram Moolenaar25394022007-05-10 19:06:20 +00003873 * Recognize the start of a new name, for '~'.
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003874 * Don't do this when "one" is TRUE, to avoid expanding "~" in
3875 * ":edit foo ~ foo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00003876 */
3877 at_start = FALSE;
3878 if (src[0] == '\\' && src[1] != NUL)
3879 {
3880 *dst++ = *src++;
3881 --dstlen;
3882 }
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003883 else if ((src[0] == ' ' || src[0] == ',') && !one)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003884 at_start = TRUE;
3885 *dst++ = *src++;
3886 --dstlen;
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003887
3888 if (startstr != NULL && src - startstr_len >= srcp
3889 && STRNCMP(src - startstr_len, startstr, startstr_len) == 0)
3890 at_start = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003891 }
3892 }
3893 *dst = NUL;
3894}
3895
3896/*
3897 * Vim's version of getenv().
3898 * Special handling of $HOME, $VIM and $VIMRUNTIME.
Bram Moolenaar2f6b0b82005-03-08 22:43:10 +00003899 * Also does ACP to 'enc' conversion for Win32.
Bram Moolenaarb453a532011-04-28 17:48:44 +02003900 * "mustfree" is set to TRUE when returned is allocated, it must be
3901 * initialized to FALSE by the caller.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003902 */
3903 char_u *
3904vim_getenv(name, mustfree)
3905 char_u *name;
Bram Moolenaarb453a532011-04-28 17:48:44 +02003906 int *mustfree;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003907{
3908 char_u *p;
3909 char_u *pend;
3910 int vimruntime;
3911
3912#if defined(OS2) || defined(MSDOS) || defined(MSWIN)
3913 /* use "C:/" when $HOME is not set */
3914 if (STRCMP(name, "HOME") == 0)
3915 return homedir;
3916#endif
3917
3918 p = mch_getenv(name);
3919 if (p != NULL && *p == NUL) /* empty is the same as not set */
3920 p = NULL;
3921
3922 if (p != NULL)
Bram Moolenaar05159a02005-02-26 23:04:13 +00003923 {
3924#if defined(FEAT_MBYTE) && defined(WIN3264)
3925 if (enc_utf8)
3926 {
3927 int len;
Bram Moolenaarb453a532011-04-28 17:48:44 +02003928 char_u *pp = NULL;
Bram Moolenaar05159a02005-02-26 23:04:13 +00003929
3930 /* Convert from active codepage to UTF-8. Other conversions are
3931 * not done, because they would fail for non-ASCII characters. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003932 acp_to_enc(p, (int)STRLEN(p), &pp, &len);
Bram Moolenaar05159a02005-02-26 23:04:13 +00003933 if (pp != NULL)
3934 {
3935 p = pp;
3936 *mustfree = TRUE;
3937 }
3938 }
3939#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003940 return p;
Bram Moolenaar05159a02005-02-26 23:04:13 +00003941 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003942
3943 vimruntime = (STRCMP(name, "VIMRUNTIME") == 0);
3944 if (!vimruntime && STRCMP(name, "VIM") != 0)
3945 return NULL;
3946
3947 /*
3948 * When expanding $VIMRUNTIME fails, try using $VIM/vim<version> or $VIM.
3949 * Don't do this when default_vimruntime_dir is non-empty.
3950 */
3951 if (vimruntime
3952#ifdef HAVE_PATHDEF
3953 && *default_vimruntime_dir == NUL
3954#endif
3955 )
3956 {
3957 p = mch_getenv((char_u *)"VIM");
3958 if (p != NULL && *p == NUL) /* empty is the same as not set */
3959 p = NULL;
3960 if (p != NULL)
3961 {
3962 p = vim_version_dir(p);
3963 if (p != NULL)
3964 *mustfree = TRUE;
3965 else
3966 p = mch_getenv((char_u *)"VIM");
Bram Moolenaar05159a02005-02-26 23:04:13 +00003967
3968#if defined(FEAT_MBYTE) && defined(WIN3264)
3969 if (enc_utf8)
3970 {
3971 int len;
Bram Moolenaarb453a532011-04-28 17:48:44 +02003972 char_u *pp = NULL;
Bram Moolenaar05159a02005-02-26 23:04:13 +00003973
3974 /* Convert from active codepage to UTF-8. Other conversions
3975 * are not done, because they would fail for non-ASCII
3976 * characters. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003977 acp_to_enc(p, (int)STRLEN(p), &pp, &len);
Bram Moolenaar05159a02005-02-26 23:04:13 +00003978 if (pp != NULL)
3979 {
Bram Moolenaarb453a532011-04-28 17:48:44 +02003980 if (*mustfree)
Bram Moolenaar05159a02005-02-26 23:04:13 +00003981 vim_free(p);
3982 p = pp;
3983 *mustfree = TRUE;
3984 }
3985 }
3986#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003987 }
3988 }
3989
3990 /*
3991 * When expanding $VIM or $VIMRUNTIME fails, try using:
3992 * - the directory name from 'helpfile' (unless it contains '$')
3993 * - the executable name from argv[0]
3994 */
3995 if (p == NULL)
3996 {
3997 if (p_hf != NULL && vim_strchr(p_hf, '$') == NULL)
3998 p = p_hf;
3999#ifdef USE_EXE_NAME
4000 /*
4001 * Use the name of the executable, obtained from argv[0].
4002 */
4003 else
4004 p = exe_name;
4005#endif
4006 if (p != NULL)
4007 {
4008 /* remove the file name */
4009 pend = gettail(p);
4010
4011 /* remove "doc/" from 'helpfile', if present */
4012 if (p == p_hf)
4013 pend = remove_tail(p, pend, (char_u *)"doc");
4014
4015#ifdef USE_EXE_NAME
4016# ifdef MACOS_X
Bram Moolenaar95e9b492006-03-15 23:04:43 +00004017 /* remove "MacOS" from exe_name and add "Resources/vim" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004018 if (p == exe_name)
4019 {
4020 char_u *pend1;
Bram Moolenaar95e9b492006-03-15 23:04:43 +00004021 char_u *pnew;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004022
Bram Moolenaar95e9b492006-03-15 23:04:43 +00004023 pend1 = remove_tail(p, pend, (char_u *)"MacOS");
4024 if (pend1 != pend)
4025 {
4026 pnew = alloc((unsigned)(pend1 - p) + 15);
4027 if (pnew != NULL)
4028 {
4029 STRNCPY(pnew, p, (pend1 - p));
4030 STRCPY(pnew + (pend1 - p), "Resources/vim");
4031 p = pnew;
4032 pend = p + STRLEN(p);
4033 }
4034 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004035 }
4036# endif
4037 /* remove "src/" from exe_name, if present */
4038 if (p == exe_name)
4039 pend = remove_tail(p, pend, (char_u *)"src");
4040#endif
4041
4042 /* for $VIM, remove "runtime/" or "vim54/", if present */
4043 if (!vimruntime)
4044 {
4045 pend = remove_tail(p, pend, (char_u *)RUNTIME_DIRNAME);
4046 pend = remove_tail(p, pend, (char_u *)VIM_VERSION_NODOT);
4047 }
4048
4049 /* remove trailing path separator */
4050#ifndef MACOS_CLASSIC
4051 /* With MacOS path (with colons) the final colon is required */
Bram Moolenaare21877a2008-02-13 09:58:14 +00004052 /* to avoid confusion between absolute and relative path */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004053 if (pend > p && after_pathsep(p, pend))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004054 --pend;
4055#endif
4056
Bram Moolenaar95e9b492006-03-15 23:04:43 +00004057#ifdef MACOS_X
4058 if (p == exe_name || p == p_hf)
4059#endif
4060 /* check that the result is a directory name */
4061 p = vim_strnsave(p, (int)(pend - p));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004062
4063 if (p != NULL && !mch_isdir(p))
4064 {
4065 vim_free(p);
4066 p = NULL;
4067 }
4068 else
4069 {
4070#ifdef USE_EXE_NAME
4071 /* may add "/vim54" or "/runtime" if it exists */
4072 if (vimruntime && (pend = vim_version_dir(p)) != NULL)
4073 {
4074 vim_free(p);
4075 p = pend;
4076 }
4077#endif
4078 *mustfree = TRUE;
4079 }
4080 }
4081 }
4082
4083#ifdef HAVE_PATHDEF
4084 /* When there is a pathdef.c file we can use default_vim_dir and
4085 * default_vimruntime_dir */
4086 if (p == NULL)
4087 {
4088 /* Only use default_vimruntime_dir when it is not empty */
4089 if (vimruntime && *default_vimruntime_dir != NUL)
4090 {
4091 p = default_vimruntime_dir;
4092 *mustfree = FALSE;
4093 }
4094 else if (*default_vim_dir != NUL)
4095 {
4096 if (vimruntime && (p = vim_version_dir(default_vim_dir)) != NULL)
4097 *mustfree = TRUE;
4098 else
4099 {
4100 p = default_vim_dir;
4101 *mustfree = FALSE;
4102 }
4103 }
4104 }
4105#endif
4106
4107 /*
4108 * Set the environment variable, so that the new value can be found fast
4109 * next time, and others can also use it (e.g. Perl).
4110 */
4111 if (p != NULL)
4112 {
4113 if (vimruntime)
4114 {
4115 vim_setenv((char_u *)"VIMRUNTIME", p);
4116 didset_vimruntime = TRUE;
4117#ifdef FEAT_GETTEXT
4118 {
Bram Moolenaard6754642005-01-17 22:18:45 +00004119 char_u *buf = concat_str(p, (char_u *)"/lang");
Bram Moolenaar071d4272004-06-13 20:20:40 +00004120
4121 if (buf != NULL)
4122 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004123 bindtextdomain(VIMPACKAGE, (char *)buf);
4124 vim_free(buf);
4125 }
4126 }
4127#endif
4128 }
4129 else
4130 {
4131 vim_setenv((char_u *)"VIM", p);
4132 didset_vim = TRUE;
4133 }
4134 }
4135 return p;
4136}
4137
4138/*
4139 * Check if the directory "vimdir/<version>" or "vimdir/runtime" exists.
4140 * Return NULL if not, return its name in allocated memory otherwise.
4141 */
4142 static char_u *
4143vim_version_dir(vimdir)
4144 char_u *vimdir;
4145{
4146 char_u *p;
4147
4148 if (vimdir == NULL || *vimdir == NUL)
4149 return NULL;
4150 p = concat_fnames(vimdir, (char_u *)VIM_VERSION_NODOT, TRUE);
4151 if (p != NULL && mch_isdir(p))
4152 return p;
4153 vim_free(p);
4154 p = concat_fnames(vimdir, (char_u *)RUNTIME_DIRNAME, TRUE);
4155 if (p != NULL && mch_isdir(p))
4156 return p;
4157 vim_free(p);
4158 return NULL;
4159}
4160
4161/*
4162 * If the string between "p" and "pend" ends in "name/", return "pend" minus
4163 * the length of "name/". Otherwise return "pend".
4164 */
4165 static char_u *
4166remove_tail(p, pend, name)
4167 char_u *p;
4168 char_u *pend;
4169 char_u *name;
4170{
4171 int len = (int)STRLEN(name) + 1;
4172 char_u *newend = pend - len;
4173
4174 if (newend >= p
4175 && fnamencmp(newend, name, len - 1) == 0
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004176 && (newend == p || after_pathsep(p, newend)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004177 return newend;
4178 return pend;
4179}
4180
Bram Moolenaar071d4272004-06-13 20:20:40 +00004181/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004182 * Our portable version of setenv.
4183 */
4184 void
4185vim_setenv(name, val)
4186 char_u *name;
4187 char_u *val;
4188{
4189#ifdef HAVE_SETENV
4190 mch_setenv((char *)name, (char *)val, 1);
4191#else
4192 char_u *envbuf;
4193
4194 /*
4195 * Putenv does not copy the string, it has to remain
4196 * valid. The allocated memory will never be freed.
4197 */
4198 envbuf = alloc((unsigned)(STRLEN(name) + STRLEN(val) + 2));
4199 if (envbuf != NULL)
4200 {
4201 sprintf((char *)envbuf, "%s=%s", name, val);
4202 putenv((char *)envbuf);
4203 }
4204#endif
4205}
4206
4207#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
4208/*
4209 * Function given to ExpandGeneric() to obtain an environment variable name.
4210 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004211 char_u *
4212get_env_name(xp, idx)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00004213 expand_T *xp UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004214 int idx;
4215{
4216# if defined(AMIGA) || defined(__MRC__) || defined(__SC__)
4217 /*
4218 * No environ[] on the Amiga and on the Mac (using MPW).
4219 */
4220 return NULL;
4221# else
4222# ifndef __WIN32__
4223 /* Borland C++ 5.2 has this in a header file. */
4224 extern char **environ;
4225# endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00004226# define ENVNAMELEN 100
4227 static char_u name[ENVNAMELEN];
Bram Moolenaar071d4272004-06-13 20:20:40 +00004228 char_u *str;
4229 int n;
4230
4231 str = (char_u *)environ[idx];
4232 if (str == NULL)
4233 return NULL;
4234
Bram Moolenaar21cf8232004-07-16 20:18:37 +00004235 for (n = 0; n < ENVNAMELEN - 1; ++n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004236 {
4237 if (str[n] == '=' || str[n] == NUL)
4238 break;
4239 name[n] = str[n];
4240 }
4241 name[n] = NUL;
4242 return name;
4243# endif
4244}
4245#endif
4246
4247/*
4248 * Replace home directory by "~" in each space or comma separated file name in
4249 * 'src'.
4250 * If anything fails (except when out of space) dst equals src.
4251 */
4252 void
4253home_replace(buf, src, dst, dstlen, one)
4254 buf_T *buf; /* when not NULL, check for help files */
4255 char_u *src; /* input file name */
4256 char_u *dst; /* where to put the result */
4257 int dstlen; /* maximum length of the result */
4258 int one; /* if TRUE, only replace one file name, include
4259 spaces and commas in the file name. */
4260{
4261 size_t dirlen = 0, envlen = 0;
4262 size_t len;
4263 char_u *homedir_env;
4264 char_u *p;
4265
4266 if (src == NULL)
4267 {
4268 *dst = NUL;
4269 return;
4270 }
4271
4272 /*
4273 * If the file is a help file, remove the path completely.
4274 */
4275 if (buf != NULL && buf->b_help)
4276 {
4277 STRCPY(dst, gettail(src));
4278 return;
4279 }
4280
4281 /*
4282 * We check both the value of the $HOME environment variable and the
4283 * "real" home directory.
4284 */
4285 if (homedir != NULL)
4286 dirlen = STRLEN(homedir);
4287
4288#ifdef VMS
4289 homedir_env = mch_getenv((char_u *)"SYS$LOGIN");
4290#else
4291 homedir_env = mch_getenv((char_u *)"HOME");
4292#endif
4293
4294 if (homedir_env != NULL && *homedir_env == NUL)
4295 homedir_env = NULL;
4296 if (homedir_env != NULL)
4297 envlen = STRLEN(homedir_env);
4298
4299 if (!one)
4300 src = skipwhite(src);
4301 while (*src && dstlen > 0)
4302 {
4303 /*
4304 * Here we are at the beginning of a file name.
4305 * First, check to see if the beginning of the file name matches
4306 * $HOME or the "real" home directory. Check that there is a '/'
4307 * after the match (so that if e.g. the file is "/home/pieter/bla",
4308 * and the home directory is "/home/piet", the file does not end up
4309 * as "~er/bla" (which would seem to indicate the file "bla" in user
4310 * er's home directory)).
4311 */
4312 p = homedir;
4313 len = dirlen;
4314 for (;;)
4315 {
4316 if ( len
4317 && fnamencmp(src, p, len) == 0
4318 && (vim_ispathsep(src[len])
4319 || (!one && (src[len] == ',' || src[len] == ' '))
4320 || src[len] == NUL))
4321 {
4322 src += len;
4323 if (--dstlen > 0)
4324 *dst++ = '~';
4325
4326 /*
4327 * If it's just the home directory, add "/".
4328 */
4329 if (!vim_ispathsep(src[0]) && --dstlen > 0)
4330 *dst++ = '/';
4331 break;
4332 }
4333 if (p == homedir_env)
4334 break;
4335 p = homedir_env;
4336 len = envlen;
4337 }
4338
4339 /* if (!one) skip to separator: space or comma */
4340 while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
4341 *dst++ = *src++;
4342 /* skip separator */
4343 while ((*src == ' ' || *src == ',') && --dstlen > 0)
4344 *dst++ = *src++;
4345 }
4346 /* if (dstlen == 0) out of space, what to do??? */
4347
4348 *dst = NUL;
4349}
4350
4351/*
4352 * Like home_replace, store the replaced string in allocated memory.
4353 * When something fails, NULL is returned.
4354 */
4355 char_u *
4356home_replace_save(buf, src)
4357 buf_T *buf; /* when not NULL, check for help files */
4358 char_u *src; /* input file name */
4359{
4360 char_u *dst;
4361 unsigned len;
4362
4363 len = 3; /* space for "~/" and trailing NUL */
4364 if (src != NULL) /* just in case */
4365 len += (unsigned)STRLEN(src);
4366 dst = alloc(len);
4367 if (dst != NULL)
4368 home_replace(buf, src, dst, len, TRUE);
4369 return dst;
4370}
4371
4372/*
4373 * Compare two file names and return:
4374 * FPC_SAME if they both exist and are the same file.
4375 * FPC_SAMEX if they both don't exist and have the same file name.
4376 * FPC_DIFF if they both exist and are different files.
4377 * FPC_NOTX if they both don't exist.
4378 * FPC_DIFFX if one of them doesn't exist.
4379 * For the first name environment variables are expanded
4380 */
4381 int
4382fullpathcmp(s1, s2, checkname)
4383 char_u *s1, *s2;
4384 int checkname; /* when both don't exist, check file names */
4385{
4386#ifdef UNIX
4387 char_u exp1[MAXPATHL];
4388 char_u full1[MAXPATHL];
4389 char_u full2[MAXPATHL];
4390 struct stat st1, st2;
4391 int r1, r2;
4392
4393 expand_env(s1, exp1, MAXPATHL);
4394 r1 = mch_stat((char *)exp1, &st1);
4395 r2 = mch_stat((char *)s2, &st2);
4396 if (r1 != 0 && r2 != 0)
4397 {
4398 /* if mch_stat() doesn't work, may compare the names */
4399 if (checkname)
4400 {
4401 if (fnamecmp(exp1, s2) == 0)
4402 return FPC_SAMEX;
4403 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4404 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4405 if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
4406 return FPC_SAMEX;
4407 }
4408 return FPC_NOTX;
4409 }
4410 if (r1 != 0 || r2 != 0)
4411 return FPC_DIFFX;
4412 if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
4413 return FPC_SAME;
4414 return FPC_DIFF;
4415#else
4416 char_u *exp1; /* expanded s1 */
4417 char_u *full1; /* full path of s1 */
4418 char_u *full2; /* full path of s2 */
4419 int retval = FPC_DIFF;
4420 int r1, r2;
4421
4422 /* allocate one buffer to store three paths (alloc()/free() is slow!) */
4423 if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
4424 {
4425 full1 = exp1 + MAXPATHL;
4426 full2 = full1 + MAXPATHL;
4427
4428 expand_env(s1, exp1, MAXPATHL);
4429 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4430 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4431
4432 /* If vim_FullName() fails, the file probably doesn't exist. */
4433 if (r1 != OK && r2 != OK)
4434 {
4435 if (checkname && fnamecmp(exp1, s2) == 0)
4436 retval = FPC_SAMEX;
4437 else
4438 retval = FPC_NOTX;
4439 }
4440 else if (r1 != OK || r2 != OK)
4441 retval = FPC_DIFFX;
4442 else if (fnamecmp(full1, full2))
4443 retval = FPC_DIFF;
4444 else
4445 retval = FPC_SAME;
4446 vim_free(exp1);
4447 }
4448 return retval;
4449#endif
4450}
4451
4452/*
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004453 * Get the tail of a path: the file name.
Bram Moolenaar31710262010-08-13 13:36:15 +02004454 * When the path ends in a path separator the tail is the NUL after it.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004455 * Fail safe: never returns NULL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004456 */
4457 char_u *
4458gettail(fname)
4459 char_u *fname;
4460{
4461 char_u *p1, *p2;
4462
4463 if (fname == NULL)
4464 return (char_u *)"";
4465 for (p1 = p2 = fname; *p2; ) /* find last part of path */
4466 {
4467 if (vim_ispathsep(*p2))
4468 p1 = p2 + 1;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004469 mb_ptr_adv(p2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004470 }
4471 return p1;
4472}
4473
Bram Moolenaar31710262010-08-13 13:36:15 +02004474#if defined(FEAT_SEARCHPATH)
4475static char_u *gettail_dir __ARGS((char_u *fname));
4476
4477/*
4478 * Return the end of the directory name, on the first path
4479 * separator:
4480 * "/path/file", "/path/dir/", "/path//dir", "/file"
4481 * ^ ^ ^ ^
4482 */
4483 static char_u *
4484gettail_dir(fname)
4485 char_u *fname;
4486{
4487 char_u *dir_end = fname;
4488 char_u *next_dir_end = fname;
4489 int look_for_sep = TRUE;
4490 char_u *p;
4491
4492 for (p = fname; *p != NUL; )
4493 {
4494 if (vim_ispathsep(*p))
4495 {
4496 if (look_for_sep)
4497 {
4498 next_dir_end = p;
4499 look_for_sep = FALSE;
4500 }
4501 }
4502 else
4503 {
4504 if (!look_for_sep)
4505 dir_end = next_dir_end;
4506 look_for_sep = TRUE;
4507 }
4508 mb_ptr_adv(p);
4509 }
4510 return dir_end;
4511}
4512#endif
4513
Bram Moolenaar071d4272004-06-13 20:20:40 +00004514/*
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004515 * Get pointer to tail of "fname", including path separators. Putting a NUL
4516 * here leaves the directory name. Takes care of "c:/" and "//".
4517 * Always returns a valid pointer.
4518 */
4519 char_u *
4520gettail_sep(fname)
4521 char_u *fname;
4522{
4523 char_u *p;
4524 char_u *t;
4525
4526 p = get_past_head(fname); /* don't remove the '/' from "c:/file" */
4527 t = gettail(fname);
4528 while (t > p && after_pathsep(fname, t))
4529 --t;
4530#ifdef VMS
4531 /* path separator is part of the path */
4532 ++t;
4533#endif
4534 return t;
4535}
4536
4537/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004538 * get the next path component (just after the next path separator).
4539 */
4540 char_u *
4541getnextcomp(fname)
4542 char_u *fname;
4543{
4544 while (*fname && !vim_ispathsep(*fname))
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004545 mb_ptr_adv(fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004546 if (*fname)
4547 ++fname;
4548 return fname;
4549}
4550
Bram Moolenaar071d4272004-06-13 20:20:40 +00004551/*
4552 * Get a pointer to one character past the head of a path name.
4553 * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
4554 * If there is no head, path is returned.
4555 */
4556 char_u *
4557get_past_head(path)
4558 char_u *path;
4559{
4560 char_u *retval;
4561
4562#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
4563 /* may skip "c:" */
4564 if (isalpha(path[0]) && path[1] == ':')
4565 retval = path + 2;
4566 else
4567 retval = path;
4568#else
4569# if defined(AMIGA)
4570 /* may skip "label:" */
4571 retval = vim_strchr(path, ':');
4572 if (retval == NULL)
4573 retval = path;
4574# else /* Unix */
4575 retval = path;
4576# endif
4577#endif
4578
4579 while (vim_ispathsep(*retval))
4580 ++retval;
4581
4582 return retval;
4583}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004584
4585/*
4586 * return TRUE if 'c' is a path separator.
4587 */
4588 int
4589vim_ispathsep(c)
4590 int c;
4591{
Bram Moolenaare60acc12011-05-10 16:41:25 +02004592#ifdef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00004593 return (c == '/'); /* UNIX has ':' inside file names */
Bram Moolenaare60acc12011-05-10 16:41:25 +02004594#else
4595# ifdef BACKSLASH_IN_FILENAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00004596 return (c == ':' || c == '/' || c == '\\');
Bram Moolenaare60acc12011-05-10 16:41:25 +02004597# else
4598# ifdef VMS
Bram Moolenaar071d4272004-06-13 20:20:40 +00004599 /* server"user passwd"::device:[full.path.name]fname.extension;version" */
4600 return (c == ':' || c == '[' || c == ']' || c == '/'
4601 || c == '<' || c == '>' || c == '"' );
Bram Moolenaare60acc12011-05-10 16:41:25 +02004602# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004603 return (c == ':' || c == '/');
Bram Moolenaare60acc12011-05-10 16:41:25 +02004604# endif /* VMS */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004605# endif
Bram Moolenaare60acc12011-05-10 16:41:25 +02004606#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004607}
4608
4609#if defined(FEAT_SEARCHPATH) || defined(PROTO)
4610/*
4611 * return TRUE if 'c' is a path list separator.
4612 */
4613 int
4614vim_ispathlistsep(c)
4615 int c;
4616{
4617#ifdef UNIX
4618 return (c == ':');
4619#else
Bram Moolenaar25394022007-05-10 19:06:20 +00004620 return (c == ';'); /* might not be right for every system... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004621#endif
4622}
4623#endif
4624
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004625#if defined(FEAT_GUI_TABLINE) || defined(FEAT_WINDOWS) \
4626 || defined(FEAT_EVAL) || defined(PROTO)
4627/*
4628 * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
4629 * It's done in-place.
4630 */
4631 void
4632shorten_dir(str)
4633 char_u *str;
4634{
4635 char_u *tail, *s, *d;
4636 int skip = FALSE;
4637
4638 tail = gettail(str);
4639 d = str;
4640 for (s = str; ; ++s)
4641 {
4642 if (s >= tail) /* copy the whole tail */
4643 {
4644 *d++ = *s;
4645 if (*s == NUL)
4646 break;
4647 }
4648 else if (vim_ispathsep(*s)) /* copy '/' and next char */
4649 {
4650 *d++ = *s;
4651 skip = FALSE;
4652 }
4653 else if (!skip)
4654 {
4655 *d++ = *s; /* copy next char */
4656 if (*s != '~' && *s != '.') /* and leading "~" and "." */
4657 skip = TRUE;
4658# ifdef FEAT_MBYTE
4659 if (has_mbyte)
4660 {
4661 int l = mb_ptr2len(s);
4662
4663 while (--l > 0)
Bram Moolenaarb6baca52006-08-15 20:24:14 +00004664 *d++ = *++s;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004665 }
4666# endif
4667 }
4668 }
4669}
4670#endif
4671
Bram Moolenaar900b4d72005-12-12 22:05:50 +00004672/*
4673 * Return TRUE if the directory of "fname" exists, FALSE otherwise.
4674 * Also returns TRUE if there is no directory name.
4675 * "fname" must be writable!.
4676 */
4677 int
4678dir_of_file_exists(fname)
4679 char_u *fname;
4680{
4681 char_u *p;
4682 int c;
4683 int retval;
4684
4685 p = gettail_sep(fname);
4686 if (p == fname)
4687 return TRUE;
4688 c = *p;
4689 *p = NUL;
4690 retval = mch_isdir(fname);
4691 *p = c;
4692 return retval;
4693}
4694
Bram Moolenaar071d4272004-06-13 20:20:40 +00004695#if (defined(CASE_INSENSITIVE_FILENAME) && defined(BACKSLASH_IN_FILENAME)) \
4696 || defined(PROTO)
4697/*
4698 * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally.
4699 */
4700 int
4701vim_fnamecmp(x, y)
4702 char_u *x, *y;
4703{
4704 return vim_fnamencmp(x, y, MAXPATHL);
4705}
4706
4707 int
4708vim_fnamencmp(x, y, len)
4709 char_u *x, *y;
4710 size_t len;
4711{
4712 while (len > 0 && *x && *y)
4713 {
4714 if (TOLOWER_LOC(*x) != TOLOWER_LOC(*y)
4715 && !(*x == '/' && *y == '\\')
4716 && !(*x == '\\' && *y == '/'))
4717 break;
4718 ++x;
4719 ++y;
4720 --len;
4721 }
4722 if (len == 0)
4723 return 0;
4724 return (*x - *y);
4725}
4726#endif
4727
4728/*
4729 * Concatenate file names fname1 and fname2 into allocated memory.
Bram Moolenaar25394022007-05-10 19:06:20 +00004730 * Only add a '/' or '\\' when 'sep' is TRUE and it is necessary.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004731 */
4732 char_u *
4733concat_fnames(fname1, fname2, sep)
4734 char_u *fname1;
4735 char_u *fname2;
4736 int sep;
4737{
4738 char_u *dest;
4739
4740 dest = alloc((unsigned)(STRLEN(fname1) + STRLEN(fname2) + 3));
4741 if (dest != NULL)
4742 {
4743 STRCPY(dest, fname1);
4744 if (sep)
4745 add_pathsep(dest);
4746 STRCAT(dest, fname2);
4747 }
4748 return dest;
4749}
4750
Bram Moolenaard6754642005-01-17 22:18:45 +00004751/*
4752 * Concatenate two strings and return the result in allocated memory.
4753 * Returns NULL when out of memory.
4754 */
4755 char_u *
4756concat_str(str1, str2)
4757 char_u *str1;
4758 char_u *str2;
4759{
4760 char_u *dest;
4761 size_t l = STRLEN(str1);
4762
4763 dest = alloc((unsigned)(l + STRLEN(str2) + 1L));
4764 if (dest != NULL)
4765 {
4766 STRCPY(dest, str1);
4767 STRCPY(dest + l, str2);
4768 }
4769 return dest;
4770}
Bram Moolenaard6754642005-01-17 22:18:45 +00004771
Bram Moolenaar071d4272004-06-13 20:20:40 +00004772/*
4773 * Add a path separator to a file name, unless it already ends in a path
4774 * separator.
4775 */
4776 void
4777add_pathsep(p)
4778 char_u *p;
4779{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004780 if (*p != NUL && !after_pathsep(p, p + STRLEN(p)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004781 STRCAT(p, PATHSEPSTR);
4782}
4783
4784/*
4785 * FullName_save - Make an allocated copy of a full file name.
4786 * Returns NULL when out of memory.
4787 */
4788 char_u *
4789FullName_save(fname, force)
4790 char_u *fname;
4791 int force; /* force expansion, even when it already looks
4792 like a full path name */
4793{
4794 char_u *buf;
4795 char_u *new_fname = NULL;
4796
4797 if (fname == NULL)
4798 return NULL;
4799
4800 buf = alloc((unsigned)MAXPATHL);
4801 if (buf != NULL)
4802 {
4803 if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
4804 new_fname = vim_strsave(buf);
4805 else
4806 new_fname = vim_strsave(fname);
4807 vim_free(buf);
4808 }
4809 return new_fname;
4810}
4811
4812#if defined(FEAT_CINDENT) || defined(FEAT_SYN_HL)
4813
4814static char_u *skip_string __ARGS((char_u *p));
4815
4816/*
4817 * Find the start of a comment, not knowing if we are in a comment right now.
4818 * Search starts at w_cursor.lnum and goes backwards.
4819 */
4820 pos_T *
4821find_start_comment(ind_maxcomment) /* XXX */
4822 int ind_maxcomment;
4823{
4824 pos_T *pos;
4825 char_u *line;
4826 char_u *p;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00004827 int cur_maxcomment = ind_maxcomment;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004828
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00004829 for (;;)
4830 {
4831 pos = findmatchlimit(NULL, '*', FM_BACKWARD, cur_maxcomment);
4832 if (pos == NULL)
4833 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004834
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00004835 /*
4836 * Check if the comment start we found is inside a string.
4837 * If it is then restrict the search to below this line and try again.
4838 */
4839 line = ml_get(pos->lnum);
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00004840 for (p = line; *p && (colnr_T)(p - line) < pos->col; ++p)
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00004841 p = skip_string(p);
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00004842 if ((colnr_T)(p - line) <= pos->col)
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00004843 break;
4844 cur_maxcomment = curwin->w_cursor.lnum - pos->lnum - 1;
4845 if (cur_maxcomment <= 0)
4846 {
4847 pos = NULL;
4848 break;
4849 }
4850 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004851 return pos;
4852}
4853
4854/*
4855 * Skip to the end of a "string" and a 'c' character.
4856 * If there is no string or character, return argument unmodified.
4857 */
4858 static char_u *
4859skip_string(p)
4860 char_u *p;
4861{
4862 int i;
4863
4864 /*
4865 * We loop, because strings may be concatenated: "date""time".
4866 */
4867 for ( ; ; ++p)
4868 {
4869 if (p[0] == '\'') /* 'c' or '\n' or '\000' */
4870 {
4871 if (!p[1]) /* ' at end of line */
4872 break;
4873 i = 2;
4874 if (p[1] == '\\') /* '\n' or '\000' */
4875 {
4876 ++i;
4877 while (vim_isdigit(p[i - 1])) /* '\000' */
4878 ++i;
4879 }
4880 if (p[i] == '\'') /* check for trailing ' */
4881 {
4882 p += i;
4883 continue;
4884 }
4885 }
4886 else if (p[0] == '"') /* start of string */
4887 {
4888 for (++p; p[0]; ++p)
4889 {
4890 if (p[0] == '\\' && p[1] != NUL)
4891 ++p;
4892 else if (p[0] == '"') /* end of string */
4893 break;
4894 }
4895 if (p[0] == '"')
4896 continue;
4897 }
4898 break; /* no string found */
4899 }
4900 if (!*p)
4901 --p; /* backup from NUL */
4902 return p;
4903}
4904#endif /* FEAT_CINDENT || FEAT_SYN_HL */
4905
4906#if defined(FEAT_CINDENT) || defined(PROTO)
4907
4908/*
4909 * Do C or expression indenting on the current line.
4910 */
4911 void
4912do_c_expr_indent()
4913{
4914# ifdef FEAT_EVAL
4915 if (*curbuf->b_p_inde != NUL)
4916 fixthisline(get_expr_indent);
4917 else
4918# endif
4919 fixthisline(get_c_indent);
4920}
4921
4922/*
4923 * Functions for C-indenting.
4924 * Most of this originally comes from Eric Fischer.
4925 */
4926/*
4927 * Below "XXX" means that this function may unlock the current line.
4928 */
4929
4930static char_u *cin_skipcomment __ARGS((char_u *));
4931static int cin_nocode __ARGS((char_u *));
4932static pos_T *find_line_comment __ARGS((void));
4933static int cin_islabel_skip __ARGS((char_u **));
4934static int cin_isdefault __ARGS((char_u *));
4935static char_u *after_label __ARGS((char_u *l));
4936static int get_indent_nolabel __ARGS((linenr_T lnum));
4937static int skip_label __ARGS((linenr_T, char_u **pp, int ind_maxcomment));
4938static int cin_first_id_amount __ARGS((void));
4939static int cin_get_equal_amount __ARGS((linenr_T lnum));
4940static int cin_ispreproc __ARGS((char_u *));
4941static int cin_ispreproc_cont __ARGS((char_u **pp, linenr_T *lnump));
4942static int cin_iscomment __ARGS((char_u *));
4943static int cin_islinecomment __ARGS((char_u *));
4944static int cin_isterminated __ARGS((char_u *, int, int));
4945static int cin_isinit __ARGS((void));
Bram Moolenaarc367faa2011-12-14 20:21:35 +01004946static int cin_isfuncdecl __ARGS((char_u **, linenr_T, linenr_T, int, int));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004947static int cin_isif __ARGS((char_u *));
4948static int cin_iselse __ARGS((char_u *));
4949static int cin_isdo __ARGS((char_u *));
4950static int cin_iswhileofdo __ARGS((char_u *, linenr_T, int));
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00004951static int cin_iswhileofdo_end __ARGS((int terminated, int ind_maxparen, int ind_maxcomment));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004952static int cin_isbreak __ARGS((char_u *));
Bram Moolenaare7c56862007-08-04 10:14:52 +00004953static int cin_is_cpp_baseclass __ARGS((colnr_T *col));
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00004954static int get_baseclass_amount __ARGS((int col, int ind_maxparen, int ind_maxcomment, int ind_cpp_baseclass));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004955static int cin_ends_in __ARGS((char_u *, char_u *, char_u *));
4956static int cin_skip2pos __ARGS((pos_T *trypos));
4957static pos_T *find_start_brace __ARGS((int));
4958static pos_T *find_match_paren __ARGS((int, int));
4959static int corr_ind_maxparen __ARGS((int ind_maxparen, pos_T *startpos));
4960static int find_last_paren __ARGS((char_u *l, int start, int end));
4961static int find_match __ARGS((int lookfor, linenr_T ourscope, int ind_maxparen, int ind_maxcomment));
Bram Moolenaared38b0a2011-05-25 15:16:18 +02004962static int cin_is_cpp_namespace __ARGS((char_u *));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004963
Bram Moolenaar39353fd2007-03-27 09:02:11 +00004964static int ind_hash_comment = 0; /* # starts a comment */
4965
Bram Moolenaar071d4272004-06-13 20:20:40 +00004966/*
4967 * Skip over white space and C comments within the line.
Bram Moolenaar39353fd2007-03-27 09:02:11 +00004968 * Also skip over Perl/shell comments if desired.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004969 */
4970 static char_u *
4971cin_skipcomment(s)
4972 char_u *s;
4973{
4974 while (*s)
4975 {
Bram Moolenaar39353fd2007-03-27 09:02:11 +00004976 char_u *prev_s = s;
4977
Bram Moolenaar071d4272004-06-13 20:20:40 +00004978 s = skipwhite(s);
Bram Moolenaar39353fd2007-03-27 09:02:11 +00004979
4980 /* Perl/shell # comment comment continues until eol. Require a space
4981 * before # to avoid recognizing $#array. */
4982 if (ind_hash_comment != 0 && s != prev_s && *s == '#')
4983 {
4984 s += STRLEN(s);
4985 break;
4986 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004987 if (*s != '/')
4988 break;
4989 ++s;
4990 if (*s == '/') /* slash-slash comment continues till eol */
4991 {
4992 s += STRLEN(s);
4993 break;
4994 }
4995 if (*s != '*')
4996 break;
4997 for (++s; *s; ++s) /* skip slash-star comment */
4998 if (s[0] == '*' && s[1] == '/')
4999 {
5000 s += 2;
5001 break;
5002 }
5003 }
5004 return s;
5005}
5006
5007/*
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005008 * Return TRUE if there is no code at *s. White space and comments are
Bram Moolenaar071d4272004-06-13 20:20:40 +00005009 * not considered code.
5010 */
5011 static int
5012cin_nocode(s)
5013 char_u *s;
5014{
5015 return *cin_skipcomment(s) == NUL;
5016}
5017
5018/*
5019 * Check previous lines for a "//" line comment, skipping over blank lines.
5020 */
5021 static pos_T *
5022find_line_comment() /* XXX */
5023{
5024 static pos_T pos;
5025 char_u *line;
5026 char_u *p;
5027
5028 pos = curwin->w_cursor;
5029 while (--pos.lnum > 0)
5030 {
5031 line = ml_get(pos.lnum);
5032 p = skipwhite(line);
5033 if (cin_islinecomment(p))
5034 {
5035 pos.col = (int)(p - line);
5036 return &pos;
5037 }
5038 if (*p != NUL)
5039 break;
5040 }
5041 return NULL;
5042}
5043
5044/*
5045 * Check if string matches "label:"; move to character after ':' if true.
5046 */
5047 static int
5048cin_islabel_skip(s)
5049 char_u **s;
5050{
5051 if (!vim_isIDc(**s)) /* need at least one ID character */
5052 return FALSE;
5053
5054 while (vim_isIDc(**s))
5055 (*s)++;
5056
5057 *s = cin_skipcomment(*s);
5058
5059 /* "::" is not a label, it's C++ */
5060 return (**s == ':' && *++*s != ':');
5061}
5062
5063/*
5064 * Recognize a label: "label:".
5065 * Note: curwin->w_cursor must be where we are looking for the label.
5066 */
5067 int
5068cin_islabel(ind_maxcomment) /* XXX */
5069 int ind_maxcomment;
5070{
5071 char_u *s;
5072
5073 s = cin_skipcomment(ml_get_curline());
5074
5075 /*
5076 * Exclude "default" from labels, since it should be indented
5077 * like a switch label. Same for C++ scope declarations.
5078 */
5079 if (cin_isdefault(s))
5080 return FALSE;
5081 if (cin_isscopedecl(s))
5082 return FALSE;
5083
5084 if (cin_islabel_skip(&s))
5085 {
5086 /*
5087 * Only accept a label if the previous line is terminated or is a case
5088 * label.
5089 */
5090 pos_T cursor_save;
5091 pos_T *trypos;
5092 char_u *line;
5093
5094 cursor_save = curwin->w_cursor;
5095 while (curwin->w_cursor.lnum > 1)
5096 {
5097 --curwin->w_cursor.lnum;
5098
5099 /*
5100 * If we're in a comment now, skip to the start of the comment.
5101 */
5102 curwin->w_cursor.col = 0;
5103 if ((trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
5104 curwin->w_cursor = *trypos;
5105
5106 line = ml_get_curline();
5107 if (cin_ispreproc(line)) /* ignore #defines, #if, etc. */
5108 continue;
5109 if (*(line = cin_skipcomment(line)) == NUL)
5110 continue;
5111
5112 curwin->w_cursor = cursor_save;
5113 if (cin_isterminated(line, TRUE, FALSE)
5114 || cin_isscopedecl(line)
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005115 || cin_iscase(line, TRUE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005116 || (cin_islabel_skip(&line) && cin_nocode(line)))
5117 return TRUE;
5118 return FALSE;
5119 }
5120 curwin->w_cursor = cursor_save;
5121 return TRUE; /* label at start of file??? */
5122 }
5123 return FALSE;
5124}
5125
5126/*
5127 * Recognize structure initialization and enumerations.
5128 * Q&D-Implementation:
5129 * check for "=" at end or "[typedef] enum" at beginning of line.
5130 */
5131 static int
5132cin_isinit(void)
5133{
5134 char_u *s;
5135
5136 s = cin_skipcomment(ml_get_curline());
5137
5138 if (STRNCMP(s, "typedef", 7) == 0 && !vim_isIDc(s[7]))
5139 s = cin_skipcomment(s + 7);
5140
Bram Moolenaara5285652011-12-14 20:05:21 +01005141 if (STRNCMP(s, "static", 6) == 0 && !vim_isIDc(s[6]))
5142 s = cin_skipcomment(s + 6);
5143
Bram Moolenaar071d4272004-06-13 20:20:40 +00005144 if (STRNCMP(s, "enum", 4) == 0 && !vim_isIDc(s[4]))
5145 return TRUE;
5146
5147 if (cin_ends_in(s, (char_u *)"=", (char_u *)"{"))
5148 return TRUE;
5149
5150 return FALSE;
5151}
5152
5153/*
5154 * Recognize a switch label: "case .*:" or "default:".
5155 */
5156 int
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005157cin_iscase(s, strict)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005158 char_u *s;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005159 int strict; /* Allow relaxed check of case statement for JS */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005160{
5161 s = cin_skipcomment(s);
5162 if (STRNCMP(s, "case", 4) == 0 && !vim_isIDc(s[4]))
5163 {
5164 for (s += 4; *s; ++s)
5165 {
5166 s = cin_skipcomment(s);
5167 if (*s == ':')
5168 {
5169 if (s[1] == ':') /* skip over "::" for C++ */
5170 ++s;
5171 else
5172 return TRUE;
5173 }
5174 if (*s == '\'' && s[1] && s[2] == '\'')
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005175 s += 2; /* skip over ':' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005176 else if (*s == '/' && (s[1] == '*' || s[1] == '/'))
5177 return FALSE; /* stop at comment */
5178 else if (*s == '"')
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005179 {
5180 /* JS etc. */
5181 if (strict)
5182 return FALSE; /* stop at string */
5183 else
5184 return TRUE;
5185 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005186 }
5187 return FALSE;
5188 }
5189
5190 if (cin_isdefault(s))
5191 return TRUE;
5192 return FALSE;
5193}
5194
5195/*
5196 * Recognize a "default" switch label.
5197 */
5198 static int
5199cin_isdefault(s)
5200 char_u *s;
5201{
5202 return (STRNCMP(s, "default", 7) == 0
5203 && *(s = cin_skipcomment(s + 7)) == ':'
5204 && s[1] != ':');
5205}
5206
5207/*
Bram Moolenaar1a509df2010-08-01 17:59:57 +02005208 * Recognize a "public/private/protected" scope declaration label.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005209 */
5210 int
5211cin_isscopedecl(s)
5212 char_u *s;
5213{
5214 int i;
5215
5216 s = cin_skipcomment(s);
5217 if (STRNCMP(s, "public", 6) == 0)
5218 i = 6;
5219 else if (STRNCMP(s, "protected", 9) == 0)
5220 i = 9;
5221 else if (STRNCMP(s, "private", 7) == 0)
5222 i = 7;
5223 else
5224 return FALSE;
5225 return (*(s = cin_skipcomment(s + i)) == ':' && s[1] != ':');
5226}
5227
Bram Moolenaared38b0a2011-05-25 15:16:18 +02005228/* Maximum number of lines to search back for a "namespace" line. */
5229#define FIND_NAMESPACE_LIM 20
5230
5231/*
5232 * Recognize a "namespace" scope declaration.
5233 */
5234 static int
5235cin_is_cpp_namespace(s)
5236 char_u *s;
5237{
5238 char_u *p;
5239 int has_name = FALSE;
5240
5241 s = cin_skipcomment(s);
5242 if (STRNCMP(s, "namespace", 9) == 0 && (s[9] == NUL || !vim_iswordc(s[9])))
5243 {
5244 p = cin_skipcomment(skipwhite(s + 9));
5245 while (*p != NUL)
5246 {
5247 if (vim_iswhite(*p))
5248 {
5249 has_name = TRUE; /* found end of a name */
5250 p = cin_skipcomment(skipwhite(p));
5251 }
5252 else if (*p == '{')
5253 {
5254 break;
5255 }
5256 else if (vim_iswordc(*p))
5257 {
5258 if (has_name)
5259 return FALSE; /* word character after skipping past name */
5260 ++p;
5261 }
5262 else
5263 {
5264 return FALSE;
5265 }
5266 }
5267 return TRUE;
5268 }
5269 return FALSE;
5270}
5271
Bram Moolenaar071d4272004-06-13 20:20:40 +00005272/*
5273 * Return a pointer to the first non-empty non-comment character after a ':'.
5274 * Return NULL if not found.
5275 * case 234: a = b;
5276 * ^
5277 */
5278 static char_u *
5279after_label(l)
5280 char_u *l;
5281{
5282 for ( ; *l; ++l)
5283 {
5284 if (*l == ':')
5285 {
5286 if (l[1] == ':') /* skip over "::" for C++ */
5287 ++l;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005288 else if (!cin_iscase(l + 1, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005289 break;
5290 }
5291 else if (*l == '\'' && l[1] && l[2] == '\'')
5292 l += 2; /* skip over 'x' */
5293 }
5294 if (*l == NUL)
5295 return NULL;
5296 l = cin_skipcomment(l + 1);
5297 if (*l == NUL)
5298 return NULL;
5299 return l;
5300}
5301
5302/*
5303 * Get indent of line "lnum", skipping a label.
5304 * Return 0 if there is nothing after the label.
5305 */
5306 static int
5307get_indent_nolabel(lnum) /* XXX */
5308 linenr_T lnum;
5309{
5310 char_u *l;
5311 pos_T fp;
5312 colnr_T col;
5313 char_u *p;
5314
5315 l = ml_get(lnum);
5316 p = after_label(l);
5317 if (p == NULL)
5318 return 0;
5319
5320 fp.col = (colnr_T)(p - l);
5321 fp.lnum = lnum;
5322 getvcol(curwin, &fp, &col, NULL, NULL);
5323 return (int)col;
5324}
5325
5326/*
5327 * Find indent for line "lnum", ignoring any case or jump label.
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005328 * Also return a pointer to the text (after the label) in "pp".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005329 * label: if (asdf && asdfasdf)
5330 * ^
5331 */
5332 static int
5333skip_label(lnum, pp, ind_maxcomment)
5334 linenr_T lnum;
5335 char_u **pp;
5336 int ind_maxcomment;
5337{
5338 char_u *l;
5339 int amount;
5340 pos_T cursor_save;
5341
5342 cursor_save = curwin->w_cursor;
5343 curwin->w_cursor.lnum = lnum;
5344 l = ml_get_curline();
5345 /* XXX */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005346 if (cin_iscase(l, FALSE) || cin_isscopedecl(l)
5347 || cin_islabel(ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005348 {
5349 amount = get_indent_nolabel(lnum);
5350 l = after_label(ml_get_curline());
5351 if (l == NULL) /* just in case */
5352 l = ml_get_curline();
5353 }
5354 else
5355 {
5356 amount = get_indent();
5357 l = ml_get_curline();
5358 }
5359 *pp = l;
5360
5361 curwin->w_cursor = cursor_save;
5362 return amount;
5363}
5364
5365/*
5366 * Return the indent of the first variable name after a type in a declaration.
5367 * int a, indent of "a"
5368 * static struct foo b, indent of "b"
5369 * enum bla c, indent of "c"
5370 * Returns zero when it doesn't look like a declaration.
5371 */
5372 static int
5373cin_first_id_amount()
5374{
5375 char_u *line, *p, *s;
5376 int len;
5377 pos_T fp;
5378 colnr_T col;
5379
5380 line = ml_get_curline();
5381 p = skipwhite(line);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005382 len = (int)(skiptowhite(p) - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005383 if (len == 6 && STRNCMP(p, "static", 6) == 0)
5384 {
5385 p = skipwhite(p + 6);
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00005386 len = (int)(skiptowhite(p) - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005387 }
5388 if (len == 6 && STRNCMP(p, "struct", 6) == 0)
5389 p = skipwhite(p + 6);
5390 else if (len == 4 && STRNCMP(p, "enum", 4) == 0)
5391 p = skipwhite(p + 4);
5392 else if ((len == 8 && STRNCMP(p, "unsigned", 8) == 0)
5393 || (len == 6 && STRNCMP(p, "signed", 6) == 0))
5394 {
5395 s = skipwhite(p + len);
5396 if ((STRNCMP(s, "int", 3) == 0 && vim_iswhite(s[3]))
5397 || (STRNCMP(s, "long", 4) == 0 && vim_iswhite(s[4]))
5398 || (STRNCMP(s, "short", 5) == 0 && vim_iswhite(s[5]))
5399 || (STRNCMP(s, "char", 4) == 0 && vim_iswhite(s[4])))
5400 p = s;
5401 }
5402 for (len = 0; vim_isIDc(p[len]); ++len)
5403 ;
5404 if (len == 0 || !vim_iswhite(p[len]) || cin_nocode(p))
5405 return 0;
5406
5407 p = skipwhite(p + len);
5408 fp.lnum = curwin->w_cursor.lnum;
5409 fp.col = (colnr_T)(p - line);
5410 getvcol(curwin, &fp, &col, NULL, NULL);
5411 return (int)col;
5412}
5413
5414/*
5415 * Return the indent of the first non-blank after an equal sign.
5416 * char *foo = "here";
5417 * Return zero if no (useful) equal sign found.
5418 * Return -1 if the line above "lnum" ends in a backslash.
5419 * foo = "asdf\
5420 * asdf\
5421 * here";
5422 */
5423 static int
5424cin_get_equal_amount(lnum)
5425 linenr_T lnum;
5426{
5427 char_u *line;
5428 char_u *s;
5429 colnr_T col;
5430 pos_T fp;
5431
5432 if (lnum > 1)
5433 {
5434 line = ml_get(lnum - 1);
5435 if (*line != NUL && line[STRLEN(line) - 1] == '\\')
5436 return -1;
5437 }
5438
5439 line = s = ml_get(lnum);
5440 while (*s != NUL && vim_strchr((char_u *)"=;{}\"'", *s) == NULL)
5441 {
5442 if (cin_iscomment(s)) /* ignore comments */
5443 s = cin_skipcomment(s);
5444 else
5445 ++s;
5446 }
5447 if (*s != '=')
5448 return 0;
5449
5450 s = skipwhite(s + 1);
5451 if (cin_nocode(s))
5452 return 0;
5453
5454 if (*s == '"') /* nice alignment for continued strings */
5455 ++s;
5456
5457 fp.lnum = lnum;
5458 fp.col = (colnr_T)(s - line);
5459 getvcol(curwin, &fp, &col, NULL, NULL);
5460 return (int)col;
5461}
5462
5463/*
5464 * Recognize a preprocessor statement: Any line that starts with '#'.
5465 */
5466 static int
5467cin_ispreproc(s)
5468 char_u *s;
5469{
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005470 if (*skipwhite(s) == '#')
Bram Moolenaar071d4272004-06-13 20:20:40 +00005471 return TRUE;
5472 return FALSE;
5473}
5474
5475/*
5476 * Return TRUE if line "*pp" at "*lnump" is a preprocessor statement or a
5477 * continuation line of a preprocessor statement. Decrease "*lnump" to the
5478 * start and return the line in "*pp".
5479 */
5480 static int
5481cin_ispreproc_cont(pp, lnump)
5482 char_u **pp;
5483 linenr_T *lnump;
5484{
5485 char_u *line = *pp;
5486 linenr_T lnum = *lnump;
5487 int retval = FALSE;
5488
Bram Moolenaard8e9bb22005-07-09 21:14:46 +00005489 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005490 {
5491 if (cin_ispreproc(line))
5492 {
5493 retval = TRUE;
5494 *lnump = lnum;
5495 break;
5496 }
5497 if (lnum == 1)
5498 break;
5499 line = ml_get(--lnum);
5500 if (*line == NUL || line[STRLEN(line) - 1] != '\\')
5501 break;
5502 }
5503
5504 if (lnum != *lnump)
5505 *pp = ml_get(*lnump);
5506 return retval;
5507}
5508
5509/*
5510 * Recognize the start of a C or C++ comment.
5511 */
5512 static int
5513cin_iscomment(p)
5514 char_u *p;
5515{
5516 return (p[0] == '/' && (p[1] == '*' || p[1] == '/'));
5517}
5518
5519/*
5520 * Recognize the start of a "//" comment.
5521 */
5522 static int
5523cin_islinecomment(p)
5524 char_u *p;
5525{
5526 return (p[0] == '/' && p[1] == '/');
5527}
5528
5529/*
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005530 * Recognize a line that starts with '{' or '}', or ends with ';', ',', '{' or
5531 * '}'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005532 * Don't consider "} else" a terminated line.
Bram Moolenaar496f9512011-05-19 16:35:09 +02005533 * If a line begins with an "else", only consider it terminated if no unmatched
5534 * opening braces follow (handle "else { foo();" correctly).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005535 * Return the character terminating the line (ending char's have precedence if
5536 * both apply in order to determine initializations).
5537 */
5538 static int
5539cin_isterminated(s, incl_open, incl_comma)
5540 char_u *s;
5541 int incl_open; /* include '{' at the end as terminator */
5542 int incl_comma; /* recognize a trailing comma */
5543{
Bram Moolenaar496f9512011-05-19 16:35:09 +02005544 char_u found_start = 0;
5545 unsigned n_open = 0;
5546 int is_else = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005547
5548 s = cin_skipcomment(s);
5549
5550 if (*s == '{' || (*s == '}' && !cin_iselse(s)))
5551 found_start = *s;
5552
Bram Moolenaar496f9512011-05-19 16:35:09 +02005553 if (!found_start)
5554 is_else = cin_iselse(s);
5555
Bram Moolenaar071d4272004-06-13 20:20:40 +00005556 while (*s)
5557 {
5558 /* skip over comments, "" strings and 'c'haracters */
5559 s = skip_string(cin_skipcomment(s));
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005560 if (*s == '}' && n_open > 0)
5561 --n_open;
Bram Moolenaar496f9512011-05-19 16:35:09 +02005562 if ((!is_else || n_open == 0)
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005563 && (*s == ';' || *s == '}' || (incl_comma && *s == ','))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005564 && cin_nocode(s + 1))
5565 return *s;
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005566 else if (*s == '{')
5567 {
5568 if (incl_open && cin_nocode(s + 1))
5569 return *s;
5570 else
5571 ++n_open;
5572 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005573
5574 if (*s)
5575 s++;
5576 }
5577 return found_start;
5578}
5579
5580/*
5581 * Recognize the basic picture of a function declaration -- it needs to
5582 * have an open paren somewhere and a close paren at the end of the line and
5583 * no semicolons anywhere.
5584 * When a line ends in a comma we continue looking in the next line.
5585 * "sp" points to a string with the line. When looking at other lines it must
5586 * be restored to the line. When it's NULL fetch lines here.
5587 * "lnum" is where we start looking.
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005588 * "min_lnum" is the line before which we will not be looking.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005589 */
5590 static int
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005591cin_isfuncdecl(sp, first_lnum, min_lnum, ind_maxparen, ind_maxcomment)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005592 char_u **sp;
5593 linenr_T first_lnum;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005594 linenr_T min_lnum;
5595 int ind_maxparen;
5596 int ind_maxcomment;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005597{
5598 char_u *s;
5599 linenr_T lnum = first_lnum;
5600 int retval = FALSE;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005601 pos_T *trypos;
5602 int just_started = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005603
5604 if (sp == NULL)
5605 s = ml_get(lnum);
5606 else
5607 s = *sp;
5608
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005609 if (find_last_paren(s, '(', ')')
5610 && (trypos = find_match_paren(ind_maxparen, ind_maxcomment)) != NULL)
5611 {
5612 lnum = trypos->lnum;
5613 if (lnum < min_lnum)
5614 return FALSE;
5615
5616 s = ml_get(lnum);
5617 }
5618
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005619 /* Ignore line starting with #. */
5620 if (cin_ispreproc(s))
5621 return FALSE;
5622
Bram Moolenaar071d4272004-06-13 20:20:40 +00005623 while (*s && *s != '(' && *s != ';' && *s != '\'' && *s != '"')
5624 {
5625 if (cin_iscomment(s)) /* ignore comments */
5626 s = cin_skipcomment(s);
5627 else
5628 ++s;
5629 }
5630 if (*s != '(')
5631 return FALSE; /* ';', ' or " before any () or no '(' */
5632
5633 while (*s && *s != ';' && *s != '\'' && *s != '"')
5634 {
5635 if (*s == ')' && cin_nocode(s + 1))
5636 {
5637 /* ')' at the end: may have found a match
5638 * Check for he previous line not to end in a backslash:
5639 * #if defined(x) && \
5640 * defined(y)
5641 */
5642 lnum = first_lnum - 1;
5643 s = ml_get(lnum);
5644 if (*s == NUL || s[STRLEN(s) - 1] != '\\')
5645 retval = TRUE;
5646 goto done;
5647 }
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005648 if ((*s == ',' && cin_nocode(s + 1)) || s[1] == NUL || cin_nocode(s))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005649 {
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005650 int comma = (*s == ',');
5651
5652 /* ',' at the end: continue looking in the next line.
5653 * At the end: check for ',' in the next line, for this style:
5654 * func(arg1
5655 * , arg2) */
5656 for (;;)
5657 {
5658 if (lnum >= curbuf->b_ml.ml_line_count)
5659 break;
5660 s = ml_get(++lnum);
5661 if (!cin_ispreproc(s))
5662 break;
5663 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005664 if (lnum >= curbuf->b_ml.ml_line_count)
5665 break;
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005666 /* Require a comma at end of the line or a comma or ')' at the
5667 * start of next line. */
5668 s = skipwhite(s);
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005669 if (!just_started && (!comma && *s != ',' && *s != ')'))
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005670 break;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005671 just_started = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005672 }
5673 else if (cin_iscomment(s)) /* ignore comments */
5674 s = cin_skipcomment(s);
5675 else
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005676 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005677 ++s;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005678 just_started = FALSE;
5679 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005680 }
5681
5682done:
5683 if (lnum != first_lnum && sp != NULL)
5684 *sp = ml_get(first_lnum);
5685
5686 return retval;
5687}
5688
5689 static int
5690cin_isif(p)
5691 char_u *p;
5692{
5693 return (STRNCMP(p, "if", 2) == 0 && !vim_isIDc(p[2]));
5694}
5695
5696 static int
5697cin_iselse(p)
5698 char_u *p;
5699{
5700 if (*p == '}') /* accept "} else" */
5701 p = cin_skipcomment(p + 1);
5702 return (STRNCMP(p, "else", 4) == 0 && !vim_isIDc(p[4]));
5703}
5704
5705 static int
5706cin_isdo(p)
5707 char_u *p;
5708{
5709 return (STRNCMP(p, "do", 2) == 0 && !vim_isIDc(p[2]));
5710}
5711
5712/*
5713 * Check if this is a "while" that should have a matching "do".
5714 * We only accept a "while (condition) ;", with only white space between the
5715 * ')' and ';'. The condition may be spread over several lines.
5716 */
5717 static int
5718cin_iswhileofdo(p, lnum, ind_maxparen) /* XXX */
5719 char_u *p;
5720 linenr_T lnum;
5721 int ind_maxparen;
5722{
5723 pos_T cursor_save;
5724 pos_T *trypos;
5725 int retval = FALSE;
5726
5727 p = cin_skipcomment(p);
5728 if (*p == '}') /* accept "} while (cond);" */
5729 p = cin_skipcomment(p + 1);
5730 if (STRNCMP(p, "while", 5) == 0 && !vim_isIDc(p[5]))
5731 {
5732 cursor_save = curwin->w_cursor;
5733 curwin->w_cursor.lnum = lnum;
5734 curwin->w_cursor.col = 0;
5735 p = ml_get_curline();
5736 while (*p && *p != 'w') /* skip any '}', until the 'w' of the "while" */
5737 {
5738 ++p;
5739 ++curwin->w_cursor.col;
5740 }
5741 if ((trypos = findmatchlimit(NULL, 0, 0, ind_maxparen)) != NULL
5742 && *cin_skipcomment(ml_get_pos(trypos) + 1) == ';')
5743 retval = TRUE;
5744 curwin->w_cursor = cursor_save;
5745 }
5746 return retval;
5747}
5748
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005749/*
5750 * Return TRUE if we are at the end of a do-while.
5751 * do
5752 * nothing;
5753 * while (foo
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00005754 * && bar); <-- here
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005755 * Adjust the cursor to the line with "while".
5756 */
5757 static int
5758cin_iswhileofdo_end(terminated, ind_maxparen, ind_maxcomment)
5759 int terminated;
5760 int ind_maxparen;
5761 int ind_maxcomment;
5762{
5763 char_u *line;
5764 char_u *p;
5765 char_u *s;
5766 pos_T *trypos;
5767 int i;
5768
5769 if (terminated != ';') /* there must be a ';' at the end */
5770 return FALSE;
5771
5772 p = line = ml_get_curline();
5773 while (*p != NUL)
5774 {
5775 p = cin_skipcomment(p);
5776 if (*p == ')')
5777 {
5778 s = skipwhite(p + 1);
5779 if (*s == ';' && cin_nocode(s + 1))
5780 {
5781 /* Found ");" at end of the line, now check there is "while"
5782 * before the matching '('. XXX */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005783 i = (int)(p - line);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005784 curwin->w_cursor.col = i;
5785 trypos = find_match_paren(ind_maxparen, ind_maxcomment);
5786 if (trypos != NULL)
5787 {
5788 s = cin_skipcomment(ml_get(trypos->lnum));
5789 if (*s == '}') /* accept "} while (cond);" */
5790 s = cin_skipcomment(s + 1);
5791 if (STRNCMP(s, "while", 5) == 0 && !vim_isIDc(s[5]))
5792 {
5793 curwin->w_cursor.lnum = trypos->lnum;
5794 return TRUE;
5795 }
5796 }
5797
5798 /* Searching may have made "line" invalid, get it again. */
5799 line = ml_get_curline();
5800 p = line + i;
5801 }
5802 }
5803 if (*p != NUL)
5804 ++p;
5805 }
5806 return FALSE;
5807}
5808
Bram Moolenaar071d4272004-06-13 20:20:40 +00005809 static int
5810cin_isbreak(p)
5811 char_u *p;
5812{
5813 return (STRNCMP(p, "break", 5) == 0 && !vim_isIDc(p[5]));
5814}
5815
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005816/*
5817 * Find the position of a C++ base-class declaration or
Bram Moolenaar071d4272004-06-13 20:20:40 +00005818 * constructor-initialization. eg:
5819 *
5820 * class MyClass :
5821 * baseClass <-- here
5822 * class MyClass : public baseClass,
5823 * anotherBaseClass <-- here (should probably lineup ??)
5824 * MyClass::MyClass(...) :
5825 * baseClass(...) <-- here (constructor-initialization)
Bram Moolenaar18144c82006-04-12 21:52:12 +00005826 *
5827 * This is a lot of guessing. Watch out for "cond ? func() : foo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005828 */
5829 static int
Bram Moolenaare7c56862007-08-04 10:14:52 +00005830cin_is_cpp_baseclass(col)
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005831 colnr_T *col; /* return: column to align with */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005832{
5833 char_u *s;
5834 int class_or_struct, lookfor_ctor_init, cpp_base_class;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005835 linenr_T lnum = curwin->w_cursor.lnum;
Bram Moolenaare7c56862007-08-04 10:14:52 +00005836 char_u *line = ml_get_curline();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005837
5838 *col = 0;
5839
Bram Moolenaar21cf8232004-07-16 20:18:37 +00005840 s = skipwhite(line);
5841 if (*s == '#') /* skip #define FOO x ? (x) : x */
5842 return FALSE;
5843 s = cin_skipcomment(s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005844 if (*s == NUL)
5845 return FALSE;
5846
5847 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
5848
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005849 /* Search for a line starting with '#', empty, ending in ';' or containing
5850 * '{' or '}' and start below it. This handles the following situations:
5851 * a = cond ?
5852 * func() :
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00005853 * asdf;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005854 * func::foo()
5855 * : something
5856 * {}
5857 * Foo::Foo (int one, int two)
5858 * : something(4),
5859 * somethingelse(3)
5860 * {}
5861 */
5862 while (lnum > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005863 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00005864 line = ml_get(lnum - 1);
5865 s = skipwhite(line);
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005866 if (*s == '#' || *s == NUL)
5867 break;
5868 while (*s != NUL)
5869 {
5870 s = cin_skipcomment(s);
5871 if (*s == '{' || *s == '}'
5872 || (*s == ';' && cin_nocode(s + 1)))
5873 break;
5874 if (*s != NUL)
5875 ++s;
5876 }
5877 if (*s != NUL)
5878 break;
5879 --lnum;
5880 }
5881
Bram Moolenaare7c56862007-08-04 10:14:52 +00005882 line = ml_get(lnum);
5883 s = cin_skipcomment(line);
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005884 for (;;)
5885 {
5886 if (*s == NUL)
5887 {
5888 if (lnum == curwin->w_cursor.lnum)
5889 break;
5890 /* Continue in the cursor line. */
Bram Moolenaare7c56862007-08-04 10:14:52 +00005891 line = ml_get(++lnum);
5892 s = cin_skipcomment(line);
5893 if (*s == NUL)
5894 continue;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005895 }
5896
Bram Moolenaaraede6ce2011-05-10 11:56:30 +02005897 if (s[0] == '"')
5898 s = skip_string(s) + 1;
5899 else if (s[0] == ':')
Bram Moolenaar071d4272004-06-13 20:20:40 +00005900 {
5901 if (s[1] == ':')
5902 {
5903 /* skip double colon. It can't be a constructor
5904 * initialization any more */
5905 lookfor_ctor_init = FALSE;
5906 s = cin_skipcomment(s + 2);
5907 }
5908 else if (lookfor_ctor_init || class_or_struct)
5909 {
5910 /* we have something found, that looks like the start of
Bram Moolenaare21877a2008-02-13 09:58:14 +00005911 * cpp-base-class-declaration or constructor-initialization */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005912 cpp_base_class = TRUE;
5913 lookfor_ctor_init = class_or_struct = FALSE;
5914 *col = 0;
5915 s = cin_skipcomment(s + 1);
5916 }
5917 else
5918 s = cin_skipcomment(s + 1);
5919 }
5920 else if ((STRNCMP(s, "class", 5) == 0 && !vim_isIDc(s[5]))
5921 || (STRNCMP(s, "struct", 6) == 0 && !vim_isIDc(s[6])))
5922 {
5923 class_or_struct = TRUE;
5924 lookfor_ctor_init = FALSE;
5925
5926 if (*s == 'c')
5927 s = cin_skipcomment(s + 5);
5928 else
5929 s = cin_skipcomment(s + 6);
5930 }
5931 else
5932 {
5933 if (s[0] == '{' || s[0] == '}' || s[0] == ';')
5934 {
5935 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
5936 }
5937 else if (s[0] == ')')
5938 {
5939 /* Constructor-initialization is assumed if we come across
5940 * something like "):" */
5941 class_or_struct = FALSE;
5942 lookfor_ctor_init = TRUE;
5943 }
Bram Moolenaar18144c82006-04-12 21:52:12 +00005944 else if (s[0] == '?')
5945 {
5946 /* Avoid seeing '() :' after '?' as constructor init. */
5947 return FALSE;
5948 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005949 else if (!vim_isIDc(s[0]))
5950 {
5951 /* if it is not an identifier, we are wrong */
5952 class_or_struct = FALSE;
5953 lookfor_ctor_init = FALSE;
5954 }
5955 else if (*col == 0)
5956 {
5957 /* it can't be a constructor-initialization any more */
5958 lookfor_ctor_init = FALSE;
5959
5960 /* the first statement starts here: lineup with this one... */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005961 if (cpp_base_class)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005962 *col = (colnr_T)(s - line);
5963 }
5964
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005965 /* When the line ends in a comma don't align with it. */
5966 if (lnum == curwin->w_cursor.lnum && *s == ',' && cin_nocode(s + 1))
5967 *col = 0;
5968
Bram Moolenaar071d4272004-06-13 20:20:40 +00005969 s = cin_skipcomment(s + 1);
5970 }
5971 }
5972
5973 return cpp_base_class;
5974}
5975
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005976 static int
5977get_baseclass_amount(col, ind_maxparen, ind_maxcomment, ind_cpp_baseclass)
5978 int col;
5979 int ind_maxparen;
5980 int ind_maxcomment;
5981 int ind_cpp_baseclass;
5982{
5983 int amount;
5984 colnr_T vcol;
5985 pos_T *trypos;
5986
5987 if (col == 0)
5988 {
5989 amount = get_indent();
5990 if (find_last_paren(ml_get_curline(), '(', ')')
5991 && (trypos = find_match_paren(ind_maxparen,
5992 ind_maxcomment)) != NULL)
5993 amount = get_indent_lnum(trypos->lnum); /* XXX */
5994 if (!cin_ends_in(ml_get_curline(), (char_u *)",", NULL))
5995 amount += ind_cpp_baseclass;
5996 }
5997 else
5998 {
5999 curwin->w_cursor.col = col;
6000 getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
6001 amount = (int)vcol;
6002 }
6003 if (amount < ind_cpp_baseclass)
6004 amount = ind_cpp_baseclass;
6005 return amount;
6006}
6007
Bram Moolenaar071d4272004-06-13 20:20:40 +00006008/*
6009 * Return TRUE if string "s" ends with the string "find", possibly followed by
6010 * white space and comments. Skip strings and comments.
6011 * Ignore "ignore" after "find" if it's not NULL.
6012 */
6013 static int
6014cin_ends_in(s, find, ignore)
6015 char_u *s;
6016 char_u *find;
6017 char_u *ignore;
6018{
6019 char_u *p = s;
6020 char_u *r;
6021 int len = (int)STRLEN(find);
6022
6023 while (*p != NUL)
6024 {
6025 p = cin_skipcomment(p);
6026 if (STRNCMP(p, find, len) == 0)
6027 {
6028 r = skipwhite(p + len);
6029 if (ignore != NULL && STRNCMP(r, ignore, STRLEN(ignore)) == 0)
6030 r = skipwhite(r + STRLEN(ignore));
6031 if (cin_nocode(r))
6032 return TRUE;
6033 }
6034 if (*p != NUL)
6035 ++p;
6036 }
6037 return FALSE;
6038}
6039
6040/*
6041 * Skip strings, chars and comments until at or past "trypos".
6042 * Return the column found.
6043 */
6044 static int
6045cin_skip2pos(trypos)
6046 pos_T *trypos;
6047{
6048 char_u *line;
6049 char_u *p;
6050
6051 p = line = ml_get(trypos->lnum);
6052 while (*p && (colnr_T)(p - line) < trypos->col)
6053 {
6054 if (cin_iscomment(p))
6055 p = cin_skipcomment(p);
6056 else
6057 {
6058 p = skip_string(p);
6059 ++p;
6060 }
6061 }
6062 return (int)(p - line);
6063}
6064
6065/*
6066 * Find the '{' at the start of the block we are in.
6067 * Return NULL if no match found.
6068 * Ignore a '{' that is in a comment, makes indenting the next three lines
6069 * work. */
6070/* foo() */
6071/* { */
6072/* } */
6073
6074 static pos_T *
6075find_start_brace(ind_maxcomment) /* XXX */
6076 int ind_maxcomment;
6077{
6078 pos_T cursor_save;
6079 pos_T *trypos;
6080 pos_T *pos;
6081 static pos_T pos_copy;
6082
6083 cursor_save = curwin->w_cursor;
6084 while ((trypos = findmatchlimit(NULL, '{', FM_BLOCKSTOP, 0)) != NULL)
6085 {
6086 pos_copy = *trypos; /* copy pos_T, next findmatch will change it */
6087 trypos = &pos_copy;
6088 curwin->w_cursor = *trypos;
6089 pos = NULL;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006090 /* ignore the { if it's in a // or / * * / comment */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006091 if ((colnr_T)cin_skip2pos(trypos) == trypos->col
6092 && (pos = find_start_comment(ind_maxcomment)) == NULL) /* XXX */
6093 break;
6094 if (pos != NULL)
6095 curwin->w_cursor.lnum = pos->lnum;
6096 }
6097 curwin->w_cursor = cursor_save;
6098 return trypos;
6099}
6100
6101/*
6102 * Find the matching '(', failing if it is in a comment.
6103 * Return NULL of no match found.
6104 */
6105 static pos_T *
6106find_match_paren(ind_maxparen, ind_maxcomment) /* XXX */
6107 int ind_maxparen;
6108 int ind_maxcomment;
6109{
6110 pos_T cursor_save;
6111 pos_T *trypos;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006112 static pos_T pos_copy;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006113
6114 cursor_save = curwin->w_cursor;
6115 if ((trypos = findmatchlimit(NULL, '(', 0, ind_maxparen)) != NULL)
6116 {
6117 /* check if the ( is in a // comment */
6118 if ((colnr_T)cin_skip2pos(trypos) > trypos->col)
6119 trypos = NULL;
6120 else
6121 {
6122 pos_copy = *trypos; /* copy trypos, findmatch will change it */
6123 trypos = &pos_copy;
6124 curwin->w_cursor = *trypos;
6125 if (find_start_comment(ind_maxcomment) != NULL) /* XXX */
6126 trypos = NULL;
6127 }
6128 }
6129 curwin->w_cursor = cursor_save;
6130 return trypos;
6131}
6132
6133/*
6134 * Return ind_maxparen corrected for the difference in line number between the
6135 * cursor position and "startpos". This makes sure that searching for a
6136 * matching paren above the cursor line doesn't find a match because of
6137 * looking a few lines further.
6138 */
6139 static int
6140corr_ind_maxparen(ind_maxparen, startpos)
6141 int ind_maxparen;
6142 pos_T *startpos;
6143{
6144 long n = (long)startpos->lnum - (long)curwin->w_cursor.lnum;
6145
6146 if (n > 0 && n < ind_maxparen / 2)
6147 return ind_maxparen - (int)n;
6148 return ind_maxparen;
6149}
6150
6151/*
6152 * Set w_cursor.col to the column number of the last unmatched ')' or '{' in
Bram Moolenaar6d8f9c62011-11-30 13:03:28 +01006153 * line "l". "l" must point to the start of the line.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006154 */
6155 static int
6156find_last_paren(l, start, end)
6157 char_u *l;
6158 int start, end;
6159{
6160 int i;
6161 int retval = FALSE;
6162 int open_count = 0;
6163
6164 curwin->w_cursor.col = 0; /* default is start of line */
6165
Bram Moolenaar6d8f9c62011-11-30 13:03:28 +01006166 for (i = 0; l[i] != NUL; i++)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006167 {
6168 i = (int)(cin_skipcomment(l + i) - l); /* ignore parens in comments */
6169 i = (int)(skip_string(l + i) - l); /* ignore parens in quotes */
6170 if (l[i] == start)
6171 ++open_count;
6172 else if (l[i] == end)
6173 {
6174 if (open_count > 0)
6175 --open_count;
6176 else
6177 {
6178 curwin->w_cursor.col = i;
6179 retval = TRUE;
6180 }
6181 }
6182 }
6183 return retval;
6184}
6185
6186 int
6187get_c_indent()
6188{
6189 /*
6190 * spaces from a block's opening brace the prevailing indent for that
6191 * block should be
6192 */
6193 int ind_level = curbuf->b_p_sw;
6194
6195 /*
6196 * spaces from the edge of the line an open brace that's at the end of a
6197 * line is imagined to be.
6198 */
6199 int ind_open_imag = 0;
6200
6201 /*
Bram Moolenaar1a509df2010-08-01 17:59:57 +02006202 * spaces from the prevailing indent for a line that is not preceded by
Bram Moolenaar071d4272004-06-13 20:20:40 +00006203 * an opening brace.
6204 */
6205 int ind_no_brace = 0;
6206
6207 /*
6208 * column where the first { of a function should be located }
6209 */
6210 int ind_first_open = 0;
6211
6212 /*
6213 * spaces from the prevailing indent a leftmost open brace should be
6214 * located
6215 */
6216 int ind_open_extra = 0;
6217
6218 /*
6219 * spaces from the matching open brace (real location for one at the left
6220 * edge; imaginary location from one that ends a line) the matching close
6221 * brace should be located
6222 */
6223 int ind_close_extra = 0;
6224
6225 /*
6226 * spaces from the edge of the line an open brace sitting in the leftmost
6227 * column is imagined to be
6228 */
6229 int ind_open_left_imag = 0;
6230
6231 /*
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006232 * Spaces jump labels should be shifted to the left if N is non-negative,
6233 * otherwise the jump label will be put to column 1.
6234 */
6235 int ind_jump_label = -1;
6236
6237 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006238 * spaces from the switch() indent a "case xx" label should be located
6239 */
6240 int ind_case = curbuf->b_p_sw;
6241
6242 /*
6243 * spaces from the "case xx:" code after a switch() should be located
6244 */
6245 int ind_case_code = curbuf->b_p_sw;
6246
6247 /*
6248 * lineup break at end of case in switch() with case label
6249 */
6250 int ind_case_break = 0;
6251
6252 /*
6253 * spaces from the class declaration indent a scope declaration label
6254 * should be located
6255 */
6256 int ind_scopedecl = curbuf->b_p_sw;
6257
6258 /*
6259 * spaces from the scope declaration label code should be located
6260 */
6261 int ind_scopedecl_code = curbuf->b_p_sw;
6262
6263 /*
6264 * amount K&R-style parameters should be indented
6265 */
6266 int ind_param = curbuf->b_p_sw;
6267
6268 /*
6269 * amount a function type spec should be indented
6270 */
6271 int ind_func_type = curbuf->b_p_sw;
6272
6273 /*
6274 * amount a cpp base class declaration or constructor initialization
6275 * should be indented
6276 */
6277 int ind_cpp_baseclass = curbuf->b_p_sw;
6278
6279 /*
6280 * additional spaces beyond the prevailing indent a continuation line
6281 * should be located
6282 */
6283 int ind_continuation = curbuf->b_p_sw;
6284
6285 /*
6286 * spaces from the indent of the line with an unclosed parentheses
6287 */
6288 int ind_unclosed = curbuf->b_p_sw * 2;
6289
6290 /*
6291 * spaces from the indent of the line with an unclosed parentheses, which
6292 * itself is also unclosed
6293 */
6294 int ind_unclosed2 = curbuf->b_p_sw;
6295
6296 /*
6297 * suppress ignoring spaces from the indent of a line starting with an
6298 * unclosed parentheses.
6299 */
6300 int ind_unclosed_noignore = 0;
6301
6302 /*
6303 * If the opening paren is the last nonwhite character on the line, and
6304 * ind_unclosed_wrapped is nonzero, use this indent relative to the outer
6305 * context (for very long lines).
6306 */
6307 int ind_unclosed_wrapped = 0;
6308
6309 /*
6310 * suppress ignoring white space when lining up with the character after
6311 * an unclosed parentheses.
6312 */
6313 int ind_unclosed_whiteok = 0;
6314
6315 /*
6316 * indent a closing parentheses under the line start of the matching
6317 * opening parentheses.
6318 */
6319 int ind_matching_paren = 0;
6320
6321 /*
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006322 * indent a closing parentheses under the previous line.
6323 */
6324 int ind_paren_prev = 0;
6325
6326 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006327 * Extra indent for comments.
6328 */
6329 int ind_comment = 0;
6330
6331 /*
6332 * spaces from the comment opener when there is nothing after it.
6333 */
6334 int ind_in_comment = 3;
6335
6336 /*
6337 * boolean: if non-zero, use ind_in_comment even if there is something
6338 * after the comment opener.
6339 */
6340 int ind_in_comment2 = 0;
6341
6342 /*
6343 * max lines to search for an open paren
6344 */
6345 int ind_maxparen = 20;
6346
6347 /*
6348 * max lines to search for an open comment
6349 */
6350 int ind_maxcomment = 70;
6351
6352 /*
6353 * handle braces for java code
6354 */
6355 int ind_java = 0;
6356
6357 /*
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006358 * not to confuse JS object properties with labels
6359 */
6360 int ind_js = 0;
6361
6362 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006363 * handle blocked cases correctly
6364 */
6365 int ind_keep_case_label = 0;
6366
Bram Moolenaared38b0a2011-05-25 15:16:18 +02006367 /*
6368 * handle C++ namespace
6369 */
6370 int ind_cpp_namespace = 0;
6371
Bram Moolenaar071d4272004-06-13 20:20:40 +00006372 pos_T cur_curpos;
6373 int amount;
6374 int scope_amount;
Bram Moolenaarb21e5842006-04-16 18:30:08 +00006375 int cur_amount = MAXCOL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006376 colnr_T col;
6377 char_u *theline;
6378 char_u *linecopy;
6379 pos_T *trypos;
6380 pos_T *tryposBrace = NULL;
6381 pos_T our_paren_pos;
6382 char_u *start;
6383 int start_brace;
Bram Moolenaare21877a2008-02-13 09:58:14 +00006384#define BRACE_IN_COL0 1 /* '{' is in column 0 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006385#define BRACE_AT_START 2 /* '{' is at start of line */
6386#define BRACE_AT_END 3 /* '{' is at end of line */
6387 linenr_T ourscope;
6388 char_u *l;
6389 char_u *look;
6390 char_u terminated;
6391 int lookfor;
6392#define LOOKFOR_INITIAL 0
6393#define LOOKFOR_IF 1
6394#define LOOKFOR_DO 2
6395#define LOOKFOR_CASE 3
6396#define LOOKFOR_ANY 4
6397#define LOOKFOR_TERM 5
6398#define LOOKFOR_UNTERM 6
6399#define LOOKFOR_SCOPEDECL 7
6400#define LOOKFOR_NOBREAK 8
6401#define LOOKFOR_CPP_BASECLASS 9
6402#define LOOKFOR_ENUM_OR_INIT 10
6403
6404 int whilelevel;
6405 linenr_T lnum;
6406 char_u *options;
6407 int fraction = 0; /* init for GCC */
6408 int divider;
6409 int n;
6410 int iscase;
6411 int lookfor_break;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02006412 int lookfor_cpp_namespace = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006413 int cont_amount = 0; /* amount for continuation line */
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006414 int original_line_islabel;
Bram Moolenaare79d1532011-10-04 18:03:47 +02006415 int added_to_amount = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006416
6417 for (options = curbuf->b_p_cino; *options; )
6418 {
6419 l = options++;
6420 if (*options == '-')
6421 ++options;
6422 n = getdigits(&options);
6423 divider = 0;
6424 if (*options == '.') /* ".5s" means a fraction */
6425 {
6426 fraction = atol((char *)++options);
6427 while (VIM_ISDIGIT(*options))
6428 {
6429 ++options;
6430 if (divider)
6431 divider *= 10;
6432 else
6433 divider = 10;
6434 }
6435 }
6436 if (*options == 's') /* "2s" means two times 'shiftwidth' */
6437 {
6438 if (n == 0 && fraction == 0)
6439 n = curbuf->b_p_sw; /* just "s" is one 'shiftwidth' */
6440 else
6441 {
6442 n *= curbuf->b_p_sw;
6443 if (divider)
6444 n += (curbuf->b_p_sw * fraction + divider / 2) / divider;
6445 }
6446 ++options;
6447 }
6448 if (l[1] == '-')
6449 n = -n;
6450 /* When adding an entry here, also update the default 'cinoptions' in
Bram Moolenaar39353fd2007-03-27 09:02:11 +00006451 * doc/indent.txt, and add explanation for it! */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006452 switch (*l)
6453 {
6454 case '>': ind_level = n; break;
6455 case 'e': ind_open_imag = n; break;
6456 case 'n': ind_no_brace = n; break;
6457 case 'f': ind_first_open = n; break;
6458 case '{': ind_open_extra = n; break;
6459 case '}': ind_close_extra = n; break;
6460 case '^': ind_open_left_imag = n; break;
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006461 case 'L': ind_jump_label = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006462 case ':': ind_case = n; break;
6463 case '=': ind_case_code = n; break;
6464 case 'b': ind_case_break = n; break;
6465 case 'p': ind_param = n; break;
6466 case 't': ind_func_type = n; break;
6467 case '/': ind_comment = n; break;
6468 case 'c': ind_in_comment = n; break;
6469 case 'C': ind_in_comment2 = n; break;
6470 case 'i': ind_cpp_baseclass = n; break;
6471 case '+': ind_continuation = n; break;
6472 case '(': ind_unclosed = n; break;
6473 case 'u': ind_unclosed2 = n; break;
6474 case 'U': ind_unclosed_noignore = n; break;
6475 case 'W': ind_unclosed_wrapped = n; break;
6476 case 'w': ind_unclosed_whiteok = n; break;
6477 case 'm': ind_matching_paren = n; break;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006478 case 'M': ind_paren_prev = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006479 case ')': ind_maxparen = n; break;
6480 case '*': ind_maxcomment = n; break;
6481 case 'g': ind_scopedecl = n; break;
6482 case 'h': ind_scopedecl_code = n; break;
6483 case 'j': ind_java = n; break;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006484 case 'J': ind_js = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006485 case 'l': ind_keep_case_label = n; break;
Bram Moolenaar39353fd2007-03-27 09:02:11 +00006486 case '#': ind_hash_comment = n; break;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02006487 case 'N': ind_cpp_namespace = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006488 }
Bram Moolenaardfdf3c42010-03-23 18:22:46 +01006489 if (*options == ',')
6490 ++options;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006491 }
6492
6493 /* remember where the cursor was when we started */
6494 cur_curpos = curwin->w_cursor;
6495
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006496 /* if we are at line 1 0 is fine, right? */
6497 if (cur_curpos.lnum == 1)
6498 return 0;
6499
Bram Moolenaar071d4272004-06-13 20:20:40 +00006500 /* Get a copy of the current contents of the line.
6501 * This is required, because only the most recent line obtained with
6502 * ml_get is valid! */
6503 linecopy = vim_strsave(ml_get(cur_curpos.lnum));
6504 if (linecopy == NULL)
6505 return 0;
6506
6507 /*
6508 * In insert mode and the cursor is on a ')' truncate the line at the
6509 * cursor position. We don't want to line up with the matching '(' when
6510 * inserting new stuff.
6511 * For unknown reasons the cursor might be past the end of the line, thus
6512 * check for that.
6513 */
6514 if ((State & INSERT)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006515 && curwin->w_cursor.col < (colnr_T)STRLEN(linecopy)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006516 && linecopy[curwin->w_cursor.col] == ')')
6517 linecopy[curwin->w_cursor.col] = NUL;
6518
6519 theline = skipwhite(linecopy);
6520
6521 /* move the cursor to the start of the line */
6522
6523 curwin->w_cursor.col = 0;
6524
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006525 original_line_islabel = cin_islabel(ind_maxcomment); /* XXX */
6526
Bram Moolenaar071d4272004-06-13 20:20:40 +00006527 /*
6528 * #defines and so on always go at the left when included in 'cinkeys'.
6529 */
6530 if (*theline == '#' && (*linecopy == '#' || in_cinkeys('#', ' ', TRUE)))
6531 {
6532 amount = 0;
6533 }
6534
6535 /*
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006536 * Is it a non-case label? Then that goes at the left margin too unless:
6537 * - JS flag is set.
6538 * - 'L' item has a positive value.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006539 */
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006540 else if (original_line_islabel && !ind_js && ind_jump_label < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006541 {
6542 amount = 0;
6543 }
6544
6545 /*
6546 * If we're inside a "//" comment and there is a "//" comment in a
6547 * previous line, lineup with that one.
6548 */
6549 else if (cin_islinecomment(theline)
6550 && (trypos = find_line_comment()) != NULL) /* XXX */
6551 {
6552 /* find how indented the line beginning the comment is */
6553 getvcol(curwin, trypos, &col, NULL, NULL);
6554 amount = col;
6555 }
6556
6557 /*
6558 * If we're inside a comment and not looking at the start of the
6559 * comment, try using the 'comments' option.
6560 */
6561 else if (!cin_iscomment(theline)
6562 && (trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
6563 {
6564 int lead_start_len = 2;
6565 int lead_middle_len = 1;
6566 char_u lead_start[COM_MAX_LEN]; /* start-comment string */
6567 char_u lead_middle[COM_MAX_LEN]; /* middle-comment string */
6568 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
6569 char_u *p;
6570 int start_align = 0;
6571 int start_off = 0;
6572 int done = FALSE;
6573
6574 /* find how indented the line beginning the comment is */
6575 getvcol(curwin, trypos, &col, NULL, NULL);
6576 amount = col;
Bram Moolenaar4aa97422011-04-11 14:27:38 +02006577 *lead_start = NUL;
6578 *lead_middle = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006579
6580 p = curbuf->b_p_com;
6581 while (*p != NUL)
6582 {
6583 int align = 0;
6584 int off = 0;
6585 int what = 0;
6586
6587 while (*p != NUL && *p != ':')
6588 {
6589 if (*p == COM_START || *p == COM_END || *p == COM_MIDDLE)
6590 what = *p++;
6591 else if (*p == COM_LEFT || *p == COM_RIGHT)
6592 align = *p++;
6593 else if (VIM_ISDIGIT(*p) || *p == '-')
6594 off = getdigits(&p);
6595 else
6596 ++p;
6597 }
6598
6599 if (*p == ':')
6600 ++p;
6601 (void)copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
6602 if (what == COM_START)
6603 {
6604 STRCPY(lead_start, lead_end);
6605 lead_start_len = (int)STRLEN(lead_start);
6606 start_off = off;
6607 start_align = align;
6608 }
6609 else if (what == COM_MIDDLE)
6610 {
6611 STRCPY(lead_middle, lead_end);
6612 lead_middle_len = (int)STRLEN(lead_middle);
6613 }
6614 else if (what == COM_END)
6615 {
6616 /* If our line starts with the middle comment string, line it
6617 * up with the comment opener per the 'comments' option. */
6618 if (STRNCMP(theline, lead_middle, lead_middle_len) == 0
6619 && STRNCMP(theline, lead_end, STRLEN(lead_end)) != 0)
6620 {
6621 done = TRUE;
6622 if (curwin->w_cursor.lnum > 1)
6623 {
6624 /* If the start comment string matches in the previous
Bram Moolenaare21877a2008-02-13 09:58:14 +00006625 * line, use the indent of that line plus offset. If
Bram Moolenaar071d4272004-06-13 20:20:40 +00006626 * the middle comment string matches in the previous
6627 * line, use the indent of that line. XXX */
6628 look = skipwhite(ml_get(curwin->w_cursor.lnum - 1));
6629 if (STRNCMP(look, lead_start, lead_start_len) == 0)
6630 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6631 else if (STRNCMP(look, lead_middle,
6632 lead_middle_len) == 0)
6633 {
6634 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6635 break;
6636 }
6637 /* If the start comment string doesn't match with the
6638 * start of the comment, skip this entry. XXX */
6639 else if (STRNCMP(ml_get(trypos->lnum) + trypos->col,
6640 lead_start, lead_start_len) != 0)
6641 continue;
6642 }
6643 if (start_off != 0)
6644 amount += start_off;
6645 else if (start_align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006646 amount += vim_strsize(lead_start)
6647 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006648 break;
6649 }
6650
6651 /* If our line starts with the end comment string, line it up
6652 * with the middle comment */
6653 if (STRNCMP(theline, lead_middle, lead_middle_len) != 0
6654 && STRNCMP(theline, lead_end, STRLEN(lead_end)) == 0)
6655 {
6656 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6657 /* XXX */
6658 if (off != 0)
6659 amount += off;
6660 else if (align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006661 amount += vim_strsize(lead_start)
6662 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006663 done = TRUE;
6664 break;
6665 }
6666 }
6667 }
6668
6669 /* If our line starts with an asterisk, line up with the
6670 * asterisk in the comment opener; otherwise, line up
6671 * with the first character of the comment text.
6672 */
6673 if (done)
6674 ;
6675 else if (theline[0] == '*')
6676 amount += 1;
6677 else
6678 {
6679 /*
6680 * If we are more than one line away from the comment opener, take
6681 * the indent of the previous non-empty line. If 'cino' has "CO"
6682 * and we are just below the comment opener and there are any
6683 * white characters after it line up with the text after it;
6684 * otherwise, add the amount specified by "c" in 'cino'
6685 */
6686 amount = -1;
6687 for (lnum = cur_curpos.lnum - 1; lnum > trypos->lnum; --lnum)
6688 {
6689 if (linewhite(lnum)) /* skip blank lines */
6690 continue;
6691 amount = get_indent_lnum(lnum); /* XXX */
6692 break;
6693 }
6694 if (amount == -1) /* use the comment opener */
6695 {
6696 if (!ind_in_comment2)
6697 {
6698 start = ml_get(trypos->lnum);
6699 look = start + trypos->col + 2; /* skip / and * */
6700 if (*look != NUL) /* if something after it */
6701 trypos->col = (colnr_T)(skipwhite(look) - start);
6702 }
6703 getvcol(curwin, trypos, &col, NULL, NULL);
6704 amount = col;
6705 if (ind_in_comment2 || *look == NUL)
6706 amount += ind_in_comment;
6707 }
6708 }
6709 }
6710
6711 /*
6712 * Are we inside parentheses or braces?
6713 */ /* XXX */
6714 else if (((trypos = find_match_paren(ind_maxparen, ind_maxcomment)) != NULL
6715 && ind_java == 0)
6716 || (tryposBrace = find_start_brace(ind_maxcomment)) != NULL
6717 || trypos != NULL)
6718 {
6719 if (trypos != NULL && tryposBrace != NULL)
6720 {
6721 /* Both an unmatched '(' and '{' is found. Use the one which is
6722 * closer to the current cursor position, set the other to NULL. */
6723 if (trypos->lnum != tryposBrace->lnum
6724 ? trypos->lnum < tryposBrace->lnum
6725 : trypos->col < tryposBrace->col)
6726 trypos = NULL;
6727 else
6728 tryposBrace = NULL;
6729 }
6730
6731 if (trypos != NULL)
6732 {
6733 /*
6734 * If the matching paren is more than one line away, use the indent of
6735 * a previous non-empty line that matches the same paren.
6736 */
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006737 if (theline[0] == ')' && ind_paren_prev)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006738 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006739 /* Line up with the start of the matching paren line. */
6740 amount = get_indent_lnum(curwin->w_cursor.lnum - 1); /* XXX */
6741 }
6742 else
6743 {
6744 amount = -1;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006745 our_paren_pos = *trypos;
6746 for (lnum = cur_curpos.lnum - 1; lnum > our_paren_pos.lnum; --lnum)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006747 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006748 l = skipwhite(ml_get(lnum));
6749 if (cin_nocode(l)) /* skip comment lines */
6750 continue;
6751 if (cin_ispreproc_cont(&l, &lnum))
6752 continue; /* ignore #define, #if, etc. */
6753 curwin->w_cursor.lnum = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006754
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006755 /* Skip a comment. XXX */
6756 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
6757 {
6758 lnum = trypos->lnum + 1;
6759 continue;
6760 }
6761
6762 /* XXX */
6763 if ((trypos = find_match_paren(
6764 corr_ind_maxparen(ind_maxparen, &cur_curpos),
Bram Moolenaar071d4272004-06-13 20:20:40 +00006765 ind_maxcomment)) != NULL
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006766 && trypos->lnum == our_paren_pos.lnum
6767 && trypos->col == our_paren_pos.col)
6768 {
6769 amount = get_indent_lnum(lnum); /* XXX */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006770
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006771 if (theline[0] == ')')
6772 {
6773 if (our_paren_pos.lnum != lnum
6774 && cur_amount > amount)
6775 cur_amount = amount;
6776 amount = -1;
6777 }
6778 break;
6779 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006780 }
6781 }
6782
6783 /*
6784 * Line up with line where the matching paren is. XXX
6785 * If the line starts with a '(' or the indent for unclosed
6786 * parentheses is zero, line up with the unclosed parentheses.
6787 */
6788 if (amount == -1)
6789 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006790 int ignore_paren_col = 0;
6791
Bram Moolenaar071d4272004-06-13 20:20:40 +00006792 amount = skip_label(our_paren_pos.lnum, &look, ind_maxcomment);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006793 look = skipwhite(look);
6794 if (*look == '(')
6795 {
6796 linenr_T save_lnum = curwin->w_cursor.lnum;
6797 char_u *line;
6798 int look_col;
6799
6800 /* Ignore a '(' in front of the line that has a match before
6801 * our matching '('. */
6802 curwin->w_cursor.lnum = our_paren_pos.lnum;
6803 line = ml_get_curline();
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006804 look_col = (int)(look - line);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006805 curwin->w_cursor.col = look_col + 1;
6806 if ((trypos = findmatchlimit(NULL, ')', 0, ind_maxparen))
6807 != NULL
6808 && trypos->lnum == our_paren_pos.lnum
6809 && trypos->col < our_paren_pos.col)
6810 ignore_paren_col = trypos->col + 1;
6811
6812 curwin->w_cursor.lnum = save_lnum;
6813 look = ml_get(our_paren_pos.lnum) + look_col;
6814 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006815 if (theline[0] == ')' || ind_unclosed == 0
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006816 || (!ind_unclosed_noignore && *look == '('
6817 && ignore_paren_col == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006818 {
6819 /*
6820 * If we're looking at a close paren, line up right there;
6821 * otherwise, line up with the next (non-white) character.
6822 * When ind_unclosed_wrapped is set and the matching paren is
6823 * the last nonwhite character of the line, use either the
6824 * indent of the current line or the indentation of the next
6825 * outer paren and add ind_unclosed_wrapped (for very long
6826 * lines).
6827 */
6828 if (theline[0] != ')')
6829 {
6830 cur_amount = MAXCOL;
6831 l = ml_get(our_paren_pos.lnum);
6832 if (ind_unclosed_wrapped
6833 && cin_ends_in(l, (char_u *)"(", NULL))
6834 {
6835 /* look for opening unmatched paren, indent one level
6836 * for each additional level */
6837 n = 1;
6838 for (col = 0; col < our_paren_pos.col; ++col)
6839 {
6840 switch (l[col])
6841 {
6842 case '(':
6843 case '{': ++n;
6844 break;
6845
6846 case ')':
6847 case '}': if (n > 1)
6848 --n;
6849 break;
6850 }
6851 }
6852
6853 our_paren_pos.col = 0;
6854 amount += n * ind_unclosed_wrapped;
6855 }
6856 else if (ind_unclosed_whiteok)
6857 our_paren_pos.col++;
6858 else
6859 {
6860 col = our_paren_pos.col + 1;
6861 while (vim_iswhite(l[col]))
6862 col++;
6863 if (l[col] != NUL) /* In case of trailing space */
6864 our_paren_pos.col = col;
6865 else
6866 our_paren_pos.col++;
6867 }
6868 }
6869
6870 /*
6871 * Find how indented the paren is, or the character after it
6872 * if we did the above "if".
6873 */
6874 if (our_paren_pos.col > 0)
6875 {
6876 getvcol(curwin, &our_paren_pos, &col, NULL, NULL);
6877 if (cur_amount > (int)col)
6878 cur_amount = col;
6879 }
6880 }
6881
6882 if (theline[0] == ')' && ind_matching_paren)
6883 {
6884 /* Line up with the start of the matching paren line. */
6885 }
6886 else if (ind_unclosed == 0 || (!ind_unclosed_noignore
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006887 && *look == '(' && ignore_paren_col == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006888 {
6889 if (cur_amount != MAXCOL)
6890 amount = cur_amount;
6891 }
6892 else
6893 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006894 /* Add ind_unclosed2 for each '(' before our matching one, but
6895 * ignore (void) before the line (ignore_paren_col). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006896 col = our_paren_pos.col;
Bram Moolenaarb21e5842006-04-16 18:30:08 +00006897 while ((int)our_paren_pos.col > ignore_paren_col)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006898 {
6899 --our_paren_pos.col;
6900 switch (*ml_get_pos(&our_paren_pos))
6901 {
6902 case '(': amount += ind_unclosed2;
6903 col = our_paren_pos.col;
6904 break;
6905 case ')': amount -= ind_unclosed2;
6906 col = MAXCOL;
6907 break;
6908 }
6909 }
6910
6911 /* Use ind_unclosed once, when the first '(' is not inside
6912 * braces */
6913 if (col == MAXCOL)
6914 amount += ind_unclosed;
6915 else
6916 {
6917 curwin->w_cursor.lnum = our_paren_pos.lnum;
6918 curwin->w_cursor.col = col;
Bram Moolenaar367bec82011-04-11 14:26:19 +02006919 if (find_match_paren(ind_maxparen, ind_maxcomment) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006920 amount += ind_unclosed2;
6921 else
6922 amount += ind_unclosed;
6923 }
6924 /*
6925 * For a line starting with ')' use the minimum of the two
6926 * positions, to avoid giving it more indent than the previous
6927 * lines:
6928 * func_long_name( if (x
6929 * arg && yy
6930 * ) ^ not here ) ^ not here
6931 */
6932 if (cur_amount < amount)
6933 amount = cur_amount;
6934 }
6935 }
6936
6937 /* add extra indent for a comment */
6938 if (cin_iscomment(theline))
6939 amount += ind_comment;
6940 }
6941
6942 /*
6943 * Are we at least inside braces, then?
6944 */
6945 else
6946 {
6947 trypos = tryposBrace;
6948
6949 ourscope = trypos->lnum;
6950 start = ml_get(ourscope);
6951
6952 /*
6953 * Now figure out how indented the line is in general.
6954 * If the brace was at the start of the line, we use that;
6955 * otherwise, check out the indentation of the line as
6956 * a whole and then add the "imaginary indent" to that.
6957 */
6958 look = skipwhite(start);
6959 if (*look == '{')
6960 {
6961 getvcol(curwin, trypos, &col, NULL, NULL);
6962 amount = col;
6963 if (*start == '{')
6964 start_brace = BRACE_IN_COL0;
6965 else
6966 start_brace = BRACE_AT_START;
6967 }
6968 else
6969 {
6970 /*
6971 * that opening brace might have been on a continuation
6972 * line. if so, find the start of the line.
6973 */
6974 curwin->w_cursor.lnum = ourscope;
6975
6976 /*
6977 * position the cursor over the rightmost paren, so that
6978 * matching it will take us back to the start of the line.
6979 */
6980 lnum = ourscope;
6981 if (find_last_paren(start, '(', ')')
6982 && (trypos = find_match_paren(ind_maxparen,
6983 ind_maxcomment)) != NULL)
6984 lnum = trypos->lnum;
6985
6986 /*
6987 * It could have been something like
6988 * case 1: if (asdf &&
6989 * ldfd) {
6990 * }
6991 */
Bram Moolenaar6ec154b2011-06-12 21:51:08 +02006992 if (ind_js || (ind_keep_case_label
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006993 && cin_iscase(skipwhite(ml_get_curline()), FALSE)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006994 amount = get_indent();
6995 else
6996 amount = skip_label(lnum, &l, ind_maxcomment);
6997
6998 start_brace = BRACE_AT_END;
6999 }
7000
7001 /*
7002 * if we're looking at a closing brace, that's where
7003 * we want to be. otherwise, add the amount of room
7004 * that an indent is supposed to be.
7005 */
7006 if (theline[0] == '}')
7007 {
7008 /*
7009 * they may want closing braces to line up with something
7010 * other than the open brace. indulge them, if so.
7011 */
7012 amount += ind_close_extra;
7013 }
7014 else
7015 {
7016 /*
7017 * If we're looking at an "else", try to find an "if"
7018 * to match it with.
7019 * If we're looking at a "while", try to find a "do"
7020 * to match it with.
7021 */
7022 lookfor = LOOKFOR_INITIAL;
7023 if (cin_iselse(theline))
7024 lookfor = LOOKFOR_IF;
7025 else if (cin_iswhileofdo(theline, cur_curpos.lnum, ind_maxparen))
7026 /* XXX */
7027 lookfor = LOOKFOR_DO;
7028 if (lookfor != LOOKFOR_INITIAL)
7029 {
7030 curwin->w_cursor.lnum = cur_curpos.lnum;
7031 if (find_match(lookfor, ourscope, ind_maxparen,
7032 ind_maxcomment) == OK)
7033 {
7034 amount = get_indent(); /* XXX */
7035 goto theend;
7036 }
7037 }
7038
7039 /*
7040 * We get here if we are not on an "while-of-do" or "else" (or
7041 * failed to find a matching "if").
7042 * Search backwards for something to line up with.
7043 * First set amount for when we don't find anything.
7044 */
7045
7046 /*
7047 * if the '{' is _really_ at the left margin, use the imaginary
7048 * location of a left-margin brace. Otherwise, correct the
7049 * location for ind_open_extra.
7050 */
7051
7052 if (start_brace == BRACE_IN_COL0) /* '{' is in column 0 */
7053 {
7054 amount = ind_open_left_imag;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007055 lookfor_cpp_namespace = TRUE;
7056 }
7057 else if (start_brace == BRACE_AT_START &&
7058 lookfor_cpp_namespace) /* '{' is at start */
7059 {
7060
7061 lookfor_cpp_namespace = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007062 }
7063 else
7064 {
7065 if (start_brace == BRACE_AT_END) /* '{' is at end of line */
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007066 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007067 amount += ind_open_imag;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007068
7069 l = skipwhite(ml_get_curline());
7070 if (cin_is_cpp_namespace(l))
7071 amount += ind_cpp_namespace;
7072 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007073 else
7074 {
7075 /* Compensate for adding ind_open_extra later. */
7076 amount -= ind_open_extra;
7077 if (amount < 0)
7078 amount = 0;
7079 }
7080 }
7081
7082 lookfor_break = FALSE;
7083
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007084 if (cin_iscase(theline, FALSE)) /* it's a switch() label */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007085 {
7086 lookfor = LOOKFOR_CASE; /* find a previous switch() label */
7087 amount += ind_case;
7088 }
7089 else if (cin_isscopedecl(theline)) /* private:, ... */
7090 {
7091 lookfor = LOOKFOR_SCOPEDECL; /* class decl is this block */
7092 amount += ind_scopedecl;
7093 }
7094 else
7095 {
7096 if (ind_case_break && cin_isbreak(theline)) /* break; ... */
7097 lookfor_break = TRUE;
7098
7099 lookfor = LOOKFOR_INITIAL;
7100 amount += ind_level; /* ind_level from start of block */
7101 }
7102 scope_amount = amount;
7103 whilelevel = 0;
7104
7105 /*
7106 * Search backwards. If we find something we recognize, line up
7107 * with that.
7108 *
7109 * if we're looking at an open brace, indent
7110 * the usual amount relative to the conditional
7111 * that opens the block.
7112 */
7113 curwin->w_cursor = cur_curpos;
7114 for (;;)
7115 {
7116 curwin->w_cursor.lnum--;
7117 curwin->w_cursor.col = 0;
7118
7119 /*
7120 * If we went all the way back to the start of our scope, line
7121 * up with it.
7122 */
7123 if (curwin->w_cursor.lnum <= ourscope)
7124 {
7125 /* we reached end of scope:
7126 * if looking for a enum or structure initialization
7127 * go further back:
7128 * if it is an initializer (enum xxx or xxx =), then
7129 * don't add ind_continuation, otherwise it is a variable
7130 * declaration:
7131 * int x,
7132 * here; <-- add ind_continuation
7133 */
7134 if (lookfor == LOOKFOR_ENUM_OR_INIT)
7135 {
7136 if (curwin->w_cursor.lnum == 0
7137 || curwin->w_cursor.lnum
7138 < ourscope - ind_maxparen)
7139 {
7140 /* nothing found (abuse ind_maxparen as limit)
7141 * assume terminated line (i.e. a variable
7142 * initialization) */
7143 if (cont_amount > 0)
7144 amount = cont_amount;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007145 else if (!ind_js)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007146 amount += ind_continuation;
7147 break;
7148 }
7149
7150 l = ml_get_curline();
7151
7152 /*
7153 * If we're in a comment now, skip to the start of the
7154 * comment.
7155 */
7156 trypos = find_start_comment(ind_maxcomment);
7157 if (trypos != NULL)
7158 {
7159 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007160 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007161 continue;
7162 }
7163
7164 /*
7165 * Skip preprocessor directives and blank lines.
7166 */
7167 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7168 continue;
7169
7170 if (cin_nocode(l))
7171 continue;
7172
7173 terminated = cin_isterminated(l, FALSE, TRUE);
7174
7175 /*
7176 * If we are at top level and the line looks like a
7177 * function declaration, we are done
7178 * (it's a variable declaration).
7179 */
7180 if (start_brace != BRACE_IN_COL0
Bram Moolenaarc367faa2011-12-14 20:21:35 +01007181 || !cin_isfuncdecl(&l, curwin->w_cursor.lnum,
7182 0, ind_maxparen, ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007183 {
7184 /* if the line is terminated with another ','
7185 * it is a continued variable initialization.
7186 * don't add extra indent.
7187 * TODO: does not work, if a function
7188 * declaration is split over multiple lines:
7189 * cin_isfuncdecl returns FALSE then.
7190 */
7191 if (terminated == ',')
7192 break;
7193
7194 /* if it es a enum declaration or an assignment,
7195 * we are done.
7196 */
7197 if (terminated != ';' && cin_isinit())
7198 break;
7199
7200 /* nothing useful found */
7201 if (terminated == 0 || terminated == '{')
7202 continue;
7203 }
7204
7205 if (terminated != ';')
7206 {
7207 /* Skip parens and braces. Position the cursor
7208 * over the rightmost paren, so that matching it
7209 * will take us back to the start of the line.
7210 */ /* XXX */
7211 trypos = NULL;
7212 if (find_last_paren(l, '(', ')'))
7213 trypos = find_match_paren(ind_maxparen,
7214 ind_maxcomment);
7215
7216 if (trypos == NULL && find_last_paren(l, '{', '}'))
7217 trypos = find_start_brace(ind_maxcomment);
7218
7219 if (trypos != NULL)
7220 {
7221 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007222 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007223 continue;
7224 }
7225 }
7226
7227 /* it's a variable declaration, add indentation
7228 * like in
7229 * int a,
7230 * b;
7231 */
7232 if (cont_amount > 0)
7233 amount = cont_amount;
7234 else
7235 amount += ind_continuation;
7236 }
7237 else if (lookfor == LOOKFOR_UNTERM)
7238 {
7239 if (cont_amount > 0)
7240 amount = cont_amount;
7241 else
7242 amount += ind_continuation;
7243 }
Bram Moolenaare79d1532011-10-04 18:03:47 +02007244 else
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007245 {
Bram Moolenaare79d1532011-10-04 18:03:47 +02007246 if (lookfor != LOOKFOR_TERM
Bram Moolenaar071d4272004-06-13 20:20:40 +00007247 && lookfor != LOOKFOR_CPP_BASECLASS)
Bram Moolenaare79d1532011-10-04 18:03:47 +02007248 {
7249 amount = scope_amount;
7250 if (theline[0] == '{')
7251 {
7252 amount += ind_open_extra;
7253 added_to_amount = ind_open_extra;
7254 }
7255 }
7256
7257 if (lookfor_cpp_namespace)
7258 {
7259 /*
7260 * Looking for C++ namespace, need to look further
7261 * back.
7262 */
7263 if (curwin->w_cursor.lnum == ourscope)
7264 continue;
7265
7266 if (curwin->w_cursor.lnum == 0
7267 || curwin->w_cursor.lnum
7268 < ourscope - FIND_NAMESPACE_LIM)
7269 break;
7270
7271 l = ml_get_curline();
7272
7273 /* If we're in a comment now, skip to the start of
7274 * the comment. */
7275 trypos = find_start_comment(ind_maxcomment);
7276 if (trypos != NULL)
7277 {
7278 curwin->w_cursor.lnum = trypos->lnum + 1;
7279 curwin->w_cursor.col = 0;
7280 continue;
7281 }
7282
7283 /* Skip preprocessor directives and blank lines. */
7284 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7285 continue;
7286
7287 /* Finally the actual check for "namespace". */
7288 if (cin_is_cpp_namespace(l))
7289 {
7290 amount += ind_cpp_namespace - added_to_amount;
7291 break;
7292 }
7293
7294 if (cin_nocode(l))
7295 continue;
7296 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007297 }
7298 break;
7299 }
7300
7301 /*
7302 * If we're in a comment now, skip to the start of the comment.
7303 */ /* XXX */
7304 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
7305 {
7306 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007307 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007308 continue;
7309 }
7310
7311 l = ml_get_curline();
7312
7313 /*
7314 * If this is a switch() label, may line up relative to that.
Bram Moolenaar18144c82006-04-12 21:52:12 +00007315 * If this is a C++ scope declaration, do the same.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007316 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007317 iscase = cin_iscase(l, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007318 if (iscase || cin_isscopedecl(l))
7319 {
7320 /* we are only looking for cpp base class
7321 * declaration/initialization any longer */
7322 if (lookfor == LOOKFOR_CPP_BASECLASS)
7323 break;
7324
7325 /* When looking for a "do" we are not interested in
7326 * labels. */
7327 if (whilelevel > 0)
7328 continue;
7329
7330 /*
7331 * case xx:
7332 * c = 99 + <- this indent plus continuation
7333 *-> here;
7334 */
7335 if (lookfor == LOOKFOR_UNTERM
7336 || lookfor == LOOKFOR_ENUM_OR_INIT)
7337 {
7338 if (cont_amount > 0)
7339 amount = cont_amount;
7340 else
7341 amount += ind_continuation;
7342 break;
7343 }
7344
7345 /*
7346 * case xx: <- line up with this case
7347 * x = 333;
7348 * case yy:
7349 */
7350 if ( (iscase && lookfor == LOOKFOR_CASE)
7351 || (iscase && lookfor_break)
7352 || (!iscase && lookfor == LOOKFOR_SCOPEDECL))
7353 {
7354 /*
7355 * Check that this case label is not for another
7356 * switch()
7357 */ /* XXX */
7358 if ((trypos = find_start_brace(ind_maxcomment)) ==
7359 NULL || trypos->lnum == ourscope)
7360 {
7361 amount = get_indent(); /* XXX */
7362 break;
7363 }
7364 continue;
7365 }
7366
7367 n = get_indent_nolabel(curwin->w_cursor.lnum); /* XXX */
7368
7369 /*
7370 * case xx: if (cond) <- line up with this if
7371 * y = y + 1;
7372 * -> s = 99;
7373 *
7374 * case xx:
7375 * if (cond) <- line up with this line
7376 * y = y + 1;
7377 * -> s = 99;
7378 */
7379 if (lookfor == LOOKFOR_TERM)
7380 {
7381 if (n)
7382 amount = n;
7383
7384 if (!lookfor_break)
7385 break;
7386 }
7387
7388 /*
7389 * case xx: x = x + 1; <- line up with this x
7390 * -> y = y + 1;
7391 *
7392 * case xx: if (cond) <- line up with this if
7393 * -> y = y + 1;
7394 */
7395 if (n)
7396 {
7397 amount = n;
7398 l = after_label(ml_get_curline());
7399 if (l != NULL && cin_is_cinword(l))
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007400 {
7401 if (theline[0] == '{')
7402 amount += ind_open_extra;
7403 else
7404 amount += ind_level + ind_no_brace;
7405 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007406 break;
7407 }
7408
7409 /*
7410 * Try to get the indent of a statement before the switch
7411 * label. If nothing is found, line up relative to the
7412 * switch label.
7413 * break; <- may line up with this line
7414 * case xx:
7415 * -> y = 1;
7416 */
7417 scope_amount = get_indent() + (iscase /* XXX */
7418 ? ind_case_code : ind_scopedecl_code);
7419 lookfor = ind_case_break ? LOOKFOR_NOBREAK : LOOKFOR_ANY;
7420 continue;
7421 }
7422
7423 /*
7424 * Looking for a switch() label or C++ scope declaration,
7425 * ignore other lines, skip {}-blocks.
7426 */
7427 if (lookfor == LOOKFOR_CASE || lookfor == LOOKFOR_SCOPEDECL)
7428 {
7429 if (find_last_paren(l, '{', '}') && (trypos =
7430 find_start_brace(ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007431 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007432 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007433 curwin->w_cursor.col = 0;
7434 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007435 continue;
7436 }
7437
7438 /*
7439 * Ignore jump labels with nothing after them.
7440 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007441 if (!ind_js && cin_islabel(ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007442 {
7443 l = after_label(ml_get_curline());
7444 if (l == NULL || cin_nocode(l))
7445 continue;
7446 }
7447
7448 /*
7449 * Ignore #defines, #if, etc.
7450 * Ignore comment and empty lines.
7451 * (need to get the line again, cin_islabel() may have
7452 * unlocked it)
7453 */
7454 l = ml_get_curline();
7455 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum)
7456 || cin_nocode(l))
7457 continue;
7458
7459 /*
7460 * Are we at the start of a cpp base class declaration or
7461 * constructor initialization?
7462 */ /* XXX */
Bram Moolenaar18144c82006-04-12 21:52:12 +00007463 n = FALSE;
7464 if (lookfor != LOOKFOR_TERM && ind_cpp_baseclass > 0)
7465 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00007466 n = cin_is_cpp_baseclass(&col);
Bram Moolenaar18144c82006-04-12 21:52:12 +00007467 l = ml_get_curline();
7468 }
7469 if (n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007470 {
7471 if (lookfor == LOOKFOR_UNTERM)
7472 {
7473 if (cont_amount > 0)
7474 amount = cont_amount;
7475 else
7476 amount += ind_continuation;
7477 }
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007478 else if (theline[0] == '{')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007479 {
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007480 /* Need to find start of the declaration. */
7481 lookfor = LOOKFOR_UNTERM;
7482 ind_continuation = 0;
7483 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007484 }
7485 else
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007486 /* XXX */
7487 amount = get_baseclass_amount(col, ind_maxparen,
7488 ind_maxcomment, ind_cpp_baseclass);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007489 break;
7490 }
7491 else if (lookfor == LOOKFOR_CPP_BASECLASS)
7492 {
7493 /* only look, whether there is a cpp base class
Bram Moolenaar18144c82006-04-12 21:52:12 +00007494 * declaration or initialization before the opening brace.
7495 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007496 if (cin_isterminated(l, TRUE, FALSE))
7497 break;
7498 else
7499 continue;
7500 }
7501
7502 /*
7503 * What happens next depends on the line being terminated.
7504 * If terminated with a ',' only consider it terminating if
Bram Moolenaar25394022007-05-10 19:06:20 +00007505 * there is another unterminated statement behind, eg:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007506 * 123,
7507 * sizeof
7508 * here
7509 * Otherwise check whether it is a enumeration or structure
7510 * initialisation (not indented) or a variable declaration
7511 * (indented).
7512 */
7513 terminated = cin_isterminated(l, FALSE, TRUE);
7514
7515 if (terminated == 0 || (lookfor != LOOKFOR_UNTERM
7516 && terminated == ','))
7517 {
7518 /*
7519 * if we're in the middle of a paren thing,
7520 * go back to the line that starts it so
7521 * we can get the right prevailing indent
7522 * if ( foo &&
7523 * bar )
7524 */
7525 /*
7526 * position the cursor over the rightmost paren, so that
7527 * matching it will take us back to the start of the line.
7528 */
7529 (void)find_last_paren(l, '(', ')');
7530 trypos = find_match_paren(
7531 corr_ind_maxparen(ind_maxparen, &cur_curpos),
7532 ind_maxcomment);
7533
7534 /*
7535 * If we are looking for ',', we also look for matching
7536 * braces.
7537 */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007538 if (trypos == NULL && terminated == ','
7539 && find_last_paren(l, '{', '}'))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007540 trypos = find_start_brace(ind_maxcomment);
7541
7542 if (trypos != NULL)
7543 {
7544 /*
7545 * Check if we are on a case label now. This is
7546 * handled above.
7547 * case xx: if ( asdf &&
7548 * asdf)
7549 */
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007550 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007551 l = ml_get_curline();
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007552 if (cin_iscase(l, FALSE) || cin_isscopedecl(l))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007553 {
7554 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007555 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007556 continue;
7557 }
7558 }
7559
7560 /*
7561 * Skip over continuation lines to find the one to get the
7562 * indent from
7563 * char *usethis = "bla\
7564 * bla",
7565 * here;
7566 */
7567 if (terminated == ',')
7568 {
7569 while (curwin->w_cursor.lnum > 1)
7570 {
7571 l = ml_get(curwin->w_cursor.lnum - 1);
7572 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
7573 break;
7574 --curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007575 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007576 }
7577 }
7578
7579 /*
7580 * Get indent and pointer to text for current line,
7581 * ignoring any jump label. XXX
7582 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007583 if (!ind_js)
7584 cur_amount = skip_label(curwin->w_cursor.lnum,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007585 &l, ind_maxcomment);
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007586 else
7587 cur_amount = get_indent();
Bram Moolenaar071d4272004-06-13 20:20:40 +00007588 /*
7589 * If this is just above the line we are indenting, and it
7590 * starts with a '{', line it up with this line.
7591 * while (not)
7592 * -> {
7593 * }
7594 */
7595 if (terminated != ',' && lookfor != LOOKFOR_TERM
7596 && theline[0] == '{')
7597 {
7598 amount = cur_amount;
7599 /*
7600 * Only add ind_open_extra when the current line
7601 * doesn't start with a '{', which must have a match
7602 * in the same line (scope is the same). Probably:
7603 * { 1, 2 },
7604 * -> { 3, 4 }
7605 */
7606 if (*skipwhite(l) != '{')
7607 amount += ind_open_extra;
7608
7609 if (ind_cpp_baseclass)
7610 {
7611 /* have to look back, whether it is a cpp base
7612 * class declaration or initialization */
7613 lookfor = LOOKFOR_CPP_BASECLASS;
7614 continue;
7615 }
7616 break;
7617 }
7618
7619 /*
7620 * Check if we are after an "if", "while", etc.
7621 * Also allow " } else".
7622 */
7623 if (cin_is_cinword(l) || cin_iselse(skipwhite(l)))
7624 {
7625 /*
7626 * Found an unterminated line after an if (), line up
7627 * with the last one.
7628 * if (cond)
7629 * 100 +
7630 * -> here;
7631 */
7632 if (lookfor == LOOKFOR_UNTERM
7633 || lookfor == LOOKFOR_ENUM_OR_INIT)
7634 {
7635 if (cont_amount > 0)
7636 amount = cont_amount;
7637 else
7638 amount += ind_continuation;
7639 break;
7640 }
7641
7642 /*
7643 * If this is just above the line we are indenting, we
7644 * are finished.
7645 * while (not)
7646 * -> here;
7647 * Otherwise this indent can be used when the line
7648 * before this is terminated.
7649 * yyy;
7650 * if (stat)
7651 * while (not)
7652 * xxx;
7653 * -> here;
7654 */
7655 amount = cur_amount;
7656 if (theline[0] == '{')
7657 amount += ind_open_extra;
7658 if (lookfor != LOOKFOR_TERM)
7659 {
7660 amount += ind_level + ind_no_brace;
7661 break;
7662 }
7663
7664 /*
7665 * Special trick: when expecting the while () after a
7666 * do, line up with the while()
7667 * do
7668 * x = 1;
7669 * -> here
7670 */
7671 l = skipwhite(ml_get_curline());
7672 if (cin_isdo(l))
7673 {
7674 if (whilelevel == 0)
7675 break;
7676 --whilelevel;
7677 }
7678
7679 /*
7680 * When searching for a terminated line, don't use the
Bram Moolenaar334adf02011-05-25 13:34:04 +02007681 * one between the "if" and the matching "else".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007682 * Need to use the scope of this "else". XXX
7683 * If whilelevel != 0 continue looking for a "do {".
7684 */
Bram Moolenaar334adf02011-05-25 13:34:04 +02007685 if (cin_iselse(l) && whilelevel == 0)
7686 {
7687 /* If we're looking at "} else", let's make sure we
7688 * find the opening brace of the enclosing scope,
7689 * not the one from "if () {". */
7690 if (*l == '}')
7691 curwin->w_cursor.col =
Bram Moolenaar9b83c2f2011-05-25 17:29:44 +02007692 (colnr_T)(l - ml_get_curline()) + 1;
Bram Moolenaar334adf02011-05-25 13:34:04 +02007693
7694 if ((trypos = find_start_brace(ind_maxcomment))
7695 == NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007696 || find_match(LOOKFOR_IF, trypos->lnum,
Bram Moolenaar334adf02011-05-25 13:34:04 +02007697 ind_maxparen, ind_maxcomment) == FAIL)
7698 break;
7699 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007700 }
7701
7702 /*
7703 * If we're below an unterminated line that is not an
7704 * "if" or something, we may line up with this line or
Bram Moolenaar25394022007-05-10 19:06:20 +00007705 * add something for a continuation line, depending on
Bram Moolenaar071d4272004-06-13 20:20:40 +00007706 * the line before this one.
7707 */
7708 else
7709 {
7710 /*
7711 * Found two unterminated lines on a row, line up with
7712 * the last one.
7713 * c = 99 +
7714 * 100 +
7715 * -> here;
7716 */
7717 if (lookfor == LOOKFOR_UNTERM)
7718 {
7719 /* When line ends in a comma add extra indent */
7720 if (terminated == ',')
7721 amount += ind_continuation;
7722 break;
7723 }
7724
7725 if (lookfor == LOOKFOR_ENUM_OR_INIT)
7726 {
7727 /* Found two lines ending in ',', lineup with the
7728 * lowest one, but check for cpp base class
7729 * declaration/initialization, if it is an
7730 * opening brace or we are looking just for
7731 * enumerations/initializations. */
7732 if (terminated == ',')
7733 {
7734 if (ind_cpp_baseclass == 0)
7735 break;
7736
7737 lookfor = LOOKFOR_CPP_BASECLASS;
7738 continue;
7739 }
7740
7741 /* Ignore unterminated lines in between, but
7742 * reduce indent. */
7743 if (amount > cur_amount)
7744 amount = cur_amount;
7745 }
7746 else
7747 {
7748 /*
7749 * Found first unterminated line on a row, may
7750 * line up with this line, remember its indent
7751 * 100 +
7752 * -> here;
7753 */
7754 amount = cur_amount;
7755
7756 /*
7757 * If previous line ends in ',', check whether we
7758 * are in an initialization or enum
7759 * struct xxx =
7760 * {
7761 * sizeof a,
7762 * 124 };
7763 * or a normal possible continuation line.
7764 * but only, of no other statement has been found
7765 * yet.
7766 */
7767 if (lookfor == LOOKFOR_INITIAL && terminated == ',')
7768 {
7769 lookfor = LOOKFOR_ENUM_OR_INIT;
7770 cont_amount = cin_first_id_amount();
7771 }
7772 else
7773 {
7774 if (lookfor == LOOKFOR_INITIAL
7775 && *l != NUL
7776 && l[STRLEN(l) - 1] == '\\')
7777 /* XXX */
7778 cont_amount = cin_get_equal_amount(
7779 curwin->w_cursor.lnum);
7780 if (lookfor != LOOKFOR_TERM)
7781 lookfor = LOOKFOR_UNTERM;
7782 }
7783 }
7784 }
7785 }
7786
7787 /*
7788 * Check if we are after a while (cond);
7789 * If so: Ignore until the matching "do".
7790 */
7791 /* XXX */
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007792 else if (cin_iswhileofdo_end(terminated, ind_maxparen,
7793 ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007794 {
7795 /*
7796 * Found an unterminated line after a while ();, line up
7797 * with the last one.
7798 * while (cond);
7799 * 100 + <- line up with this one
7800 * -> here;
7801 */
7802 if (lookfor == LOOKFOR_UNTERM
7803 || lookfor == LOOKFOR_ENUM_OR_INIT)
7804 {
7805 if (cont_amount > 0)
7806 amount = cont_amount;
7807 else
7808 amount += ind_continuation;
7809 break;
7810 }
7811
7812 if (whilelevel == 0)
7813 {
7814 lookfor = LOOKFOR_TERM;
7815 amount = get_indent(); /* XXX */
7816 if (theline[0] == '{')
7817 amount += ind_open_extra;
7818 }
7819 ++whilelevel;
7820 }
7821
7822 /*
7823 * We are after a "normal" statement.
7824 * If we had another statement we can stop now and use the
7825 * indent of that other statement.
7826 * Otherwise the indent of the current statement may be used,
7827 * search backwards for the next "normal" statement.
7828 */
7829 else
7830 {
7831 /*
7832 * Skip single break line, if before a switch label. It
7833 * may be lined up with the case label.
7834 */
7835 if (lookfor == LOOKFOR_NOBREAK
7836 && cin_isbreak(skipwhite(ml_get_curline())))
7837 {
7838 lookfor = LOOKFOR_ANY;
7839 continue;
7840 }
7841
7842 /*
7843 * Handle "do {" line.
7844 */
7845 if (whilelevel > 0)
7846 {
7847 l = cin_skipcomment(ml_get_curline());
7848 if (cin_isdo(l))
7849 {
7850 amount = get_indent(); /* XXX */
7851 --whilelevel;
7852 continue;
7853 }
7854 }
7855
7856 /*
7857 * Found a terminated line above an unterminated line. Add
7858 * the amount for a continuation line.
7859 * x = 1;
7860 * y = foo +
7861 * -> here;
7862 * or
7863 * int x = 1;
7864 * int foo,
7865 * -> here;
7866 */
7867 if (lookfor == LOOKFOR_UNTERM
7868 || lookfor == LOOKFOR_ENUM_OR_INIT)
7869 {
7870 if (cont_amount > 0)
7871 amount = cont_amount;
7872 else
7873 amount += ind_continuation;
7874 break;
7875 }
7876
7877 /*
7878 * Found a terminated line above a terminated line or "if"
7879 * etc. line. Use the amount of the line below us.
7880 * x = 1; x = 1;
7881 * if (asdf) y = 2;
7882 * while (asdf) ->here;
7883 * here;
7884 * ->foo;
7885 */
7886 if (lookfor == LOOKFOR_TERM)
7887 {
7888 if (!lookfor_break && whilelevel == 0)
7889 break;
7890 }
7891
7892 /*
7893 * First line above the one we're indenting is terminated.
7894 * To know what needs to be done look further backward for
7895 * a terminated line.
7896 */
7897 else
7898 {
7899 /*
7900 * position the cursor over the rightmost paren, so
7901 * that matching it will take us back to the start of
7902 * the line. Helps for:
7903 * func(asdr,
7904 * asdfasdf);
7905 * here;
7906 */
7907term_again:
7908 l = ml_get_curline();
7909 if (find_last_paren(l, '(', ')')
7910 && (trypos = find_match_paren(ind_maxparen,
7911 ind_maxcomment)) != NULL)
7912 {
7913 /*
7914 * Check if we are on a case label now. This is
7915 * handled above.
7916 * case xx: if ( asdf &&
7917 * asdf)
7918 */
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007919 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007920 l = ml_get_curline();
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007921 if (cin_iscase(l, FALSE) || cin_isscopedecl(l))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007922 {
7923 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007924 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007925 continue;
7926 }
7927 }
7928
7929 /* When aligning with the case statement, don't align
7930 * with a statement after it.
7931 * case 1: { <-- don't use this { position
7932 * stat;
7933 * }
7934 * case 2:
7935 * stat;
7936 * }
7937 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007938 iscase = (ind_keep_case_label && cin_iscase(l, FALSE));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007939
7940 /*
7941 * Get indent and pointer to text for current line,
7942 * ignoring any jump label.
7943 */
7944 amount = skip_label(curwin->w_cursor.lnum,
7945 &l, ind_maxcomment);
7946
7947 if (theline[0] == '{')
7948 amount += ind_open_extra;
7949 /* See remark above: "Only add ind_open_extra.." */
Bram Moolenaar18144c82006-04-12 21:52:12 +00007950 l = skipwhite(l);
7951 if (*l == '{')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007952 amount -= ind_open_extra;
7953 lookfor = iscase ? LOOKFOR_ANY : LOOKFOR_TERM;
7954
7955 /*
Bram Moolenaar18144c82006-04-12 21:52:12 +00007956 * When a terminated line starts with "else" skip to
7957 * the matching "if":
7958 * else 3;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00007959 * indent this;
Bram Moolenaar18144c82006-04-12 21:52:12 +00007960 * Need to use the scope of this "else". XXX
7961 * If whilelevel != 0 continue looking for a "do {".
7962 */
7963 if (lookfor == LOOKFOR_TERM
7964 && *l != '}'
7965 && cin_iselse(l)
7966 && whilelevel == 0)
7967 {
7968 if ((trypos = find_start_brace(ind_maxcomment))
7969 == NULL
7970 || find_match(LOOKFOR_IF, trypos->lnum,
7971 ind_maxparen, ind_maxcomment) == FAIL)
7972 break;
7973 continue;
7974 }
7975
7976 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007977 * If we're at the end of a block, skip to the start of
7978 * that block.
7979 */
Bram Moolenaar6d8f9c62011-11-30 13:03:28 +01007980 l = ml_get_curline();
Bram Moolenaar50f42ca2011-07-15 14:12:30 +02007981 if (find_last_paren(l, '{', '}')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007982 && (trypos = find_start_brace(ind_maxcomment))
7983 != NULL) /* XXX */
7984 {
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007985 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007986 /* if not "else {" check for terminated again */
7987 /* but skip block for "} else {" */
7988 l = cin_skipcomment(ml_get_curline());
7989 if (*l == '}' || !cin_iselse(l))
7990 goto term_again;
7991 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007992 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007993 }
7994 }
7995 }
7996 }
7997 }
7998 }
7999
8000 /* add extra indent for a comment */
8001 if (cin_iscomment(theline))
8002 amount += ind_comment;
Bram Moolenaar02c707a2010-07-17 17:12:06 +02008003
8004 /* subtract extra left-shift for jump labels */
8005 if (ind_jump_label > 0 && original_line_islabel)
8006 amount -= ind_jump_label;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008007 }
8008
8009 /*
8010 * ok -- we're not inside any sort of structure at all!
8011 *
8012 * this means we're at the top level, and everything should
8013 * basically just match where the previous line is, except
8014 * for the lines immediately following a function declaration,
8015 * which are K&R-style parameters and need to be indented.
8016 */
8017 else
8018 {
8019 /*
8020 * if our line starts with an open brace, forget about any
8021 * prevailing indent and make sure it looks like the start
8022 * of a function
8023 */
8024
8025 if (theline[0] == '{')
8026 {
8027 amount = ind_first_open;
8028 }
8029
8030 /*
8031 * If the NEXT line is a function declaration, the current
8032 * line needs to be indented as a function type spec.
Bram Moolenaar1a89bbe2010-03-02 12:38:22 +01008033 * Don't do this if the current line looks like a comment or if the
8034 * current line is terminated, ie. ends in ';', or if the current line
8035 * contains { or }: "void f() {\n if (1)"
Bram Moolenaar071d4272004-06-13 20:20:40 +00008036 */
8037 else if (cur_curpos.lnum < curbuf->b_ml.ml_line_count
8038 && !cin_nocode(theline)
Bram Moolenaar1a89bbe2010-03-02 12:38:22 +01008039 && vim_strchr(theline, '{') == NULL
8040 && vim_strchr(theline, '}') == NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00008041 && !cin_ends_in(theline, (char_u *)":", NULL)
8042 && !cin_ends_in(theline, (char_u *)",", NULL)
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008043 && cin_isfuncdecl(NULL, cur_curpos.lnum + 1,
8044 cur_curpos.lnum + 1,
8045 ind_maxparen, ind_maxcomment)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008046 && !cin_isterminated(theline, FALSE, TRUE))
8047 {
8048 amount = ind_func_type;
8049 }
8050 else
8051 {
8052 amount = 0;
8053 curwin->w_cursor = cur_curpos;
8054
8055 /* search backwards until we find something we recognize */
8056
8057 while (curwin->w_cursor.lnum > 1)
8058 {
8059 curwin->w_cursor.lnum--;
8060 curwin->w_cursor.col = 0;
8061
8062 l = ml_get_curline();
8063
8064 /*
8065 * If we're in a comment now, skip to the start of the comment.
8066 */ /* XXX */
8067 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
8068 {
8069 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008070 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008071 continue;
8072 }
8073
8074 /*
Bram Moolenaar18144c82006-04-12 21:52:12 +00008075 * Are we at the start of a cpp base class declaration or
8076 * constructor initialization?
Bram Moolenaar071d4272004-06-13 20:20:40 +00008077 */ /* XXX */
Bram Moolenaar18144c82006-04-12 21:52:12 +00008078 n = FALSE;
8079 if (ind_cpp_baseclass != 0 && theline[0] != '{')
8080 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00008081 n = cin_is_cpp_baseclass(&col);
Bram Moolenaar18144c82006-04-12 21:52:12 +00008082 l = ml_get_curline();
8083 }
8084 if (n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008085 {
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00008086 /* XXX */
8087 amount = get_baseclass_amount(col, ind_maxparen,
8088 ind_maxcomment, ind_cpp_baseclass);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008089 break;
8090 }
8091
8092 /*
8093 * Skip preprocessor directives and blank lines.
8094 */
8095 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
8096 continue;
8097
8098 if (cin_nocode(l))
8099 continue;
8100
8101 /*
8102 * If the previous line ends in ',', use one level of
8103 * indentation:
8104 * int foo,
8105 * bar;
8106 * do this before checking for '}' in case of eg.
8107 * enum foobar
8108 * {
8109 * ...
8110 * } foo,
8111 * bar;
8112 */
8113 n = 0;
8114 if (cin_ends_in(l, (char_u *)",", NULL)
8115 || (*l != NUL && (n = l[STRLEN(l) - 1]) == '\\'))
8116 {
8117 /* take us back to opening paren */
8118 if (find_last_paren(l, '(', ')')
8119 && (trypos = find_match_paren(ind_maxparen,
8120 ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008121 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008122
8123 /* For a line ending in ',' that is a continuation line go
8124 * back to the first line with a backslash:
8125 * char *foo = "bla\
8126 * bla",
8127 * here;
8128 */
8129 while (n == 0 && curwin->w_cursor.lnum > 1)
8130 {
8131 l = ml_get(curwin->w_cursor.lnum - 1);
8132 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
8133 break;
8134 --curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008135 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008136 }
8137
8138 amount = get_indent(); /* XXX */
8139
8140 if (amount == 0)
8141 amount = cin_first_id_amount();
8142 if (amount == 0)
8143 amount = ind_continuation;
8144 break;
8145 }
8146
8147 /*
8148 * If the line looks like a function declaration, and we're
8149 * not in a comment, put it the left margin.
8150 */
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008151 if (cin_isfuncdecl(NULL, cur_curpos.lnum, 0,
8152 ind_maxparen, ind_maxcomment)) /* XXX */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008153 break;
8154 l = ml_get_curline();
8155
8156 /*
8157 * Finding the closing '}' of a previous function. Put
8158 * current line at the left margin. For when 'cino' has "fs".
8159 */
8160 if (*skipwhite(l) == '}')
8161 break;
8162
8163 /* (matching {)
8164 * If the previous line ends on '};' (maybe followed by
8165 * comments) align at column 0. For example:
8166 * char *string_array[] = { "foo",
8167 * / * x * / "b};ar" }; / * foobar * /
8168 */
8169 if (cin_ends_in(l, (char_u *)"};", NULL))
8170 break;
8171
8172 /*
Bram Moolenaar3388bb42011-11-30 17:20:23 +01008173 * Find a line only has a semicolon that belongs to a previous
8174 * line ending in '}', e.g. before an #endif. Don't increase
8175 * indent then.
8176 */
8177 if (*(look = skipwhite(l)) == ';' && cin_nocode(look + 1))
8178 {
8179 pos_T curpos_save = curwin->w_cursor;
8180
8181 while (curwin->w_cursor.lnum > 1)
8182 {
8183 look = ml_get(--curwin->w_cursor.lnum);
8184 if (!(cin_nocode(look) || cin_ispreproc_cont(
8185 &look, &curwin->w_cursor.lnum)))
8186 break;
8187 }
8188 if (curwin->w_cursor.lnum > 0
8189 && cin_ends_in(look, (char_u *)"}", NULL))
8190 break;
8191
8192 curwin->w_cursor = curpos_save;
8193 }
8194
8195 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008196 * If the PREVIOUS line is a function declaration, the current
8197 * line (and the ones that follow) needs to be indented as
8198 * parameters.
8199 */
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008200 if (cin_isfuncdecl(&l, curwin->w_cursor.lnum, 0,
8201 ind_maxparen, ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008202 {
8203 amount = ind_param;
8204 break;
8205 }
8206
8207 /*
8208 * If the previous line ends in ';' and the line before the
8209 * previous line ends in ',' or '\', ident to column zero:
8210 * int foo,
8211 * bar;
8212 * indent_to_0 here;
8213 */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00008214 if (cin_ends_in(l, (char_u *)";", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008215 {
8216 l = ml_get(curwin->w_cursor.lnum - 1);
8217 if (cin_ends_in(l, (char_u *)",", NULL)
8218 || (*l != NUL && l[STRLEN(l) - 1] == '\\'))
8219 break;
8220 l = ml_get_curline();
8221 }
8222
8223 /*
8224 * Doesn't look like anything interesting -- so just
8225 * use the indent of this line.
8226 *
8227 * Position the cursor over the rightmost paren, so that
8228 * matching it will take us back to the start of the line.
8229 */
8230 find_last_paren(l, '(', ')');
8231
8232 if ((trypos = find_match_paren(ind_maxparen,
8233 ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008234 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008235 amount = get_indent(); /* XXX */
8236 break;
8237 }
8238
8239 /* add extra indent for a comment */
8240 if (cin_iscomment(theline))
8241 amount += ind_comment;
8242
8243 /* add extra indent if the previous line ended in a backslash:
8244 * "asdfasdf\
8245 * here";
8246 * char *foo = "asdf\
8247 * here";
8248 */
8249 if (cur_curpos.lnum > 1)
8250 {
8251 l = ml_get(cur_curpos.lnum - 1);
8252 if (*l != NUL && l[STRLEN(l) - 1] == '\\')
8253 {
8254 cur_amount = cin_get_equal_amount(cur_curpos.lnum - 1);
8255 if (cur_amount > 0)
8256 amount = cur_amount;
8257 else if (cur_amount == 0)
8258 amount += ind_continuation;
8259 }
8260 }
8261 }
8262 }
8263
8264theend:
8265 /* put the cursor back where it belongs */
8266 curwin->w_cursor = cur_curpos;
8267
8268 vim_free(linecopy);
8269
8270 if (amount < 0)
8271 return 0;
8272 return amount;
8273}
8274
8275 static int
8276find_match(lookfor, ourscope, ind_maxparen, ind_maxcomment)
8277 int lookfor;
8278 linenr_T ourscope;
8279 int ind_maxparen;
8280 int ind_maxcomment;
8281{
8282 char_u *look;
8283 pos_T *theirscope;
8284 char_u *mightbeif;
8285 int elselevel;
8286 int whilelevel;
8287
8288 if (lookfor == LOOKFOR_IF)
8289 {
8290 elselevel = 1;
8291 whilelevel = 0;
8292 }
8293 else
8294 {
8295 elselevel = 0;
8296 whilelevel = 1;
8297 }
8298
8299 curwin->w_cursor.col = 0;
8300
8301 while (curwin->w_cursor.lnum > ourscope + 1)
8302 {
8303 curwin->w_cursor.lnum--;
8304 curwin->w_cursor.col = 0;
8305
8306 look = cin_skipcomment(ml_get_curline());
8307 if (cin_iselse(look)
8308 || cin_isif(look)
8309 || cin_isdo(look) /* XXX */
8310 || cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
8311 {
8312 /*
8313 * if we've gone outside the braces entirely,
8314 * we must be out of scope...
8315 */
8316 theirscope = find_start_brace(ind_maxcomment); /* XXX */
8317 if (theirscope == NULL)
8318 break;
8319
8320 /*
8321 * and if the brace enclosing this is further
8322 * back than the one enclosing the else, we're
8323 * out of luck too.
8324 */
8325 if (theirscope->lnum < ourscope)
8326 break;
8327
8328 /*
8329 * and if they're enclosed in a *deeper* brace,
8330 * then we can ignore it because it's in a
8331 * different scope...
8332 */
8333 if (theirscope->lnum > ourscope)
8334 continue;
8335
8336 /*
8337 * if it was an "else" (that's not an "else if")
8338 * then we need to go back to another if, so
8339 * increment elselevel
8340 */
8341 look = cin_skipcomment(ml_get_curline());
8342 if (cin_iselse(look))
8343 {
8344 mightbeif = cin_skipcomment(look + 4);
8345 if (!cin_isif(mightbeif))
8346 ++elselevel;
8347 continue;
8348 }
8349
8350 /*
8351 * if it was a "while" then we need to go back to
8352 * another "do", so increment whilelevel. XXX
8353 */
8354 if (cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
8355 {
8356 ++whilelevel;
8357 continue;
8358 }
8359
8360 /* If it's an "if" decrement elselevel */
8361 look = cin_skipcomment(ml_get_curline());
8362 if (cin_isif(look))
8363 {
8364 elselevel--;
8365 /*
8366 * When looking for an "if" ignore "while"s that
8367 * get in the way.
8368 */
8369 if (elselevel == 0 && lookfor == LOOKFOR_IF)
8370 whilelevel = 0;
8371 }
8372
8373 /* If it's a "do" decrement whilelevel */
8374 if (cin_isdo(look))
8375 whilelevel--;
8376
8377 /*
8378 * if we've used up all the elses, then
8379 * this must be the if that we want!
8380 * match the indent level of that if.
8381 */
8382 if (elselevel <= 0 && whilelevel <= 0)
8383 {
8384 return OK;
8385 }
8386 }
8387 }
8388 return FAIL;
8389}
8390
8391# if defined(FEAT_EVAL) || defined(PROTO)
8392/*
8393 * Get indent level from 'indentexpr'.
8394 */
8395 int
8396get_expr_indent()
8397{
8398 int indent;
8399 pos_T pos;
8400 int save_State;
Bram Moolenaard1f56e62006-02-22 21:25:37 +00008401 int use_sandbox = was_set_insecurely((char_u *)"indentexpr",
8402 OPT_LOCAL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008403
8404 pos = curwin->w_cursor;
8405 set_vim_var_nr(VV_LNUM, curwin->w_cursor.lnum);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00008406 if (use_sandbox)
8407 ++sandbox;
8408 ++textlock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008409 indent = eval_to_number(curbuf->b_p_inde);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00008410 if (use_sandbox)
8411 --sandbox;
8412 --textlock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008413
8414 /* Restore the cursor position so that 'indentexpr' doesn't need to.
8415 * Pretend to be in Insert mode, allow cursor past end of line for "o"
8416 * command. */
8417 save_State = State;
8418 State = INSERT;
8419 curwin->w_cursor = pos;
8420 check_cursor();
8421 State = save_State;
8422
8423 /* If there is an error, just keep the current indent. */
8424 if (indent < 0)
8425 indent = get_indent();
8426
8427 return indent;
8428}
8429# endif
8430
8431#endif /* FEAT_CINDENT */
8432
8433#if defined(FEAT_LISP) || defined(PROTO)
8434
8435static int lisp_match __ARGS((char_u *p));
8436
8437 static int
8438lisp_match(p)
8439 char_u *p;
8440{
8441 char_u buf[LSIZE];
8442 int len;
8443 char_u *word = p_lispwords;
8444
8445 while (*word != NUL)
8446 {
8447 (void)copy_option_part(&word, buf, LSIZE, ",");
8448 len = (int)STRLEN(buf);
8449 if (STRNCMP(buf, p, len) == 0 && p[len] == ' ')
8450 return TRUE;
8451 }
8452 return FALSE;
8453}
8454
8455/*
8456 * When 'p' is present in 'cpoptions, a Vi compatible method is used.
8457 * The incompatible newer method is quite a bit better at indenting
8458 * code in lisp-like languages than the traditional one; it's still
8459 * mostly heuristics however -- Dirk van Deun, dirk@rave.org
8460 *
8461 * TODO:
8462 * Findmatch() should be adapted for lisp, also to make showmatch
8463 * work correctly: now (v5.3) it seems all C/C++ oriented:
8464 * - it does not recognize the #\( and #\) notations as character literals
8465 * - it doesn't know about comments starting with a semicolon
8466 * - it incorrectly interprets '(' as a character literal
8467 * All this messes up get_lisp_indent in some rare cases.
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008468 * Update from Sergey Khorev:
8469 * I tried to fix the first two issues.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008470 */
8471 int
8472get_lisp_indent()
8473{
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008474 pos_T *pos, realpos, paren;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008475 int amount;
8476 char_u *that;
8477 colnr_T col;
8478 colnr_T firsttry;
8479 int parencount, quotecount;
8480 int vi_lisp;
8481
8482 /* Set vi_lisp to use the vi-compatible method */
8483 vi_lisp = (vim_strchr(p_cpo, CPO_LISP) != NULL);
8484
8485 realpos = curwin->w_cursor;
8486 curwin->w_cursor.col = 0;
8487
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008488 if ((pos = findmatch(NULL, '(')) == NULL)
8489 pos = findmatch(NULL, '[');
8490 else
8491 {
8492 paren = *pos;
8493 pos = findmatch(NULL, '[');
8494 if (pos == NULL || ltp(pos, &paren))
8495 pos = &paren;
8496 }
8497 if (pos != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008498 {
8499 /* Extra trick: Take the indent of the first previous non-white
8500 * line that is at the same () level. */
8501 amount = -1;
8502 parencount = 0;
8503
8504 while (--curwin->w_cursor.lnum >= pos->lnum)
8505 {
8506 if (linewhite(curwin->w_cursor.lnum))
8507 continue;
8508 for (that = ml_get_curline(); *that != NUL; ++that)
8509 {
8510 if (*that == ';')
8511 {
8512 while (*(that + 1) != NUL)
8513 ++that;
8514 continue;
8515 }
8516 if (*that == '\\')
8517 {
8518 if (*(that + 1) != NUL)
8519 ++that;
8520 continue;
8521 }
8522 if (*that == '"' && *(that + 1) != NUL)
8523 {
Bram Moolenaar15ff6c12006-09-15 18:18:09 +00008524 while (*++that && *that != '"')
8525 {
8526 /* skipping escaped characters in the string */
8527 if (*that == '\\')
8528 {
8529 if (*++that == NUL)
8530 break;
8531 if (that[1] == NUL)
8532 {
8533 ++that;
8534 break;
8535 }
8536 }
8537 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008538 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008539 if (*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008540 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008541 else if (*that == ')' || *that == ']')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008542 --parencount;
8543 }
8544 if (parencount == 0)
8545 {
8546 amount = get_indent();
8547 break;
8548 }
8549 }
8550
8551 if (amount == -1)
8552 {
8553 curwin->w_cursor.lnum = pos->lnum;
8554 curwin->w_cursor.col = pos->col;
8555 col = pos->col;
8556
8557 that = ml_get_curline();
8558
8559 if (vi_lisp && get_indent() == 0)
8560 amount = 2;
8561 else
8562 {
8563 amount = 0;
8564 while (*that && col)
8565 {
8566 amount += lbr_chartabsize_adv(&that, (colnr_T)amount);
8567 col--;
8568 }
8569
8570 /*
8571 * Some keywords require "body" indenting rules (the
8572 * non-standard-lisp ones are Scheme special forms):
8573 *
8574 * (let ((a 1)) instead (let ((a 1))
8575 * (...)) of (...))
8576 */
8577
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008578 if (!vi_lisp && (*that == '(' || *that == '[')
8579 && lisp_match(that + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008580 amount += 2;
8581 else
8582 {
8583 that++;
8584 amount++;
8585 firsttry = amount;
8586
8587 while (vim_iswhite(*that))
8588 {
8589 amount += lbr_chartabsize(that, (colnr_T)amount);
8590 ++that;
8591 }
8592
8593 if (*that && *that != ';') /* not a comment line */
8594 {
Bram Moolenaare21877a2008-02-13 09:58:14 +00008595 /* test *that != '(' to accommodate first let/do
Bram Moolenaar071d4272004-06-13 20:20:40 +00008596 * argument if it is more than one line */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008597 if (!vi_lisp && *that != '(' && *that != '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008598 firsttry++;
8599
8600 parencount = 0;
8601 quotecount = 0;
8602
8603 if (vi_lisp
8604 || (*that != '"'
8605 && *that != '\''
8606 && *that != '#'
8607 && (*that < '0' || *that > '9')))
8608 {
8609 while (*that
8610 && (!vim_iswhite(*that)
8611 || quotecount
8612 || parencount)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008613 && (!((*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008614 && !quotecount
8615 && !parencount
8616 && vi_lisp)))
8617 {
8618 if (*that == '"')
8619 quotecount = !quotecount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008620 if ((*that == '(' || *that == '[')
8621 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008622 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008623 if ((*that == ')' || *that == ']')
8624 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008625 --parencount;
8626 if (*that == '\\' && *(that+1) != NUL)
8627 amount += lbr_chartabsize_adv(&that,
8628 (colnr_T)amount);
8629 amount += lbr_chartabsize_adv(&that,
8630 (colnr_T)amount);
8631 }
8632 }
8633 while (vim_iswhite(*that))
8634 {
8635 amount += lbr_chartabsize(that, (colnr_T)amount);
8636 that++;
8637 }
8638 if (!*that || *that == ';')
8639 amount = firsttry;
8640 }
8641 }
8642 }
8643 }
8644 }
8645 else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008646 amount = 0; /* no matching '(' or '[' found, use zero indent */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008647
8648 curwin->w_cursor = realpos;
8649
8650 return amount;
8651}
8652#endif /* FEAT_LISP */
8653
8654 void
8655prepare_to_exit()
8656{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00008657#if defined(SIGHUP) && defined(SIG_IGN)
8658 /* Ignore SIGHUP, because a dropped connection causes a read error, which
8659 * makes Vim exit and then handling SIGHUP causes various reentrance
8660 * problems. */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00008661 signal(SIGHUP, SIG_IGN);
8662#endif
8663
Bram Moolenaar071d4272004-06-13 20:20:40 +00008664#ifdef FEAT_GUI
8665 if (gui.in_use)
8666 {
8667 gui.dying = TRUE;
8668 out_trash(); /* trash any pending output */
8669 }
8670 else
8671#endif
8672 {
8673 windgoto((int)Rows - 1, 0);
8674
8675 /*
8676 * Switch terminal mode back now, so messages end up on the "normal"
8677 * screen (if there are two screens).
8678 */
8679 settmode(TMODE_COOK);
8680#ifdef WIN3264
8681 if (can_end_termcap_mode(FALSE) == TRUE)
8682#endif
8683 stoptermcap();
8684 out_flush();
8685 }
8686}
8687
8688/*
8689 * Preserve files and exit.
8690 * When called IObuff must contain a message.
8691 */
8692 void
8693preserve_exit()
8694{
8695 buf_T *buf;
8696
8697 prepare_to_exit();
8698
Bram Moolenaar4770d092006-01-12 23:22:24 +00008699 /* Setting this will prevent free() calls. That avoids calling free()
8700 * recursively when free() was invoked with a bad pointer. */
8701 really_exiting = TRUE;
8702
Bram Moolenaar071d4272004-06-13 20:20:40 +00008703 out_str(IObuff);
8704 screen_start(); /* don't know where cursor is now */
8705 out_flush();
8706
8707 ml_close_notmod(); /* close all not-modified buffers */
8708
8709 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8710 {
8711 if (buf->b_ml.ml_mfp != NULL && buf->b_ml.ml_mfp->mf_fname != NULL)
8712 {
8713 OUT_STR(_("Vim: preserving files...\n"));
8714 screen_start(); /* don't know where cursor is now */
8715 out_flush();
8716 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
8717 break;
8718 }
8719 }
8720
8721 ml_close_all(FALSE); /* close all memfiles, without deleting */
8722
8723 OUT_STR(_("Vim: Finished.\n"));
8724
8725 getout(1);
8726}
8727
8728/*
8729 * return TRUE if "fname" exists.
8730 */
8731 int
8732vim_fexists(fname)
8733 char_u *fname;
8734{
8735 struct stat st;
8736
8737 if (mch_stat((char *)fname, &st))
8738 return FALSE;
8739 return TRUE;
8740}
8741
8742/*
8743 * Check for CTRL-C pressed, but only once in a while.
8744 * Should be used instead of ui_breakcheck() for functions that check for
8745 * each line in the file. Calling ui_breakcheck() each time takes too much
8746 * time, because it can be a system call.
8747 */
8748
8749#ifndef BREAKCHECK_SKIP
8750# ifdef FEAT_GUI /* assume the GUI only runs on fast computers */
8751# define BREAKCHECK_SKIP 200
8752# else
8753# define BREAKCHECK_SKIP 32
8754# endif
8755#endif
8756
8757static int breakcheck_count = 0;
8758
8759 void
8760line_breakcheck()
8761{
8762 if (++breakcheck_count >= BREAKCHECK_SKIP)
8763 {
8764 breakcheck_count = 0;
8765 ui_breakcheck();
8766 }
8767}
8768
8769/*
8770 * Like line_breakcheck() but check 10 times less often.
8771 */
8772 void
8773fast_breakcheck()
8774{
8775 if (++breakcheck_count >= BREAKCHECK_SKIP * 10)
8776 {
8777 breakcheck_count = 0;
8778 ui_breakcheck();
8779 }
8780}
8781
8782/*
Bram Moolenaard7834d32009-12-02 16:14:36 +00008783 * Invoke expand_wildcards() for one pattern.
8784 * Expand items like "%:h" before the expansion.
8785 * Returns OK or FAIL.
8786 */
8787 int
8788expand_wildcards_eval(pat, num_file, file, flags)
8789 char_u **pat; /* pointer to input pattern */
8790 int *num_file; /* resulting number of files */
8791 char_u ***file; /* array of resulting files */
8792 int flags; /* EW_DIR, etc. */
8793{
8794 int ret = FAIL;
8795 char_u *eval_pat = NULL;
8796 char_u *exp_pat = *pat;
8797 char_u *ignored_msg;
8798 int usedlen;
8799
8800 if (*exp_pat == '%' || *exp_pat == '#' || *exp_pat == '<')
8801 {
8802 ++emsg_off;
8803 eval_pat = eval_vars(exp_pat, exp_pat, &usedlen,
8804 NULL, &ignored_msg, NULL);
8805 --emsg_off;
8806 if (eval_pat != NULL)
8807 exp_pat = concat_str(eval_pat, exp_pat + usedlen);
8808 }
8809
8810 if (exp_pat != NULL)
8811 ret = expand_wildcards(1, &exp_pat, num_file, file, flags);
8812
8813 if (eval_pat != NULL)
8814 {
8815 vim_free(exp_pat);
8816 vim_free(eval_pat);
8817 }
8818
8819 return ret;
8820}
8821
8822/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008823 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching
8824 * 'wildignore'.
Bram Moolenaar9e193ac2010-07-19 23:11:27 +02008825 * Returns OK or FAIL. When FAIL then "num_file" won't be set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008826 */
8827 int
8828expand_wildcards(num_pat, pat, num_file, file, flags)
8829 int num_pat; /* number of input patterns */
8830 char_u **pat; /* array of input patterns */
8831 int *num_file; /* resulting number of files */
8832 char_u ***file; /* array of resulting files */
8833 int flags; /* EW_DIR, etc. */
8834{
8835 int retval;
8836 int i, j;
8837 char_u *p;
8838 int non_suf_match; /* number without matching suffix */
8839
8840 retval = gen_expand_wildcards(num_pat, pat, num_file, file, flags);
8841
8842 /* When keeping all matches, return here */
Bram Moolenaar9e193ac2010-07-19 23:11:27 +02008843 if ((flags & EW_KEEPALL) || retval == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008844 return retval;
8845
8846#ifdef FEAT_WILDIGN
8847 /*
8848 * Remove names that match 'wildignore'.
8849 */
8850 if (*p_wig)
8851 {
8852 char_u *ffname;
8853
8854 /* check all files in (*file)[] */
8855 for (i = 0; i < *num_file; ++i)
8856 {
8857 ffname = FullName_save((*file)[i], FALSE);
8858 if (ffname == NULL) /* out of memory */
8859 break;
8860# ifdef VMS
8861 vms_remove_version(ffname);
8862# endif
8863 if (match_file_list(p_wig, (*file)[i], ffname))
8864 {
8865 /* remove this matching file from the list */
8866 vim_free((*file)[i]);
8867 for (j = i; j + 1 < *num_file; ++j)
8868 (*file)[j] = (*file)[j + 1];
8869 --*num_file;
8870 --i;
8871 }
8872 vim_free(ffname);
8873 }
8874 }
8875#endif
8876
8877 /*
8878 * Move the names where 'suffixes' match to the end.
8879 */
8880 if (*num_file > 1)
8881 {
8882 non_suf_match = 0;
8883 for (i = 0; i < *num_file; ++i)
8884 {
8885 if (!match_suffix((*file)[i]))
8886 {
8887 /*
8888 * Move the name without matching suffix to the front
8889 * of the list.
8890 */
8891 p = (*file)[i];
8892 for (j = i; j > non_suf_match; --j)
8893 (*file)[j] = (*file)[j - 1];
8894 (*file)[non_suf_match++] = p;
8895 }
8896 }
8897 }
8898
8899 return retval;
8900}
8901
8902/*
8903 * Return TRUE if "fname" matches with an entry in 'suffixes'.
8904 */
8905 int
8906match_suffix(fname)
8907 char_u *fname;
8908{
8909 int fnamelen, setsuflen;
8910 char_u *setsuf;
8911#define MAXSUFLEN 30 /* maximum length of a file suffix */
8912 char_u suf_buf[MAXSUFLEN];
8913
8914 fnamelen = (int)STRLEN(fname);
8915 setsuflen = 0;
8916 for (setsuf = p_su; *setsuf; )
8917 {
8918 setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
Bram Moolenaar055a2ba2009-07-14 19:40:21 +00008919 if (setsuflen == 0)
8920 {
8921 char_u *tail = gettail(fname);
8922
8923 /* empty entry: match name without a '.' */
8924 if (vim_strchr(tail, '.') == NULL)
8925 {
8926 setsuflen = 1;
8927 break;
8928 }
8929 }
8930 else
8931 {
8932 if (fnamelen >= setsuflen
8933 && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
8934 (size_t)setsuflen) == 0)
8935 break;
8936 setsuflen = 0;
8937 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008938 }
8939 return (setsuflen != 0);
8940}
8941
8942#if !defined(NO_EXPANDPATH) || defined(PROTO)
8943
8944# ifdef VIM_BACKTICK
8945static int vim_backtick __ARGS((char_u *p));
8946static int expand_backtick __ARGS((garray_T *gap, char_u *pat, int flags));
8947# endif
8948
8949# if defined(MSDOS) || defined(FEAT_GUI_W16) || defined(WIN3264)
8950/*
8951 * File name expansion code for MS-DOS, Win16 and Win32. It's here because
8952 * it's shared between these systems.
8953 */
8954# if defined(DJGPP) || defined(PROTO)
8955# define _cdecl /* DJGPP doesn't have this */
8956# else
8957# ifdef __BORLANDC__
8958# define _cdecl _RTLENTRYF
8959# endif
8960# endif
8961
8962/*
8963 * comparison function for qsort in dos_expandpath()
8964 */
8965 static int _cdecl
8966pstrcmp(const void *a, const void *b)
8967{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00008968 return (pathcmp(*(char **)a, *(char **)b, -1));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008969}
8970
8971# ifndef WIN3264
8972 static void
8973namelowcpy(
8974 char_u *d,
8975 char_u *s)
8976{
8977# ifdef DJGPP
8978 if (USE_LONG_FNAME) /* don't lower case on Windows 95/NT systems */
8979 while (*s)
8980 *d++ = *s++;
8981 else
8982# endif
8983 while (*s)
8984 *d++ = TOLOWER_LOC(*s++);
8985 *d = NUL;
8986}
8987# endif
8988
8989/*
Bram Moolenaar231334e2005-07-25 20:46:57 +00008990 * Recursively expand one path component into all matching files and/or
8991 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008992 * Return the number of matches found.
8993 * "path" has backslashes before chars that are not to be expanded, starting
8994 * at "path[wildoff]".
Bram Moolenaar231334e2005-07-25 20:46:57 +00008995 * Return the number of matches found.
8996 * NOTE: much of this is identical to unix_expandpath(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00008997 */
8998 static int
8999dos_expandpath(
9000 garray_T *gap,
9001 char_u *path,
9002 int wildoff,
Bram Moolenaar231334e2005-07-25 20:46:57 +00009003 int flags, /* EW_* flags */
Bram Moolenaar25394022007-05-10 19:06:20 +00009004 int didstar) /* expanded "**" once already */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009005{
Bram Moolenaar231334e2005-07-25 20:46:57 +00009006 char_u *buf;
9007 char_u *path_end;
9008 char_u *p, *s, *e;
9009 int start_len = gap->ga_len;
9010 char_u *pat;
9011 regmatch_T regmatch;
9012 int starts_with_dot;
9013 int matches;
9014 int len;
9015 int starstar = FALSE;
9016 static int stardepth = 0; /* depth for "**" expansion */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009017#ifdef WIN3264
9018 WIN32_FIND_DATA fb;
9019 HANDLE hFind = (HANDLE)0;
9020# ifdef FEAT_MBYTE
9021 WIN32_FIND_DATAW wfb;
9022 WCHAR *wn = NULL; /* UCS-2 name, NULL when not used. */
9023# endif
9024#else
9025 struct ffblk fb;
9026#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009027 char_u *matchname;
Bram Moolenaar231334e2005-07-25 20:46:57 +00009028 int ok;
9029
9030 /* Expanding "**" may take a long time, check for CTRL-C. */
9031 if (stardepth > 0)
9032 {
9033 ui_breakcheck();
9034 if (got_int)
9035 return 0;
9036 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009037
9038 /* make room for file name */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009039 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009040 if (buf == NULL)
9041 return 0;
9042
9043 /*
9044 * Find the first part in the path name that contains a wildcard or a ~1.
9045 * Copy it into buf, including the preceding characters.
9046 */
9047 p = buf;
9048 s = buf;
9049 e = NULL;
9050 path_end = path;
9051 while (*path_end != NUL)
9052 {
9053 /* May ignore a wildcard that has a backslash before it; it will
9054 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
9055 if (path_end >= path + wildoff && rem_backslash(path_end))
9056 *p++ = *path_end++;
9057 else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
9058 {
9059 if (e != NULL)
9060 break;
9061 s = p + 1;
9062 }
9063 else if (path_end >= path + wildoff
9064 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
9065 e = p;
9066#ifdef FEAT_MBYTE
9067 if (has_mbyte)
9068 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00009069 len = (*mb_ptr2len)(path_end);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009070 STRNCPY(p, path_end, len);
9071 p += len;
9072 path_end += len;
9073 }
9074 else
9075#endif
9076 *p++ = *path_end++;
9077 }
9078 e = p;
9079 *e = NUL;
9080
9081 /* now we have one wildcard component between s and e */
9082 /* Remove backslashes between "wildoff" and the start of the wildcard
9083 * component. */
9084 for (p = buf + wildoff; p < s; ++p)
9085 if (rem_backslash(p))
9086 {
Bram Moolenaar8c8de832008-06-24 22:58:06 +00009087 STRMOVE(p, p + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009088 --e;
9089 --s;
9090 }
9091
Bram Moolenaar231334e2005-07-25 20:46:57 +00009092 /* Check for "**" between "s" and "e". */
9093 for (p = s; p < e; ++p)
9094 if (p[0] == '*' && p[1] == '*')
9095 starstar = TRUE;
9096
Bram Moolenaar071d4272004-06-13 20:20:40 +00009097 starts_with_dot = (*s == '.');
9098 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
9099 if (pat == NULL)
9100 {
9101 vim_free(buf);
9102 return 0;
9103 }
9104
9105 /* compile the regexp into a program */
Bram Moolenaarb5609832011-07-20 15:04:58 +02009106 if (flags & EW_NOERROR)
9107 ++emsg_silent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009108 regmatch.rm_ic = TRUE; /* Always ignore case */
9109 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
Bram Moolenaarb5609832011-07-20 15:04:58 +02009110 if (flags & EW_NOERROR)
9111 --emsg_silent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009112 vim_free(pat);
9113
9114 if (regmatch.regprog == NULL)
9115 {
9116 vim_free(buf);
9117 return 0;
9118 }
9119
9120 /* remember the pattern or file name being looked for */
9121 matchname = vim_strsave(s);
9122
Bram Moolenaar231334e2005-07-25 20:46:57 +00009123 /* If "**" is by itself, this is the first time we encounter it and more
9124 * is following then find matches without any directory. */
9125 if (!didstar && stardepth < 100 && starstar && e - s == 2
9126 && *path_end == '/')
9127 {
9128 STRCPY(s, path_end + 1);
9129 ++stardepth;
9130 (void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
9131 --stardepth;
9132 }
9133
Bram Moolenaar071d4272004-06-13 20:20:40 +00009134 /* Scan all files in the directory with "dir/ *.*" */
9135 STRCPY(s, "*.*");
9136#ifdef WIN3264
9137# ifdef FEAT_MBYTE
9138 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
9139 {
9140 /* The active codepage differs from 'encoding'. Attempt using the
9141 * wide function. If it fails because it is not implemented fall back
9142 * to the non-wide version (for Windows 98) */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009143 wn = enc_to_utf16(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009144 if (wn != NULL)
9145 {
9146 hFind = FindFirstFileW(wn, &wfb);
9147 if (hFind == INVALID_HANDLE_VALUE
9148 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
9149 {
9150 vim_free(wn);
9151 wn = NULL;
9152 }
9153 }
9154 }
9155
9156 if (wn == NULL)
9157# endif
9158 hFind = FindFirstFile(buf, &fb);
9159 ok = (hFind != INVALID_HANDLE_VALUE);
9160#else
9161 /* If we are expanding wildcards we try both files and directories */
9162 ok = (findfirst((char *)buf, &fb,
9163 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
9164#endif
9165
9166 while (ok)
9167 {
9168#ifdef WIN3264
9169# ifdef FEAT_MBYTE
9170 if (wn != NULL)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009171 p = utf16_to_enc(wfb.cFileName, NULL); /* p is allocated here */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009172 else
9173# endif
9174 p = (char_u *)fb.cFileName;
9175#else
9176 p = (char_u *)fb.ff_name;
9177#endif
9178 /* Ignore entries starting with a dot, unless when asked for. Accept
9179 * all entries found with "matchname". */
9180 if ((p[0] != '.' || starts_with_dot)
9181 && (matchname == NULL
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009182 || vim_regexec(&regmatch, p, (colnr_T)0)
9183 || ((flags & EW_NOTWILD)
9184 && fnamencmp(path + (s - buf), p, e - s) == 0)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009185 {
9186#ifdef WIN3264
9187 STRCPY(s, p);
9188#else
9189 namelowcpy(s, p);
9190#endif
9191 len = (int)STRLEN(buf);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009192
9193 if (starstar && stardepth < 100)
9194 {
9195 /* For "**" in the pattern first go deeper in the tree to
9196 * find matches. */
9197 STRCPY(buf + len, "/**");
9198 STRCPY(buf + len + 3, path_end);
9199 ++stardepth;
9200 (void)dos_expandpath(gap, buf, len + 1, flags, TRUE);
9201 --stardepth;
9202 }
9203
Bram Moolenaar071d4272004-06-13 20:20:40 +00009204 STRCPY(buf + len, path_end);
9205 if (mch_has_exp_wildcard(path_end))
9206 {
9207 /* need to expand another component of the path */
9208 /* remove backslashes for the remaining components only */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009209 (void)dos_expandpath(gap, buf, len + 1, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009210 }
9211 else
9212 {
9213 /* no more wildcards, check if there is a match */
9214 /* remove backslashes for the remaining components only */
9215 if (*path_end != 0)
9216 backslash_halve(buf + len + 1);
9217 if (mch_getperm(buf) >= 0) /* add existing file */
9218 addfile(gap, buf, flags);
9219 }
9220 }
9221
9222#ifdef WIN3264
9223# ifdef FEAT_MBYTE
9224 if (wn != NULL)
9225 {
9226 vim_free(p);
9227 ok = FindNextFileW(hFind, &wfb);
9228 }
9229 else
9230# endif
9231 ok = FindNextFile(hFind, &fb);
9232#else
9233 ok = (findnext(&fb) == 0);
9234#endif
9235
9236 /* If no more matches and no match was used, try expanding the name
9237 * itself. Finds the long name of a short filename. */
9238 if (!ok && matchname != NULL && gap->ga_len == start_len)
9239 {
9240 STRCPY(s, matchname);
9241#ifdef WIN3264
9242 FindClose(hFind);
9243# ifdef FEAT_MBYTE
9244 if (wn != NULL)
9245 {
9246 vim_free(wn);
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009247 wn = enc_to_utf16(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009248 if (wn != NULL)
9249 hFind = FindFirstFileW(wn, &wfb);
9250 }
9251 if (wn == NULL)
9252# endif
9253 hFind = FindFirstFile(buf, &fb);
9254 ok = (hFind != INVALID_HANDLE_VALUE);
9255#else
9256 ok = (findfirst((char *)buf, &fb,
9257 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
9258#endif
9259 vim_free(matchname);
9260 matchname = NULL;
9261 }
9262 }
9263
9264#ifdef WIN3264
9265 FindClose(hFind);
9266# ifdef FEAT_MBYTE
9267 vim_free(wn);
9268# endif
9269#endif
9270 vim_free(buf);
9271 vim_free(regmatch.regprog);
9272 vim_free(matchname);
9273
9274 matches = gap->ga_len - start_len;
9275 if (matches > 0)
9276 qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
9277 sizeof(char_u *), pstrcmp);
9278 return matches;
9279}
9280
9281 int
9282mch_expandpath(
9283 garray_T *gap,
9284 char_u *path,
9285 int flags) /* EW_* flags */
9286{
Bram Moolenaar231334e2005-07-25 20:46:57 +00009287 return dos_expandpath(gap, path, 0, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009288}
9289# endif /* MSDOS || FEAT_GUI_W16 || WIN3264 */
9290
Bram Moolenaar231334e2005-07-25 20:46:57 +00009291#if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
9292 || defined(PROTO)
9293/*
9294 * Unix style wildcard expansion code.
9295 * It's here because it's used both for Unix and Mac.
9296 */
9297static int pstrcmp __ARGS((const void *, const void *));
9298
9299 static int
9300pstrcmp(a, b)
9301 const void *a, *b;
9302{
9303 return (pathcmp(*(char **)a, *(char **)b, -1));
9304}
9305
9306/*
9307 * Recursively expand one path component into all matching files and/or
9308 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
9309 * "path" has backslashes before chars that are not to be expanded, starting
9310 * at "path + wildoff".
9311 * Return the number of matches found.
9312 * NOTE: much of this is identical to dos_expandpath(), keep in sync!
9313 */
9314 int
9315unix_expandpath(gap, path, wildoff, flags, didstar)
9316 garray_T *gap;
9317 char_u *path;
9318 int wildoff;
9319 int flags; /* EW_* flags */
9320 int didstar; /* expanded "**" once already */
9321{
9322 char_u *buf;
9323 char_u *path_end;
9324 char_u *p, *s, *e;
9325 int start_len = gap->ga_len;
9326 char_u *pat;
9327 regmatch_T regmatch;
9328 int starts_with_dot;
9329 int matches;
9330 int len;
9331 int starstar = FALSE;
9332 static int stardepth = 0; /* depth for "**" expansion */
9333
9334 DIR *dirp;
9335 struct dirent *dp;
9336
9337 /* Expanding "**" may take a long time, check for CTRL-C. */
9338 if (stardepth > 0)
9339 {
9340 ui_breakcheck();
9341 if (got_int)
9342 return 0;
9343 }
9344
9345 /* make room for file name */
9346 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
9347 if (buf == NULL)
9348 return 0;
9349
9350 /*
9351 * Find the first part in the path name that contains a wildcard.
9352 * Copy it into "buf", including the preceding characters.
9353 */
9354 p = buf;
9355 s = buf;
9356 e = NULL;
9357 path_end = path;
9358 while (*path_end != NUL)
9359 {
9360 /* May ignore a wildcard that has a backslash before it; it will
9361 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
9362 if (path_end >= path + wildoff && rem_backslash(path_end))
9363 *p++ = *path_end++;
9364 else if (*path_end == '/')
9365 {
9366 if (e != NULL)
9367 break;
9368 s = p + 1;
9369 }
9370 else if (path_end >= path + wildoff
9371 && vim_strchr((char_u *)"*?[{~$", *path_end) != NULL)
9372 e = p;
9373#ifdef FEAT_MBYTE
9374 if (has_mbyte)
9375 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00009376 len = (*mb_ptr2len)(path_end);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009377 STRNCPY(p, path_end, len);
9378 p += len;
9379 path_end += len;
9380 }
9381 else
9382#endif
9383 *p++ = *path_end++;
9384 }
9385 e = p;
9386 *e = NUL;
9387
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009388 /* Now we have one wildcard component between "s" and "e". */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009389 /* Remove backslashes between "wildoff" and the start of the wildcard
9390 * component. */
9391 for (p = buf + wildoff; p < s; ++p)
9392 if (rem_backslash(p))
9393 {
Bram Moolenaar8c8de832008-06-24 22:58:06 +00009394 STRMOVE(p, p + 1);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009395 --e;
9396 --s;
9397 }
9398
9399 /* Check for "**" between "s" and "e". */
9400 for (p = s; p < e; ++p)
9401 if (p[0] == '*' && p[1] == '*')
9402 starstar = TRUE;
9403
9404 /* convert the file pattern to a regexp pattern */
9405 starts_with_dot = (*s == '.');
9406 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
9407 if (pat == NULL)
9408 {
9409 vim_free(buf);
9410 return 0;
9411 }
9412
9413 /* compile the regexp into a program */
Bram Moolenaarcc016f52005-12-10 20:23:46 +00009414#ifdef CASE_INSENSITIVE_FILENAME
Bram Moolenaar231334e2005-07-25 20:46:57 +00009415 regmatch.rm_ic = TRUE; /* Behave like Terminal.app */
9416#else
Bram Moolenaar94950a92010-12-02 16:01:29 +01009417 if (flags & EW_ICASE)
9418 regmatch.rm_ic = TRUE; /* 'wildignorecase' set */
9419 else
9420 regmatch.rm_ic = FALSE; /* Don't ignore case */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009421#endif
9422 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
9423 vim_free(pat);
9424
9425 if (regmatch.regprog == NULL)
9426 {
9427 vim_free(buf);
9428 return 0;
9429 }
9430
9431 /* If "**" is by itself, this is the first time we encounter it and more
9432 * is following then find matches without any directory. */
9433 if (!didstar && stardepth < 100 && starstar && e - s == 2
9434 && *path_end == '/')
9435 {
9436 STRCPY(s, path_end + 1);
9437 ++stardepth;
9438 (void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
9439 --stardepth;
9440 }
9441
9442 /* open the directory for scanning */
9443 *s = NUL;
9444 dirp = opendir(*buf == NUL ? "." : (char *)buf);
9445
9446 /* Find all matching entries */
9447 if (dirp != NULL)
9448 {
9449 for (;;)
9450 {
9451 dp = readdir(dirp);
9452 if (dp == NULL)
9453 break;
9454 if ((dp->d_name[0] != '.' || starts_with_dot)
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009455 && (vim_regexec(&regmatch, (char_u *)dp->d_name, (colnr_T)0)
9456 || ((flags & EW_NOTWILD)
9457 && fnamencmp(path + (s - buf), dp->d_name, e - s) == 0)))
Bram Moolenaar231334e2005-07-25 20:46:57 +00009458 {
9459 STRCPY(s, dp->d_name);
9460 len = STRLEN(buf);
9461
9462 if (starstar && stardepth < 100)
9463 {
9464 /* For "**" in the pattern first go deeper in the tree to
9465 * find matches. */
9466 STRCPY(buf + len, "/**");
9467 STRCPY(buf + len + 3, path_end);
9468 ++stardepth;
9469 (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
9470 --stardepth;
9471 }
9472
9473 STRCPY(buf + len, path_end);
9474 if (mch_has_exp_wildcard(path_end)) /* handle more wildcards */
9475 {
9476 /* need to expand another component of the path */
9477 /* remove backslashes for the remaining components only */
9478 (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
9479 }
9480 else
9481 {
9482 /* no more wildcards, check if there is a match */
9483 /* remove backslashes for the remaining components only */
9484 if (*path_end != NUL)
9485 backslash_halve(buf + len + 1);
9486 if (mch_getperm(buf) >= 0) /* add existing file */
9487 {
Bram Moolenaar95e9b492006-03-15 23:04:43 +00009488#ifdef MACOS_CONVERT
Bram Moolenaar231334e2005-07-25 20:46:57 +00009489 size_t precomp_len = STRLEN(buf)+1;
9490 char_u *precomp_buf =
9491 mac_precompose_path(buf, precomp_len, &precomp_len);
Bram Moolenaar95e9b492006-03-15 23:04:43 +00009492
Bram Moolenaar231334e2005-07-25 20:46:57 +00009493 if (precomp_buf)
9494 {
9495 mch_memmove(buf, precomp_buf, precomp_len);
9496 vim_free(precomp_buf);
9497 }
9498#endif
9499 addfile(gap, buf, flags);
9500 }
9501 }
9502 }
9503 }
9504
9505 closedir(dirp);
9506 }
9507
9508 vim_free(buf);
9509 vim_free(regmatch.regprog);
9510
9511 matches = gap->ga_len - start_len;
9512 if (matches > 0)
9513 qsort(((char_u **)gap->ga_data) + start_len, matches,
9514 sizeof(char_u *), pstrcmp);
9515 return matches;
9516}
9517#endif
9518
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009519#if defined(FEAT_SEARCHPATH)
9520static int find_previous_pathsep __ARGS((char_u *path, char_u **psep));
9521static int is_unique __ARGS((char_u *maybe_unique, garray_T *gap, int i));
Bram Moolenaar162bd912010-07-28 22:29:10 +02009522static void expand_path_option __ARGS((char_u *curdir, garray_T *gap));
9523static char_u *get_path_cutoff __ARGS((char_u *fname, garray_T *gap));
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009524static void uniquefy_paths __ARGS((garray_T *gap, char_u *pattern));
9525static int expand_in_path __ARGS((garray_T *gap, char_u *pattern, int flags));
9526
9527/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009528 * Moves "*psep" back to the previous path separator in "path".
9529 * Returns FAIL is "*psep" ends up at the beginning of "path".
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009530 */
9531 static int
9532find_previous_pathsep(path, psep)
9533 char_u *path;
9534 char_u **psep;
9535{
9536 /* skip the current separator */
9537 if (*psep > path && vim_ispathsep(**psep))
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009538 --*psep;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009539
9540 /* find the previous separator */
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009541 while (*psep > path)
9542 {
9543 if (vim_ispathsep(**psep))
9544 return OK;
9545 mb_ptr_back(path, *psep);
9546 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009547
9548 return FAIL;
9549}
9550
9551/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009552 * Returns TRUE if "maybe_unique" is unique wrt other_paths in "gap".
9553 * "maybe_unique" is the end portion of "((char_u **)gap->ga_data)[i]".
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009554 */
9555 static int
9556is_unique(maybe_unique, gap, i)
9557 char_u *maybe_unique;
9558 garray_T *gap;
9559 int i;
9560{
9561 int j;
9562 int candidate_len;
9563 int other_path_len;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009564 char_u **other_paths = (char_u **)gap->ga_data;
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009565 char_u *rival;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009566
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009567 for (j = 0; j < gap->ga_len; j++)
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009568 {
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009569 if (j == i)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009570 continue; /* don't compare it with itself */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009571
Bram Moolenaar624c7aa2010-07-16 20:38:52 +02009572 candidate_len = (int)STRLEN(maybe_unique);
9573 other_path_len = (int)STRLEN(other_paths[j]);
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009574 if (other_path_len < candidate_len)
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009575 continue; /* it's different when it's shorter */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009576
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009577 rival = other_paths[j] + other_path_len - candidate_len;
Bram Moolenaarda9836c2010-08-16 21:53:27 +02009578 if (fnamecmp(maybe_unique, rival) == 0
9579 && (rival == other_paths[j] || vim_ispathsep(*(rival - 1))))
Bram Moolenaar162bd912010-07-28 22:29:10 +02009580 return FALSE; /* match */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009581 }
9582
Bram Moolenaar162bd912010-07-28 22:29:10 +02009583 return TRUE; /* no match found */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009584}
9585
9586/*
Bram Moolenaar1a509df2010-08-01 17:59:57 +02009587 * Split the 'path' option into an array of strings in garray_T. Relative
Bram Moolenaar162bd912010-07-28 22:29:10 +02009588 * paths are expanded to their equivalent fullpath. This includes the "."
9589 * (relative to current buffer directory) and empty path (relative to current
9590 * directory) notations.
9591 *
9592 * TODO: handle upward search (;) and path limiter (**N) notations by
9593 * expanding each into their equivalent path(s).
9594 */
9595 static void
9596expand_path_option(curdir, gap)
9597 char_u *curdir;
9598 garray_T *gap;
9599{
9600 char_u *path_option = *curbuf->b_p_path == NUL
9601 ? p_path : curbuf->b_p_path;
9602 char_u *buf;
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009603 char_u *p;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009604 int len;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009605
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +02009606 if ((buf = alloc((int)MAXPATHL)) == NULL)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009607 return;
9608
9609 while (*path_option != NUL)
9610 {
9611 copy_option_part(&path_option, buf, MAXPATHL, " ,");
9612
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009613 if (buf[0] == '.' && (buf[1] == NUL || vim_ispathsep(buf[1])))
Bram Moolenaar162bd912010-07-28 22:29:10 +02009614 {
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009615 /* Relative to current buffer:
9616 * "/path/file" + "." -> "/path/"
9617 * "/path/file" + "./subdir" -> "/path/subdir" */
Bram Moolenaar162bd912010-07-28 22:29:10 +02009618 if (curbuf->b_ffname == NULL)
9619 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009620 p = gettail(curbuf->b_ffname);
9621 len = (int)(p - curbuf->b_ffname);
9622 if (len + (int)STRLEN(buf) >= MAXPATHL)
9623 continue;
9624 if (buf[1] == NUL)
9625 buf[len] = NUL;
9626 else
9627 STRMOVE(buf + len, buf + 2);
9628 mch_memmove(buf, curbuf->b_ffname, len);
9629 simplify_filename(buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009630 }
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009631 else if (buf[0] == NUL)
9632 /* relative to current directory */
Bram Moolenaar162bd912010-07-28 22:29:10 +02009633 STRCPY(buf, curdir);
Bram Moolenaar84f888a2010-08-05 21:40:16 +02009634 else if (path_with_url(buf))
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009635 /* URL can't be used here */
Bram Moolenaar84f888a2010-08-05 21:40:16 +02009636 continue;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009637 else if (!mch_isFullName(buf))
9638 {
9639 /* Expand relative path to their full path equivalent */
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009640 len = (int)STRLEN(curdir);
9641 if (len + (int)STRLEN(buf) + 3 > MAXPATHL)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009642 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009643 STRMOVE(buf + len + 1, buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009644 STRCPY(buf, curdir);
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009645 buf[len] = PATHSEP;
Bram Moolenaar57adda12010-08-03 22:11:29 +02009646 simplify_filename(buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009647 }
9648
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009649 if (ga_grow(gap, 1) == FAIL)
9650 break;
9651 p = vim_strsave(buf);
9652 if (p == NULL)
9653 break;
9654 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009655 }
9656
9657 vim_free(buf);
9658}
9659
9660/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009661 * Returns a pointer to the file or directory name in "fname" that matches the
9662 * longest path in "ga"p, or NULL if there is no match. For example:
Bram Moolenaar162bd912010-07-28 22:29:10 +02009663 *
9664 * path: /foo/bar/baz
9665 * fname: /foo/bar/baz/quux.txt
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009666 * returns: ^this
Bram Moolenaar162bd912010-07-28 22:29:10 +02009667 */
9668 static char_u *
9669get_path_cutoff(fname, gap)
9670 char_u *fname;
9671 garray_T *gap;
9672{
9673 int i;
9674 int maxlen = 0;
9675 char_u **path_part = (char_u **)gap->ga_data;
9676 char_u *cutoff = NULL;
9677
9678 for (i = 0; i < gap->ga_len; i++)
9679 {
9680 int j = 0;
9681
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009682 while ((fname[j] == path_part[i][j]
Bram Moolenaar2d7c47d2010-08-10 19:50:26 +02009683# if defined(MSWIN) || defined(MSDOS)
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009684 || (vim_ispathsep(fname[j]) && vim_ispathsep(path_part[i][j]))
9685#endif
9686 ) && fname[j] != NUL && path_part[i][j] != NUL)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009687 j++;
9688 if (j > maxlen)
9689 {
9690 maxlen = j;
9691 cutoff = &fname[j];
9692 }
9693 }
9694
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009695 /* skip to the file or directory name */
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009696 if (cutoff != NULL)
Bram Moolenaar31710262010-08-13 13:36:15 +02009697 while (vim_ispathsep(*cutoff))
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009698 mb_ptr_adv(cutoff);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009699
9700 return cutoff;
9701}
9702
9703/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009704 * Sorts, removes duplicates and modifies all the fullpath names in "gap" so
9705 * that they are unique with respect to each other while conserving the part
9706 * that matches the pattern. Beware, this is at least O(n^2) wrt "gap->ga_len".
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009707 */
9708 static void
9709uniquefy_paths(gap, pattern)
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +02009710 garray_T *gap;
9711 char_u *pattern;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009712{
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +02009713 int i;
9714 int len;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009715 char_u **fnames = (char_u **)gap->ga_data;
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009716 int sort_again = FALSE;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009717 char_u *pat;
9718 char_u *file_pattern;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009719 char_u *curdir;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009720 regmatch_T regmatch;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009721 garray_T path_ga;
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009722 char_u **in_curdir = NULL;
9723 char_u *short_name;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009724
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +02009725 remove_duplicates(gap);
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009726 ga_init2(&path_ga, (int)sizeof(char_u *), 1);
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009727
9728 /*
9729 * We need to prepend a '*' at the beginning of file_pattern so that the
9730 * regex matches anywhere in the path. FIXME: is this valid for all
Bram Moolenaarb31e4382010-07-24 16:01:56 +02009731 * possible patterns?
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009732 */
Bram Moolenaar624c7aa2010-07-16 20:38:52 +02009733 len = (int)STRLEN(pattern);
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009734 file_pattern = alloc(len + 2);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009735 if (file_pattern == NULL)
9736 return;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009737 file_pattern[0] = '*';
Bram Moolenaar162bd912010-07-28 22:29:10 +02009738 file_pattern[1] = NUL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009739 STRCAT(file_pattern, pattern);
9740 pat = file_pat_to_reg_pat(file_pattern, NULL, NULL, TRUE);
9741 vim_free(file_pattern);
Bram Moolenaarb31e4382010-07-24 16:01:56 +02009742 if (pat == NULL)
9743 return;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009744
Bram Moolenaarb31e4382010-07-24 16:01:56 +02009745 regmatch.rm_ic = TRUE; /* always ignore case */
9746 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
9747 vim_free(pat);
9748 if (regmatch.regprog == NULL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009749 return;
9750
Bram Moolenaar162bd912010-07-28 22:29:10 +02009751 if ((curdir = alloc((int)(MAXPATHL))) == NULL)
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009752 goto theend;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009753 mch_dirname(curdir, MAXPATHL);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009754 expand_path_option(curdir, &path_ga);
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009755
9756 in_curdir = (char_u **)alloc_clear(gap->ga_len * sizeof(char_u *));
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009757 if (in_curdir == NULL)
9758 goto theend;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009759
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009760 for (i = 0; i < gap->ga_len && !got_int; i++)
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009761 {
Bram Moolenaar162bd912010-07-28 22:29:10 +02009762 char_u *path = fnames[i];
9763 int is_in_curdir;
Bram Moolenaar31710262010-08-13 13:36:15 +02009764 char_u *dir_end = gettail_dir(path);
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009765 char_u *pathsep_p;
9766 char_u *path_cutoff;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009767
Bram Moolenaar624c7aa2010-07-16 20:38:52 +02009768 len = (int)STRLEN(path);
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009769 is_in_curdir = fnamencmp(curdir, path, dir_end - path) == 0
Bram Moolenaar162bd912010-07-28 22:29:10 +02009770 && curdir[dir_end - path] == NUL;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009771 if (is_in_curdir)
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009772 in_curdir[i] = vim_strsave(path);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009773
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009774 /* Shorten the filename while maintaining its uniqueness */
9775 path_cutoff = get_path_cutoff(path, &path_ga);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009776
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009777 /* we start at the end of the path */
9778 pathsep_p = path + len - 1;
9779
9780 while (find_previous_pathsep(path, &pathsep_p))
9781 if (vim_regexec(&regmatch, pathsep_p + 1, (colnr_T)0)
9782 && is_unique(pathsep_p + 1, gap, i)
9783 && path_cutoff != NULL && pathsep_p + 1 >= path_cutoff)
9784 {
9785 sort_again = TRUE;
9786 mch_memmove(path, pathsep_p + 1, STRLEN(pathsep_p));
9787 break;
9788 }
Bram Moolenaar9bc040c2010-08-11 22:05:57 +02009789
9790 if (mch_isFullName(path))
9791 {
9792 /*
9793 * Last resort: shorten relative to curdir if possible.
9794 * 'possible' means:
9795 * 1. It is under the current directory.
9796 * 2. The result is actually shorter than the original.
9797 *
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009798 * Before curdir After
9799 * /foo/bar/file.txt /foo/bar ./file.txt
9800 * c:\foo\bar\file.txt c:\foo\bar .\file.txt
9801 * /file.txt / /file.txt
9802 * c:\file.txt c:\ .\file.txt
Bram Moolenaar9bc040c2010-08-11 22:05:57 +02009803 */
9804 short_name = shorten_fname(path, curdir);
Bram Moolenaar31710262010-08-13 13:36:15 +02009805 if (short_name != NULL && short_name > path + 1
9806#if defined(MSWIN) || defined(MSDOS)
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009807 /* On windows,
Bram Moolenaar31710262010-08-13 13:36:15 +02009808 * shorten_fname("c:\a\a.txt", "c:\a\b")
Bram Moolenaar31710262010-08-13 13:36:15 +02009809 * returns "\a\a.txt", which is not really the short
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009810 * name, hence: */
Bram Moolenaar31710262010-08-13 13:36:15 +02009811 && !vim_ispathsep(*short_name)
9812#endif
9813 )
Bram Moolenaar9bc040c2010-08-11 22:05:57 +02009814 {
9815 STRCPY(path, ".");
9816 add_pathsep(path);
Bram Moolenaarcda000e2010-08-14 13:34:39 +02009817 STRMOVE(path + STRLEN(path), short_name);
Bram Moolenaar9bc040c2010-08-11 22:05:57 +02009818 }
9819 }
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009820 ui_breakcheck();
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009821 }
9822
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009823 /* Shorten filenames in /in/current/directory/{filename} */
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009824 for (i = 0; i < gap->ga_len && !got_int; i++)
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009825 {
9826 char_u *rel_path;
9827 char_u *path = in_curdir[i];
9828
9829 if (path == NULL)
9830 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009831
9832 /* If the {filename} is not unique, change it to ./{filename}.
9833 * Else reduce it to {filename} */
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009834 short_name = shorten_fname(path, curdir);
9835 if (short_name == NULL)
9836 short_name = path;
9837 if (is_unique(short_name, gap, i))
9838 {
9839 STRCPY(fnames[i], short_name);
9840 continue;
9841 }
9842
9843 rel_path = alloc((int)(STRLEN(short_name) + STRLEN(PATHSEPSTR) + 2));
9844 if (rel_path == NULL)
9845 goto theend;
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009846 STRCPY(rel_path, ".");
9847 add_pathsep(rel_path);
9848 STRCAT(rel_path, short_name);
9849
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009850 vim_free(fnames[i]);
9851 fnames[i] = rel_path;
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009852 sort_again = TRUE;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009853 ui_breakcheck();
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009854 }
9855
Bram Moolenaar162bd912010-07-28 22:29:10 +02009856theend:
9857 vim_free(curdir);
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009858 if (in_curdir != NULL)
9859 {
9860 for (i = 0; i < gap->ga_len; i++)
9861 vim_free(in_curdir[i]);
9862 vim_free(in_curdir);
9863 }
Bram Moolenaar162bd912010-07-28 22:29:10 +02009864 ga_clear_strings(&path_ga);
Bram Moolenaarb31e4382010-07-24 16:01:56 +02009865 vim_free(regmatch.regprog);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009866
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009867 if (sort_again)
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +02009868 remove_duplicates(gap);
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009869}
9870
9871/*
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +02009872 * Calls globpath() with 'path' values for the given pattern and stores the
9873 * result in "gap".
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009874 * Returns the total number of matches.
9875 */
9876 static int
9877expand_in_path(gap, pattern, flags)
9878 garray_T *gap;
9879 char_u *pattern;
9880 int flags; /* EW_* flags */
9881{
Bram Moolenaar162bd912010-07-28 22:29:10 +02009882 char_u *curdir;
9883 garray_T path_ga;
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009884 char_u *files = NULL;
9885 char_u *s; /* start */
9886 char_u *e; /* end */
9887 char_u *paths = NULL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009888
Bram Moolenaar7f0f6212010-08-03 22:21:00 +02009889 if ((curdir = alloc((unsigned)MAXPATHL)) == NULL)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009890 return 0;
9891 mch_dirname(curdir, MAXPATHL);
9892
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009893 ga_init2(&path_ga, (int)sizeof(char_u *), 1);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009894 expand_path_option(curdir, &path_ga);
9895 vim_free(curdir);
Bram Moolenaar006d2b02010-08-04 12:39:44 +02009896 if (path_ga.ga_len == 0)
9897 return 0;
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +02009898
9899 paths = ga_concat_strings(&path_ga);
9900 ga_clear_strings(&path_ga);
9901 if (paths == NULL)
Bram Moolenaar7f0f6212010-08-03 22:21:00 +02009902 return 0;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009903
Bram Moolenaar94950a92010-12-02 16:01:29 +01009904 files = globpath(paths, pattern, (flags & EW_ICASE) ? WILD_ICASE : 0);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009905 vim_free(paths);
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009906 if (files == NULL)
9907 return 0;
9908
9909 /* Copy each path in files into gap */
9910 s = e = files;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009911 while (*s != NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009912 {
Bram Moolenaar162bd912010-07-28 22:29:10 +02009913 while (*e != '\n' && *e != NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009914 e++;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009915 if (*e == NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009916 {
9917 addfile(gap, s, flags);
9918 break;
9919 }
9920 else
9921 {
9922 /* *e is '\n' */
Bram Moolenaar162bd912010-07-28 22:29:10 +02009923 *e = NUL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009924 addfile(gap, s, flags);
9925 e++;
9926 s = e;
9927 }
9928 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009929 vim_free(files);
9930
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009931 return gap->ga_len;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009932}
9933#endif
9934
Bram Moolenaar1587a1e2010-07-29 20:59:59 +02009935#if defined(FEAT_SEARCHPATH) || defined(FEAT_CMDL_COMPL) || defined(PROTO)
9936/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009937 * Sort "gap" and remove duplicate entries. "gap" is expected to contain a
9938 * list of file names in allocated memory.
Bram Moolenaar1587a1e2010-07-29 20:59:59 +02009939 */
9940 void
9941remove_duplicates(gap)
9942 garray_T *gap;
9943{
9944 int i;
9945 int j;
9946 char_u **fnames = (char_u **)gap->ga_data;
9947
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009948 sort_strings(fnames, gap->ga_len);
Bram Moolenaar1587a1e2010-07-29 20:59:59 +02009949 for (i = gap->ga_len - 1; i > 0; --i)
9950 if (fnamecmp(fnames[i - 1], fnames[i]) == 0)
9951 {
9952 vim_free(fnames[i]);
9953 for (j = i + 1; j < gap->ga_len; ++j)
9954 fnames[j - 1] = fnames[j];
9955 --gap->ga_len;
9956 }
9957}
9958#endif
9959
Bram Moolenaar071d4272004-06-13 20:20:40 +00009960/*
9961 * Generic wildcard expansion code.
9962 *
9963 * Characters in "pat" that should not be expanded must be preceded with a
9964 * backslash. E.g., "/path\ with\ spaces/my\*star*"
9965 *
9966 * Return FAIL when no single file was found. In this case "num_file" is not
9967 * set, and "file" may contain an error message.
9968 * Return OK when some files found. "num_file" is set to the number of
9969 * matches, "file" to the array of matches. Call FreeWild() later.
9970 */
9971 int
9972gen_expand_wildcards(num_pat, pat, num_file, file, flags)
9973 int num_pat; /* number of input patterns */
9974 char_u **pat; /* array of input patterns */
9975 int *num_file; /* resulting number of files */
9976 char_u ***file; /* array of resulting files */
9977 int flags; /* EW_* flags */
9978{
9979 int i;
9980 garray_T ga;
9981 char_u *p;
9982 static int recursive = FALSE;
9983 int add_pat;
Bram Moolenaard732f9a2010-08-15 13:29:11 +02009984#if defined(FEAT_SEARCHPATH)
9985 int did_expand_in_path = FALSE;
9986#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009987
9988 /*
9989 * expand_env() is called to expand things like "~user". If this fails,
9990 * it calls ExpandOne(), which brings us back here. In this case, always
9991 * call the machine specific expansion function, if possible. Otherwise,
9992 * return FAIL.
9993 */
9994 if (recursive)
9995#ifdef SPECIAL_WILDCHAR
9996 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
9997#else
9998 return FAIL;
9999#endif
10000
10001#ifdef SPECIAL_WILDCHAR
10002 /*
10003 * If there are any special wildcard characters which we cannot handle
10004 * here, call machine specific function for all the expansion. This
10005 * avoids starting the shell for each argument separately.
10006 * For `=expr` do use the internal function.
10007 */
10008 for (i = 0; i < num_pat; i++)
10009 {
10010 if (vim_strpbrk(pat[i], (char_u *)SPECIAL_WILDCHAR) != NULL
10011# ifdef VIM_BACKTICK
10012 && !(vim_backtick(pat[i]) && pat[i][1] == '=')
10013# endif
10014 )
10015 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
10016 }
10017#endif
10018
10019 recursive = TRUE;
10020
10021 /*
10022 * The matching file names are stored in a growarray. Init it empty.
10023 */
10024 ga_init2(&ga, (int)sizeof(char_u *), 30);
10025
10026 for (i = 0; i < num_pat; ++i)
10027 {
10028 add_pat = -1;
10029 p = pat[i];
10030
10031#ifdef VIM_BACKTICK
10032 if (vim_backtick(p))
10033 add_pat = expand_backtick(&ga, p, flags);
10034 else
10035#endif
10036 {
10037 /*
10038 * First expand environment variables, "~/" and "~user/".
10039 */
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010040 if (vim_strchr(p, '$') != NULL || *p == '~')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010041 {
Bram Moolenaar9f0545d2007-09-26 20:36:32 +000010042 p = expand_env_save_opt(p, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010043 if (p == NULL)
10044 p = pat[i];
10045#ifdef UNIX
10046 /*
10047 * On Unix, if expand_env() can't expand an environment
10048 * variable, use the shell to do that. Discard previously
10049 * found file names and start all over again.
10050 */
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010051 else if (vim_strchr(p, '$') != NULL || *p == '~')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010052 {
10053 vim_free(p);
Bram Moolenaar782027e2009-06-24 14:25:49 +000010054 ga_clear_strings(&ga);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010055 i = mch_expand_wildcards(num_pat, pat, num_file, file,
10056 flags);
10057 recursive = FALSE;
10058 return i;
10059 }
10060#endif
10061 }
10062
10063 /*
10064 * If there are wildcards: Expand file names and add each match to
10065 * the list. If there is no match, and EW_NOTFOUND is given, add
10066 * the pattern.
10067 * If there are no wildcards: Add the file name if it exists or
10068 * when EW_NOTFOUND is given.
10069 */
10070 if (mch_has_exp_wildcard(p))
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010071 {
10072#if defined(FEAT_SEARCHPATH)
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010073 if ((flags & EW_PATH)
10074 && !mch_isFullName(p)
10075 && !(p[0] == '.'
10076 && (vim_ispathsep(p[1])
10077 || (p[1] == '.' && vim_ispathsep(p[2]))))
10078 )
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010079 {
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010080 /* :find completion where 'path' is used.
10081 * Recursiveness is OK here. */
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010082 recursive = FALSE;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010083 add_pat = expand_in_path(&ga, p, flags);
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010084 recursive = TRUE;
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010085 did_expand_in_path = TRUE;
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010086 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010087 else
10088#endif
10089 add_pat = mch_expandpath(&ga, p, flags);
10090 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010091 }
10092
10093 if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
10094 {
10095 char_u *t = backslash_halve_save(p);
10096
10097#if defined(MACOS_CLASSIC)
10098 slash_to_colon(t);
10099#endif
10100 /* When EW_NOTFOUND is used, always add files and dirs. Makes
10101 * "vim c:/" work. */
10102 if (flags & EW_NOTFOUND)
10103 addfile(&ga, t, flags | EW_DIR | EW_FILE);
10104 else if (mch_getperm(t) >= 0)
10105 addfile(&ga, t, flags);
10106 vim_free(t);
10107 }
10108
Bram Moolenaarb28ebbc2010-07-14 16:59:57 +020010109#if defined(FEAT_SEARCHPATH)
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010110 if (did_expand_in_path && ga.ga_len > 0 && (flags & EW_PATH))
Bram Moolenaarb28ebbc2010-07-14 16:59:57 +020010111 uniquefy_paths(&ga, p);
10112#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000010113 if (p != pat[i])
10114 vim_free(p);
10115 }
10116
10117 *num_file = ga.ga_len;
10118 *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data : (char_u **)"";
10119
10120 recursive = FALSE;
10121
10122 return (ga.ga_data != NULL) ? OK : FAIL;
10123}
10124
10125# ifdef VIM_BACKTICK
10126
10127/*
10128 * Return TRUE if we can expand this backtick thing here.
10129 */
10130 static int
10131vim_backtick(p)
10132 char_u *p;
10133{
10134 return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
10135}
10136
10137/*
10138 * Expand an item in `backticks` by executing it as a command.
10139 * Currently only works when pat[] starts and ends with a `.
10140 * Returns number of file names found.
10141 */
10142 static int
10143expand_backtick(gap, pat, flags)
10144 garray_T *gap;
10145 char_u *pat;
10146 int flags; /* EW_* flags */
10147{
10148 char_u *p;
10149 char_u *cmd;
10150 char_u *buffer;
10151 int cnt = 0;
10152 int i;
10153
10154 /* Create the command: lop off the backticks. */
10155 cmd = vim_strnsave(pat + 1, (int)STRLEN(pat) - 2);
10156 if (cmd == NULL)
10157 return 0;
10158
10159#ifdef FEAT_EVAL
10160 if (*cmd == '=') /* `={expr}`: Expand expression */
Bram Moolenaar362e1a32006-03-06 23:29:24 +000010161 buffer = eval_to_string(cmd + 1, &p, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010162 else
10163#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010164 buffer = get_cmd_output(cmd, NULL,
10165 (flags & EW_SILENT) ? SHELL_SILENT : 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010166 vim_free(cmd);
10167 if (buffer == NULL)
10168 return 0;
10169
10170 cmd = buffer;
10171 while (*cmd != NUL)
10172 {
10173 cmd = skipwhite(cmd); /* skip over white space */
10174 p = cmd;
10175 while (*p != NUL && *p != '\r' && *p != '\n') /* skip over entry */
10176 ++p;
10177 /* add an entry if it is not empty */
10178 if (p > cmd)
10179 {
10180 i = *p;
10181 *p = NUL;
10182 addfile(gap, cmd, flags);
10183 *p = i;
10184 ++cnt;
10185 }
10186 cmd = p;
10187 while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
10188 ++cmd;
10189 }
10190
10191 vim_free(buffer);
10192 return cnt;
10193}
10194# endif /* VIM_BACKTICK */
10195
10196/*
10197 * Add a file to a file list. Accepted flags:
10198 * EW_DIR add directories
10199 * EW_FILE add files
Bram Moolenaar1f35bf92006-03-07 22:38:47 +000010200 * EW_EXEC add executable files
Bram Moolenaar071d4272004-06-13 20:20:40 +000010201 * EW_NOTFOUND add even when it doesn't exist
10202 * EW_ADDSLASH add slash after directory name
10203 */
10204 void
10205addfile(gap, f, flags)
10206 garray_T *gap;
10207 char_u *f; /* filename */
10208 int flags;
10209{
10210 char_u *p;
10211 int isdir;
10212
10213 /* if the file/dir doesn't exist, may not add it */
10214 if (!(flags & EW_NOTFOUND) && mch_getperm(f) < 0)
10215 return;
10216
10217#ifdef FNAME_ILLEGAL
10218 /* if the file/dir contains illegal characters, don't add it */
10219 if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
10220 return;
10221#endif
10222
10223 isdir = mch_isdir(f);
10224 if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
10225 return;
10226
Bram Moolenaar1f35bf92006-03-07 22:38:47 +000010227 /* If the file isn't executable, may not add it. Do accept directories. */
10228 if (!isdir && (flags & EW_EXEC) && !mch_can_exe(f))
10229 return;
10230
Bram Moolenaar071d4272004-06-13 20:20:40 +000010231 /* Make room for another item in the file list. */
10232 if (ga_grow(gap, 1) == FAIL)
10233 return;
10234
10235 p = alloc((unsigned)(STRLEN(f) + 1 + isdir));
10236 if (p == NULL)
10237 return;
10238
10239 STRCPY(p, f);
10240#ifdef BACKSLASH_IN_FILENAME
10241 slash_adjust(p);
10242#endif
10243 /*
10244 * Append a slash or backslash after directory names if none is present.
10245 */
10246#ifndef DONT_ADD_PATHSEP_TO_DIR
10247 if (isdir && (flags & EW_ADDSLASH))
10248 add_pathsep(p);
10249#endif
10250 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010251}
10252#endif /* !NO_EXPANDPATH */
10253
10254#if defined(VIM_BACKTICK) || defined(FEAT_EVAL) || defined(PROTO)
10255
10256#ifndef SEEK_SET
10257# define SEEK_SET 0
10258#endif
10259#ifndef SEEK_END
10260# define SEEK_END 2
10261#endif
10262
10263/*
10264 * Get the stdout of an external command.
10265 * Returns an allocated string, or NULL for error.
10266 */
10267 char_u *
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010268get_cmd_output(cmd, infile, flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010269 char_u *cmd;
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010270 char_u *infile; /* optional input file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010271 int flags; /* can be SHELL_SILENT */
10272{
10273 char_u *tempname;
10274 char_u *command;
10275 char_u *buffer = NULL;
10276 int len;
10277 int i = 0;
10278 FILE *fd;
10279
10280 if (check_restricted() || check_secure())
10281 return NULL;
10282
10283 /* get a name for the temp file */
10284 if ((tempname = vim_tempname('o')) == NULL)
10285 {
10286 EMSG(_(e_notmp));
10287 return NULL;
10288 }
10289
10290 /* Add the redirection stuff */
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010291 command = make_filter_cmd(cmd, infile, tempname);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010292 if (command == NULL)
10293 goto done;
10294
10295 /*
10296 * Call the shell to execute the command (errors are ignored).
10297 * Don't check timestamps here.
10298 */
10299 ++no_check_timestamps;
10300 call_shell(command, SHELL_DOOUT | SHELL_EXPAND | flags);
10301 --no_check_timestamps;
10302
10303 vim_free(command);
10304
10305 /*
10306 * read the names from the file into memory
10307 */
10308# ifdef VMS
Bram Moolenaar25394022007-05-10 19:06:20 +000010309 /* created temporary file is not always readable as binary */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010310 fd = mch_fopen((char *)tempname, "r");
10311# else
10312 fd = mch_fopen((char *)tempname, READBIN);
10313# endif
10314
10315 if (fd == NULL)
10316 {
10317 EMSG2(_(e_notopen), tempname);
10318 goto done;
10319 }
10320
10321 fseek(fd, 0L, SEEK_END);
10322 len = ftell(fd); /* get size of temp file */
10323 fseek(fd, 0L, SEEK_SET);
10324
10325 buffer = alloc(len + 1);
10326 if (buffer != NULL)
10327 i = (int)fread((char *)buffer, (size_t)1, (size_t)len, fd);
10328 fclose(fd);
10329 mch_remove(tempname);
10330 if (buffer == NULL)
10331 goto done;
10332#ifdef VMS
10333 len = i; /* VMS doesn't give us what we asked for... */
10334#endif
10335 if (i != len)
10336 {
10337 EMSG2(_(e_notread), tempname);
10338 vim_free(buffer);
10339 buffer = NULL;
10340 }
10341 else
Bram Moolenaar162bd912010-07-28 22:29:10 +020010342 buffer[len] = NUL; /* make sure the buffer is terminated */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010343
10344done:
10345 vim_free(tempname);
10346 return buffer;
10347}
10348#endif
10349
10350/*
10351 * Free the list of files returned by expand_wildcards() or other expansion
10352 * functions.
10353 */
10354 void
10355FreeWild(count, files)
10356 int count;
10357 char_u **files;
10358{
Bram Moolenaarfc1421e2006-04-20 22:17:20 +000010359 if (count <= 0 || files == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010360 return;
10361#if defined(__EMX__) && defined(__ALWAYS_HAS_TRAILING_NULL_POINTER) /* XXX */
10362 /*
10363 * Is this still OK for when other functions than expand_wildcards() have
10364 * been used???
10365 */
10366 _fnexplodefree((char **)files);
10367#else
10368 while (count--)
10369 vim_free(files[count]);
10370 vim_free(files);
10371#endif
10372}
10373
10374/*
Bram Moolenaara9dc3752010-07-11 20:46:53 +020010375 * Return TRUE when need to go to Insert mode because of 'insertmode'.
Bram Moolenaar071d4272004-06-13 20:20:40 +000010376 * Don't do this when still processing a command or a mapping.
10377 * Don't do this when inside a ":normal" command.
10378 */
10379 int
10380goto_im()
10381{
10382 return (p_im && stuff_empty() && typebuf_typed());
10383}