blob: b0f7e91fcccfdb0c9c1266877b7556134cbe9233 [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);
366 if (todo >= tab_pad)
367 {
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 */
375 while (todo >= (int)curbuf->b_p_ts)
376 {
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;
1564
1565 i = 0;
1566 while (vim_iswhite(line[i])) /* leading white space is ignored */
1567 ++i;
1568
1569 /*
1570 * Repeat to match several nested comment strings.
1571 */
1572 while (line[i])
1573 {
1574 /*
1575 * scan through the 'comments' option for a match
1576 */
1577 found_one = FALSE;
1578 for (list = curbuf->b_p_com; *list; )
1579 {
1580 /*
1581 * Get one option part into part_buf[]. Advance list to next one.
1582 * put string at start of string.
1583 */
1584 if (!got_com && flags != NULL) /* remember where flags started */
1585 *flags = list;
1586 (void)copy_option_part(&list, part_buf, COM_MAX_LEN, ",");
1587 string = vim_strchr(part_buf, ':');
1588 if (string == NULL) /* missing ':', ignore this part */
1589 continue;
1590 *string++ = NUL; /* isolate flags from string */
1591
1592 /*
1593 * When already found a nested comment, only accept further
1594 * nested comments.
1595 */
1596 if (got_com && vim_strchr(part_buf, COM_NEST) == NULL)
1597 continue;
1598
1599 /* When 'O' flag used don't use for "O" command */
1600 if (backward && vim_strchr(part_buf, COM_NOBACK) != NULL)
1601 continue;
1602
1603 /*
1604 * Line contents and string must match.
1605 * When string starts with white space, must have some white space
1606 * (but the amount does not need to match, there might be a mix of
1607 * TABs and spaces).
1608 */
1609 if (vim_iswhite(string[0]))
1610 {
1611 if (i == 0 || !vim_iswhite(line[i - 1]))
1612 continue;
1613 while (vim_iswhite(string[0]))
1614 ++string;
1615 }
1616 for (j = 0; string[j] != NUL && string[j] == line[i + j]; ++j)
1617 ;
1618 if (string[j] != NUL)
1619 continue;
1620
1621 /*
1622 * When 'b' flag used, there must be white space or an
1623 * end-of-line after the string in the line.
1624 */
1625 if (vim_strchr(part_buf, COM_BLANK) != NULL
1626 && !vim_iswhite(line[i + j]) && line[i + j] != NUL)
1627 continue;
1628
1629 /*
1630 * We have found a match, stop searching.
1631 */
1632 i += j;
1633 got_com = TRUE;
1634 found_one = TRUE;
1635 break;
1636 }
1637
1638 /*
1639 * No match found, stop scanning.
1640 */
1641 if (!found_one)
1642 break;
1643
1644 /*
1645 * Include any trailing white space.
1646 */
1647 while (vim_iswhite(line[i]))
1648 ++i;
1649
1650 /*
1651 * If this comment doesn't nest, stop here.
1652 */
1653 if (vim_strchr(part_buf, COM_NEST) == NULL)
1654 break;
1655 }
1656 return (got_com ? i : 0);
1657}
1658#endif
1659
1660/*
1661 * Return the number of window lines occupied by buffer line "lnum".
1662 */
1663 int
1664plines(lnum)
1665 linenr_T lnum;
1666{
1667 return plines_win(curwin, lnum, TRUE);
1668}
1669
1670 int
1671plines_win(wp, lnum, winheight)
1672 win_T *wp;
1673 linenr_T lnum;
1674 int winheight; /* when TRUE limit to window height */
1675{
1676#if defined(FEAT_DIFF) || defined(PROTO)
1677 /* Check for filler lines above this buffer line. When folded the result
1678 * is one line anyway. */
1679 return plines_win_nofill(wp, lnum, winheight) + diff_check_fill(wp, lnum);
1680}
1681
1682 int
1683plines_nofill(lnum)
1684 linenr_T lnum;
1685{
1686 return plines_win_nofill(curwin, lnum, TRUE);
1687}
1688
1689 int
1690plines_win_nofill(wp, lnum, winheight)
1691 win_T *wp;
1692 linenr_T lnum;
1693 int winheight; /* when TRUE limit to window height */
1694{
1695#endif
1696 int lines;
1697
1698 if (!wp->w_p_wrap)
1699 return 1;
1700
1701#ifdef FEAT_VERTSPLIT
1702 if (wp->w_width == 0)
1703 return 1;
1704#endif
1705
1706#ifdef FEAT_FOLDING
1707 /* A folded lines is handled just like an empty line. */
1708 /* NOTE: Caller must handle lines that are MAYBE folded. */
1709 if (lineFolded(wp, lnum) == TRUE)
1710 return 1;
1711#endif
1712
1713 lines = plines_win_nofold(wp, lnum);
1714 if (winheight > 0 && lines > wp->w_height)
1715 return (int)wp->w_height;
1716 return lines;
1717}
1718
1719/*
1720 * Return number of window lines physical line "lnum" will occupy in window
1721 * "wp". Does not care about folding, 'wrap' or 'diff'.
1722 */
1723 int
1724plines_win_nofold(wp, lnum)
1725 win_T *wp;
1726 linenr_T lnum;
1727{
1728 char_u *s;
1729 long col;
1730 int width;
1731
1732 s = ml_get_buf(wp->w_buffer, lnum, FALSE);
1733 if (*s == NUL) /* empty line */
1734 return 1;
1735 col = win_linetabsize(wp, s, (colnr_T)MAXCOL);
1736
1737 /*
1738 * If list mode is on, then the '$' at the end of the line may take up one
1739 * extra column.
1740 */
1741 if (wp->w_p_list && lcs_eol != NUL)
1742 col += 1;
1743
1744 /*
Bram Moolenaar64486672010-05-16 15:46:46 +02001745 * Add column offset for 'number', 'relativenumber' and 'foldcolumn'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001746 */
1747 width = W_WIDTH(wp) - win_col_off(wp);
1748 if (width <= 0)
1749 return 32000;
1750 if (col <= width)
1751 return 1;
1752 col -= width;
1753 width += win_col_off2(wp);
1754 return (col + (width - 1)) / width + 1;
1755}
1756
1757/*
1758 * Like plines_win(), but only reports the number of physical screen lines
1759 * used from the start of the line to the given column number.
1760 */
1761 int
1762plines_win_col(wp, lnum, column)
1763 win_T *wp;
1764 linenr_T lnum;
1765 long column;
1766{
1767 long col;
1768 char_u *s;
1769 int lines = 0;
1770 int width;
1771
1772#ifdef FEAT_DIFF
1773 /* Check for filler lines above this buffer line. When folded the result
1774 * is one line anyway. */
1775 lines = diff_check_fill(wp, lnum);
1776#endif
1777
1778 if (!wp->w_p_wrap)
1779 return lines + 1;
1780
1781#ifdef FEAT_VERTSPLIT
1782 if (wp->w_width == 0)
1783 return lines + 1;
1784#endif
1785
1786 s = ml_get_buf(wp->w_buffer, lnum, FALSE);
1787
1788 col = 0;
1789 while (*s != NUL && --column >= 0)
1790 {
1791 col += win_lbr_chartabsize(wp, s, (colnr_T)col, NULL);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001792 mb_ptr_adv(s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001793 }
1794
1795 /*
1796 * If *s is a TAB, and the TAB is not displayed as ^I, and we're not in
1797 * INSERT mode, then col must be adjusted so that it represents the last
1798 * screen position of the TAB. This only fixes an error when the TAB wraps
1799 * from one screen line to the next (when 'columns' is not a multiple of
1800 * 'ts') -- webb.
1801 */
1802 if (*s == TAB && (State & NORMAL) && (!wp->w_p_list || lcs_tab1))
1803 col += win_lbr_chartabsize(wp, s, (colnr_T)col, NULL) - 1;
1804
1805 /*
Bram Moolenaar64486672010-05-16 15:46:46 +02001806 * Add column offset for 'number', 'relativenumber', 'foldcolumn', etc.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001807 */
1808 width = W_WIDTH(wp) - win_col_off(wp);
Bram Moolenaar26470632006-10-24 19:12:40 +00001809 if (width <= 0)
1810 return 9999;
1811
1812 lines += 1;
1813 if (col > width)
1814 lines += (col - width) / (width + win_col_off2(wp)) + 1;
1815 return lines;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001816}
1817
1818 int
1819plines_m_win(wp, first, last)
1820 win_T *wp;
1821 linenr_T first, last;
1822{
1823 int count = 0;
1824
1825 while (first <= last)
1826 {
1827#ifdef FEAT_FOLDING
1828 int x;
1829
1830 /* Check if there are any really folded lines, but also included lines
1831 * that are maybe folded. */
1832 x = foldedCount(wp, first, NULL);
1833 if (x > 0)
1834 {
1835 ++count; /* count 1 for "+-- folded" line */
1836 first += x;
1837 }
1838 else
1839#endif
1840 {
1841#ifdef FEAT_DIFF
1842 if (first == wp->w_topline)
1843 count += plines_win_nofill(wp, first, TRUE) + wp->w_topfill;
1844 else
1845#endif
1846 count += plines_win(wp, first, TRUE);
1847 ++first;
1848 }
1849 }
1850 return (count);
1851}
1852
1853#if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) || defined(PROTO)
1854/*
1855 * Insert string "p" at the cursor position. Stops at a NUL byte.
1856 * Handles Replace mode and multi-byte characters.
1857 */
1858 void
1859ins_bytes(p)
1860 char_u *p;
1861{
1862 ins_bytes_len(p, (int)STRLEN(p));
1863}
1864#endif
1865
1866#if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) \
1867 || defined(FEAT_COMMENTS) || defined(FEAT_MBYTE) || defined(PROTO)
1868/*
1869 * Insert string "p" with length "len" at the cursor position.
1870 * Handles Replace mode and multi-byte characters.
1871 */
1872 void
1873ins_bytes_len(p, len)
1874 char_u *p;
1875 int len;
1876{
1877 int i;
1878# ifdef FEAT_MBYTE
1879 int n;
1880
Bram Moolenaar176dd1e2008-06-21 14:30:28 +00001881 if (has_mbyte)
1882 for (i = 0; i < len; i += n)
1883 {
1884 if (enc_utf8)
1885 /* avoid reading past p[len] */
1886 n = utfc_ptr2len_len(p + i, len - i);
1887 else
1888 n = (*mb_ptr2len)(p + i);
1889 ins_char_bytes(p + i, n);
1890 }
1891 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001892# endif
Bram Moolenaar176dd1e2008-06-21 14:30:28 +00001893 for (i = 0; i < len; ++i)
1894 ins_char(p[i]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001895}
1896#endif
1897
1898/*
1899 * Insert or replace a single character at the cursor position.
1900 * When in REPLACE or VREPLACE mode, replace any existing character.
1901 * Caller must have prepared for undo.
1902 * For multi-byte characters we get the whole character, the caller must
1903 * convert bytes to a character.
1904 */
1905 void
1906ins_char(c)
1907 int c;
1908{
1909#if defined(FEAT_MBYTE) || defined(PROTO)
1910 char_u buf[MB_MAXBYTES];
1911 int n;
1912
1913 n = (*mb_char2bytes)(c, buf);
1914
1915 /* When "c" is 0x100, 0x200, etc. we don't want to insert a NUL byte.
1916 * Happens for CTRL-Vu9900. */
1917 if (buf[0] == 0)
1918 buf[0] = '\n';
1919
1920 ins_char_bytes(buf, n);
1921}
1922
1923 void
1924ins_char_bytes(buf, charlen)
1925 char_u *buf;
1926 int charlen;
1927{
1928 int c = buf[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001929#endif
1930 int newlen; /* nr of bytes inserted */
1931 int oldlen; /* nr of bytes deleted (0 when not replacing) */
1932 char_u *p;
1933 char_u *newp;
1934 char_u *oldp;
1935 int linelen; /* length of old line including NUL */
1936 colnr_T col;
1937 linenr_T lnum = curwin->w_cursor.lnum;
1938 int i;
1939
1940#ifdef FEAT_VIRTUALEDIT
1941 /* Break tabs if needed. */
1942 if (virtual_active() && curwin->w_cursor.coladd > 0)
1943 coladvance_force(getviscol());
1944#endif
1945
1946 col = curwin->w_cursor.col;
1947 oldp = ml_get(lnum);
1948 linelen = (int)STRLEN(oldp) + 1;
1949
1950 /* The lengths default to the values for when not replacing. */
1951 oldlen = 0;
1952#ifdef FEAT_MBYTE
1953 newlen = charlen;
1954#else
1955 newlen = 1;
1956#endif
1957
1958 if (State & REPLACE_FLAG)
1959 {
1960#ifdef FEAT_VREPLACE
1961 if (State & VREPLACE_FLAG)
1962 {
1963 colnr_T new_vcol = 0; /* init for GCC */
1964 colnr_T vcol;
1965 int old_list;
1966#ifndef FEAT_MBYTE
1967 char_u buf[2];
1968#endif
1969
1970 /*
1971 * Disable 'list' temporarily, unless 'cpo' contains the 'L' flag.
1972 * Returns the old value of list, so when finished,
1973 * curwin->w_p_list should be set back to this.
1974 */
1975 old_list = curwin->w_p_list;
1976 if (old_list && vim_strchr(p_cpo, CPO_LISTWM) == NULL)
1977 curwin->w_p_list = FALSE;
1978
1979 /*
1980 * In virtual replace mode each character may replace one or more
1981 * characters (zero if it's a TAB). Count the number of bytes to
1982 * be deleted to make room for the new character, counting screen
1983 * cells. May result in adding spaces to fill a gap.
1984 */
1985 getvcol(curwin, &curwin->w_cursor, NULL, &vcol, NULL);
1986#ifndef FEAT_MBYTE
1987 buf[0] = c;
1988 buf[1] = NUL;
1989#endif
1990 new_vcol = vcol + chartabsize(buf, vcol);
1991 while (oldp[col + oldlen] != NUL && vcol < new_vcol)
1992 {
1993 vcol += chartabsize(oldp + col + oldlen, vcol);
1994 /* Don't need to remove a TAB that takes us to the right
1995 * position. */
1996 if (vcol > new_vcol && oldp[col + oldlen] == TAB)
1997 break;
1998#ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00001999 oldlen += (*mb_ptr2len)(oldp + col + oldlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002000#else
2001 ++oldlen;
2002#endif
2003 /* Deleted a bit too much, insert spaces. */
2004 if (vcol > new_vcol)
2005 newlen += vcol - new_vcol;
2006 }
2007 curwin->w_p_list = old_list;
2008 }
2009 else
2010#endif
2011 if (oldp[col] != NUL)
2012 {
2013 /* normal replace */
2014#ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002015 oldlen = (*mb_ptr2len)(oldp + col);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002016#else
2017 oldlen = 1;
2018#endif
2019 }
2020
2021
2022 /* Push the replaced bytes onto the replace stack, so that they can be
2023 * put back when BS is used. The bytes of a multi-byte character are
2024 * done the other way around, so that the first byte is popped off
2025 * first (it tells the byte length of the character). */
2026 replace_push(NUL);
2027 for (i = 0; i < oldlen; ++i)
2028 {
2029#ifdef FEAT_MBYTE
Bram Moolenaar2c994e82008-01-02 16:49:36 +00002030 if (has_mbyte)
2031 i += replace_push_mb(oldp + col + i) - 1;
2032 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002033#endif
Bram Moolenaar2c994e82008-01-02 16:49:36 +00002034 replace_push(oldp[col + i]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002035 }
2036 }
2037
2038 newp = alloc_check((unsigned)(linelen + newlen - oldlen));
2039 if (newp == NULL)
2040 return;
2041
2042 /* Copy bytes before the cursor. */
2043 if (col > 0)
2044 mch_memmove(newp, oldp, (size_t)col);
2045
2046 /* Copy bytes after the changed character(s). */
2047 p = newp + col;
2048 mch_memmove(p + newlen, oldp + col + oldlen,
2049 (size_t)(linelen - col - oldlen));
2050
2051 /* Insert or overwrite the new character. */
2052#ifdef FEAT_MBYTE
2053 mch_memmove(p, buf, charlen);
2054 i = charlen;
2055#else
2056 *p = c;
2057 i = 1;
2058#endif
2059
2060 /* Fill with spaces when necessary. */
2061 while (i < newlen)
2062 p[i++] = ' ';
2063
2064 /* Replace the line in the buffer. */
2065 ml_replace(lnum, newp, FALSE);
2066
2067 /* mark the buffer as changed and prepare for displaying */
2068 changed_bytes(lnum, col);
2069
2070 /*
2071 * If we're in Insert or Replace mode and 'showmatch' is set, then briefly
2072 * show the match for right parens and braces.
2073 */
2074 if (p_sm && (State & INSERT)
2075 && msg_silent == 0
2076#ifdef FEAT_MBYTE
2077 && charlen == 1
2078#endif
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00002079#ifdef FEAT_INS_EXPAND
2080 && !ins_compl_active()
2081#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002082 )
2083 showmatch(c);
2084
2085#ifdef FEAT_RIGHTLEFT
2086 if (!p_ri || (State & REPLACE_FLAG))
2087#endif
2088 {
2089 /* Normal insert: move cursor right */
2090#ifdef FEAT_MBYTE
2091 curwin->w_cursor.col += charlen;
2092#else
2093 ++curwin->w_cursor.col;
2094#endif
2095 }
2096 /*
2097 * TODO: should try to update w_row here, to avoid recomputing it later.
2098 */
2099}
2100
2101/*
2102 * Insert a string at the cursor position.
2103 * Note: Does NOT handle Replace mode.
2104 * Caller must have prepared for undo.
2105 */
2106 void
2107ins_str(s)
2108 char_u *s;
2109{
2110 char_u *oldp, *newp;
2111 int newlen = (int)STRLEN(s);
2112 int oldlen;
2113 colnr_T col;
2114 linenr_T lnum = curwin->w_cursor.lnum;
2115
2116#ifdef FEAT_VIRTUALEDIT
2117 if (virtual_active() && curwin->w_cursor.coladd > 0)
2118 coladvance_force(getviscol());
2119#endif
2120
2121 col = curwin->w_cursor.col;
2122 oldp = ml_get(lnum);
2123 oldlen = (int)STRLEN(oldp);
2124
2125 newp = alloc_check((unsigned)(oldlen + newlen + 1));
2126 if (newp == NULL)
2127 return;
2128 if (col > 0)
2129 mch_memmove(newp, oldp, (size_t)col);
2130 mch_memmove(newp + col, s, (size_t)newlen);
2131 mch_memmove(newp + col + newlen, oldp + col, (size_t)(oldlen - col + 1));
2132 ml_replace(lnum, newp, FALSE);
2133 changed_bytes(lnum, col);
2134 curwin->w_cursor.col += newlen;
2135}
2136
2137/*
2138 * Delete one character under the cursor.
2139 * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
2140 * Caller must have prepared for undo.
2141 *
2142 * return FAIL for failure, OK otherwise
2143 */
2144 int
2145del_char(fixpos)
2146 int fixpos;
2147{
2148#ifdef FEAT_MBYTE
2149 if (has_mbyte)
2150 {
2151 /* Make sure the cursor is at the start of a character. */
2152 mb_adjust_cursor();
2153 if (*ml_get_cursor() == NUL)
2154 return FAIL;
2155 return del_chars(1L, fixpos);
2156 }
2157#endif
Bram Moolenaare3226be2005-12-18 22:10:00 +00002158 return del_bytes(1L, fixpos, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002159}
2160
2161#if defined(FEAT_MBYTE) || defined(PROTO)
2162/*
2163 * Like del_bytes(), but delete characters instead of bytes.
2164 */
2165 int
2166del_chars(count, fixpos)
2167 long count;
2168 int fixpos;
2169{
2170 long bytes = 0;
2171 long i;
2172 char_u *p;
2173 int l;
2174
2175 p = ml_get_cursor();
2176 for (i = 0; i < count && *p != NUL; ++i)
2177 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002178 l = (*mb_ptr2len)(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002179 bytes += l;
2180 p += l;
2181 }
Bram Moolenaare3226be2005-12-18 22:10:00 +00002182 return del_bytes(bytes, fixpos, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002183}
2184#endif
2185
2186/*
2187 * Delete "count" bytes under the cursor.
2188 * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
2189 * Caller must have prepared for undo.
2190 *
2191 * return FAIL for failure, OK otherwise
2192 */
2193 int
Bram Moolenaarca003e12006-03-17 23:19:38 +00002194del_bytes(count, fixpos_arg, use_delcombine)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002195 long count;
Bram Moolenaarca003e12006-03-17 23:19:38 +00002196 int fixpos_arg;
Bram Moolenaar78a15312009-05-15 19:33:18 +00002197 int use_delcombine UNUSED; /* 'delcombine' option applies */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002198{
2199 char_u *oldp, *newp;
2200 colnr_T oldlen;
2201 linenr_T lnum = curwin->w_cursor.lnum;
2202 colnr_T col = curwin->w_cursor.col;
2203 int was_alloced;
2204 long movelen;
Bram Moolenaarca003e12006-03-17 23:19:38 +00002205 int fixpos = fixpos_arg;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002206
2207 oldp = ml_get(lnum);
2208 oldlen = (int)STRLEN(oldp);
2209
2210 /*
2211 * Can't do anything when the cursor is on the NUL after the line.
2212 */
2213 if (col >= oldlen)
2214 return FAIL;
2215
2216#ifdef FEAT_MBYTE
2217 /* If 'delcombine' is set and deleting (less than) one character, only
2218 * delete the last combining character. */
Bram Moolenaare3226be2005-12-18 22:10:00 +00002219 if (p_deco && use_delcombine && enc_utf8
2220 && utfc_ptr2len(oldp + col) >= count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002221 {
Bram Moolenaar362e1a32006-03-06 23:29:24 +00002222 int cc[MAX_MCO];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002223 int n;
2224
Bram Moolenaar362e1a32006-03-06 23:29:24 +00002225 (void)utfc_ptr2char(oldp + col, cc);
2226 if (cc[0] != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002227 {
2228 /* Find the last composing char, there can be several. */
2229 n = col;
2230 do
2231 {
2232 col = n;
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002233 count = utf_ptr2len(oldp + n);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002234 n += count;
2235 } while (UTF_COMPOSINGLIKE(oldp + col, oldp + n));
2236 fixpos = 0;
2237 }
2238 }
2239#endif
2240
2241 /*
2242 * When count is too big, reduce it.
2243 */
2244 movelen = (long)oldlen - (long)col - count + 1; /* includes trailing NUL */
2245 if (movelen <= 1)
2246 {
2247 /*
2248 * If we just took off the last character of a non-blank line, and
Bram Moolenaarca003e12006-03-17 23:19:38 +00002249 * fixpos is TRUE, we don't want to end up positioned at the NUL,
2250 * unless "restart_edit" is set or 'virtualedit' contains "onemore".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002251 */
Bram Moolenaarca003e12006-03-17 23:19:38 +00002252 if (col > 0 && fixpos && restart_edit == 0
2253#ifdef FEAT_VIRTUALEDIT
2254 && (ve_flags & VE_ONEMORE) == 0
2255#endif
2256 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00002257 {
2258 --curwin->w_cursor.col;
2259#ifdef FEAT_VIRTUALEDIT
2260 curwin->w_cursor.coladd = 0;
2261#endif
2262#ifdef FEAT_MBYTE
2263 if (has_mbyte)
2264 curwin->w_cursor.col -=
2265 (*mb_head_off)(oldp, oldp + curwin->w_cursor.col);
2266#endif
2267 }
2268 count = oldlen - col;
2269 movelen = 1;
2270 }
2271
2272 /*
2273 * If the old line has been allocated the deletion can be done in the
2274 * existing line. Otherwise a new line has to be allocated
Bram Moolenaare21877a2008-02-13 09:58:14 +00002275 * Can't do this when using Netbeans, because we would need to invoke
2276 * netbeans_removed(), which deallocates the line. Let ml_replace() take
Bram Moolenaar1a509df2010-08-01 17:59:57 +02002277 * care of notifying Netbeans.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002278 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002279#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02002280 if (netbeans_active())
Bram Moolenaare21877a2008-02-13 09:58:14 +00002281 was_alloced = FALSE;
2282 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002283#endif
Bram Moolenaare21877a2008-02-13 09:58:14 +00002284 was_alloced = ml_line_alloced(); /* check if oldp was allocated */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002285 if (was_alloced)
2286 newp = oldp; /* use same allocated memory */
2287 else
2288 { /* need to allocate a new line */
2289 newp = alloc((unsigned)(oldlen + 1 - count));
2290 if (newp == NULL)
2291 return FAIL;
2292 mch_memmove(newp, oldp, (size_t)col);
2293 }
2294 mch_memmove(newp + col, oldp + col + count, (size_t)movelen);
2295 if (!was_alloced)
2296 ml_replace(lnum, newp, FALSE);
2297
2298 /* mark the buffer as changed and prepare for displaying */
2299 changed_bytes(lnum, curwin->w_cursor.col);
2300
2301 return OK;
2302}
2303
2304/*
2305 * Delete from cursor to end of line.
2306 * Caller must have prepared for undo.
2307 *
2308 * return FAIL for failure, OK otherwise
2309 */
2310 int
2311truncate_line(fixpos)
2312 int fixpos; /* if TRUE fix the cursor position when done */
2313{
2314 char_u *newp;
2315 linenr_T lnum = curwin->w_cursor.lnum;
2316 colnr_T col = curwin->w_cursor.col;
2317
2318 if (col == 0)
2319 newp = vim_strsave((char_u *)"");
2320 else
2321 newp = vim_strnsave(ml_get(lnum), col);
2322
2323 if (newp == NULL)
2324 return FAIL;
2325
2326 ml_replace(lnum, newp, FALSE);
2327
2328 /* mark the buffer as changed and prepare for displaying */
2329 changed_bytes(lnum, curwin->w_cursor.col);
2330
2331 /*
2332 * If "fixpos" is TRUE we don't want to end up positioned at the NUL.
2333 */
2334 if (fixpos && curwin->w_cursor.col > 0)
2335 --curwin->w_cursor.col;
2336
2337 return OK;
2338}
2339
2340/*
2341 * Delete "nlines" lines at the cursor.
2342 * Saves the lines for undo first if "undo" is TRUE.
2343 */
2344 void
2345del_lines(nlines, undo)
2346 long nlines; /* number of lines to delete */
2347 int undo; /* if TRUE, prepare for undo */
2348{
2349 long n;
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002350 linenr_T first = curwin->w_cursor.lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002351
2352 if (nlines <= 0)
2353 return;
2354
2355 /* save the deleted lines for undo */
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002356 if (undo && u_savedel(first, nlines) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002357 return;
2358
2359 for (n = 0; n < nlines; )
2360 {
2361 if (curbuf->b_ml.ml_flags & ML_EMPTY) /* nothing to delete */
2362 break;
2363
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002364 ml_delete(first, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002365 ++n;
2366
2367 /* If we delete the last line in the file, stop */
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002368 if (first > curbuf->b_ml.ml_line_count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002369 break;
2370 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002371
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002372 /* Correct the cursor position before calling deleted_lines_mark(), it may
2373 * trigger a callback to display the cursor. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002374 curwin->w_cursor.col = 0;
2375 check_cursor_lnum();
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002376
2377 /* adjust marks, mark the buffer as changed and prepare for displaying */
2378 deleted_lines_mark(first, n);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002379}
2380
2381 int
2382gchar_pos(pos)
2383 pos_T *pos;
2384{
2385 char_u *ptr = ml_get_pos(pos);
2386
2387#ifdef FEAT_MBYTE
2388 if (has_mbyte)
2389 return (*mb_ptr2char)(ptr);
2390#endif
2391 return (int)*ptr;
2392}
2393
2394 int
2395gchar_cursor()
2396{
2397#ifdef FEAT_MBYTE
2398 if (has_mbyte)
2399 return (*mb_ptr2char)(ml_get_cursor());
2400#endif
2401 return (int)*ml_get_cursor();
2402}
2403
2404/*
2405 * Write a character at the current cursor position.
2406 * It is directly written into the block.
2407 */
2408 void
2409pchar_cursor(c)
2410 int c;
2411{
2412 *(ml_get_buf(curbuf, curwin->w_cursor.lnum, TRUE)
2413 + curwin->w_cursor.col) = c;
2414}
2415
2416#if 0 /* not used */
2417/*
2418 * Put *pos at end of current buffer
2419 */
2420 void
2421goto_endofbuf(pos)
2422 pos_T *pos;
2423{
2424 char_u *p;
2425
2426 pos->lnum = curbuf->b_ml.ml_line_count;
2427 pos->col = 0;
2428 p = ml_get(pos->lnum);
2429 while (*p++)
2430 ++pos->col;
2431}
2432#endif
2433
2434/*
2435 * When extra == 0: Return TRUE if the cursor is before or on the first
2436 * non-blank in the line.
2437 * When extra == 1: Return TRUE if the cursor is before the first non-blank in
2438 * the line.
2439 */
2440 int
2441inindent(extra)
2442 int extra;
2443{
2444 char_u *ptr;
2445 colnr_T col;
2446
2447 for (col = 0, ptr = ml_get_curline(); vim_iswhite(*ptr); ++col)
2448 ++ptr;
2449 if (col >= curwin->w_cursor.col + extra)
2450 return TRUE;
2451 else
2452 return FALSE;
2453}
2454
2455/*
2456 * Skip to next part of an option argument: Skip space and comma.
2457 */
2458 char_u *
2459skip_to_option_part(p)
2460 char_u *p;
2461{
2462 if (*p == ',')
2463 ++p;
2464 while (*p == ' ')
2465 ++p;
2466 return p;
2467}
2468
2469/*
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002470 * Call this function when something in the current buffer is changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002471 *
2472 * Most often called through changed_bytes() and changed_lines(), which also
2473 * mark the area of the display to be redrawn.
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002474 *
2475 * Careful: may trigger autocommands that reload the buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002476 */
2477 void
2478changed()
2479{
2480#if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
2481 /* The text of the preediting area is inserted, but this doesn't
2482 * mean a change of the buffer yet. That is delayed until the
2483 * text is committed. (this means preedit becomes empty) */
2484 if (im_is_preediting() && !xim_changed_while_preediting)
2485 return;
2486 xim_changed_while_preediting = FALSE;
2487#endif
2488
2489 if (!curbuf->b_changed)
2490 {
2491 int save_msg_scroll = msg_scroll;
2492
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002493 /* Give a warning about changing a read-only file. This may also
2494 * check-out the file, thus change "curbuf"! */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002495 change_warning(0);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002496
Bram Moolenaar071d4272004-06-13 20:20:40 +00002497 /* Create a swap file if that is wanted.
2498 * Don't do this for "nofile" and "nowrite" buffer types. */
2499 if (curbuf->b_may_swap
2500#ifdef FEAT_QUICKFIX
2501 && !bt_dontwrite(curbuf)
2502#endif
2503 )
2504 {
2505 ml_open_file(curbuf);
2506
2507 /* The ml_open_file() can cause an ATTENTION message.
2508 * Wait two seconds, to make sure the user reads this unexpected
2509 * message. Since we could be anywhere, call wait_return() now,
2510 * and don't let the emsg() set msg_scroll. */
2511 if (need_wait_return && emsg_silent == 0)
2512 {
2513 out_flush();
2514 ui_delay(2000L, TRUE);
2515 wait_return(TRUE);
2516 msg_scroll = save_msg_scroll;
2517 }
2518 }
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02002519 changed_int();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002520 }
2521 ++curbuf->b_changedtick;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002522}
2523
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02002524/*
2525 * Internal part of changed(), no user interaction.
2526 */
2527 void
2528changed_int()
2529{
2530 curbuf->b_changed = TRUE;
2531 ml_setflags(curbuf);
2532#ifdef FEAT_WINDOWS
2533 check_status(curbuf);
2534 redraw_tabline = TRUE;
2535#endif
2536#ifdef FEAT_TITLE
2537 need_maketitle = TRUE; /* set window title later */
2538#endif
2539}
2540
Bram Moolenaardba8a912005-04-24 22:08:39 +00002541static void changedOneline __ARGS((buf_T *buf, linenr_T lnum));
2542static void changed_lines_buf __ARGS((buf_T *buf, linenr_T lnum, linenr_T lnume, long xtra));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002543static void changed_common __ARGS((linenr_T lnum, colnr_T col, linenr_T lnume, long xtra));
2544
2545/*
2546 * Changed bytes within a single line for the current buffer.
2547 * - marks the windows on this buffer to be redisplayed
2548 * - marks the buffer changed by calling changed()
2549 * - invalidates cached values
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002550 * Careful: may trigger autocommands that reload the buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002551 */
2552 void
2553changed_bytes(lnum, col)
2554 linenr_T lnum;
2555 colnr_T col;
2556{
Bram Moolenaardba8a912005-04-24 22:08:39 +00002557 changedOneline(curbuf, lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002558 changed_common(lnum, col, lnum + 1, 0L);
Bram Moolenaardba8a912005-04-24 22:08:39 +00002559
2560#ifdef FEAT_DIFF
2561 /* Diff highlighting in other diff windows may need to be updated too. */
2562 if (curwin->w_p_diff)
2563 {
2564 win_T *wp;
2565 linenr_T wlnum;
2566
2567 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2568 if (wp->w_p_diff && wp != curwin)
2569 {
2570 redraw_win_later(wp, VALID);
2571 wlnum = diff_lnum_win(lnum, wp);
2572 if (wlnum > 0)
2573 changedOneline(wp->w_buffer, wlnum);
2574 }
2575 }
2576#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002577}
2578
2579 static void
Bram Moolenaardba8a912005-04-24 22:08:39 +00002580changedOneline(buf, lnum)
2581 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002582 linenr_T lnum;
2583{
Bram Moolenaardba8a912005-04-24 22:08:39 +00002584 if (buf->b_mod_set)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002585 {
2586 /* find the maximum area that must be redisplayed */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002587 if (lnum < buf->b_mod_top)
2588 buf->b_mod_top = lnum;
2589 else if (lnum >= buf->b_mod_bot)
2590 buf->b_mod_bot = lnum + 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002591 }
2592 else
2593 {
2594 /* set the area that must be redisplayed to one line */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002595 buf->b_mod_set = TRUE;
2596 buf->b_mod_top = lnum;
2597 buf->b_mod_bot = lnum + 1;
2598 buf->b_mod_xlines = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002599 }
2600}
2601
2602/*
2603 * Appended "count" lines below line "lnum" in the current buffer.
2604 * Must be called AFTER the change and after mark_adjust().
2605 * Takes care of marking the buffer to be redrawn and sets the changed flag.
2606 */
2607 void
2608appended_lines(lnum, count)
2609 linenr_T lnum;
2610 long count;
2611{
2612 changed_lines(lnum + 1, 0, lnum + 1, count);
2613}
2614
2615/*
2616 * Like appended_lines(), but adjust marks first.
2617 */
2618 void
2619appended_lines_mark(lnum, count)
2620 linenr_T lnum;
2621 long count;
2622{
2623 mark_adjust(lnum + 1, (linenr_T)MAXLNUM, count, 0L);
2624 changed_lines(lnum + 1, 0, lnum + 1, count);
2625}
2626
2627/*
2628 * Deleted "count" lines at line "lnum" in the current buffer.
2629 * Must be called AFTER the change and after mark_adjust().
2630 * Takes care of marking the buffer to be redrawn and sets the changed flag.
2631 */
2632 void
2633deleted_lines(lnum, count)
2634 linenr_T lnum;
2635 long count;
2636{
2637 changed_lines(lnum, 0, lnum + count, -count);
2638}
2639
2640/*
2641 * Like deleted_lines(), but adjust marks first.
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002642 * Make sure the cursor is on a valid line before calling, a GUI callback may
2643 * be triggered to display the cursor.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002644 */
2645 void
2646deleted_lines_mark(lnum, count)
2647 linenr_T lnum;
2648 long count;
2649{
2650 mark_adjust(lnum, (linenr_T)(lnum + count - 1), (long)MAXLNUM, -count);
2651 changed_lines(lnum, 0, lnum + count, -count);
2652}
2653
2654/*
2655 * Changed lines for the current buffer.
2656 * Must be called AFTER the change and after mark_adjust().
2657 * - mark the buffer changed by calling changed()
2658 * - mark the windows on this buffer to be redisplayed
2659 * - invalidate cached values
2660 * "lnum" is the first line that needs displaying, "lnume" the first line
2661 * below the changed lines (BEFORE the change).
2662 * When only inserting lines, "lnum" and "lnume" are equal.
2663 * Takes care of calling changed() and updating b_mod_*.
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002664 * Careful: may trigger autocommands that reload the buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002665 */
2666 void
2667changed_lines(lnum, col, lnume, xtra)
2668 linenr_T lnum; /* first line with change */
2669 colnr_T col; /* column in first line with change */
2670 linenr_T lnume; /* line below last changed line */
2671 long xtra; /* number of extra lines (negative when deleting) */
2672{
Bram Moolenaardba8a912005-04-24 22:08:39 +00002673 changed_lines_buf(curbuf, lnum, lnume, xtra);
2674
2675#ifdef FEAT_DIFF
2676 if (xtra == 0 && curwin->w_p_diff)
2677 {
2678 /* When the number of lines doesn't change then mark_adjust() isn't
2679 * called and other diff buffers still need to be marked for
2680 * displaying. */
2681 win_T *wp;
2682 linenr_T wlnum;
2683
2684 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2685 if (wp->w_p_diff && wp != curwin)
2686 {
2687 redraw_win_later(wp, VALID);
2688 wlnum = diff_lnum_win(lnum, wp);
2689 if (wlnum > 0)
2690 changed_lines_buf(wp->w_buffer, wlnum,
2691 lnume - lnum + wlnum, 0L);
2692 }
2693 }
2694#endif
2695
2696 changed_common(lnum, col, lnume, xtra);
2697}
2698
2699 static void
2700changed_lines_buf(buf, lnum, lnume, xtra)
2701 buf_T *buf;
2702 linenr_T lnum; /* first line with change */
2703 linenr_T lnume; /* line below last changed line */
2704 long xtra; /* number of extra lines (negative when deleting) */
2705{
2706 if (buf->b_mod_set)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002707 {
2708 /* find the maximum area that must be redisplayed */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002709 if (lnum < buf->b_mod_top)
2710 buf->b_mod_top = lnum;
2711 if (lnum < buf->b_mod_bot)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002712 {
2713 /* adjust old bot position for xtra lines */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002714 buf->b_mod_bot += xtra;
2715 if (buf->b_mod_bot < lnum)
2716 buf->b_mod_bot = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002717 }
Bram Moolenaardba8a912005-04-24 22:08:39 +00002718 if (lnume + xtra > buf->b_mod_bot)
2719 buf->b_mod_bot = lnume + xtra;
2720 buf->b_mod_xlines += xtra;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002721 }
2722 else
2723 {
2724 /* set the area that must be redisplayed */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002725 buf->b_mod_set = TRUE;
2726 buf->b_mod_top = lnum;
2727 buf->b_mod_bot = lnume + xtra;
2728 buf->b_mod_xlines = xtra;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002729 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002730}
2731
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002732/*
2733 * Common code for when a change is was made.
2734 * See changed_lines() for the arguments.
2735 * Careful: may trigger autocommands that reload the buffer.
2736 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002737 static void
2738changed_common(lnum, col, lnume, xtra)
2739 linenr_T lnum;
2740 colnr_T col;
2741 linenr_T lnume;
2742 long xtra;
2743{
2744 win_T *wp;
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00002745#ifdef FEAT_WINDOWS
2746 tabpage_T *tp;
2747#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002748 int i;
2749#ifdef FEAT_JUMPLIST
2750 int cols;
2751 pos_T *p;
2752 int add;
2753#endif
2754
2755 /* mark the buffer as modified */
2756 changed();
2757
2758 /* set the '. mark */
2759 if (!cmdmod.keepjumps)
2760 {
2761 curbuf->b_last_change.lnum = lnum;
2762 curbuf->b_last_change.col = col;
2763
2764#ifdef FEAT_JUMPLIST
2765 /* Create a new entry if a new undo-able change was started or we
2766 * don't have an entry yet. */
2767 if (curbuf->b_new_change || curbuf->b_changelistlen == 0)
2768 {
2769 if (curbuf->b_changelistlen == 0)
2770 add = TRUE;
2771 else
2772 {
2773 /* Don't create a new entry when the line number is the same
2774 * as the last one and the column is not too far away. Avoids
2775 * creating many entries for typing "xxxxx". */
2776 p = &curbuf->b_changelist[curbuf->b_changelistlen - 1];
2777 if (p->lnum != lnum)
2778 add = TRUE;
2779 else
2780 {
2781 cols = comp_textwidth(FALSE);
2782 if (cols == 0)
2783 cols = 79;
2784 add = (p->col + cols < col || col + cols < p->col);
2785 }
2786 }
2787 if (add)
2788 {
2789 /* This is the first of a new sequence of undo-able changes
2790 * and it's at some distance of the last change. Use a new
2791 * position in the changelist. */
2792 curbuf->b_new_change = FALSE;
2793
2794 if (curbuf->b_changelistlen == JUMPLISTSIZE)
2795 {
2796 /* changelist is full: remove oldest entry */
2797 curbuf->b_changelistlen = JUMPLISTSIZE - 1;
2798 mch_memmove(curbuf->b_changelist, curbuf->b_changelist + 1,
2799 sizeof(pos_T) * (JUMPLISTSIZE - 1));
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00002800 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002801 {
2802 /* Correct position in changelist for other windows on
2803 * this buffer. */
2804 if (wp->w_buffer == curbuf && wp->w_changelistidx > 0)
2805 --wp->w_changelistidx;
2806 }
2807 }
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00002808 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002809 {
2810 /* For other windows, if the position in the changelist is
2811 * at the end it stays at the end. */
2812 if (wp->w_buffer == curbuf
2813 && wp->w_changelistidx == curbuf->b_changelistlen)
2814 ++wp->w_changelistidx;
2815 }
2816 ++curbuf->b_changelistlen;
2817 }
2818 }
2819 curbuf->b_changelist[curbuf->b_changelistlen - 1] =
2820 curbuf->b_last_change;
2821 /* The current window is always after the last change, so that "g,"
2822 * takes you back to it. */
2823 curwin->w_changelistidx = curbuf->b_changelistlen;
2824#endif
2825 }
2826
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00002827 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002828 {
2829 if (wp->w_buffer == curbuf)
2830 {
2831 /* Mark this window to be redrawn later. */
2832 if (wp->w_redr_type < VALID)
2833 wp->w_redr_type = VALID;
2834
2835 /* Check if a change in the buffer has invalidated the cached
2836 * values for the cursor. */
2837#ifdef FEAT_FOLDING
2838 /*
2839 * Update the folds for this window. Can't postpone this, because
2840 * a following operator might work on the whole fold: ">>dd".
2841 */
2842 foldUpdate(wp, lnum, lnume + xtra - 1);
2843
2844 /* The change may cause lines above or below the change to become
2845 * included in a fold. Set lnum/lnume to the first/last line that
2846 * might be displayed differently.
2847 * Set w_cline_folded here as an efficient way to update it when
2848 * inserting lines just above a closed fold. */
2849 i = hasFoldingWin(wp, lnum, &lnum, NULL, FALSE, NULL);
2850 if (wp->w_cursor.lnum == lnum)
2851 wp->w_cline_folded = i;
2852 i = hasFoldingWin(wp, lnume, NULL, &lnume, FALSE, NULL);
2853 if (wp->w_cursor.lnum == lnume)
2854 wp->w_cline_folded = i;
2855
2856 /* If the changed line is in a range of previously folded lines,
2857 * compare with the first line in that range. */
2858 if (wp->w_cursor.lnum <= lnum)
2859 {
2860 i = find_wl_entry(wp, lnum);
2861 if (i >= 0 && wp->w_cursor.lnum > wp->w_lines[i].wl_lnum)
2862 changed_line_abv_curs_win(wp);
2863 }
2864#endif
2865
2866 if (wp->w_cursor.lnum > lnum)
2867 changed_line_abv_curs_win(wp);
2868 else if (wp->w_cursor.lnum == lnum && wp->w_cursor.col >= col)
2869 changed_cline_bef_curs_win(wp);
2870 if (wp->w_botline >= lnum)
2871 {
2872 /* Assume that botline doesn't change (inserted lines make
2873 * other lines scroll down below botline). */
2874 approximate_botline_win(wp);
2875 }
2876
2877 /* Check if any w_lines[] entries have become invalid.
2878 * For entries below the change: Correct the lnums for
2879 * inserted/deleted lines. Makes it possible to stop displaying
2880 * after the change. */
2881 for (i = 0; i < wp->w_lines_valid; ++i)
2882 if (wp->w_lines[i].wl_valid)
2883 {
2884 if (wp->w_lines[i].wl_lnum >= lnum)
2885 {
2886 if (wp->w_lines[i].wl_lnum < lnume)
2887 {
2888 /* line included in change */
2889 wp->w_lines[i].wl_valid = FALSE;
2890 }
2891 else if (xtra != 0)
2892 {
2893 /* line below change */
2894 wp->w_lines[i].wl_lnum += xtra;
2895#ifdef FEAT_FOLDING
2896 wp->w_lines[i].wl_lastlnum += xtra;
2897#endif
2898 }
2899 }
2900#ifdef FEAT_FOLDING
2901 else if (wp->w_lines[i].wl_lastlnum >= lnum)
2902 {
2903 /* change somewhere inside this range of folded lines,
2904 * may need to be redrawn */
2905 wp->w_lines[i].wl_valid = FALSE;
2906 }
2907#endif
2908 }
Bram Moolenaar3234cc62009-11-03 17:47:12 +00002909
2910#ifdef FEAT_FOLDING
2911 /* Take care of side effects for setting w_topline when folds have
2912 * changed. Esp. when the buffer was changed in another window. */
2913 if (hasAnyFolding(wp))
2914 set_topline(wp, wp->w_topline);
2915#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002916 }
2917 }
2918
2919 /* Call update_screen() later, which checks out what needs to be redrawn,
2920 * since it notices b_mod_set and then uses b_mod_*. */
2921 if (must_redraw < VALID)
2922 must_redraw = VALID;
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002923
2924#ifdef FEAT_AUTOCMD
2925 /* when the cursor line is changed always trigger CursorMoved */
Bram Moolenaare163f1c2006-10-17 09:12:21 +00002926 if (lnum <= curwin->w_cursor.lnum
2927 && lnume + (xtra < 0 ? -xtra : xtra) > curwin->w_cursor.lnum)
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002928 last_cursormoved.lnum = 0;
2929#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002930}
2931
2932/*
2933 * unchanged() is called when the changed flag must be reset for buffer 'buf'
2934 */
2935 void
2936unchanged(buf, ff)
2937 buf_T *buf;
2938 int ff; /* also reset 'fileformat' */
2939{
2940 if (buf->b_changed || (ff && file_ff_differs(buf)))
2941 {
2942 buf->b_changed = 0;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002943 ml_setflags(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002944 if (ff)
2945 save_file_ff(buf);
2946#ifdef FEAT_WINDOWS
2947 check_status(buf);
Bram Moolenaar997fb4b2006-02-17 21:53:23 +00002948 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002949#endif
2950#ifdef FEAT_TITLE
2951 need_maketitle = TRUE; /* set window title later */
2952#endif
2953 }
2954 ++buf->b_changedtick;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002955#ifdef FEAT_NETBEANS_INTG
2956 netbeans_unmodified(buf);
2957#endif
2958}
2959
2960#if defined(FEAT_WINDOWS) || defined(PROTO)
2961/*
2962 * check_status: called when the status bars for the buffer 'buf'
2963 * need to be updated
2964 */
2965 void
2966check_status(buf)
2967 buf_T *buf;
2968{
2969 win_T *wp;
2970
2971 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2972 if (wp->w_buffer == buf && wp->w_status_height)
2973 {
2974 wp->w_redr_status = TRUE;
2975 if (must_redraw < VALID)
2976 must_redraw = VALID;
2977 }
2978}
2979#endif
2980
2981/*
2982 * If the file is readonly, give a warning message with the first change.
2983 * Don't do this for autocommands.
2984 * Don't use emsg(), because it flushes the macro buffer.
Bram Moolenaard5cdbeb2005-10-10 20:59:28 +00002985 * If we have undone all changes b_changed will be FALSE, but "b_did_warn"
Bram Moolenaar071d4272004-06-13 20:20:40 +00002986 * will be TRUE.
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002987 * Careful: may trigger autocommands that reload the buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002988 */
2989 void
2990change_warning(col)
2991 int col; /* column for message; non-zero when in insert
2992 mode and 'showmode' is on */
2993{
Bram Moolenaar496c5262009-03-18 14:42:00 +00002994 static char *w_readonly = N_("W10: Warning: Changing a readonly file");
2995
Bram Moolenaar071d4272004-06-13 20:20:40 +00002996 if (curbuf->b_did_warn == FALSE
2997 && curbufIsChanged() == 0
2998#ifdef FEAT_AUTOCMD
2999 && !autocmd_busy
3000#endif
3001 && curbuf->b_p_ro)
3002 {
3003#ifdef FEAT_AUTOCMD
Bram Moolenaar910f66f2006-04-05 20:41:53 +00003004 ++curbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003005 apply_autocmds(EVENT_FILECHANGEDRO, NULL, NULL, FALSE, curbuf);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00003006 --curbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003007 if (!curbuf->b_p_ro)
3008 return;
3009#endif
3010 /*
3011 * Do what msg() does, but with a column offset if the warning should
3012 * be after the mode message.
3013 */
3014 msg_start();
3015 if (msg_row == Rows - 1)
3016 msg_col = col;
Bram Moolenaar2df6dcc2004-07-12 15:53:54 +00003017 msg_source(hl_attr(HLF_W));
Bram Moolenaar496c5262009-03-18 14:42:00 +00003018 MSG_PUTS_ATTR(_(w_readonly), hl_attr(HLF_W) | MSG_HIST);
3019#ifdef FEAT_EVAL
3020 set_vim_var_string(VV_WARNINGMSG, (char_u *)_(w_readonly), -1);
3021#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003022 msg_clr_eos();
3023 (void)msg_end();
3024 if (msg_silent == 0 && !silent_mode)
3025 {
3026 out_flush();
3027 ui_delay(1000L, TRUE); /* give the user time to think about it */
3028 }
3029 curbuf->b_did_warn = TRUE;
3030 redraw_cmdline = FALSE; /* don't redraw and erase the message */
3031 if (msg_row < Rows - 1)
3032 showmode();
3033 }
3034}
3035
3036/*
3037 * Ask for a reply from the user, a 'y' or a 'n'.
3038 * No other characters are accepted, the message is repeated until a valid
3039 * reply is entered or CTRL-C is hit.
3040 * If direct is TRUE, don't use vgetc() but ui_inchar(), don't get characters
3041 * from any buffers but directly from the user.
3042 *
3043 * return the 'y' or 'n'
3044 */
3045 int
3046ask_yesno(str, direct)
3047 char_u *str;
3048 int direct;
3049{
3050 int r = ' ';
3051 int save_State = State;
3052
3053 if (exiting) /* put terminal in raw mode for this question */
3054 settmode(TMODE_RAW);
3055 ++no_wait_return;
3056#ifdef USE_ON_FLY_SCROLL
3057 dont_scroll = TRUE; /* disallow scrolling here */
3058#endif
3059 State = CONFIRM; /* mouse behaves like with :confirm */
3060#ifdef FEAT_MOUSE
3061 setmouse(); /* disables mouse for xterm */
3062#endif
3063 ++no_mapping;
3064 ++allow_keys; /* no mapping here, but recognize keys */
3065
3066 while (r != 'y' && r != 'n')
3067 {
3068 /* same highlighting as for wait_return */
3069 smsg_attr(hl_attr(HLF_R), (char_u *)"%s (y/n)?", str);
3070 if (direct)
3071 r = get_keystroke();
3072 else
Bram Moolenaar913626c2008-01-03 11:43:42 +00003073 r = plain_vgetc();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003074 if (r == Ctrl_C || r == ESC)
3075 r = 'n';
3076 msg_putchar(r); /* show what you typed */
3077 out_flush();
3078 }
3079 --no_wait_return;
3080 State = save_State;
3081#ifdef FEAT_MOUSE
3082 setmouse();
3083#endif
3084 --no_mapping;
3085 --allow_keys;
3086
3087 return r;
3088}
3089
3090/*
3091 * Get a key stroke directly from the user.
3092 * Ignores mouse clicks and scrollbar events, except a click for the left
3093 * button (used at the more prompt).
3094 * Doesn't use vgetc(), because it syncs undo and eats mapped characters.
3095 * Disadvantage: typeahead is ignored.
3096 * Translates the interrupt character for unix to ESC.
3097 */
3098 int
3099get_keystroke()
3100{
3101#define CBUFLEN 151
3102 char_u buf[CBUFLEN];
3103 int len = 0;
3104 int n;
3105 int save_mapped_ctrl_c = mapped_ctrl_c;
Bram Moolenaar4395a712006-09-05 18:57:57 +00003106 int waited = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003107
3108 mapped_ctrl_c = FALSE; /* mappings are not used here */
3109 for (;;)
3110 {
3111 cursor_on();
3112 out_flush();
3113
3114 /* First time: blocking wait. Second time: wait up to 100ms for a
3115 * terminal code to complete. Leave some room for check_termcode() to
3116 * insert a key code into (max 5 chars plus NUL). And
3117 * fix_input_buffer() can triple the number of bytes. */
3118 n = ui_inchar(buf + len, (CBUFLEN - 6 - len) / 3,
3119 len == 0 ? -1L : 100L, 0);
3120 if (n > 0)
3121 {
3122 /* Replace zero and CSI by a special key code. */
3123 n = fix_input_buffer(buf + len, n, FALSE);
3124 len += n;
Bram Moolenaar4395a712006-09-05 18:57:57 +00003125 waited = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003126 }
Bram Moolenaar4395a712006-09-05 18:57:57 +00003127 else if (len > 0)
3128 ++waited; /* keep track of the waiting time */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003129
Bram Moolenaar4395a712006-09-05 18:57:57 +00003130 /* Incomplete termcode and not timed out yet: get more characters */
3131 if ((n = check_termcode(1, buf, len)) < 0
3132 && (!p_ttimeout || waited * 100L < (p_ttm < 0 ? p_tm : p_ttm)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003133 continue;
Bram Moolenaar4395a712006-09-05 18:57:57 +00003134
Bram Moolenaar071d4272004-06-13 20:20:40 +00003135 /* found a termcode: adjust length */
3136 if (n > 0)
3137 len = n;
3138 if (len == 0) /* nothing typed yet */
3139 continue;
3140
3141 /* Handle modifier and/or special key code. */
3142 n = buf[0];
3143 if (n == K_SPECIAL)
3144 {
3145 n = TO_SPECIAL(buf[1], buf[2]);
3146 if (buf[1] == KS_MODIFIER
3147 || n == K_IGNORE
3148#ifdef FEAT_MOUSE
3149 || n == K_LEFTMOUSE_NM
3150 || n == K_LEFTDRAG
3151 || n == K_LEFTRELEASE
3152 || n == K_LEFTRELEASE_NM
3153 || n == K_MIDDLEMOUSE
3154 || n == K_MIDDLEDRAG
3155 || n == K_MIDDLERELEASE
3156 || n == K_RIGHTMOUSE
3157 || n == K_RIGHTDRAG
3158 || n == K_RIGHTRELEASE
3159 || n == K_MOUSEDOWN
3160 || n == K_MOUSEUP
Bram Moolenaar8d9b40e2010-07-25 15:49:07 +02003161 || n == K_MOUSELEFT
3162 || n == K_MOUSERIGHT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003163 || n == K_X1MOUSE
3164 || n == K_X1DRAG
3165 || n == K_X1RELEASE
3166 || n == K_X2MOUSE
3167 || n == K_X2DRAG
3168 || n == K_X2RELEASE
3169# ifdef FEAT_GUI
3170 || n == K_VER_SCROLLBAR
3171 || n == K_HOR_SCROLLBAR
3172# endif
3173#endif
3174 )
3175 {
3176 if (buf[1] == KS_MODIFIER)
3177 mod_mask = buf[2];
3178 len -= 3;
3179 if (len > 0)
3180 mch_memmove(buf, buf + 3, (size_t)len);
3181 continue;
3182 }
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00003183 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003184 }
3185#ifdef FEAT_MBYTE
3186 if (has_mbyte)
3187 {
3188 if (MB_BYTE2LEN(n) > len)
3189 continue; /* more bytes to get */
3190 buf[len >= CBUFLEN ? CBUFLEN - 1 : len] = NUL;
3191 n = (*mb_ptr2char)(buf);
3192 }
3193#endif
3194#ifdef UNIX
3195 if (n == intr_char)
3196 n = ESC;
3197#endif
3198 break;
3199 }
3200
3201 mapped_ctrl_c = save_mapped_ctrl_c;
3202 return n;
3203}
3204
3205/*
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003206 * Get a number from the user.
3207 * When "mouse_used" is not NULL allow using the mouse.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003208 */
3209 int
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003210get_number(colon, mouse_used)
3211 int colon; /* allow colon to abort */
3212 int *mouse_used;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003213{
3214 int n = 0;
3215 int c;
Bram Moolenaar3991dab2006-03-27 17:01:56 +00003216 int typed = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003217
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003218 if (mouse_used != NULL)
3219 *mouse_used = FALSE;
3220
Bram Moolenaar071d4272004-06-13 20:20:40 +00003221 /* When not printing messages, the user won't know what to type, return a
3222 * zero (as if CR was hit). */
3223 if (msg_silent != 0)
3224 return 0;
3225
3226#ifdef USE_ON_FLY_SCROLL
3227 dont_scroll = TRUE; /* disallow scrolling here */
3228#endif
3229 ++no_mapping;
3230 ++allow_keys; /* no mapping here, but recognize keys */
3231 for (;;)
3232 {
3233 windgoto(msg_row, msg_col);
3234 c = safe_vgetc();
3235 if (VIM_ISDIGIT(c))
3236 {
3237 n = n * 10 + c - '0';
3238 msg_putchar(c);
Bram Moolenaar3991dab2006-03-27 17:01:56 +00003239 ++typed;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003240 }
3241 else if (c == K_DEL || c == K_KDEL || c == K_BS || c == Ctrl_H)
3242 {
Bram Moolenaar3991dab2006-03-27 17:01:56 +00003243 if (typed > 0)
3244 {
3245 MSG_PUTS("\b \b");
3246 --typed;
3247 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003248 n /= 10;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003249 }
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003250#ifdef FEAT_MOUSE
3251 else if (mouse_used != NULL && c == K_LEFTMOUSE)
3252 {
3253 *mouse_used = TRUE;
3254 n = mouse_row + 1;
3255 break;
3256 }
3257#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003258 else if (n == 0 && c == ':' && colon)
3259 {
3260 stuffcharReadbuff(':');
3261 if (!exmode_active)
3262 cmdline_row = msg_row;
3263 skip_redraw = TRUE; /* skip redraw once */
3264 do_redraw = FALSE;
3265 break;
3266 }
3267 else if (c == CAR || c == NL || c == Ctrl_C || c == ESC)
3268 break;
3269 }
3270 --no_mapping;
3271 --allow_keys;
3272 return n;
3273}
3274
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003275/*
3276 * Ask the user to enter a number.
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003277 * When "mouse_used" is not NULL allow using the mouse and in that case return
3278 * the line number.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003279 */
3280 int
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003281prompt_for_number(mouse_used)
3282 int *mouse_used;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003283{
3284 int i;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003285 int save_cmdline_row;
3286 int save_State;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003287
3288 /* When using ":silent" assume that <CR> was entered. */
Bram Moolenaar42eeac32005-06-29 22:40:58 +00003289 if (mouse_used != NULL)
Bram Moolenaard812df62008-11-09 12:46:09 +00003290 MSG_PUTS(_("Type number and <Enter> or click with mouse (empty cancels): "));
Bram Moolenaar42eeac32005-06-29 22:40:58 +00003291 else
Bram Moolenaard812df62008-11-09 12:46:09 +00003292 MSG_PUTS(_("Type number and <Enter> (empty cancels): "));
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003293
Bram Moolenaar203335e2006-09-03 14:35:42 +00003294 /* Set the state such that text can be selected/copied/pasted and we still
3295 * get mouse events. */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003296 save_cmdline_row = cmdline_row;
Bram Moolenaar203335e2006-09-03 14:35:42 +00003297 cmdline_row = 0;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003298 save_State = State;
Bram Moolenaar203335e2006-09-03 14:35:42 +00003299 State = CMDLINE;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003300
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003301 i = get_number(TRUE, mouse_used);
3302 if (KeyTyped)
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003303 {
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003304 /* don't call wait_return() now */
3305 /* msg_putchar('\n'); */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003306 cmdline_row = msg_row - 1;
3307 need_wait_return = FALSE;
3308 msg_didany = FALSE;
Bram Moolenaarb2450162009-07-22 09:04:20 +00003309 msg_didout = FALSE;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003310 }
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003311 else
3312 cmdline_row = save_cmdline_row;
3313 State = save_State;
3314
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003315 return i;
3316}
3317
Bram Moolenaar071d4272004-06-13 20:20:40 +00003318 void
3319msgmore(n)
3320 long n;
3321{
3322 long pn;
3323
3324 if (global_busy /* no messages now, wait until global is finished */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003325 || !messaging()) /* 'lazyredraw' set, don't do messages now */
3326 return;
3327
Bram Moolenaar7df2d662005-01-25 22:18:08 +00003328 /* We don't want to overwrite another important message, but do overwrite
3329 * a previous "more lines" or "fewer lines" message, so that "5dd" and
3330 * then "put" reports the last action. */
3331 if (keep_msg != NULL && !keep_msg_more)
3332 return;
3333
Bram Moolenaar071d4272004-06-13 20:20:40 +00003334 if (n > 0)
3335 pn = n;
3336 else
3337 pn = -n;
3338
3339 if (pn > p_report)
3340 {
3341 if (pn == 1)
3342 {
3343 if (n > 0)
3344 STRCPY(msg_buf, _("1 more line"));
3345 else
3346 STRCPY(msg_buf, _("1 line less"));
3347 }
3348 else
3349 {
3350 if (n > 0)
3351 sprintf((char *)msg_buf, _("%ld more lines"), pn);
3352 else
3353 sprintf((char *)msg_buf, _("%ld fewer lines"), pn);
3354 }
3355 if (got_int)
3356 STRCAT(msg_buf, _(" (Interrupted)"));
3357 if (msg(msg_buf))
3358 {
Bram Moolenaar238a5642006-02-21 22:12:05 +00003359 set_keep_msg(msg_buf, 0);
Bram Moolenaar7df2d662005-01-25 22:18:08 +00003360 keep_msg_more = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003361 }
3362 }
3363}
3364
3365/*
3366 * flush map and typeahead buffers and give a warning for an error
3367 */
3368 void
3369beep_flush()
3370{
3371 if (emsg_silent == 0)
3372 {
3373 flush_buffers(FALSE);
3374 vim_beep();
3375 }
3376}
3377
3378/*
3379 * give a warning for an error
3380 */
3381 void
3382vim_beep()
3383{
3384 if (emsg_silent == 0)
3385 {
3386 if (p_vb
3387#ifdef FEAT_GUI
3388 /* While the GUI is starting up the termcap is set for the GUI
3389 * but the output still goes to a terminal. */
3390 && !(gui.in_use && gui.starting)
3391#endif
3392 )
3393 {
3394 out_str(T_VB);
3395 }
3396 else
3397 {
3398#ifdef MSDOS
3399 /*
3400 * The number of beeps outputted is reduced to avoid having to wait
3401 * for all the beeps to finish. This is only a problem on systems
3402 * where the beeps don't overlap.
3403 */
3404 if (beep_count == 0 || beep_count == 10)
3405 {
3406 out_char(BELL);
3407 beep_count = 1;
3408 }
3409 else
3410 ++beep_count;
3411#else
3412 out_char(BELL);
3413#endif
3414 }
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003415
3416 /* When 'verbose' is set and we are sourcing a script or executing a
3417 * function give the user a hint where the beep comes from. */
3418 if (vim_strchr(p_debug, 'e') != NULL)
3419 {
3420 msg_source(hl_attr(HLF_W));
3421 msg_attr((char_u *)_("Beep!"), hl_attr(HLF_W));
3422 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003423 }
3424}
3425
3426/*
3427 * To get the "real" home directory:
3428 * - get value of $HOME
3429 * For Unix:
3430 * - go to that directory
3431 * - do mch_dirname() to get the real name of that directory.
3432 * This also works with mounts and links.
3433 * Don't do this for MS-DOS, it will change the "current dir" for a drive.
3434 */
3435static char_u *homedir = NULL;
3436
3437 void
3438init_homedir()
3439{
3440 char_u *var;
3441
Bram Moolenaar05159a02005-02-26 23:04:13 +00003442 /* In case we are called a second time (when 'encoding' changes). */
3443 vim_free(homedir);
3444 homedir = NULL;
3445
Bram Moolenaar071d4272004-06-13 20:20:40 +00003446#ifdef VMS
3447 var = mch_getenv((char_u *)"SYS$LOGIN");
3448#else
3449 var = mch_getenv((char_u *)"HOME");
3450#endif
3451
3452 if (var != NULL && *var == NUL) /* empty is same as not set */
3453 var = NULL;
3454
3455#ifdef WIN3264
3456 /*
3457 * Weird but true: $HOME may contain an indirect reference to another
3458 * variable, esp. "%USERPROFILE%". Happens when $USERPROFILE isn't set
3459 * when $HOME is being set.
3460 */
3461 if (var != NULL && *var == '%')
3462 {
3463 char_u *p;
3464 char_u *exp;
3465
3466 p = vim_strchr(var + 1, '%');
3467 if (p != NULL)
3468 {
Bram Moolenaarce0842a2005-07-18 21:58:11 +00003469 vim_strncpy(NameBuff, var + 1, p - (var + 1));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003470 exp = mch_getenv(NameBuff);
3471 if (exp != NULL && *exp != NUL
3472 && STRLEN(exp) + STRLEN(p) < MAXPATHL)
3473 {
Bram Moolenaar555b2802005-05-19 21:08:39 +00003474 vim_snprintf((char *)NameBuff, MAXPATHL, "%s%s", exp, p + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003475 var = NameBuff;
3476 /* Also set $HOME, it's needed for _viminfo. */
3477 vim_setenv((char_u *)"HOME", NameBuff);
3478 }
3479 }
3480 }
3481
3482 /*
3483 * Typically, $HOME is not defined on Windows, unless the user has
3484 * specifically defined it for Vim's sake. However, on Windows NT
3485 * platforms, $HOMEDRIVE and $HOMEPATH are automatically defined for
3486 * each user. Try constructing $HOME from these.
3487 */
3488 if (var == NULL)
3489 {
3490 char_u *homedrive, *homepath;
3491
3492 homedrive = mch_getenv((char_u *)"HOMEDRIVE");
3493 homepath = mch_getenv((char_u *)"HOMEPATH");
Bram Moolenaar6f977012010-01-06 17:53:38 +01003494 if (homepath == NULL || *homepath == NUL)
3495 homepath = "\\";
3496 if (homedrive != NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00003497 && STRLEN(homedrive) + STRLEN(homepath) < MAXPATHL)
3498 {
3499 sprintf((char *)NameBuff, "%s%s", homedrive, homepath);
3500 if (NameBuff[0] != NUL)
3501 {
3502 var = NameBuff;
3503 /* Also set $HOME, it's needed for _viminfo. */
3504 vim_setenv((char_u *)"HOME", NameBuff);
3505 }
3506 }
3507 }
Bram Moolenaar05159a02005-02-26 23:04:13 +00003508
3509# if defined(FEAT_MBYTE)
3510 if (enc_utf8 && var != NULL)
3511 {
3512 int len;
3513 char_u *pp;
3514
3515 /* Convert from active codepage to UTF-8. Other conversions are
3516 * not done, because they would fail for non-ASCII characters. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003517 acp_to_enc(var, (int)STRLEN(var), &pp, &len);
Bram Moolenaar05159a02005-02-26 23:04:13 +00003518 if (pp != NULL)
3519 {
3520 homedir = pp;
3521 return;
3522 }
3523 }
3524# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003525#endif
3526
3527#if defined(OS2) || defined(MSDOS) || defined(MSWIN)
3528 /*
3529 * Default home dir is C:/
3530 * Best assumption we can make in such a situation.
3531 */
3532 if (var == NULL)
3533 var = "C:/";
3534#endif
3535 if (var != NULL)
3536 {
3537#ifdef UNIX
3538 /*
3539 * Change to the directory and get the actual path. This resolves
3540 * links. Don't do it when we can't return.
3541 */
3542 if (mch_dirname(NameBuff, MAXPATHL) == OK
3543 && mch_chdir((char *)NameBuff) == 0)
3544 {
3545 if (!mch_chdir((char *)var) && mch_dirname(IObuff, IOSIZE) == OK)
3546 var = IObuff;
3547 if (mch_chdir((char *)NameBuff) != 0)
3548 EMSG(_(e_prev_dir));
3549 }
3550#endif
3551 homedir = vim_strsave(var);
3552 }
3553}
3554
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003555#if defined(EXITFREE) || defined(PROTO)
3556 void
3557free_homedir()
3558{
3559 vim_free(homedir);
3560}
3561#endif
3562
Bram Moolenaar071d4272004-06-13 20:20:40 +00003563/*
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003564 * Call expand_env() and store the result in an allocated string.
3565 * This is not very memory efficient, this expects the result to be freed
3566 * again soon.
3567 */
3568 char_u *
3569expand_env_save(src)
3570 char_u *src;
3571{
3572 return expand_env_save_opt(src, FALSE);
3573}
3574
3575/*
3576 * Idem, but when "one" is TRUE handle the string as one file name, only
3577 * expand "~" at the start.
3578 */
3579 char_u *
3580expand_env_save_opt(src, one)
3581 char_u *src;
3582 int one;
3583{
3584 char_u *p;
3585
3586 p = alloc(MAXPATHL);
3587 if (p != NULL)
3588 expand_env_esc(src, p, MAXPATHL, FALSE, one, NULL);
3589 return p;
3590}
3591
3592/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003593 * Expand environment variable with path name.
3594 * "~/" is also expanded, using $HOME. For Unix "~user/" is expanded.
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003595 * Skips over "\ ", "\~" and "\$" (not for Win32 though).
Bram Moolenaar071d4272004-06-13 20:20:40 +00003596 * If anything fails no expansion is done and dst equals src.
3597 */
3598 void
3599expand_env(src, dst, dstlen)
3600 char_u *src; /* input string e.g. "$HOME/vim.hlp" */
3601 char_u *dst; /* where to put the result */
3602 int dstlen; /* maximum length of the result */
3603{
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003604 expand_env_esc(src, dst, dstlen, FALSE, FALSE, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003605}
3606
3607 void
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003608expand_env_esc(srcp, dst, dstlen, esc, one, startstr)
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003609 char_u *srcp; /* input string e.g. "$HOME/vim.hlp" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003610 char_u *dst; /* where to put the result */
3611 int dstlen; /* maximum length of the result */
3612 int esc; /* escape spaces in expanded variables */
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003613 int one; /* "srcp" is one file name */
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003614 char_u *startstr; /* start again after this (can be NULL) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003615{
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003616 char_u *src;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003617 char_u *tail;
3618 int c;
3619 char_u *var;
3620 int copy_char;
3621 int mustfree; /* var was allocated, need to free it later */
3622 int at_start = TRUE; /* at start of a name */
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003623 int startstr_len = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003624
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003625 if (startstr != NULL)
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003626 startstr_len = (int)STRLEN(startstr);
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003627
3628 src = skipwhite(srcp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003629 --dstlen; /* leave one char space for "\," */
3630 while (*src && dstlen > 0)
3631 {
3632 copy_char = TRUE;
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003633 if ((*src == '$'
3634#ifdef VMS
3635 && at_start
3636#endif
3637 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003638#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3639 || *src == '%'
3640#endif
3641 || (*src == '~' && at_start))
3642 {
3643 mustfree = FALSE;
3644
3645 /*
3646 * The variable name is copied into dst temporarily, because it may
3647 * be a string in read-only memory and a NUL needs to be appended.
3648 */
3649 if (*src != '~') /* environment var */
3650 {
3651 tail = src + 1;
3652 var = dst;
3653 c = dstlen - 1;
3654
3655#ifdef UNIX
3656 /* Unix has ${var-name} type environment vars */
3657 if (*tail == '{' && !vim_isIDc('{'))
3658 {
3659 tail++; /* ignore '{' */
3660 while (c-- > 0 && *tail && *tail != '}')
3661 *var++ = *tail++;
3662 }
3663 else
3664#endif
3665 {
3666 while (c-- > 0 && *tail != NUL && ((vim_isIDc(*tail))
3667#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3668 || (*src == '%' && *tail != '%')
3669#endif
3670 ))
3671 {
3672#ifdef OS2 /* env vars only in uppercase */
3673 *var++ = TOUPPER_LOC(*tail);
3674 tail++; /* toupper() may be a macro! */
3675#else
3676 *var++ = *tail++;
3677#endif
3678 }
3679 }
3680
3681#if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
3682# ifdef UNIX
3683 if (src[1] == '{' && *tail != '}')
3684# else
3685 if (*src == '%' && *tail != '%')
3686# endif
3687 var = NULL;
3688 else
3689 {
3690# ifdef UNIX
3691 if (src[1] == '{')
3692# else
3693 if (*src == '%')
3694#endif
3695 ++tail;
3696#endif
3697 *var = NUL;
3698 var = vim_getenv(dst, &mustfree);
3699#if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
3700 }
3701#endif
3702 }
3703 /* home directory */
3704 else if ( src[1] == NUL
3705 || vim_ispathsep(src[1])
3706 || vim_strchr((char_u *)" ,\t\n", src[1]) != NULL)
3707 {
3708 var = homedir;
3709 tail = src + 1;
3710 }
3711 else /* user directory */
3712 {
3713#if defined(UNIX) || (defined(VMS) && defined(USER_HOME))
3714 /*
3715 * Copy ~user to dst[], so we can put a NUL after it.
3716 */
3717 tail = src;
3718 var = dst;
3719 c = dstlen - 1;
3720 while ( c-- > 0
3721 && *tail
3722 && vim_isfilec(*tail)
3723 && !vim_ispathsep(*tail))
3724 *var++ = *tail++;
3725 *var = NUL;
3726# ifdef UNIX
3727 /*
3728 * If the system supports getpwnam(), use it.
3729 * Otherwise, or if getpwnam() fails, the shell is used to
3730 * expand ~user. This is slower and may fail if the shell
3731 * does not support ~user (old versions of /bin/sh).
3732 */
3733# if defined(HAVE_GETPWNAM) && defined(HAVE_PWD_H)
3734 {
3735 struct passwd *pw;
3736
Bram Moolenaara40ceaf2006-01-13 22:35:40 +00003737 /* Note: memory allocated by getpwnam() is never freed.
3738 * Calling endpwent() apparently doesn't help. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003739 pw = getpwnam((char *)dst + 1);
3740 if (pw != NULL)
3741 var = (char_u *)pw->pw_dir;
3742 else
3743 var = NULL;
3744 }
3745 if (var == NULL)
3746# endif
3747 {
3748 expand_T xpc;
3749
3750 ExpandInit(&xpc);
3751 xpc.xp_context = EXPAND_FILES;
3752 var = ExpandOne(&xpc, dst, NULL,
3753 WILD_ADD_SLASH|WILD_SILENT, WILD_EXPAND_FREE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003754 mustfree = TRUE;
3755 }
3756
3757# else /* !UNIX, thus VMS */
3758 /*
3759 * USER_HOME is a comma-separated list of
3760 * directories to search for the user account in.
3761 */
3762 {
3763 char_u test[MAXPATHL], paths[MAXPATHL];
3764 char_u *path, *next_path, *ptr;
3765 struct stat st;
3766
3767 STRCPY(paths, USER_HOME);
3768 next_path = paths;
3769 while (*next_path)
3770 {
3771 for (path = next_path; *next_path && *next_path != ',';
3772 next_path++);
3773 if (*next_path)
3774 *next_path++ = NUL;
3775 STRCPY(test, path);
3776 STRCAT(test, "/");
3777 STRCAT(test, dst + 1);
3778 if (mch_stat(test, &st) == 0)
3779 {
3780 var = alloc(STRLEN(test) + 1);
3781 STRCPY(var, test);
3782 mustfree = TRUE;
3783 break;
3784 }
3785 }
3786 }
3787# endif /* UNIX */
3788#else
3789 /* cannot expand user's home directory, so don't try */
3790 var = NULL;
3791 tail = (char_u *)""; /* for gcc */
3792#endif /* UNIX || VMS */
3793 }
3794
3795#ifdef BACKSLASH_IN_FILENAME
3796 /* If 'shellslash' is set change backslashes to forward slashes.
3797 * Can't use slash_adjust(), p_ssl may be set temporarily. */
3798 if (p_ssl && var != NULL && vim_strchr(var, '\\') != NULL)
3799 {
3800 char_u *p = vim_strsave(var);
3801
3802 if (p != NULL)
3803 {
3804 if (mustfree)
3805 vim_free(var);
3806 var = p;
3807 mustfree = TRUE;
3808 forward_slash(var);
3809 }
3810 }
3811#endif
3812
3813 /* If "var" contains white space, escape it with a backslash.
3814 * Required for ":e ~/tt" when $HOME includes a space. */
3815 if (esc && var != NULL && vim_strpbrk(var, (char_u *)" \t") != NULL)
3816 {
3817 char_u *p = vim_strsave_escaped(var, (char_u *)" \t");
3818
3819 if (p != NULL)
3820 {
3821 if (mustfree)
3822 vim_free(var);
3823 var = p;
3824 mustfree = TRUE;
3825 }
3826 }
3827
3828 if (var != NULL && *var != NUL
3829 && (STRLEN(var) + STRLEN(tail) + 1 < (unsigned)dstlen))
3830 {
3831 STRCPY(dst, var);
3832 dstlen -= (int)STRLEN(var);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003833 c = (int)STRLEN(var);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003834 /* if var[] ends in a path separator and tail[] starts
3835 * with it, skip a character */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003836 if (*var != NUL && after_pathsep(dst, dst + c)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003837#if defined(BACKSLASH_IN_FILENAME) || defined(AMIGA)
3838 && dst[-1] != ':'
3839#endif
3840 && vim_ispathsep(*tail))
3841 ++tail;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003842 dst += c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003843 src = tail;
3844 copy_char = FALSE;
3845 }
3846 if (mustfree)
3847 vim_free(var);
3848 }
3849
3850 if (copy_char) /* copy at least one char */
3851 {
3852 /*
Bram Moolenaar25394022007-05-10 19:06:20 +00003853 * Recognize the start of a new name, for '~'.
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003854 * Don't do this when "one" is TRUE, to avoid expanding "~" in
3855 * ":edit foo ~ foo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00003856 */
3857 at_start = FALSE;
3858 if (src[0] == '\\' && src[1] != NUL)
3859 {
3860 *dst++ = *src++;
3861 --dstlen;
3862 }
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003863 else if ((src[0] == ' ' || src[0] == ',') && !one)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003864 at_start = TRUE;
3865 *dst++ = *src++;
3866 --dstlen;
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003867
3868 if (startstr != NULL && src - startstr_len >= srcp
3869 && STRNCMP(src - startstr_len, startstr, startstr_len) == 0)
3870 at_start = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003871 }
3872 }
3873 *dst = NUL;
3874}
3875
3876/*
3877 * Vim's version of getenv().
3878 * Special handling of $HOME, $VIM and $VIMRUNTIME.
Bram Moolenaar2f6b0b82005-03-08 22:43:10 +00003879 * Also does ACP to 'enc' conversion for Win32.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003880 */
3881 char_u *
3882vim_getenv(name, mustfree)
3883 char_u *name;
3884 int *mustfree; /* set to TRUE when returned is allocated */
3885{
3886 char_u *p;
3887 char_u *pend;
3888 int vimruntime;
3889
3890#if defined(OS2) || defined(MSDOS) || defined(MSWIN)
3891 /* use "C:/" when $HOME is not set */
3892 if (STRCMP(name, "HOME") == 0)
3893 return homedir;
3894#endif
3895
3896 p = mch_getenv(name);
3897 if (p != NULL && *p == NUL) /* empty is the same as not set */
3898 p = NULL;
3899
3900 if (p != NULL)
Bram Moolenaar05159a02005-02-26 23:04:13 +00003901 {
3902#if defined(FEAT_MBYTE) && defined(WIN3264)
3903 if (enc_utf8)
3904 {
3905 int len;
3906 char_u *pp;
3907
3908 /* Convert from active codepage to UTF-8. Other conversions are
3909 * not done, because they would fail for non-ASCII characters. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003910 acp_to_enc(p, (int)STRLEN(p), &pp, &len);
Bram Moolenaar05159a02005-02-26 23:04:13 +00003911 if (pp != NULL)
3912 {
3913 p = pp;
3914 *mustfree = TRUE;
3915 }
3916 }
3917#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003918 return p;
Bram Moolenaar05159a02005-02-26 23:04:13 +00003919 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003920
3921 vimruntime = (STRCMP(name, "VIMRUNTIME") == 0);
3922 if (!vimruntime && STRCMP(name, "VIM") != 0)
3923 return NULL;
3924
3925 /*
3926 * When expanding $VIMRUNTIME fails, try using $VIM/vim<version> or $VIM.
3927 * Don't do this when default_vimruntime_dir is non-empty.
3928 */
3929 if (vimruntime
3930#ifdef HAVE_PATHDEF
3931 && *default_vimruntime_dir == NUL
3932#endif
3933 )
3934 {
3935 p = mch_getenv((char_u *)"VIM");
3936 if (p != NULL && *p == NUL) /* empty is the same as not set */
3937 p = NULL;
3938 if (p != NULL)
3939 {
3940 p = vim_version_dir(p);
3941 if (p != NULL)
3942 *mustfree = TRUE;
3943 else
3944 p = mch_getenv((char_u *)"VIM");
Bram Moolenaar05159a02005-02-26 23:04:13 +00003945
3946#if defined(FEAT_MBYTE) && defined(WIN3264)
3947 if (enc_utf8)
3948 {
3949 int len;
3950 char_u *pp;
3951
3952 /* Convert from active codepage to UTF-8. Other conversions
3953 * are not done, because they would fail for non-ASCII
3954 * characters. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003955 acp_to_enc(p, (int)STRLEN(p), &pp, &len);
Bram Moolenaar05159a02005-02-26 23:04:13 +00003956 if (pp != NULL)
3957 {
3958 if (mustfree)
3959 vim_free(p);
3960 p = pp;
3961 *mustfree = TRUE;
3962 }
3963 }
3964#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003965 }
3966 }
3967
3968 /*
3969 * When expanding $VIM or $VIMRUNTIME fails, try using:
3970 * - the directory name from 'helpfile' (unless it contains '$')
3971 * - the executable name from argv[0]
3972 */
3973 if (p == NULL)
3974 {
3975 if (p_hf != NULL && vim_strchr(p_hf, '$') == NULL)
3976 p = p_hf;
3977#ifdef USE_EXE_NAME
3978 /*
3979 * Use the name of the executable, obtained from argv[0].
3980 */
3981 else
3982 p = exe_name;
3983#endif
3984 if (p != NULL)
3985 {
3986 /* remove the file name */
3987 pend = gettail(p);
3988
3989 /* remove "doc/" from 'helpfile', if present */
3990 if (p == p_hf)
3991 pend = remove_tail(p, pend, (char_u *)"doc");
3992
3993#ifdef USE_EXE_NAME
3994# ifdef MACOS_X
Bram Moolenaar95e9b492006-03-15 23:04:43 +00003995 /* remove "MacOS" from exe_name and add "Resources/vim" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003996 if (p == exe_name)
3997 {
3998 char_u *pend1;
Bram Moolenaar95e9b492006-03-15 23:04:43 +00003999 char_u *pnew;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004000
Bram Moolenaar95e9b492006-03-15 23:04:43 +00004001 pend1 = remove_tail(p, pend, (char_u *)"MacOS");
4002 if (pend1 != pend)
4003 {
4004 pnew = alloc((unsigned)(pend1 - p) + 15);
4005 if (pnew != NULL)
4006 {
4007 STRNCPY(pnew, p, (pend1 - p));
4008 STRCPY(pnew + (pend1 - p), "Resources/vim");
4009 p = pnew;
4010 pend = p + STRLEN(p);
4011 }
4012 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004013 }
4014# endif
4015 /* remove "src/" from exe_name, if present */
4016 if (p == exe_name)
4017 pend = remove_tail(p, pend, (char_u *)"src");
4018#endif
4019
4020 /* for $VIM, remove "runtime/" or "vim54/", if present */
4021 if (!vimruntime)
4022 {
4023 pend = remove_tail(p, pend, (char_u *)RUNTIME_DIRNAME);
4024 pend = remove_tail(p, pend, (char_u *)VIM_VERSION_NODOT);
4025 }
4026
4027 /* remove trailing path separator */
4028#ifndef MACOS_CLASSIC
4029 /* With MacOS path (with colons) the final colon is required */
Bram Moolenaare21877a2008-02-13 09:58:14 +00004030 /* to avoid confusion between absolute and relative path */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004031 if (pend > p && after_pathsep(p, pend))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004032 --pend;
4033#endif
4034
Bram Moolenaar95e9b492006-03-15 23:04:43 +00004035#ifdef MACOS_X
4036 if (p == exe_name || p == p_hf)
4037#endif
4038 /* check that the result is a directory name */
4039 p = vim_strnsave(p, (int)(pend - p));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004040
4041 if (p != NULL && !mch_isdir(p))
4042 {
4043 vim_free(p);
4044 p = NULL;
4045 }
4046 else
4047 {
4048#ifdef USE_EXE_NAME
4049 /* may add "/vim54" or "/runtime" if it exists */
4050 if (vimruntime && (pend = vim_version_dir(p)) != NULL)
4051 {
4052 vim_free(p);
4053 p = pend;
4054 }
4055#endif
4056 *mustfree = TRUE;
4057 }
4058 }
4059 }
4060
4061#ifdef HAVE_PATHDEF
4062 /* When there is a pathdef.c file we can use default_vim_dir and
4063 * default_vimruntime_dir */
4064 if (p == NULL)
4065 {
4066 /* Only use default_vimruntime_dir when it is not empty */
4067 if (vimruntime && *default_vimruntime_dir != NUL)
4068 {
4069 p = default_vimruntime_dir;
4070 *mustfree = FALSE;
4071 }
4072 else if (*default_vim_dir != NUL)
4073 {
4074 if (vimruntime && (p = vim_version_dir(default_vim_dir)) != NULL)
4075 *mustfree = TRUE;
4076 else
4077 {
4078 p = default_vim_dir;
4079 *mustfree = FALSE;
4080 }
4081 }
4082 }
4083#endif
4084
4085 /*
4086 * Set the environment variable, so that the new value can be found fast
4087 * next time, and others can also use it (e.g. Perl).
4088 */
4089 if (p != NULL)
4090 {
4091 if (vimruntime)
4092 {
4093 vim_setenv((char_u *)"VIMRUNTIME", p);
4094 didset_vimruntime = TRUE;
4095#ifdef FEAT_GETTEXT
4096 {
Bram Moolenaard6754642005-01-17 22:18:45 +00004097 char_u *buf = concat_str(p, (char_u *)"/lang");
Bram Moolenaar071d4272004-06-13 20:20:40 +00004098
4099 if (buf != NULL)
4100 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004101 bindtextdomain(VIMPACKAGE, (char *)buf);
4102 vim_free(buf);
4103 }
4104 }
4105#endif
4106 }
4107 else
4108 {
4109 vim_setenv((char_u *)"VIM", p);
4110 didset_vim = TRUE;
4111 }
4112 }
4113 return p;
4114}
4115
4116/*
4117 * Check if the directory "vimdir/<version>" or "vimdir/runtime" exists.
4118 * Return NULL if not, return its name in allocated memory otherwise.
4119 */
4120 static char_u *
4121vim_version_dir(vimdir)
4122 char_u *vimdir;
4123{
4124 char_u *p;
4125
4126 if (vimdir == NULL || *vimdir == NUL)
4127 return NULL;
4128 p = concat_fnames(vimdir, (char_u *)VIM_VERSION_NODOT, TRUE);
4129 if (p != NULL && mch_isdir(p))
4130 return p;
4131 vim_free(p);
4132 p = concat_fnames(vimdir, (char_u *)RUNTIME_DIRNAME, TRUE);
4133 if (p != NULL && mch_isdir(p))
4134 return p;
4135 vim_free(p);
4136 return NULL;
4137}
4138
4139/*
4140 * If the string between "p" and "pend" ends in "name/", return "pend" minus
4141 * the length of "name/". Otherwise return "pend".
4142 */
4143 static char_u *
4144remove_tail(p, pend, name)
4145 char_u *p;
4146 char_u *pend;
4147 char_u *name;
4148{
4149 int len = (int)STRLEN(name) + 1;
4150 char_u *newend = pend - len;
4151
4152 if (newend >= p
4153 && fnamencmp(newend, name, len - 1) == 0
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004154 && (newend == p || after_pathsep(p, newend)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004155 return newend;
4156 return pend;
4157}
4158
Bram Moolenaar071d4272004-06-13 20:20:40 +00004159/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004160 * Our portable version of setenv.
4161 */
4162 void
4163vim_setenv(name, val)
4164 char_u *name;
4165 char_u *val;
4166{
4167#ifdef HAVE_SETENV
4168 mch_setenv((char *)name, (char *)val, 1);
4169#else
4170 char_u *envbuf;
4171
4172 /*
4173 * Putenv does not copy the string, it has to remain
4174 * valid. The allocated memory will never be freed.
4175 */
4176 envbuf = alloc((unsigned)(STRLEN(name) + STRLEN(val) + 2));
4177 if (envbuf != NULL)
4178 {
4179 sprintf((char *)envbuf, "%s=%s", name, val);
4180 putenv((char *)envbuf);
4181 }
4182#endif
4183}
4184
4185#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
4186/*
4187 * Function given to ExpandGeneric() to obtain an environment variable name.
4188 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004189 char_u *
4190get_env_name(xp, idx)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00004191 expand_T *xp UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004192 int idx;
4193{
4194# if defined(AMIGA) || defined(__MRC__) || defined(__SC__)
4195 /*
4196 * No environ[] on the Amiga and on the Mac (using MPW).
4197 */
4198 return NULL;
4199# else
4200# ifndef __WIN32__
4201 /* Borland C++ 5.2 has this in a header file. */
4202 extern char **environ;
4203# endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00004204# define ENVNAMELEN 100
4205 static char_u name[ENVNAMELEN];
Bram Moolenaar071d4272004-06-13 20:20:40 +00004206 char_u *str;
4207 int n;
4208
4209 str = (char_u *)environ[idx];
4210 if (str == NULL)
4211 return NULL;
4212
Bram Moolenaar21cf8232004-07-16 20:18:37 +00004213 for (n = 0; n < ENVNAMELEN - 1; ++n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004214 {
4215 if (str[n] == '=' || str[n] == NUL)
4216 break;
4217 name[n] = str[n];
4218 }
4219 name[n] = NUL;
4220 return name;
4221# endif
4222}
4223#endif
4224
4225/*
4226 * Replace home directory by "~" in each space or comma separated file name in
4227 * 'src'.
4228 * If anything fails (except when out of space) dst equals src.
4229 */
4230 void
4231home_replace(buf, src, dst, dstlen, one)
4232 buf_T *buf; /* when not NULL, check for help files */
4233 char_u *src; /* input file name */
4234 char_u *dst; /* where to put the result */
4235 int dstlen; /* maximum length of the result */
4236 int one; /* if TRUE, only replace one file name, include
4237 spaces and commas in the file name. */
4238{
4239 size_t dirlen = 0, envlen = 0;
4240 size_t len;
4241 char_u *homedir_env;
4242 char_u *p;
4243
4244 if (src == NULL)
4245 {
4246 *dst = NUL;
4247 return;
4248 }
4249
4250 /*
4251 * If the file is a help file, remove the path completely.
4252 */
4253 if (buf != NULL && buf->b_help)
4254 {
4255 STRCPY(dst, gettail(src));
4256 return;
4257 }
4258
4259 /*
4260 * We check both the value of the $HOME environment variable and the
4261 * "real" home directory.
4262 */
4263 if (homedir != NULL)
4264 dirlen = STRLEN(homedir);
4265
4266#ifdef VMS
4267 homedir_env = mch_getenv((char_u *)"SYS$LOGIN");
4268#else
4269 homedir_env = mch_getenv((char_u *)"HOME");
4270#endif
4271
4272 if (homedir_env != NULL && *homedir_env == NUL)
4273 homedir_env = NULL;
4274 if (homedir_env != NULL)
4275 envlen = STRLEN(homedir_env);
4276
4277 if (!one)
4278 src = skipwhite(src);
4279 while (*src && dstlen > 0)
4280 {
4281 /*
4282 * Here we are at the beginning of a file name.
4283 * First, check to see if the beginning of the file name matches
4284 * $HOME or the "real" home directory. Check that there is a '/'
4285 * after the match (so that if e.g. the file is "/home/pieter/bla",
4286 * and the home directory is "/home/piet", the file does not end up
4287 * as "~er/bla" (which would seem to indicate the file "bla" in user
4288 * er's home directory)).
4289 */
4290 p = homedir;
4291 len = dirlen;
4292 for (;;)
4293 {
4294 if ( len
4295 && fnamencmp(src, p, len) == 0
4296 && (vim_ispathsep(src[len])
4297 || (!one && (src[len] == ',' || src[len] == ' '))
4298 || src[len] == NUL))
4299 {
4300 src += len;
4301 if (--dstlen > 0)
4302 *dst++ = '~';
4303
4304 /*
4305 * If it's just the home directory, add "/".
4306 */
4307 if (!vim_ispathsep(src[0]) && --dstlen > 0)
4308 *dst++ = '/';
4309 break;
4310 }
4311 if (p == homedir_env)
4312 break;
4313 p = homedir_env;
4314 len = envlen;
4315 }
4316
4317 /* if (!one) skip to separator: space or comma */
4318 while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
4319 *dst++ = *src++;
4320 /* skip separator */
4321 while ((*src == ' ' || *src == ',') && --dstlen > 0)
4322 *dst++ = *src++;
4323 }
4324 /* if (dstlen == 0) out of space, what to do??? */
4325
4326 *dst = NUL;
4327}
4328
4329/*
4330 * Like home_replace, store the replaced string in allocated memory.
4331 * When something fails, NULL is returned.
4332 */
4333 char_u *
4334home_replace_save(buf, src)
4335 buf_T *buf; /* when not NULL, check for help files */
4336 char_u *src; /* input file name */
4337{
4338 char_u *dst;
4339 unsigned len;
4340
4341 len = 3; /* space for "~/" and trailing NUL */
4342 if (src != NULL) /* just in case */
4343 len += (unsigned)STRLEN(src);
4344 dst = alloc(len);
4345 if (dst != NULL)
4346 home_replace(buf, src, dst, len, TRUE);
4347 return dst;
4348}
4349
4350/*
4351 * Compare two file names and return:
4352 * FPC_SAME if they both exist and are the same file.
4353 * FPC_SAMEX if they both don't exist and have the same file name.
4354 * FPC_DIFF if they both exist and are different files.
4355 * FPC_NOTX if they both don't exist.
4356 * FPC_DIFFX if one of them doesn't exist.
4357 * For the first name environment variables are expanded
4358 */
4359 int
4360fullpathcmp(s1, s2, checkname)
4361 char_u *s1, *s2;
4362 int checkname; /* when both don't exist, check file names */
4363{
4364#ifdef UNIX
4365 char_u exp1[MAXPATHL];
4366 char_u full1[MAXPATHL];
4367 char_u full2[MAXPATHL];
4368 struct stat st1, st2;
4369 int r1, r2;
4370
4371 expand_env(s1, exp1, MAXPATHL);
4372 r1 = mch_stat((char *)exp1, &st1);
4373 r2 = mch_stat((char *)s2, &st2);
4374 if (r1 != 0 && r2 != 0)
4375 {
4376 /* if mch_stat() doesn't work, may compare the names */
4377 if (checkname)
4378 {
4379 if (fnamecmp(exp1, s2) == 0)
4380 return FPC_SAMEX;
4381 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4382 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4383 if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
4384 return FPC_SAMEX;
4385 }
4386 return FPC_NOTX;
4387 }
4388 if (r1 != 0 || r2 != 0)
4389 return FPC_DIFFX;
4390 if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
4391 return FPC_SAME;
4392 return FPC_DIFF;
4393#else
4394 char_u *exp1; /* expanded s1 */
4395 char_u *full1; /* full path of s1 */
4396 char_u *full2; /* full path of s2 */
4397 int retval = FPC_DIFF;
4398 int r1, r2;
4399
4400 /* allocate one buffer to store three paths (alloc()/free() is slow!) */
4401 if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
4402 {
4403 full1 = exp1 + MAXPATHL;
4404 full2 = full1 + MAXPATHL;
4405
4406 expand_env(s1, exp1, MAXPATHL);
4407 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4408 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4409
4410 /* If vim_FullName() fails, the file probably doesn't exist. */
4411 if (r1 != OK && r2 != OK)
4412 {
4413 if (checkname && fnamecmp(exp1, s2) == 0)
4414 retval = FPC_SAMEX;
4415 else
4416 retval = FPC_NOTX;
4417 }
4418 else if (r1 != OK || r2 != OK)
4419 retval = FPC_DIFFX;
4420 else if (fnamecmp(full1, full2))
4421 retval = FPC_DIFF;
4422 else
4423 retval = FPC_SAME;
4424 vim_free(exp1);
4425 }
4426 return retval;
4427#endif
4428}
4429
4430/*
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004431 * Get the tail of a path: the file name.
4432 * Fail safe: never returns NULL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004433 */
4434 char_u *
4435gettail(fname)
4436 char_u *fname;
4437{
4438 char_u *p1, *p2;
4439
4440 if (fname == NULL)
4441 return (char_u *)"";
4442 for (p1 = p2 = fname; *p2; ) /* find last part of path */
4443 {
4444 if (vim_ispathsep(*p2))
4445 p1 = p2 + 1;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004446 mb_ptr_adv(p2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004447 }
4448 return p1;
4449}
4450
4451/*
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004452 * Get pointer to tail of "fname", including path separators. Putting a NUL
4453 * here leaves the directory name. Takes care of "c:/" and "//".
4454 * Always returns a valid pointer.
4455 */
4456 char_u *
4457gettail_sep(fname)
4458 char_u *fname;
4459{
4460 char_u *p;
4461 char_u *t;
4462
4463 p = get_past_head(fname); /* don't remove the '/' from "c:/file" */
4464 t = gettail(fname);
4465 while (t > p && after_pathsep(fname, t))
4466 --t;
4467#ifdef VMS
4468 /* path separator is part of the path */
4469 ++t;
4470#endif
4471 return t;
4472}
4473
4474/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004475 * get the next path component (just after the next path separator).
4476 */
4477 char_u *
4478getnextcomp(fname)
4479 char_u *fname;
4480{
4481 while (*fname && !vim_ispathsep(*fname))
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004482 mb_ptr_adv(fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004483 if (*fname)
4484 ++fname;
4485 return fname;
4486}
4487
Bram Moolenaar071d4272004-06-13 20:20:40 +00004488/*
4489 * Get a pointer to one character past the head of a path name.
4490 * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
4491 * If there is no head, path is returned.
4492 */
4493 char_u *
4494get_past_head(path)
4495 char_u *path;
4496{
4497 char_u *retval;
4498
4499#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
4500 /* may skip "c:" */
4501 if (isalpha(path[0]) && path[1] == ':')
4502 retval = path + 2;
4503 else
4504 retval = path;
4505#else
4506# if defined(AMIGA)
4507 /* may skip "label:" */
4508 retval = vim_strchr(path, ':');
4509 if (retval == NULL)
4510 retval = path;
4511# else /* Unix */
4512 retval = path;
4513# endif
4514#endif
4515
4516 while (vim_ispathsep(*retval))
4517 ++retval;
4518
4519 return retval;
4520}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004521
4522/*
4523 * return TRUE if 'c' is a path separator.
4524 */
4525 int
4526vim_ispathsep(c)
4527 int c;
4528{
4529#ifdef RISCOS
4530 return (c == '.' || c == ':');
4531#else
4532# ifdef UNIX
4533 return (c == '/'); /* UNIX has ':' inside file names */
4534# else
4535# ifdef BACKSLASH_IN_FILENAME
4536 return (c == ':' || c == '/' || c == '\\');
4537# else
4538# ifdef VMS
4539 /* server"user passwd"::device:[full.path.name]fname.extension;version" */
4540 return (c == ':' || c == '[' || c == ']' || c == '/'
4541 || c == '<' || c == '>' || c == '"' );
Bram Moolenaar1056d982006-03-09 22:37:52 +00004542# else /* Amiga */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004543 return (c == ':' || c == '/');
Bram Moolenaar071d4272004-06-13 20:20:40 +00004544# endif /* VMS */
4545# endif
4546# endif
4547#endif /* RISC OS */
4548}
4549
4550#if defined(FEAT_SEARCHPATH) || defined(PROTO)
4551/*
4552 * return TRUE if 'c' is a path list separator.
4553 */
4554 int
4555vim_ispathlistsep(c)
4556 int c;
4557{
4558#ifdef UNIX
4559 return (c == ':');
4560#else
Bram Moolenaar25394022007-05-10 19:06:20 +00004561 return (c == ';'); /* might not be right for every system... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004562#endif
4563}
4564#endif
4565
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004566#if defined(FEAT_GUI_TABLINE) || defined(FEAT_WINDOWS) \
4567 || defined(FEAT_EVAL) || defined(PROTO)
4568/*
4569 * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
4570 * It's done in-place.
4571 */
4572 void
4573shorten_dir(str)
4574 char_u *str;
4575{
4576 char_u *tail, *s, *d;
4577 int skip = FALSE;
4578
4579 tail = gettail(str);
4580 d = str;
4581 for (s = str; ; ++s)
4582 {
4583 if (s >= tail) /* copy the whole tail */
4584 {
4585 *d++ = *s;
4586 if (*s == NUL)
4587 break;
4588 }
4589 else if (vim_ispathsep(*s)) /* copy '/' and next char */
4590 {
4591 *d++ = *s;
4592 skip = FALSE;
4593 }
4594 else if (!skip)
4595 {
4596 *d++ = *s; /* copy next char */
4597 if (*s != '~' && *s != '.') /* and leading "~" and "." */
4598 skip = TRUE;
4599# ifdef FEAT_MBYTE
4600 if (has_mbyte)
4601 {
4602 int l = mb_ptr2len(s);
4603
4604 while (--l > 0)
Bram Moolenaarb6baca52006-08-15 20:24:14 +00004605 *d++ = *++s;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004606 }
4607# endif
4608 }
4609 }
4610}
4611#endif
4612
Bram Moolenaar900b4d72005-12-12 22:05:50 +00004613/*
4614 * Return TRUE if the directory of "fname" exists, FALSE otherwise.
4615 * Also returns TRUE if there is no directory name.
4616 * "fname" must be writable!.
4617 */
4618 int
4619dir_of_file_exists(fname)
4620 char_u *fname;
4621{
4622 char_u *p;
4623 int c;
4624 int retval;
4625
4626 p = gettail_sep(fname);
4627 if (p == fname)
4628 return TRUE;
4629 c = *p;
4630 *p = NUL;
4631 retval = mch_isdir(fname);
4632 *p = c;
4633 return retval;
4634}
4635
Bram Moolenaar071d4272004-06-13 20:20:40 +00004636#if (defined(CASE_INSENSITIVE_FILENAME) && defined(BACKSLASH_IN_FILENAME)) \
4637 || defined(PROTO)
4638/*
4639 * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally.
4640 */
4641 int
4642vim_fnamecmp(x, y)
4643 char_u *x, *y;
4644{
4645 return vim_fnamencmp(x, y, MAXPATHL);
4646}
4647
4648 int
4649vim_fnamencmp(x, y, len)
4650 char_u *x, *y;
4651 size_t len;
4652{
4653 while (len > 0 && *x && *y)
4654 {
4655 if (TOLOWER_LOC(*x) != TOLOWER_LOC(*y)
4656 && !(*x == '/' && *y == '\\')
4657 && !(*x == '\\' && *y == '/'))
4658 break;
4659 ++x;
4660 ++y;
4661 --len;
4662 }
4663 if (len == 0)
4664 return 0;
4665 return (*x - *y);
4666}
4667#endif
4668
4669/*
4670 * Concatenate file names fname1 and fname2 into allocated memory.
Bram Moolenaar25394022007-05-10 19:06:20 +00004671 * Only add a '/' or '\\' when 'sep' is TRUE and it is necessary.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004672 */
4673 char_u *
4674concat_fnames(fname1, fname2, sep)
4675 char_u *fname1;
4676 char_u *fname2;
4677 int sep;
4678{
4679 char_u *dest;
4680
4681 dest = alloc((unsigned)(STRLEN(fname1) + STRLEN(fname2) + 3));
4682 if (dest != NULL)
4683 {
4684 STRCPY(dest, fname1);
4685 if (sep)
4686 add_pathsep(dest);
4687 STRCAT(dest, fname2);
4688 }
4689 return dest;
4690}
4691
Bram Moolenaard6754642005-01-17 22:18:45 +00004692/*
4693 * Concatenate two strings and return the result in allocated memory.
4694 * Returns NULL when out of memory.
4695 */
4696 char_u *
4697concat_str(str1, str2)
4698 char_u *str1;
4699 char_u *str2;
4700{
4701 char_u *dest;
4702 size_t l = STRLEN(str1);
4703
4704 dest = alloc((unsigned)(l + STRLEN(str2) + 1L));
4705 if (dest != NULL)
4706 {
4707 STRCPY(dest, str1);
4708 STRCPY(dest + l, str2);
4709 }
4710 return dest;
4711}
Bram Moolenaard6754642005-01-17 22:18:45 +00004712
Bram Moolenaar071d4272004-06-13 20:20:40 +00004713/*
4714 * Add a path separator to a file name, unless it already ends in a path
4715 * separator.
4716 */
4717 void
4718add_pathsep(p)
4719 char_u *p;
4720{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004721 if (*p != NUL && !after_pathsep(p, p + STRLEN(p)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004722 STRCAT(p, PATHSEPSTR);
4723}
4724
4725/*
4726 * FullName_save - Make an allocated copy of a full file name.
4727 * Returns NULL when out of memory.
4728 */
4729 char_u *
4730FullName_save(fname, force)
4731 char_u *fname;
4732 int force; /* force expansion, even when it already looks
4733 like a full path name */
4734{
4735 char_u *buf;
4736 char_u *new_fname = NULL;
4737
4738 if (fname == NULL)
4739 return NULL;
4740
4741 buf = alloc((unsigned)MAXPATHL);
4742 if (buf != NULL)
4743 {
4744 if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
4745 new_fname = vim_strsave(buf);
4746 else
4747 new_fname = vim_strsave(fname);
4748 vim_free(buf);
4749 }
4750 return new_fname;
4751}
4752
4753#if defined(FEAT_CINDENT) || defined(FEAT_SYN_HL)
4754
4755static char_u *skip_string __ARGS((char_u *p));
4756
4757/*
4758 * Find the start of a comment, not knowing if we are in a comment right now.
4759 * Search starts at w_cursor.lnum and goes backwards.
4760 */
4761 pos_T *
4762find_start_comment(ind_maxcomment) /* XXX */
4763 int ind_maxcomment;
4764{
4765 pos_T *pos;
4766 char_u *line;
4767 char_u *p;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00004768 int cur_maxcomment = ind_maxcomment;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004769
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00004770 for (;;)
4771 {
4772 pos = findmatchlimit(NULL, '*', FM_BACKWARD, cur_maxcomment);
4773 if (pos == NULL)
4774 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004775
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00004776 /*
4777 * Check if the comment start we found is inside a string.
4778 * If it is then restrict the search to below this line and try again.
4779 */
4780 line = ml_get(pos->lnum);
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00004781 for (p = line; *p && (colnr_T)(p - line) < pos->col; ++p)
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00004782 p = skip_string(p);
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00004783 if ((colnr_T)(p - line) <= pos->col)
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00004784 break;
4785 cur_maxcomment = curwin->w_cursor.lnum - pos->lnum - 1;
4786 if (cur_maxcomment <= 0)
4787 {
4788 pos = NULL;
4789 break;
4790 }
4791 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004792 return pos;
4793}
4794
4795/*
4796 * Skip to the end of a "string" and a 'c' character.
4797 * If there is no string or character, return argument unmodified.
4798 */
4799 static char_u *
4800skip_string(p)
4801 char_u *p;
4802{
4803 int i;
4804
4805 /*
4806 * We loop, because strings may be concatenated: "date""time".
4807 */
4808 for ( ; ; ++p)
4809 {
4810 if (p[0] == '\'') /* 'c' or '\n' or '\000' */
4811 {
4812 if (!p[1]) /* ' at end of line */
4813 break;
4814 i = 2;
4815 if (p[1] == '\\') /* '\n' or '\000' */
4816 {
4817 ++i;
4818 while (vim_isdigit(p[i - 1])) /* '\000' */
4819 ++i;
4820 }
4821 if (p[i] == '\'') /* check for trailing ' */
4822 {
4823 p += i;
4824 continue;
4825 }
4826 }
4827 else if (p[0] == '"') /* start of string */
4828 {
4829 for (++p; p[0]; ++p)
4830 {
4831 if (p[0] == '\\' && p[1] != NUL)
4832 ++p;
4833 else if (p[0] == '"') /* end of string */
4834 break;
4835 }
4836 if (p[0] == '"')
4837 continue;
4838 }
4839 break; /* no string found */
4840 }
4841 if (!*p)
4842 --p; /* backup from NUL */
4843 return p;
4844}
4845#endif /* FEAT_CINDENT || FEAT_SYN_HL */
4846
4847#if defined(FEAT_CINDENT) || defined(PROTO)
4848
4849/*
4850 * Do C or expression indenting on the current line.
4851 */
4852 void
4853do_c_expr_indent()
4854{
4855# ifdef FEAT_EVAL
4856 if (*curbuf->b_p_inde != NUL)
4857 fixthisline(get_expr_indent);
4858 else
4859# endif
4860 fixthisline(get_c_indent);
4861}
4862
4863/*
4864 * Functions for C-indenting.
4865 * Most of this originally comes from Eric Fischer.
4866 */
4867/*
4868 * Below "XXX" means that this function may unlock the current line.
4869 */
4870
4871static char_u *cin_skipcomment __ARGS((char_u *));
4872static int cin_nocode __ARGS((char_u *));
4873static pos_T *find_line_comment __ARGS((void));
4874static int cin_islabel_skip __ARGS((char_u **));
4875static int cin_isdefault __ARGS((char_u *));
4876static char_u *after_label __ARGS((char_u *l));
4877static int get_indent_nolabel __ARGS((linenr_T lnum));
4878static int skip_label __ARGS((linenr_T, char_u **pp, int ind_maxcomment));
4879static int cin_first_id_amount __ARGS((void));
4880static int cin_get_equal_amount __ARGS((linenr_T lnum));
4881static int cin_ispreproc __ARGS((char_u *));
4882static int cin_ispreproc_cont __ARGS((char_u **pp, linenr_T *lnump));
4883static int cin_iscomment __ARGS((char_u *));
4884static int cin_islinecomment __ARGS((char_u *));
4885static int cin_isterminated __ARGS((char_u *, int, int));
4886static int cin_isinit __ARGS((void));
4887static int cin_isfuncdecl __ARGS((char_u **, linenr_T));
4888static int cin_isif __ARGS((char_u *));
4889static int cin_iselse __ARGS((char_u *));
4890static int cin_isdo __ARGS((char_u *));
4891static int cin_iswhileofdo __ARGS((char_u *, linenr_T, int));
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00004892static int cin_iswhileofdo_end __ARGS((int terminated, int ind_maxparen, int ind_maxcomment));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004893static int cin_isbreak __ARGS((char_u *));
Bram Moolenaare7c56862007-08-04 10:14:52 +00004894static int cin_is_cpp_baseclass __ARGS((colnr_T *col));
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00004895static int get_baseclass_amount __ARGS((int col, int ind_maxparen, int ind_maxcomment, int ind_cpp_baseclass));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004896static int cin_ends_in __ARGS((char_u *, char_u *, char_u *));
4897static int cin_skip2pos __ARGS((pos_T *trypos));
4898static pos_T *find_start_brace __ARGS((int));
4899static pos_T *find_match_paren __ARGS((int, int));
4900static int corr_ind_maxparen __ARGS((int ind_maxparen, pos_T *startpos));
4901static int find_last_paren __ARGS((char_u *l, int start, int end));
4902static int find_match __ARGS((int lookfor, linenr_T ourscope, int ind_maxparen, int ind_maxcomment));
4903
Bram Moolenaar39353fd2007-03-27 09:02:11 +00004904static int ind_hash_comment = 0; /* # starts a comment */
4905
Bram Moolenaar071d4272004-06-13 20:20:40 +00004906/*
4907 * Skip over white space and C comments within the line.
Bram Moolenaar39353fd2007-03-27 09:02:11 +00004908 * Also skip over Perl/shell comments if desired.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004909 */
4910 static char_u *
4911cin_skipcomment(s)
4912 char_u *s;
4913{
4914 while (*s)
4915 {
Bram Moolenaar39353fd2007-03-27 09:02:11 +00004916 char_u *prev_s = s;
4917
Bram Moolenaar071d4272004-06-13 20:20:40 +00004918 s = skipwhite(s);
Bram Moolenaar39353fd2007-03-27 09:02:11 +00004919
4920 /* Perl/shell # comment comment continues until eol. Require a space
4921 * before # to avoid recognizing $#array. */
4922 if (ind_hash_comment != 0 && s != prev_s && *s == '#')
4923 {
4924 s += STRLEN(s);
4925 break;
4926 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004927 if (*s != '/')
4928 break;
4929 ++s;
4930 if (*s == '/') /* slash-slash comment continues till eol */
4931 {
4932 s += STRLEN(s);
4933 break;
4934 }
4935 if (*s != '*')
4936 break;
4937 for (++s; *s; ++s) /* skip slash-star comment */
4938 if (s[0] == '*' && s[1] == '/')
4939 {
4940 s += 2;
4941 break;
4942 }
4943 }
4944 return s;
4945}
4946
4947/*
4948 * Return TRUE if there there is no code at *s. White space and comments are
4949 * not considered code.
4950 */
4951 static int
4952cin_nocode(s)
4953 char_u *s;
4954{
4955 return *cin_skipcomment(s) == NUL;
4956}
4957
4958/*
4959 * Check previous lines for a "//" line comment, skipping over blank lines.
4960 */
4961 static pos_T *
4962find_line_comment() /* XXX */
4963{
4964 static pos_T pos;
4965 char_u *line;
4966 char_u *p;
4967
4968 pos = curwin->w_cursor;
4969 while (--pos.lnum > 0)
4970 {
4971 line = ml_get(pos.lnum);
4972 p = skipwhite(line);
4973 if (cin_islinecomment(p))
4974 {
4975 pos.col = (int)(p - line);
4976 return &pos;
4977 }
4978 if (*p != NUL)
4979 break;
4980 }
4981 return NULL;
4982}
4983
4984/*
4985 * Check if string matches "label:"; move to character after ':' if true.
4986 */
4987 static int
4988cin_islabel_skip(s)
4989 char_u **s;
4990{
4991 if (!vim_isIDc(**s)) /* need at least one ID character */
4992 return FALSE;
4993
4994 while (vim_isIDc(**s))
4995 (*s)++;
4996
4997 *s = cin_skipcomment(*s);
4998
4999 /* "::" is not a label, it's C++ */
5000 return (**s == ':' && *++*s != ':');
5001}
5002
5003/*
5004 * Recognize a label: "label:".
5005 * Note: curwin->w_cursor must be where we are looking for the label.
5006 */
5007 int
5008cin_islabel(ind_maxcomment) /* XXX */
5009 int ind_maxcomment;
5010{
5011 char_u *s;
5012
5013 s = cin_skipcomment(ml_get_curline());
5014
5015 /*
5016 * Exclude "default" from labels, since it should be indented
5017 * like a switch label. Same for C++ scope declarations.
5018 */
5019 if (cin_isdefault(s))
5020 return FALSE;
5021 if (cin_isscopedecl(s))
5022 return FALSE;
5023
5024 if (cin_islabel_skip(&s))
5025 {
5026 /*
5027 * Only accept a label if the previous line is terminated or is a case
5028 * label.
5029 */
5030 pos_T cursor_save;
5031 pos_T *trypos;
5032 char_u *line;
5033
5034 cursor_save = curwin->w_cursor;
5035 while (curwin->w_cursor.lnum > 1)
5036 {
5037 --curwin->w_cursor.lnum;
5038
5039 /*
5040 * If we're in a comment now, skip to the start of the comment.
5041 */
5042 curwin->w_cursor.col = 0;
5043 if ((trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
5044 curwin->w_cursor = *trypos;
5045
5046 line = ml_get_curline();
5047 if (cin_ispreproc(line)) /* ignore #defines, #if, etc. */
5048 continue;
5049 if (*(line = cin_skipcomment(line)) == NUL)
5050 continue;
5051
5052 curwin->w_cursor = cursor_save;
5053 if (cin_isterminated(line, TRUE, FALSE)
5054 || cin_isscopedecl(line)
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005055 || cin_iscase(line, TRUE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005056 || (cin_islabel_skip(&line) && cin_nocode(line)))
5057 return TRUE;
5058 return FALSE;
5059 }
5060 curwin->w_cursor = cursor_save;
5061 return TRUE; /* label at start of file??? */
5062 }
5063 return FALSE;
5064}
5065
5066/*
5067 * Recognize structure initialization and enumerations.
5068 * Q&D-Implementation:
5069 * check for "=" at end or "[typedef] enum" at beginning of line.
5070 */
5071 static int
5072cin_isinit(void)
5073{
5074 char_u *s;
5075
5076 s = cin_skipcomment(ml_get_curline());
5077
5078 if (STRNCMP(s, "typedef", 7) == 0 && !vim_isIDc(s[7]))
5079 s = cin_skipcomment(s + 7);
5080
5081 if (STRNCMP(s, "enum", 4) == 0 && !vim_isIDc(s[4]))
5082 return TRUE;
5083
5084 if (cin_ends_in(s, (char_u *)"=", (char_u *)"{"))
5085 return TRUE;
5086
5087 return FALSE;
5088}
5089
5090/*
5091 * Recognize a switch label: "case .*:" or "default:".
5092 */
5093 int
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005094cin_iscase(s, strict)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005095 char_u *s;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005096 int strict; /* Allow relaxed check of case statement for JS */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005097{
5098 s = cin_skipcomment(s);
5099 if (STRNCMP(s, "case", 4) == 0 && !vim_isIDc(s[4]))
5100 {
5101 for (s += 4; *s; ++s)
5102 {
5103 s = cin_skipcomment(s);
5104 if (*s == ':')
5105 {
5106 if (s[1] == ':') /* skip over "::" for C++ */
5107 ++s;
5108 else
5109 return TRUE;
5110 }
5111 if (*s == '\'' && s[1] && s[2] == '\'')
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005112 s += 2; /* skip over ':' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005113 else if (*s == '/' && (s[1] == '*' || s[1] == '/'))
5114 return FALSE; /* stop at comment */
5115 else if (*s == '"')
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005116 {
5117 /* JS etc. */
5118 if (strict)
5119 return FALSE; /* stop at string */
5120 else
5121 return TRUE;
5122 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005123 }
5124 return FALSE;
5125 }
5126
5127 if (cin_isdefault(s))
5128 return TRUE;
5129 return FALSE;
5130}
5131
5132/*
5133 * Recognize a "default" switch label.
5134 */
5135 static int
5136cin_isdefault(s)
5137 char_u *s;
5138{
5139 return (STRNCMP(s, "default", 7) == 0
5140 && *(s = cin_skipcomment(s + 7)) == ':'
5141 && s[1] != ':');
5142}
5143
5144/*
Bram Moolenaar1a509df2010-08-01 17:59:57 +02005145 * Recognize a "public/private/protected" scope declaration label.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005146 */
5147 int
5148cin_isscopedecl(s)
5149 char_u *s;
5150{
5151 int i;
5152
5153 s = cin_skipcomment(s);
5154 if (STRNCMP(s, "public", 6) == 0)
5155 i = 6;
5156 else if (STRNCMP(s, "protected", 9) == 0)
5157 i = 9;
5158 else if (STRNCMP(s, "private", 7) == 0)
5159 i = 7;
5160 else
5161 return FALSE;
5162 return (*(s = cin_skipcomment(s + i)) == ':' && s[1] != ':');
5163}
5164
5165/*
5166 * Return a pointer to the first non-empty non-comment character after a ':'.
5167 * Return NULL if not found.
5168 * case 234: a = b;
5169 * ^
5170 */
5171 static char_u *
5172after_label(l)
5173 char_u *l;
5174{
5175 for ( ; *l; ++l)
5176 {
5177 if (*l == ':')
5178 {
5179 if (l[1] == ':') /* skip over "::" for C++ */
5180 ++l;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005181 else if (!cin_iscase(l + 1, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005182 break;
5183 }
5184 else if (*l == '\'' && l[1] && l[2] == '\'')
5185 l += 2; /* skip over 'x' */
5186 }
5187 if (*l == NUL)
5188 return NULL;
5189 l = cin_skipcomment(l + 1);
5190 if (*l == NUL)
5191 return NULL;
5192 return l;
5193}
5194
5195/*
5196 * Get indent of line "lnum", skipping a label.
5197 * Return 0 if there is nothing after the label.
5198 */
5199 static int
5200get_indent_nolabel(lnum) /* XXX */
5201 linenr_T lnum;
5202{
5203 char_u *l;
5204 pos_T fp;
5205 colnr_T col;
5206 char_u *p;
5207
5208 l = ml_get(lnum);
5209 p = after_label(l);
5210 if (p == NULL)
5211 return 0;
5212
5213 fp.col = (colnr_T)(p - l);
5214 fp.lnum = lnum;
5215 getvcol(curwin, &fp, &col, NULL, NULL);
5216 return (int)col;
5217}
5218
5219/*
5220 * Find indent for line "lnum", ignoring any case or jump label.
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005221 * Also return a pointer to the text (after the label) in "pp".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005222 * label: if (asdf && asdfasdf)
5223 * ^
5224 */
5225 static int
5226skip_label(lnum, pp, ind_maxcomment)
5227 linenr_T lnum;
5228 char_u **pp;
5229 int ind_maxcomment;
5230{
5231 char_u *l;
5232 int amount;
5233 pos_T cursor_save;
5234
5235 cursor_save = curwin->w_cursor;
5236 curwin->w_cursor.lnum = lnum;
5237 l = ml_get_curline();
5238 /* XXX */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005239 if (cin_iscase(l, FALSE) || cin_isscopedecl(l)
5240 || cin_islabel(ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005241 {
5242 amount = get_indent_nolabel(lnum);
5243 l = after_label(ml_get_curline());
5244 if (l == NULL) /* just in case */
5245 l = ml_get_curline();
5246 }
5247 else
5248 {
5249 amount = get_indent();
5250 l = ml_get_curline();
5251 }
5252 *pp = l;
5253
5254 curwin->w_cursor = cursor_save;
5255 return amount;
5256}
5257
5258/*
5259 * Return the indent of the first variable name after a type in a declaration.
5260 * int a, indent of "a"
5261 * static struct foo b, indent of "b"
5262 * enum bla c, indent of "c"
5263 * Returns zero when it doesn't look like a declaration.
5264 */
5265 static int
5266cin_first_id_amount()
5267{
5268 char_u *line, *p, *s;
5269 int len;
5270 pos_T fp;
5271 colnr_T col;
5272
5273 line = ml_get_curline();
5274 p = skipwhite(line);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005275 len = (int)(skiptowhite(p) - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005276 if (len == 6 && STRNCMP(p, "static", 6) == 0)
5277 {
5278 p = skipwhite(p + 6);
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00005279 len = (int)(skiptowhite(p) - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005280 }
5281 if (len == 6 && STRNCMP(p, "struct", 6) == 0)
5282 p = skipwhite(p + 6);
5283 else if (len == 4 && STRNCMP(p, "enum", 4) == 0)
5284 p = skipwhite(p + 4);
5285 else if ((len == 8 && STRNCMP(p, "unsigned", 8) == 0)
5286 || (len == 6 && STRNCMP(p, "signed", 6) == 0))
5287 {
5288 s = skipwhite(p + len);
5289 if ((STRNCMP(s, "int", 3) == 0 && vim_iswhite(s[3]))
5290 || (STRNCMP(s, "long", 4) == 0 && vim_iswhite(s[4]))
5291 || (STRNCMP(s, "short", 5) == 0 && vim_iswhite(s[5]))
5292 || (STRNCMP(s, "char", 4) == 0 && vim_iswhite(s[4])))
5293 p = s;
5294 }
5295 for (len = 0; vim_isIDc(p[len]); ++len)
5296 ;
5297 if (len == 0 || !vim_iswhite(p[len]) || cin_nocode(p))
5298 return 0;
5299
5300 p = skipwhite(p + len);
5301 fp.lnum = curwin->w_cursor.lnum;
5302 fp.col = (colnr_T)(p - line);
5303 getvcol(curwin, &fp, &col, NULL, NULL);
5304 return (int)col;
5305}
5306
5307/*
5308 * Return the indent of the first non-blank after an equal sign.
5309 * char *foo = "here";
5310 * Return zero if no (useful) equal sign found.
5311 * Return -1 if the line above "lnum" ends in a backslash.
5312 * foo = "asdf\
5313 * asdf\
5314 * here";
5315 */
5316 static int
5317cin_get_equal_amount(lnum)
5318 linenr_T lnum;
5319{
5320 char_u *line;
5321 char_u *s;
5322 colnr_T col;
5323 pos_T fp;
5324
5325 if (lnum > 1)
5326 {
5327 line = ml_get(lnum - 1);
5328 if (*line != NUL && line[STRLEN(line) - 1] == '\\')
5329 return -1;
5330 }
5331
5332 line = s = ml_get(lnum);
5333 while (*s != NUL && vim_strchr((char_u *)"=;{}\"'", *s) == NULL)
5334 {
5335 if (cin_iscomment(s)) /* ignore comments */
5336 s = cin_skipcomment(s);
5337 else
5338 ++s;
5339 }
5340 if (*s != '=')
5341 return 0;
5342
5343 s = skipwhite(s + 1);
5344 if (cin_nocode(s))
5345 return 0;
5346
5347 if (*s == '"') /* nice alignment for continued strings */
5348 ++s;
5349
5350 fp.lnum = lnum;
5351 fp.col = (colnr_T)(s - line);
5352 getvcol(curwin, &fp, &col, NULL, NULL);
5353 return (int)col;
5354}
5355
5356/*
5357 * Recognize a preprocessor statement: Any line that starts with '#'.
5358 */
5359 static int
5360cin_ispreproc(s)
5361 char_u *s;
5362{
5363 s = skipwhite(s);
5364 if (*s == '#')
5365 return TRUE;
5366 return FALSE;
5367}
5368
5369/*
5370 * Return TRUE if line "*pp" at "*lnump" is a preprocessor statement or a
5371 * continuation line of a preprocessor statement. Decrease "*lnump" to the
5372 * start and return the line in "*pp".
5373 */
5374 static int
5375cin_ispreproc_cont(pp, lnump)
5376 char_u **pp;
5377 linenr_T *lnump;
5378{
5379 char_u *line = *pp;
5380 linenr_T lnum = *lnump;
5381 int retval = FALSE;
5382
Bram Moolenaard8e9bb22005-07-09 21:14:46 +00005383 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005384 {
5385 if (cin_ispreproc(line))
5386 {
5387 retval = TRUE;
5388 *lnump = lnum;
5389 break;
5390 }
5391 if (lnum == 1)
5392 break;
5393 line = ml_get(--lnum);
5394 if (*line == NUL || line[STRLEN(line) - 1] != '\\')
5395 break;
5396 }
5397
5398 if (lnum != *lnump)
5399 *pp = ml_get(*lnump);
5400 return retval;
5401}
5402
5403/*
5404 * Recognize the start of a C or C++ comment.
5405 */
5406 static int
5407cin_iscomment(p)
5408 char_u *p;
5409{
5410 return (p[0] == '/' && (p[1] == '*' || p[1] == '/'));
5411}
5412
5413/*
5414 * Recognize the start of a "//" comment.
5415 */
5416 static int
5417cin_islinecomment(p)
5418 char_u *p;
5419{
5420 return (p[0] == '/' && p[1] == '/');
5421}
5422
5423/*
5424 * Recognize a line that starts with '{' or '}', or ends with ';', '{' or '}'.
5425 * Don't consider "} else" a terminated line.
5426 * Return the character terminating the line (ending char's have precedence if
5427 * both apply in order to determine initializations).
5428 */
5429 static int
5430cin_isterminated(s, incl_open, incl_comma)
5431 char_u *s;
5432 int incl_open; /* include '{' at the end as terminator */
5433 int incl_comma; /* recognize a trailing comma */
5434{
5435 char_u found_start = 0;
5436
5437 s = cin_skipcomment(s);
5438
5439 if (*s == '{' || (*s == '}' && !cin_iselse(s)))
5440 found_start = *s;
5441
5442 while (*s)
5443 {
5444 /* skip over comments, "" strings and 'c'haracters */
5445 s = skip_string(cin_skipcomment(s));
5446 if ((*s == ';' || (incl_open && *s == '{') || *s == '}'
5447 || (incl_comma && *s == ','))
5448 && cin_nocode(s + 1))
5449 return *s;
5450
5451 if (*s)
5452 s++;
5453 }
5454 return found_start;
5455}
5456
5457/*
5458 * Recognize the basic picture of a function declaration -- it needs to
5459 * have an open paren somewhere and a close paren at the end of the line and
5460 * no semicolons anywhere.
5461 * When a line ends in a comma we continue looking in the next line.
5462 * "sp" points to a string with the line. When looking at other lines it must
5463 * be restored to the line. When it's NULL fetch lines here.
5464 * "lnum" is where we start looking.
5465 */
5466 static int
5467cin_isfuncdecl(sp, first_lnum)
5468 char_u **sp;
5469 linenr_T first_lnum;
5470{
5471 char_u *s;
5472 linenr_T lnum = first_lnum;
5473 int retval = FALSE;
5474
5475 if (sp == NULL)
5476 s = ml_get(lnum);
5477 else
5478 s = *sp;
5479
5480 while (*s && *s != '(' && *s != ';' && *s != '\'' && *s != '"')
5481 {
5482 if (cin_iscomment(s)) /* ignore comments */
5483 s = cin_skipcomment(s);
5484 else
5485 ++s;
5486 }
5487 if (*s != '(')
5488 return FALSE; /* ';', ' or " before any () or no '(' */
5489
5490 while (*s && *s != ';' && *s != '\'' && *s != '"')
5491 {
5492 if (*s == ')' && cin_nocode(s + 1))
5493 {
5494 /* ')' at the end: may have found a match
5495 * Check for he previous line not to end in a backslash:
5496 * #if defined(x) && \
5497 * defined(y)
5498 */
5499 lnum = first_lnum - 1;
5500 s = ml_get(lnum);
5501 if (*s == NUL || s[STRLEN(s) - 1] != '\\')
5502 retval = TRUE;
5503 goto done;
5504 }
5505 if (*s == ',' && cin_nocode(s + 1))
5506 {
5507 /* ',' at the end: continue looking in the next line */
5508 if (lnum >= curbuf->b_ml.ml_line_count)
5509 break;
5510
5511 s = ml_get(++lnum);
5512 }
5513 else if (cin_iscomment(s)) /* ignore comments */
5514 s = cin_skipcomment(s);
5515 else
5516 ++s;
5517 }
5518
5519done:
5520 if (lnum != first_lnum && sp != NULL)
5521 *sp = ml_get(first_lnum);
5522
5523 return retval;
5524}
5525
5526 static int
5527cin_isif(p)
5528 char_u *p;
5529{
5530 return (STRNCMP(p, "if", 2) == 0 && !vim_isIDc(p[2]));
5531}
5532
5533 static int
5534cin_iselse(p)
5535 char_u *p;
5536{
5537 if (*p == '}') /* accept "} else" */
5538 p = cin_skipcomment(p + 1);
5539 return (STRNCMP(p, "else", 4) == 0 && !vim_isIDc(p[4]));
5540}
5541
5542 static int
5543cin_isdo(p)
5544 char_u *p;
5545{
5546 return (STRNCMP(p, "do", 2) == 0 && !vim_isIDc(p[2]));
5547}
5548
5549/*
5550 * Check if this is a "while" that should have a matching "do".
5551 * We only accept a "while (condition) ;", with only white space between the
5552 * ')' and ';'. The condition may be spread over several lines.
5553 */
5554 static int
5555cin_iswhileofdo(p, lnum, ind_maxparen) /* XXX */
5556 char_u *p;
5557 linenr_T lnum;
5558 int ind_maxparen;
5559{
5560 pos_T cursor_save;
5561 pos_T *trypos;
5562 int retval = FALSE;
5563
5564 p = cin_skipcomment(p);
5565 if (*p == '}') /* accept "} while (cond);" */
5566 p = cin_skipcomment(p + 1);
5567 if (STRNCMP(p, "while", 5) == 0 && !vim_isIDc(p[5]))
5568 {
5569 cursor_save = curwin->w_cursor;
5570 curwin->w_cursor.lnum = lnum;
5571 curwin->w_cursor.col = 0;
5572 p = ml_get_curline();
5573 while (*p && *p != 'w') /* skip any '}', until the 'w' of the "while" */
5574 {
5575 ++p;
5576 ++curwin->w_cursor.col;
5577 }
5578 if ((trypos = findmatchlimit(NULL, 0, 0, ind_maxparen)) != NULL
5579 && *cin_skipcomment(ml_get_pos(trypos) + 1) == ';')
5580 retval = TRUE;
5581 curwin->w_cursor = cursor_save;
5582 }
5583 return retval;
5584}
5585
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005586/*
5587 * Return TRUE if we are at the end of a do-while.
5588 * do
5589 * nothing;
5590 * while (foo
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00005591 * && bar); <-- here
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005592 * Adjust the cursor to the line with "while".
5593 */
5594 static int
5595cin_iswhileofdo_end(terminated, ind_maxparen, ind_maxcomment)
5596 int terminated;
5597 int ind_maxparen;
5598 int ind_maxcomment;
5599{
5600 char_u *line;
5601 char_u *p;
5602 char_u *s;
5603 pos_T *trypos;
5604 int i;
5605
5606 if (terminated != ';') /* there must be a ';' at the end */
5607 return FALSE;
5608
5609 p = line = ml_get_curline();
5610 while (*p != NUL)
5611 {
5612 p = cin_skipcomment(p);
5613 if (*p == ')')
5614 {
5615 s = skipwhite(p + 1);
5616 if (*s == ';' && cin_nocode(s + 1))
5617 {
5618 /* Found ");" at end of the line, now check there is "while"
5619 * before the matching '('. XXX */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005620 i = (int)(p - line);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005621 curwin->w_cursor.col = i;
5622 trypos = find_match_paren(ind_maxparen, ind_maxcomment);
5623 if (trypos != NULL)
5624 {
5625 s = cin_skipcomment(ml_get(trypos->lnum));
5626 if (*s == '}') /* accept "} while (cond);" */
5627 s = cin_skipcomment(s + 1);
5628 if (STRNCMP(s, "while", 5) == 0 && !vim_isIDc(s[5]))
5629 {
5630 curwin->w_cursor.lnum = trypos->lnum;
5631 return TRUE;
5632 }
5633 }
5634
5635 /* Searching may have made "line" invalid, get it again. */
5636 line = ml_get_curline();
5637 p = line + i;
5638 }
5639 }
5640 if (*p != NUL)
5641 ++p;
5642 }
5643 return FALSE;
5644}
5645
Bram Moolenaar071d4272004-06-13 20:20:40 +00005646 static int
5647cin_isbreak(p)
5648 char_u *p;
5649{
5650 return (STRNCMP(p, "break", 5) == 0 && !vim_isIDc(p[5]));
5651}
5652
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005653/*
5654 * Find the position of a C++ base-class declaration or
Bram Moolenaar071d4272004-06-13 20:20:40 +00005655 * constructor-initialization. eg:
5656 *
5657 * class MyClass :
5658 * baseClass <-- here
5659 * class MyClass : public baseClass,
5660 * anotherBaseClass <-- here (should probably lineup ??)
5661 * MyClass::MyClass(...) :
5662 * baseClass(...) <-- here (constructor-initialization)
Bram Moolenaar18144c82006-04-12 21:52:12 +00005663 *
5664 * This is a lot of guessing. Watch out for "cond ? func() : foo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005665 */
5666 static int
Bram Moolenaare7c56862007-08-04 10:14:52 +00005667cin_is_cpp_baseclass(col)
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005668 colnr_T *col; /* return: column to align with */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005669{
5670 char_u *s;
5671 int class_or_struct, lookfor_ctor_init, cpp_base_class;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005672 linenr_T lnum = curwin->w_cursor.lnum;
Bram Moolenaare7c56862007-08-04 10:14:52 +00005673 char_u *line = ml_get_curline();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005674
5675 *col = 0;
5676
Bram Moolenaar21cf8232004-07-16 20:18:37 +00005677 s = skipwhite(line);
5678 if (*s == '#') /* skip #define FOO x ? (x) : x */
5679 return FALSE;
5680 s = cin_skipcomment(s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005681 if (*s == NUL)
5682 return FALSE;
5683
5684 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
5685
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005686 /* Search for a line starting with '#', empty, ending in ';' or containing
5687 * '{' or '}' and start below it. This handles the following situations:
5688 * a = cond ?
5689 * func() :
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00005690 * asdf;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005691 * func::foo()
5692 * : something
5693 * {}
5694 * Foo::Foo (int one, int two)
5695 * : something(4),
5696 * somethingelse(3)
5697 * {}
5698 */
5699 while (lnum > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005700 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00005701 line = ml_get(lnum - 1);
5702 s = skipwhite(line);
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005703 if (*s == '#' || *s == NUL)
5704 break;
5705 while (*s != NUL)
5706 {
5707 s = cin_skipcomment(s);
5708 if (*s == '{' || *s == '}'
5709 || (*s == ';' && cin_nocode(s + 1)))
5710 break;
5711 if (*s != NUL)
5712 ++s;
5713 }
5714 if (*s != NUL)
5715 break;
5716 --lnum;
5717 }
5718
Bram Moolenaare7c56862007-08-04 10:14:52 +00005719 line = ml_get(lnum);
5720 s = cin_skipcomment(line);
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005721 for (;;)
5722 {
5723 if (*s == NUL)
5724 {
5725 if (lnum == curwin->w_cursor.lnum)
5726 break;
5727 /* Continue in the cursor line. */
Bram Moolenaare7c56862007-08-04 10:14:52 +00005728 line = ml_get(++lnum);
5729 s = cin_skipcomment(line);
5730 if (*s == NUL)
5731 continue;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005732 }
5733
Bram Moolenaar071d4272004-06-13 20:20:40 +00005734 if (s[0] == ':')
5735 {
5736 if (s[1] == ':')
5737 {
5738 /* skip double colon. It can't be a constructor
5739 * initialization any more */
5740 lookfor_ctor_init = FALSE;
5741 s = cin_skipcomment(s + 2);
5742 }
5743 else if (lookfor_ctor_init || class_or_struct)
5744 {
5745 /* we have something found, that looks like the start of
Bram Moolenaare21877a2008-02-13 09:58:14 +00005746 * cpp-base-class-declaration or constructor-initialization */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005747 cpp_base_class = TRUE;
5748 lookfor_ctor_init = class_or_struct = FALSE;
5749 *col = 0;
5750 s = cin_skipcomment(s + 1);
5751 }
5752 else
5753 s = cin_skipcomment(s + 1);
5754 }
5755 else if ((STRNCMP(s, "class", 5) == 0 && !vim_isIDc(s[5]))
5756 || (STRNCMP(s, "struct", 6) == 0 && !vim_isIDc(s[6])))
5757 {
5758 class_or_struct = TRUE;
5759 lookfor_ctor_init = FALSE;
5760
5761 if (*s == 'c')
5762 s = cin_skipcomment(s + 5);
5763 else
5764 s = cin_skipcomment(s + 6);
5765 }
5766 else
5767 {
5768 if (s[0] == '{' || s[0] == '}' || s[0] == ';')
5769 {
5770 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
5771 }
5772 else if (s[0] == ')')
5773 {
5774 /* Constructor-initialization is assumed if we come across
5775 * something like "):" */
5776 class_or_struct = FALSE;
5777 lookfor_ctor_init = TRUE;
5778 }
Bram Moolenaar18144c82006-04-12 21:52:12 +00005779 else if (s[0] == '?')
5780 {
5781 /* Avoid seeing '() :' after '?' as constructor init. */
5782 return FALSE;
5783 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005784 else if (!vim_isIDc(s[0]))
5785 {
5786 /* if it is not an identifier, we are wrong */
5787 class_or_struct = FALSE;
5788 lookfor_ctor_init = FALSE;
5789 }
5790 else if (*col == 0)
5791 {
5792 /* it can't be a constructor-initialization any more */
5793 lookfor_ctor_init = FALSE;
5794
5795 /* the first statement starts here: lineup with this one... */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005796 if (cpp_base_class)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005797 *col = (colnr_T)(s - line);
5798 }
5799
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005800 /* When the line ends in a comma don't align with it. */
5801 if (lnum == curwin->w_cursor.lnum && *s == ',' && cin_nocode(s + 1))
5802 *col = 0;
5803
Bram Moolenaar071d4272004-06-13 20:20:40 +00005804 s = cin_skipcomment(s + 1);
5805 }
5806 }
5807
5808 return cpp_base_class;
5809}
5810
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005811 static int
5812get_baseclass_amount(col, ind_maxparen, ind_maxcomment, ind_cpp_baseclass)
5813 int col;
5814 int ind_maxparen;
5815 int ind_maxcomment;
5816 int ind_cpp_baseclass;
5817{
5818 int amount;
5819 colnr_T vcol;
5820 pos_T *trypos;
5821
5822 if (col == 0)
5823 {
5824 amount = get_indent();
5825 if (find_last_paren(ml_get_curline(), '(', ')')
5826 && (trypos = find_match_paren(ind_maxparen,
5827 ind_maxcomment)) != NULL)
5828 amount = get_indent_lnum(trypos->lnum); /* XXX */
5829 if (!cin_ends_in(ml_get_curline(), (char_u *)",", NULL))
5830 amount += ind_cpp_baseclass;
5831 }
5832 else
5833 {
5834 curwin->w_cursor.col = col;
5835 getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
5836 amount = (int)vcol;
5837 }
5838 if (amount < ind_cpp_baseclass)
5839 amount = ind_cpp_baseclass;
5840 return amount;
5841}
5842
Bram Moolenaar071d4272004-06-13 20:20:40 +00005843/*
5844 * Return TRUE if string "s" ends with the string "find", possibly followed by
5845 * white space and comments. Skip strings and comments.
5846 * Ignore "ignore" after "find" if it's not NULL.
5847 */
5848 static int
5849cin_ends_in(s, find, ignore)
5850 char_u *s;
5851 char_u *find;
5852 char_u *ignore;
5853{
5854 char_u *p = s;
5855 char_u *r;
5856 int len = (int)STRLEN(find);
5857
5858 while (*p != NUL)
5859 {
5860 p = cin_skipcomment(p);
5861 if (STRNCMP(p, find, len) == 0)
5862 {
5863 r = skipwhite(p + len);
5864 if (ignore != NULL && STRNCMP(r, ignore, STRLEN(ignore)) == 0)
5865 r = skipwhite(r + STRLEN(ignore));
5866 if (cin_nocode(r))
5867 return TRUE;
5868 }
5869 if (*p != NUL)
5870 ++p;
5871 }
5872 return FALSE;
5873}
5874
5875/*
5876 * Skip strings, chars and comments until at or past "trypos".
5877 * Return the column found.
5878 */
5879 static int
5880cin_skip2pos(trypos)
5881 pos_T *trypos;
5882{
5883 char_u *line;
5884 char_u *p;
5885
5886 p = line = ml_get(trypos->lnum);
5887 while (*p && (colnr_T)(p - line) < trypos->col)
5888 {
5889 if (cin_iscomment(p))
5890 p = cin_skipcomment(p);
5891 else
5892 {
5893 p = skip_string(p);
5894 ++p;
5895 }
5896 }
5897 return (int)(p - line);
5898}
5899
5900/*
5901 * Find the '{' at the start of the block we are in.
5902 * Return NULL if no match found.
5903 * Ignore a '{' that is in a comment, makes indenting the next three lines
5904 * work. */
5905/* foo() */
5906/* { */
5907/* } */
5908
5909 static pos_T *
5910find_start_brace(ind_maxcomment) /* XXX */
5911 int ind_maxcomment;
5912{
5913 pos_T cursor_save;
5914 pos_T *trypos;
5915 pos_T *pos;
5916 static pos_T pos_copy;
5917
5918 cursor_save = curwin->w_cursor;
5919 while ((trypos = findmatchlimit(NULL, '{', FM_BLOCKSTOP, 0)) != NULL)
5920 {
5921 pos_copy = *trypos; /* copy pos_T, next findmatch will change it */
5922 trypos = &pos_copy;
5923 curwin->w_cursor = *trypos;
5924 pos = NULL;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005925 /* ignore the { if it's in a // or / * * / comment */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005926 if ((colnr_T)cin_skip2pos(trypos) == trypos->col
5927 && (pos = find_start_comment(ind_maxcomment)) == NULL) /* XXX */
5928 break;
5929 if (pos != NULL)
5930 curwin->w_cursor.lnum = pos->lnum;
5931 }
5932 curwin->w_cursor = cursor_save;
5933 return trypos;
5934}
5935
5936/*
5937 * Find the matching '(', failing if it is in a comment.
5938 * Return NULL of no match found.
5939 */
5940 static pos_T *
5941find_match_paren(ind_maxparen, ind_maxcomment) /* XXX */
5942 int ind_maxparen;
5943 int ind_maxcomment;
5944{
5945 pos_T cursor_save;
5946 pos_T *trypos;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005947 static pos_T pos_copy;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005948
5949 cursor_save = curwin->w_cursor;
5950 if ((trypos = findmatchlimit(NULL, '(', 0, ind_maxparen)) != NULL)
5951 {
5952 /* check if the ( is in a // comment */
5953 if ((colnr_T)cin_skip2pos(trypos) > trypos->col)
5954 trypos = NULL;
5955 else
5956 {
5957 pos_copy = *trypos; /* copy trypos, findmatch will change it */
5958 trypos = &pos_copy;
5959 curwin->w_cursor = *trypos;
5960 if (find_start_comment(ind_maxcomment) != NULL) /* XXX */
5961 trypos = NULL;
5962 }
5963 }
5964 curwin->w_cursor = cursor_save;
5965 return trypos;
5966}
5967
5968/*
5969 * Return ind_maxparen corrected for the difference in line number between the
5970 * cursor position and "startpos". This makes sure that searching for a
5971 * matching paren above the cursor line doesn't find a match because of
5972 * looking a few lines further.
5973 */
5974 static int
5975corr_ind_maxparen(ind_maxparen, startpos)
5976 int ind_maxparen;
5977 pos_T *startpos;
5978{
5979 long n = (long)startpos->lnum - (long)curwin->w_cursor.lnum;
5980
5981 if (n > 0 && n < ind_maxparen / 2)
5982 return ind_maxparen - (int)n;
5983 return ind_maxparen;
5984}
5985
5986/*
5987 * Set w_cursor.col to the column number of the last unmatched ')' or '{' in
5988 * line "l".
5989 */
5990 static int
5991find_last_paren(l, start, end)
5992 char_u *l;
5993 int start, end;
5994{
5995 int i;
5996 int retval = FALSE;
5997 int open_count = 0;
5998
5999 curwin->w_cursor.col = 0; /* default is start of line */
6000
6001 for (i = 0; l[i]; i++)
6002 {
6003 i = (int)(cin_skipcomment(l + i) - l); /* ignore parens in comments */
6004 i = (int)(skip_string(l + i) - l); /* ignore parens in quotes */
6005 if (l[i] == start)
6006 ++open_count;
6007 else if (l[i] == end)
6008 {
6009 if (open_count > 0)
6010 --open_count;
6011 else
6012 {
6013 curwin->w_cursor.col = i;
6014 retval = TRUE;
6015 }
6016 }
6017 }
6018 return retval;
6019}
6020
6021 int
6022get_c_indent()
6023{
6024 /*
6025 * spaces from a block's opening brace the prevailing indent for that
6026 * block should be
6027 */
6028 int ind_level = curbuf->b_p_sw;
6029
6030 /*
6031 * spaces from the edge of the line an open brace that's at the end of a
6032 * line is imagined to be.
6033 */
6034 int ind_open_imag = 0;
6035
6036 /*
Bram Moolenaar1a509df2010-08-01 17:59:57 +02006037 * spaces from the prevailing indent for a line that is not preceded by
Bram Moolenaar071d4272004-06-13 20:20:40 +00006038 * an opening brace.
6039 */
6040 int ind_no_brace = 0;
6041
6042 /*
6043 * column where the first { of a function should be located }
6044 */
6045 int ind_first_open = 0;
6046
6047 /*
6048 * spaces from the prevailing indent a leftmost open brace should be
6049 * located
6050 */
6051 int ind_open_extra = 0;
6052
6053 /*
6054 * spaces from the matching open brace (real location for one at the left
6055 * edge; imaginary location from one that ends a line) the matching close
6056 * brace should be located
6057 */
6058 int ind_close_extra = 0;
6059
6060 /*
6061 * spaces from the edge of the line an open brace sitting in the leftmost
6062 * column is imagined to be
6063 */
6064 int ind_open_left_imag = 0;
6065
6066 /*
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006067 * Spaces jump labels should be shifted to the left if N is non-negative,
6068 * otherwise the jump label will be put to column 1.
6069 */
6070 int ind_jump_label = -1;
6071
6072 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006073 * spaces from the switch() indent a "case xx" label should be located
6074 */
6075 int ind_case = curbuf->b_p_sw;
6076
6077 /*
6078 * spaces from the "case xx:" code after a switch() should be located
6079 */
6080 int ind_case_code = curbuf->b_p_sw;
6081
6082 /*
6083 * lineup break at end of case in switch() with case label
6084 */
6085 int ind_case_break = 0;
6086
6087 /*
6088 * spaces from the class declaration indent a scope declaration label
6089 * should be located
6090 */
6091 int ind_scopedecl = curbuf->b_p_sw;
6092
6093 /*
6094 * spaces from the scope declaration label code should be located
6095 */
6096 int ind_scopedecl_code = curbuf->b_p_sw;
6097
6098 /*
6099 * amount K&R-style parameters should be indented
6100 */
6101 int ind_param = curbuf->b_p_sw;
6102
6103 /*
6104 * amount a function type spec should be indented
6105 */
6106 int ind_func_type = curbuf->b_p_sw;
6107
6108 /*
6109 * amount a cpp base class declaration or constructor initialization
6110 * should be indented
6111 */
6112 int ind_cpp_baseclass = curbuf->b_p_sw;
6113
6114 /*
6115 * additional spaces beyond the prevailing indent a continuation line
6116 * should be located
6117 */
6118 int ind_continuation = curbuf->b_p_sw;
6119
6120 /*
6121 * spaces from the indent of the line with an unclosed parentheses
6122 */
6123 int ind_unclosed = curbuf->b_p_sw * 2;
6124
6125 /*
6126 * spaces from the indent of the line with an unclosed parentheses, which
6127 * itself is also unclosed
6128 */
6129 int ind_unclosed2 = curbuf->b_p_sw;
6130
6131 /*
6132 * suppress ignoring spaces from the indent of a line starting with an
6133 * unclosed parentheses.
6134 */
6135 int ind_unclosed_noignore = 0;
6136
6137 /*
6138 * If the opening paren is the last nonwhite character on the line, and
6139 * ind_unclosed_wrapped is nonzero, use this indent relative to the outer
6140 * context (for very long lines).
6141 */
6142 int ind_unclosed_wrapped = 0;
6143
6144 /*
6145 * suppress ignoring white space when lining up with the character after
6146 * an unclosed parentheses.
6147 */
6148 int ind_unclosed_whiteok = 0;
6149
6150 /*
6151 * indent a closing parentheses under the line start of the matching
6152 * opening parentheses.
6153 */
6154 int ind_matching_paren = 0;
6155
6156 /*
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006157 * indent a closing parentheses under the previous line.
6158 */
6159 int ind_paren_prev = 0;
6160
6161 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006162 * Extra indent for comments.
6163 */
6164 int ind_comment = 0;
6165
6166 /*
6167 * spaces from the comment opener when there is nothing after it.
6168 */
6169 int ind_in_comment = 3;
6170
6171 /*
6172 * boolean: if non-zero, use ind_in_comment even if there is something
6173 * after the comment opener.
6174 */
6175 int ind_in_comment2 = 0;
6176
6177 /*
6178 * max lines to search for an open paren
6179 */
6180 int ind_maxparen = 20;
6181
6182 /*
6183 * max lines to search for an open comment
6184 */
6185 int ind_maxcomment = 70;
6186
6187 /*
6188 * handle braces for java code
6189 */
6190 int ind_java = 0;
6191
6192 /*
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006193 * not to confuse JS object properties with labels
6194 */
6195 int ind_js = 0;
6196
6197 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006198 * handle blocked cases correctly
6199 */
6200 int ind_keep_case_label = 0;
6201
6202 pos_T cur_curpos;
6203 int amount;
6204 int scope_amount;
Bram Moolenaarb21e5842006-04-16 18:30:08 +00006205 int cur_amount = MAXCOL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006206 colnr_T col;
6207 char_u *theline;
6208 char_u *linecopy;
6209 pos_T *trypos;
6210 pos_T *tryposBrace = NULL;
6211 pos_T our_paren_pos;
6212 char_u *start;
6213 int start_brace;
Bram Moolenaare21877a2008-02-13 09:58:14 +00006214#define BRACE_IN_COL0 1 /* '{' is in column 0 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006215#define BRACE_AT_START 2 /* '{' is at start of line */
6216#define BRACE_AT_END 3 /* '{' is at end of line */
6217 linenr_T ourscope;
6218 char_u *l;
6219 char_u *look;
6220 char_u terminated;
6221 int lookfor;
6222#define LOOKFOR_INITIAL 0
6223#define LOOKFOR_IF 1
6224#define LOOKFOR_DO 2
6225#define LOOKFOR_CASE 3
6226#define LOOKFOR_ANY 4
6227#define LOOKFOR_TERM 5
6228#define LOOKFOR_UNTERM 6
6229#define LOOKFOR_SCOPEDECL 7
6230#define LOOKFOR_NOBREAK 8
6231#define LOOKFOR_CPP_BASECLASS 9
6232#define LOOKFOR_ENUM_OR_INIT 10
6233
6234 int whilelevel;
6235 linenr_T lnum;
6236 char_u *options;
6237 int fraction = 0; /* init for GCC */
6238 int divider;
6239 int n;
6240 int iscase;
6241 int lookfor_break;
6242 int cont_amount = 0; /* amount for continuation line */
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006243 int original_line_islabel;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006244
6245 for (options = curbuf->b_p_cino; *options; )
6246 {
6247 l = options++;
6248 if (*options == '-')
6249 ++options;
6250 n = getdigits(&options);
6251 divider = 0;
6252 if (*options == '.') /* ".5s" means a fraction */
6253 {
6254 fraction = atol((char *)++options);
6255 while (VIM_ISDIGIT(*options))
6256 {
6257 ++options;
6258 if (divider)
6259 divider *= 10;
6260 else
6261 divider = 10;
6262 }
6263 }
6264 if (*options == 's') /* "2s" means two times 'shiftwidth' */
6265 {
6266 if (n == 0 && fraction == 0)
6267 n = curbuf->b_p_sw; /* just "s" is one 'shiftwidth' */
6268 else
6269 {
6270 n *= curbuf->b_p_sw;
6271 if (divider)
6272 n += (curbuf->b_p_sw * fraction + divider / 2) / divider;
6273 }
6274 ++options;
6275 }
6276 if (l[1] == '-')
6277 n = -n;
6278 /* When adding an entry here, also update the default 'cinoptions' in
Bram Moolenaar39353fd2007-03-27 09:02:11 +00006279 * doc/indent.txt, and add explanation for it! */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006280 switch (*l)
6281 {
6282 case '>': ind_level = n; break;
6283 case 'e': ind_open_imag = n; break;
6284 case 'n': ind_no_brace = n; break;
6285 case 'f': ind_first_open = n; break;
6286 case '{': ind_open_extra = n; break;
6287 case '}': ind_close_extra = n; break;
6288 case '^': ind_open_left_imag = n; break;
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006289 case 'L': ind_jump_label = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006290 case ':': ind_case = n; break;
6291 case '=': ind_case_code = n; break;
6292 case 'b': ind_case_break = n; break;
6293 case 'p': ind_param = n; break;
6294 case 't': ind_func_type = n; break;
6295 case '/': ind_comment = n; break;
6296 case 'c': ind_in_comment = n; break;
6297 case 'C': ind_in_comment2 = n; break;
6298 case 'i': ind_cpp_baseclass = n; break;
6299 case '+': ind_continuation = n; break;
6300 case '(': ind_unclosed = n; break;
6301 case 'u': ind_unclosed2 = n; break;
6302 case 'U': ind_unclosed_noignore = n; break;
6303 case 'W': ind_unclosed_wrapped = n; break;
6304 case 'w': ind_unclosed_whiteok = n; break;
6305 case 'm': ind_matching_paren = n; break;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006306 case 'M': ind_paren_prev = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006307 case ')': ind_maxparen = n; break;
6308 case '*': ind_maxcomment = n; break;
6309 case 'g': ind_scopedecl = n; break;
6310 case 'h': ind_scopedecl_code = n; break;
6311 case 'j': ind_java = n; break;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006312 case 'J': ind_js = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006313 case 'l': ind_keep_case_label = n; break;
Bram Moolenaar39353fd2007-03-27 09:02:11 +00006314 case '#': ind_hash_comment = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006315 }
Bram Moolenaardfdf3c42010-03-23 18:22:46 +01006316 if (*options == ',')
6317 ++options;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006318 }
6319
6320 /* remember where the cursor was when we started */
6321 cur_curpos = curwin->w_cursor;
6322
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006323 /* if we are at line 1 0 is fine, right? */
6324 if (cur_curpos.lnum == 1)
6325 return 0;
6326
Bram Moolenaar071d4272004-06-13 20:20:40 +00006327 /* Get a copy of the current contents of the line.
6328 * This is required, because only the most recent line obtained with
6329 * ml_get is valid! */
6330 linecopy = vim_strsave(ml_get(cur_curpos.lnum));
6331 if (linecopy == NULL)
6332 return 0;
6333
6334 /*
6335 * In insert mode and the cursor is on a ')' truncate the line at the
6336 * cursor position. We don't want to line up with the matching '(' when
6337 * inserting new stuff.
6338 * For unknown reasons the cursor might be past the end of the line, thus
6339 * check for that.
6340 */
6341 if ((State & INSERT)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006342 && curwin->w_cursor.col < (colnr_T)STRLEN(linecopy)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006343 && linecopy[curwin->w_cursor.col] == ')')
6344 linecopy[curwin->w_cursor.col] = NUL;
6345
6346 theline = skipwhite(linecopy);
6347
6348 /* move the cursor to the start of the line */
6349
6350 curwin->w_cursor.col = 0;
6351
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006352 original_line_islabel = cin_islabel(ind_maxcomment); /* XXX */
6353
Bram Moolenaar071d4272004-06-13 20:20:40 +00006354 /*
6355 * #defines and so on always go at the left when included in 'cinkeys'.
6356 */
6357 if (*theline == '#' && (*linecopy == '#' || in_cinkeys('#', ' ', TRUE)))
6358 {
6359 amount = 0;
6360 }
6361
6362 /*
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006363 * Is it a non-case label? Then that goes at the left margin too unless:
6364 * - JS flag is set.
6365 * - 'L' item has a positive value.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006366 */
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006367 else if (original_line_islabel && !ind_js && ind_jump_label < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006368 {
6369 amount = 0;
6370 }
6371
6372 /*
6373 * If we're inside a "//" comment and there is a "//" comment in a
6374 * previous line, lineup with that one.
6375 */
6376 else if (cin_islinecomment(theline)
6377 && (trypos = find_line_comment()) != NULL) /* XXX */
6378 {
6379 /* find how indented the line beginning the comment is */
6380 getvcol(curwin, trypos, &col, NULL, NULL);
6381 amount = col;
6382 }
6383
6384 /*
6385 * If we're inside a comment and not looking at the start of the
6386 * comment, try using the 'comments' option.
6387 */
6388 else if (!cin_iscomment(theline)
6389 && (trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
6390 {
6391 int lead_start_len = 2;
6392 int lead_middle_len = 1;
6393 char_u lead_start[COM_MAX_LEN]; /* start-comment string */
6394 char_u lead_middle[COM_MAX_LEN]; /* middle-comment string */
6395 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
6396 char_u *p;
6397 int start_align = 0;
6398 int start_off = 0;
6399 int done = FALSE;
6400
6401 /* find how indented the line beginning the comment is */
6402 getvcol(curwin, trypos, &col, NULL, NULL);
6403 amount = col;
6404
6405 p = curbuf->b_p_com;
6406 while (*p != NUL)
6407 {
6408 int align = 0;
6409 int off = 0;
6410 int what = 0;
6411
6412 while (*p != NUL && *p != ':')
6413 {
6414 if (*p == COM_START || *p == COM_END || *p == COM_MIDDLE)
6415 what = *p++;
6416 else if (*p == COM_LEFT || *p == COM_RIGHT)
6417 align = *p++;
6418 else if (VIM_ISDIGIT(*p) || *p == '-')
6419 off = getdigits(&p);
6420 else
6421 ++p;
6422 }
6423
6424 if (*p == ':')
6425 ++p;
6426 (void)copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
6427 if (what == COM_START)
6428 {
6429 STRCPY(lead_start, lead_end);
6430 lead_start_len = (int)STRLEN(lead_start);
6431 start_off = off;
6432 start_align = align;
6433 }
6434 else if (what == COM_MIDDLE)
6435 {
6436 STRCPY(lead_middle, lead_end);
6437 lead_middle_len = (int)STRLEN(lead_middle);
6438 }
6439 else if (what == COM_END)
6440 {
6441 /* If our line starts with the middle comment string, line it
6442 * up with the comment opener per the 'comments' option. */
6443 if (STRNCMP(theline, lead_middle, lead_middle_len) == 0
6444 && STRNCMP(theline, lead_end, STRLEN(lead_end)) != 0)
6445 {
6446 done = TRUE;
6447 if (curwin->w_cursor.lnum > 1)
6448 {
6449 /* If the start comment string matches in the previous
Bram Moolenaare21877a2008-02-13 09:58:14 +00006450 * line, use the indent of that line plus offset. If
Bram Moolenaar071d4272004-06-13 20:20:40 +00006451 * the middle comment string matches in the previous
6452 * line, use the indent of that line. XXX */
6453 look = skipwhite(ml_get(curwin->w_cursor.lnum - 1));
6454 if (STRNCMP(look, lead_start, lead_start_len) == 0)
6455 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6456 else if (STRNCMP(look, lead_middle,
6457 lead_middle_len) == 0)
6458 {
6459 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6460 break;
6461 }
6462 /* If the start comment string doesn't match with the
6463 * start of the comment, skip this entry. XXX */
6464 else if (STRNCMP(ml_get(trypos->lnum) + trypos->col,
6465 lead_start, lead_start_len) != 0)
6466 continue;
6467 }
6468 if (start_off != 0)
6469 amount += start_off;
6470 else if (start_align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006471 amount += vim_strsize(lead_start)
6472 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006473 break;
6474 }
6475
6476 /* If our line starts with the end comment string, line it up
6477 * with the middle comment */
6478 if (STRNCMP(theline, lead_middle, lead_middle_len) != 0
6479 && STRNCMP(theline, lead_end, STRLEN(lead_end)) == 0)
6480 {
6481 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6482 /* XXX */
6483 if (off != 0)
6484 amount += off;
6485 else if (align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006486 amount += vim_strsize(lead_start)
6487 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006488 done = TRUE;
6489 break;
6490 }
6491 }
6492 }
6493
6494 /* If our line starts with an asterisk, line up with the
6495 * asterisk in the comment opener; otherwise, line up
6496 * with the first character of the comment text.
6497 */
6498 if (done)
6499 ;
6500 else if (theline[0] == '*')
6501 amount += 1;
6502 else
6503 {
6504 /*
6505 * If we are more than one line away from the comment opener, take
6506 * the indent of the previous non-empty line. If 'cino' has "CO"
6507 * and we are just below the comment opener and there are any
6508 * white characters after it line up with the text after it;
6509 * otherwise, add the amount specified by "c" in 'cino'
6510 */
6511 amount = -1;
6512 for (lnum = cur_curpos.lnum - 1; lnum > trypos->lnum; --lnum)
6513 {
6514 if (linewhite(lnum)) /* skip blank lines */
6515 continue;
6516 amount = get_indent_lnum(lnum); /* XXX */
6517 break;
6518 }
6519 if (amount == -1) /* use the comment opener */
6520 {
6521 if (!ind_in_comment2)
6522 {
6523 start = ml_get(trypos->lnum);
6524 look = start + trypos->col + 2; /* skip / and * */
6525 if (*look != NUL) /* if something after it */
6526 trypos->col = (colnr_T)(skipwhite(look) - start);
6527 }
6528 getvcol(curwin, trypos, &col, NULL, NULL);
6529 amount = col;
6530 if (ind_in_comment2 || *look == NUL)
6531 amount += ind_in_comment;
6532 }
6533 }
6534 }
6535
6536 /*
6537 * Are we inside parentheses or braces?
6538 */ /* XXX */
6539 else if (((trypos = find_match_paren(ind_maxparen, ind_maxcomment)) != NULL
6540 && ind_java == 0)
6541 || (tryposBrace = find_start_brace(ind_maxcomment)) != NULL
6542 || trypos != NULL)
6543 {
6544 if (trypos != NULL && tryposBrace != NULL)
6545 {
6546 /* Both an unmatched '(' and '{' is found. Use the one which is
6547 * closer to the current cursor position, set the other to NULL. */
6548 if (trypos->lnum != tryposBrace->lnum
6549 ? trypos->lnum < tryposBrace->lnum
6550 : trypos->col < tryposBrace->col)
6551 trypos = NULL;
6552 else
6553 tryposBrace = NULL;
6554 }
6555
6556 if (trypos != NULL)
6557 {
6558 /*
6559 * If the matching paren is more than one line away, use the indent of
6560 * a previous non-empty line that matches the same paren.
6561 */
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006562 if (theline[0] == ')' && ind_paren_prev)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006563 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006564 /* Line up with the start of the matching paren line. */
6565 amount = get_indent_lnum(curwin->w_cursor.lnum - 1); /* XXX */
6566 }
6567 else
6568 {
6569 amount = -1;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006570 our_paren_pos = *trypos;
6571 for (lnum = cur_curpos.lnum - 1; lnum > our_paren_pos.lnum; --lnum)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006572 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006573 l = skipwhite(ml_get(lnum));
6574 if (cin_nocode(l)) /* skip comment lines */
6575 continue;
6576 if (cin_ispreproc_cont(&l, &lnum))
6577 continue; /* ignore #define, #if, etc. */
6578 curwin->w_cursor.lnum = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006579
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006580 /* Skip a comment. XXX */
6581 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
6582 {
6583 lnum = trypos->lnum + 1;
6584 continue;
6585 }
6586
6587 /* XXX */
6588 if ((trypos = find_match_paren(
6589 corr_ind_maxparen(ind_maxparen, &cur_curpos),
Bram Moolenaar071d4272004-06-13 20:20:40 +00006590 ind_maxcomment)) != NULL
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006591 && trypos->lnum == our_paren_pos.lnum
6592 && trypos->col == our_paren_pos.col)
6593 {
6594 amount = get_indent_lnum(lnum); /* XXX */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006595
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006596 if (theline[0] == ')')
6597 {
6598 if (our_paren_pos.lnum != lnum
6599 && cur_amount > amount)
6600 cur_amount = amount;
6601 amount = -1;
6602 }
6603 break;
6604 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006605 }
6606 }
6607
6608 /*
6609 * Line up with line where the matching paren is. XXX
6610 * If the line starts with a '(' or the indent for unclosed
6611 * parentheses is zero, line up with the unclosed parentheses.
6612 */
6613 if (amount == -1)
6614 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006615 int ignore_paren_col = 0;
6616
Bram Moolenaar071d4272004-06-13 20:20:40 +00006617 amount = skip_label(our_paren_pos.lnum, &look, ind_maxcomment);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006618 look = skipwhite(look);
6619 if (*look == '(')
6620 {
6621 linenr_T save_lnum = curwin->w_cursor.lnum;
6622 char_u *line;
6623 int look_col;
6624
6625 /* Ignore a '(' in front of the line that has a match before
6626 * our matching '('. */
6627 curwin->w_cursor.lnum = our_paren_pos.lnum;
6628 line = ml_get_curline();
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006629 look_col = (int)(look - line);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006630 curwin->w_cursor.col = look_col + 1;
6631 if ((trypos = findmatchlimit(NULL, ')', 0, ind_maxparen))
6632 != NULL
6633 && trypos->lnum == our_paren_pos.lnum
6634 && trypos->col < our_paren_pos.col)
6635 ignore_paren_col = trypos->col + 1;
6636
6637 curwin->w_cursor.lnum = save_lnum;
6638 look = ml_get(our_paren_pos.lnum) + look_col;
6639 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006640 if (theline[0] == ')' || ind_unclosed == 0
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006641 || (!ind_unclosed_noignore && *look == '('
6642 && ignore_paren_col == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006643 {
6644 /*
6645 * If we're looking at a close paren, line up right there;
6646 * otherwise, line up with the next (non-white) character.
6647 * When ind_unclosed_wrapped is set and the matching paren is
6648 * the last nonwhite character of the line, use either the
6649 * indent of the current line or the indentation of the next
6650 * outer paren and add ind_unclosed_wrapped (for very long
6651 * lines).
6652 */
6653 if (theline[0] != ')')
6654 {
6655 cur_amount = MAXCOL;
6656 l = ml_get(our_paren_pos.lnum);
6657 if (ind_unclosed_wrapped
6658 && cin_ends_in(l, (char_u *)"(", NULL))
6659 {
6660 /* look for opening unmatched paren, indent one level
6661 * for each additional level */
6662 n = 1;
6663 for (col = 0; col < our_paren_pos.col; ++col)
6664 {
6665 switch (l[col])
6666 {
6667 case '(':
6668 case '{': ++n;
6669 break;
6670
6671 case ')':
6672 case '}': if (n > 1)
6673 --n;
6674 break;
6675 }
6676 }
6677
6678 our_paren_pos.col = 0;
6679 amount += n * ind_unclosed_wrapped;
6680 }
6681 else if (ind_unclosed_whiteok)
6682 our_paren_pos.col++;
6683 else
6684 {
6685 col = our_paren_pos.col + 1;
6686 while (vim_iswhite(l[col]))
6687 col++;
6688 if (l[col] != NUL) /* In case of trailing space */
6689 our_paren_pos.col = col;
6690 else
6691 our_paren_pos.col++;
6692 }
6693 }
6694
6695 /*
6696 * Find how indented the paren is, or the character after it
6697 * if we did the above "if".
6698 */
6699 if (our_paren_pos.col > 0)
6700 {
6701 getvcol(curwin, &our_paren_pos, &col, NULL, NULL);
6702 if (cur_amount > (int)col)
6703 cur_amount = col;
6704 }
6705 }
6706
6707 if (theline[0] == ')' && ind_matching_paren)
6708 {
6709 /* Line up with the start of the matching paren line. */
6710 }
6711 else if (ind_unclosed == 0 || (!ind_unclosed_noignore
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006712 && *look == '(' && ignore_paren_col == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006713 {
6714 if (cur_amount != MAXCOL)
6715 amount = cur_amount;
6716 }
6717 else
6718 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006719 /* Add ind_unclosed2 for each '(' before our matching one, but
6720 * ignore (void) before the line (ignore_paren_col). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006721 col = our_paren_pos.col;
Bram Moolenaarb21e5842006-04-16 18:30:08 +00006722 while ((int)our_paren_pos.col > ignore_paren_col)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006723 {
6724 --our_paren_pos.col;
6725 switch (*ml_get_pos(&our_paren_pos))
6726 {
6727 case '(': amount += ind_unclosed2;
6728 col = our_paren_pos.col;
6729 break;
6730 case ')': amount -= ind_unclosed2;
6731 col = MAXCOL;
6732 break;
6733 }
6734 }
6735
6736 /* Use ind_unclosed once, when the first '(' is not inside
6737 * braces */
6738 if (col == MAXCOL)
6739 amount += ind_unclosed;
6740 else
6741 {
6742 curwin->w_cursor.lnum = our_paren_pos.lnum;
6743 curwin->w_cursor.col = col;
6744 if ((trypos = find_match_paren(ind_maxparen,
6745 ind_maxcomment)) != NULL)
6746 amount += ind_unclosed2;
6747 else
6748 amount += ind_unclosed;
6749 }
6750 /*
6751 * For a line starting with ')' use the minimum of the two
6752 * positions, to avoid giving it more indent than the previous
6753 * lines:
6754 * func_long_name( if (x
6755 * arg && yy
6756 * ) ^ not here ) ^ not here
6757 */
6758 if (cur_amount < amount)
6759 amount = cur_amount;
6760 }
6761 }
6762
6763 /* add extra indent for a comment */
6764 if (cin_iscomment(theline))
6765 amount += ind_comment;
6766 }
6767
6768 /*
6769 * Are we at least inside braces, then?
6770 */
6771 else
6772 {
6773 trypos = tryposBrace;
6774
6775 ourscope = trypos->lnum;
6776 start = ml_get(ourscope);
6777
6778 /*
6779 * Now figure out how indented the line is in general.
6780 * If the brace was at the start of the line, we use that;
6781 * otherwise, check out the indentation of the line as
6782 * a whole and then add the "imaginary indent" to that.
6783 */
6784 look = skipwhite(start);
6785 if (*look == '{')
6786 {
6787 getvcol(curwin, trypos, &col, NULL, NULL);
6788 amount = col;
6789 if (*start == '{')
6790 start_brace = BRACE_IN_COL0;
6791 else
6792 start_brace = BRACE_AT_START;
6793 }
6794 else
6795 {
6796 /*
6797 * that opening brace might have been on a continuation
6798 * line. if so, find the start of the line.
6799 */
6800 curwin->w_cursor.lnum = ourscope;
6801
6802 /*
6803 * position the cursor over the rightmost paren, so that
6804 * matching it will take us back to the start of the line.
6805 */
6806 lnum = ourscope;
6807 if (find_last_paren(start, '(', ')')
6808 && (trypos = find_match_paren(ind_maxparen,
6809 ind_maxcomment)) != NULL)
6810 lnum = trypos->lnum;
6811
6812 /*
6813 * It could have been something like
6814 * case 1: if (asdf &&
6815 * ldfd) {
6816 * }
6817 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006818 if ((ind_keep_case_label
6819 && cin_iscase(skipwhite(ml_get_curline()), FALSE)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006820 amount = get_indent();
6821 else
6822 amount = skip_label(lnum, &l, ind_maxcomment);
6823
6824 start_brace = BRACE_AT_END;
6825 }
6826
6827 /*
6828 * if we're looking at a closing brace, that's where
6829 * we want to be. otherwise, add the amount of room
6830 * that an indent is supposed to be.
6831 */
6832 if (theline[0] == '}')
6833 {
6834 /*
6835 * they may want closing braces to line up with something
6836 * other than the open brace. indulge them, if so.
6837 */
6838 amount += ind_close_extra;
6839 }
6840 else
6841 {
6842 /*
6843 * If we're looking at an "else", try to find an "if"
6844 * to match it with.
6845 * If we're looking at a "while", try to find a "do"
6846 * to match it with.
6847 */
6848 lookfor = LOOKFOR_INITIAL;
6849 if (cin_iselse(theline))
6850 lookfor = LOOKFOR_IF;
6851 else if (cin_iswhileofdo(theline, cur_curpos.lnum, ind_maxparen))
6852 /* XXX */
6853 lookfor = LOOKFOR_DO;
6854 if (lookfor != LOOKFOR_INITIAL)
6855 {
6856 curwin->w_cursor.lnum = cur_curpos.lnum;
6857 if (find_match(lookfor, ourscope, ind_maxparen,
6858 ind_maxcomment) == OK)
6859 {
6860 amount = get_indent(); /* XXX */
6861 goto theend;
6862 }
6863 }
6864
6865 /*
6866 * We get here if we are not on an "while-of-do" or "else" (or
6867 * failed to find a matching "if").
6868 * Search backwards for something to line up with.
6869 * First set amount for when we don't find anything.
6870 */
6871
6872 /*
6873 * if the '{' is _really_ at the left margin, use the imaginary
6874 * location of a left-margin brace. Otherwise, correct the
6875 * location for ind_open_extra.
6876 */
6877
6878 if (start_brace == BRACE_IN_COL0) /* '{' is in column 0 */
6879 {
6880 amount = ind_open_left_imag;
6881 }
6882 else
6883 {
6884 if (start_brace == BRACE_AT_END) /* '{' is at end of line */
6885 amount += ind_open_imag;
6886 else
6887 {
6888 /* Compensate for adding ind_open_extra later. */
6889 amount -= ind_open_extra;
6890 if (amount < 0)
6891 amount = 0;
6892 }
6893 }
6894
6895 lookfor_break = FALSE;
6896
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006897 if (cin_iscase(theline, FALSE)) /* it's a switch() label */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006898 {
6899 lookfor = LOOKFOR_CASE; /* find a previous switch() label */
6900 amount += ind_case;
6901 }
6902 else if (cin_isscopedecl(theline)) /* private:, ... */
6903 {
6904 lookfor = LOOKFOR_SCOPEDECL; /* class decl is this block */
6905 amount += ind_scopedecl;
6906 }
6907 else
6908 {
6909 if (ind_case_break && cin_isbreak(theline)) /* break; ... */
6910 lookfor_break = TRUE;
6911
6912 lookfor = LOOKFOR_INITIAL;
6913 amount += ind_level; /* ind_level from start of block */
6914 }
6915 scope_amount = amount;
6916 whilelevel = 0;
6917
6918 /*
6919 * Search backwards. If we find something we recognize, line up
6920 * with that.
6921 *
6922 * if we're looking at an open brace, indent
6923 * the usual amount relative to the conditional
6924 * that opens the block.
6925 */
6926 curwin->w_cursor = cur_curpos;
6927 for (;;)
6928 {
6929 curwin->w_cursor.lnum--;
6930 curwin->w_cursor.col = 0;
6931
6932 /*
6933 * If we went all the way back to the start of our scope, line
6934 * up with it.
6935 */
6936 if (curwin->w_cursor.lnum <= ourscope)
6937 {
6938 /* we reached end of scope:
6939 * if looking for a enum or structure initialization
6940 * go further back:
6941 * if it is an initializer (enum xxx or xxx =), then
6942 * don't add ind_continuation, otherwise it is a variable
6943 * declaration:
6944 * int x,
6945 * here; <-- add ind_continuation
6946 */
6947 if (lookfor == LOOKFOR_ENUM_OR_INIT)
6948 {
6949 if (curwin->w_cursor.lnum == 0
6950 || curwin->w_cursor.lnum
6951 < ourscope - ind_maxparen)
6952 {
6953 /* nothing found (abuse ind_maxparen as limit)
6954 * assume terminated line (i.e. a variable
6955 * initialization) */
6956 if (cont_amount > 0)
6957 amount = cont_amount;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006958 else if (!ind_js)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006959 amount += ind_continuation;
6960 break;
6961 }
6962
6963 l = ml_get_curline();
6964
6965 /*
6966 * If we're in a comment now, skip to the start of the
6967 * comment.
6968 */
6969 trypos = find_start_comment(ind_maxcomment);
6970 if (trypos != NULL)
6971 {
6972 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00006973 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006974 continue;
6975 }
6976
6977 /*
6978 * Skip preprocessor directives and blank lines.
6979 */
6980 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
6981 continue;
6982
6983 if (cin_nocode(l))
6984 continue;
6985
6986 terminated = cin_isterminated(l, FALSE, TRUE);
6987
6988 /*
6989 * If we are at top level and the line looks like a
6990 * function declaration, we are done
6991 * (it's a variable declaration).
6992 */
6993 if (start_brace != BRACE_IN_COL0
6994 || !cin_isfuncdecl(&l, curwin->w_cursor.lnum))
6995 {
6996 /* if the line is terminated with another ','
6997 * it is a continued variable initialization.
6998 * don't add extra indent.
6999 * TODO: does not work, if a function
7000 * declaration is split over multiple lines:
7001 * cin_isfuncdecl returns FALSE then.
7002 */
7003 if (terminated == ',')
7004 break;
7005
7006 /* if it es a enum declaration or an assignment,
7007 * we are done.
7008 */
7009 if (terminated != ';' && cin_isinit())
7010 break;
7011
7012 /* nothing useful found */
7013 if (terminated == 0 || terminated == '{')
7014 continue;
7015 }
7016
7017 if (terminated != ';')
7018 {
7019 /* Skip parens and braces. Position the cursor
7020 * over the rightmost paren, so that matching it
7021 * will take us back to the start of the line.
7022 */ /* XXX */
7023 trypos = NULL;
7024 if (find_last_paren(l, '(', ')'))
7025 trypos = find_match_paren(ind_maxparen,
7026 ind_maxcomment);
7027
7028 if (trypos == NULL && find_last_paren(l, '{', '}'))
7029 trypos = find_start_brace(ind_maxcomment);
7030
7031 if (trypos != NULL)
7032 {
7033 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007034 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007035 continue;
7036 }
7037 }
7038
7039 /* it's a variable declaration, add indentation
7040 * like in
7041 * int a,
7042 * b;
7043 */
7044 if (cont_amount > 0)
7045 amount = cont_amount;
7046 else
7047 amount += ind_continuation;
7048 }
7049 else if (lookfor == LOOKFOR_UNTERM)
7050 {
7051 if (cont_amount > 0)
7052 amount = cont_amount;
7053 else
7054 amount += ind_continuation;
7055 }
7056 else if (lookfor != LOOKFOR_TERM
7057 && lookfor != LOOKFOR_CPP_BASECLASS)
7058 {
7059 amount = scope_amount;
7060 if (theline[0] == '{')
7061 amount += ind_open_extra;
7062 }
7063 break;
7064 }
7065
7066 /*
7067 * If we're in a comment now, skip to the start of the comment.
7068 */ /* XXX */
7069 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
7070 {
7071 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007072 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007073 continue;
7074 }
7075
7076 l = ml_get_curline();
7077
7078 /*
7079 * If this is a switch() label, may line up relative to that.
Bram Moolenaar18144c82006-04-12 21:52:12 +00007080 * If this is a C++ scope declaration, do the same.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007081 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007082 iscase = cin_iscase(l, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007083 if (iscase || cin_isscopedecl(l))
7084 {
7085 /* we are only looking for cpp base class
7086 * declaration/initialization any longer */
7087 if (lookfor == LOOKFOR_CPP_BASECLASS)
7088 break;
7089
7090 /* When looking for a "do" we are not interested in
7091 * labels. */
7092 if (whilelevel > 0)
7093 continue;
7094
7095 /*
7096 * case xx:
7097 * c = 99 + <- this indent plus continuation
7098 *-> here;
7099 */
7100 if (lookfor == LOOKFOR_UNTERM
7101 || lookfor == LOOKFOR_ENUM_OR_INIT)
7102 {
7103 if (cont_amount > 0)
7104 amount = cont_amount;
7105 else
7106 amount += ind_continuation;
7107 break;
7108 }
7109
7110 /*
7111 * case xx: <- line up with this case
7112 * x = 333;
7113 * case yy:
7114 */
7115 if ( (iscase && lookfor == LOOKFOR_CASE)
7116 || (iscase && lookfor_break)
7117 || (!iscase && lookfor == LOOKFOR_SCOPEDECL))
7118 {
7119 /*
7120 * Check that this case label is not for another
7121 * switch()
7122 */ /* XXX */
7123 if ((trypos = find_start_brace(ind_maxcomment)) ==
7124 NULL || trypos->lnum == ourscope)
7125 {
7126 amount = get_indent(); /* XXX */
7127 break;
7128 }
7129 continue;
7130 }
7131
7132 n = get_indent_nolabel(curwin->w_cursor.lnum); /* XXX */
7133
7134 /*
7135 * case xx: if (cond) <- line up with this if
7136 * y = y + 1;
7137 * -> s = 99;
7138 *
7139 * case xx:
7140 * if (cond) <- line up with this line
7141 * y = y + 1;
7142 * -> s = 99;
7143 */
7144 if (lookfor == LOOKFOR_TERM)
7145 {
7146 if (n)
7147 amount = n;
7148
7149 if (!lookfor_break)
7150 break;
7151 }
7152
7153 /*
7154 * case xx: x = x + 1; <- line up with this x
7155 * -> y = y + 1;
7156 *
7157 * case xx: if (cond) <- line up with this if
7158 * -> y = y + 1;
7159 */
7160 if (n)
7161 {
7162 amount = n;
7163 l = after_label(ml_get_curline());
7164 if (l != NULL && cin_is_cinword(l))
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007165 {
7166 if (theline[0] == '{')
7167 amount += ind_open_extra;
7168 else
7169 amount += ind_level + ind_no_brace;
7170 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007171 break;
7172 }
7173
7174 /*
7175 * Try to get the indent of a statement before the switch
7176 * label. If nothing is found, line up relative to the
7177 * switch label.
7178 * break; <- may line up with this line
7179 * case xx:
7180 * -> y = 1;
7181 */
7182 scope_amount = get_indent() + (iscase /* XXX */
7183 ? ind_case_code : ind_scopedecl_code);
7184 lookfor = ind_case_break ? LOOKFOR_NOBREAK : LOOKFOR_ANY;
7185 continue;
7186 }
7187
7188 /*
7189 * Looking for a switch() label or C++ scope declaration,
7190 * ignore other lines, skip {}-blocks.
7191 */
7192 if (lookfor == LOOKFOR_CASE || lookfor == LOOKFOR_SCOPEDECL)
7193 {
7194 if (find_last_paren(l, '{', '}') && (trypos =
7195 find_start_brace(ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007196 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007197 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007198 curwin->w_cursor.col = 0;
7199 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007200 continue;
7201 }
7202
7203 /*
7204 * Ignore jump labels with nothing after them.
7205 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007206 if (!ind_js && cin_islabel(ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007207 {
7208 l = after_label(ml_get_curline());
7209 if (l == NULL || cin_nocode(l))
7210 continue;
7211 }
7212
7213 /*
7214 * Ignore #defines, #if, etc.
7215 * Ignore comment and empty lines.
7216 * (need to get the line again, cin_islabel() may have
7217 * unlocked it)
7218 */
7219 l = ml_get_curline();
7220 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum)
7221 || cin_nocode(l))
7222 continue;
7223
7224 /*
7225 * Are we at the start of a cpp base class declaration or
7226 * constructor initialization?
7227 */ /* XXX */
Bram Moolenaar18144c82006-04-12 21:52:12 +00007228 n = FALSE;
7229 if (lookfor != LOOKFOR_TERM && ind_cpp_baseclass > 0)
7230 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00007231 n = cin_is_cpp_baseclass(&col);
Bram Moolenaar18144c82006-04-12 21:52:12 +00007232 l = ml_get_curline();
7233 }
7234 if (n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007235 {
7236 if (lookfor == LOOKFOR_UNTERM)
7237 {
7238 if (cont_amount > 0)
7239 amount = cont_amount;
7240 else
7241 amount += ind_continuation;
7242 }
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007243 else if (theline[0] == '{')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007244 {
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007245 /* Need to find start of the declaration. */
7246 lookfor = LOOKFOR_UNTERM;
7247 ind_continuation = 0;
7248 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007249 }
7250 else
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007251 /* XXX */
7252 amount = get_baseclass_amount(col, ind_maxparen,
7253 ind_maxcomment, ind_cpp_baseclass);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007254 break;
7255 }
7256 else if (lookfor == LOOKFOR_CPP_BASECLASS)
7257 {
7258 /* only look, whether there is a cpp base class
Bram Moolenaar18144c82006-04-12 21:52:12 +00007259 * declaration or initialization before the opening brace.
7260 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007261 if (cin_isterminated(l, TRUE, FALSE))
7262 break;
7263 else
7264 continue;
7265 }
7266
7267 /*
7268 * What happens next depends on the line being terminated.
7269 * If terminated with a ',' only consider it terminating if
Bram Moolenaar25394022007-05-10 19:06:20 +00007270 * there is another unterminated statement behind, eg:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007271 * 123,
7272 * sizeof
7273 * here
7274 * Otherwise check whether it is a enumeration or structure
7275 * initialisation (not indented) or a variable declaration
7276 * (indented).
7277 */
7278 terminated = cin_isterminated(l, FALSE, TRUE);
7279
7280 if (terminated == 0 || (lookfor != LOOKFOR_UNTERM
7281 && terminated == ','))
7282 {
7283 /*
7284 * if we're in the middle of a paren thing,
7285 * go back to the line that starts it so
7286 * we can get the right prevailing indent
7287 * if ( foo &&
7288 * bar )
7289 */
7290 /*
7291 * position the cursor over the rightmost paren, so that
7292 * matching it will take us back to the start of the line.
7293 */
7294 (void)find_last_paren(l, '(', ')');
7295 trypos = find_match_paren(
7296 corr_ind_maxparen(ind_maxparen, &cur_curpos),
7297 ind_maxcomment);
7298
7299 /*
7300 * If we are looking for ',', we also look for matching
7301 * braces.
7302 */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007303 if (trypos == NULL && terminated == ','
7304 && find_last_paren(l, '{', '}'))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007305 trypos = find_start_brace(ind_maxcomment);
7306
7307 if (trypos != NULL)
7308 {
7309 /*
7310 * Check if we are on a case label now. This is
7311 * handled above.
7312 * case xx: if ( asdf &&
7313 * asdf)
7314 */
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007315 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007316 l = ml_get_curline();
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007317 if (cin_iscase(l, FALSE) || cin_isscopedecl(l))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007318 {
7319 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007320 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007321 continue;
7322 }
7323 }
7324
7325 /*
7326 * Skip over continuation lines to find the one to get the
7327 * indent from
7328 * char *usethis = "bla\
7329 * bla",
7330 * here;
7331 */
7332 if (terminated == ',')
7333 {
7334 while (curwin->w_cursor.lnum > 1)
7335 {
7336 l = ml_get(curwin->w_cursor.lnum - 1);
7337 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
7338 break;
7339 --curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007340 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007341 }
7342 }
7343
7344 /*
7345 * Get indent and pointer to text for current line,
7346 * ignoring any jump label. XXX
7347 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007348 if (!ind_js)
7349 cur_amount = skip_label(curwin->w_cursor.lnum,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007350 &l, ind_maxcomment);
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007351 else
7352 cur_amount = get_indent();
Bram Moolenaar071d4272004-06-13 20:20:40 +00007353 /*
7354 * If this is just above the line we are indenting, and it
7355 * starts with a '{', line it up with this line.
7356 * while (not)
7357 * -> {
7358 * }
7359 */
7360 if (terminated != ',' && lookfor != LOOKFOR_TERM
7361 && theline[0] == '{')
7362 {
7363 amount = cur_amount;
7364 /*
7365 * Only add ind_open_extra when the current line
7366 * doesn't start with a '{', which must have a match
7367 * in the same line (scope is the same). Probably:
7368 * { 1, 2 },
7369 * -> { 3, 4 }
7370 */
7371 if (*skipwhite(l) != '{')
7372 amount += ind_open_extra;
7373
7374 if (ind_cpp_baseclass)
7375 {
7376 /* have to look back, whether it is a cpp base
7377 * class declaration or initialization */
7378 lookfor = LOOKFOR_CPP_BASECLASS;
7379 continue;
7380 }
7381 break;
7382 }
7383
7384 /*
7385 * Check if we are after an "if", "while", etc.
7386 * Also allow " } else".
7387 */
7388 if (cin_is_cinword(l) || cin_iselse(skipwhite(l)))
7389 {
7390 /*
7391 * Found an unterminated line after an if (), line up
7392 * with the last one.
7393 * if (cond)
7394 * 100 +
7395 * -> here;
7396 */
7397 if (lookfor == LOOKFOR_UNTERM
7398 || lookfor == LOOKFOR_ENUM_OR_INIT)
7399 {
7400 if (cont_amount > 0)
7401 amount = cont_amount;
7402 else
7403 amount += ind_continuation;
7404 break;
7405 }
7406
7407 /*
7408 * If this is just above the line we are indenting, we
7409 * are finished.
7410 * while (not)
7411 * -> here;
7412 * Otherwise this indent can be used when the line
7413 * before this is terminated.
7414 * yyy;
7415 * if (stat)
7416 * while (not)
7417 * xxx;
7418 * -> here;
7419 */
7420 amount = cur_amount;
7421 if (theline[0] == '{')
7422 amount += ind_open_extra;
7423 if (lookfor != LOOKFOR_TERM)
7424 {
7425 amount += ind_level + ind_no_brace;
7426 break;
7427 }
7428
7429 /*
7430 * Special trick: when expecting the while () after a
7431 * do, line up with the while()
7432 * do
7433 * x = 1;
7434 * -> here
7435 */
7436 l = skipwhite(ml_get_curline());
7437 if (cin_isdo(l))
7438 {
7439 if (whilelevel == 0)
7440 break;
7441 --whilelevel;
7442 }
7443
7444 /*
7445 * When searching for a terminated line, don't use the
7446 * one between the "if" and the "else".
7447 * Need to use the scope of this "else". XXX
7448 * If whilelevel != 0 continue looking for a "do {".
7449 */
7450 if (cin_iselse(l)
7451 && whilelevel == 0
7452 && ((trypos = find_start_brace(ind_maxcomment))
7453 == NULL
7454 || find_match(LOOKFOR_IF, trypos->lnum,
7455 ind_maxparen, ind_maxcomment) == FAIL))
7456 break;
7457 }
7458
7459 /*
7460 * If we're below an unterminated line that is not an
7461 * "if" or something, we may line up with this line or
Bram Moolenaar25394022007-05-10 19:06:20 +00007462 * add something for a continuation line, depending on
Bram Moolenaar071d4272004-06-13 20:20:40 +00007463 * the line before this one.
7464 */
7465 else
7466 {
7467 /*
7468 * Found two unterminated lines on a row, line up with
7469 * the last one.
7470 * c = 99 +
7471 * 100 +
7472 * -> here;
7473 */
7474 if (lookfor == LOOKFOR_UNTERM)
7475 {
7476 /* When line ends in a comma add extra indent */
7477 if (terminated == ',')
7478 amount += ind_continuation;
7479 break;
7480 }
7481
7482 if (lookfor == LOOKFOR_ENUM_OR_INIT)
7483 {
7484 /* Found two lines ending in ',', lineup with the
7485 * lowest one, but check for cpp base class
7486 * declaration/initialization, if it is an
7487 * opening brace or we are looking just for
7488 * enumerations/initializations. */
7489 if (terminated == ',')
7490 {
7491 if (ind_cpp_baseclass == 0)
7492 break;
7493
7494 lookfor = LOOKFOR_CPP_BASECLASS;
7495 continue;
7496 }
7497
7498 /* Ignore unterminated lines in between, but
7499 * reduce indent. */
7500 if (amount > cur_amount)
7501 amount = cur_amount;
7502 }
7503 else
7504 {
7505 /*
7506 * Found first unterminated line on a row, may
7507 * line up with this line, remember its indent
7508 * 100 +
7509 * -> here;
7510 */
7511 amount = cur_amount;
7512
7513 /*
7514 * If previous line ends in ',', check whether we
7515 * are in an initialization or enum
7516 * struct xxx =
7517 * {
7518 * sizeof a,
7519 * 124 };
7520 * or a normal possible continuation line.
7521 * but only, of no other statement has been found
7522 * yet.
7523 */
7524 if (lookfor == LOOKFOR_INITIAL && terminated == ',')
7525 {
7526 lookfor = LOOKFOR_ENUM_OR_INIT;
7527 cont_amount = cin_first_id_amount();
7528 }
7529 else
7530 {
7531 if (lookfor == LOOKFOR_INITIAL
7532 && *l != NUL
7533 && l[STRLEN(l) - 1] == '\\')
7534 /* XXX */
7535 cont_amount = cin_get_equal_amount(
7536 curwin->w_cursor.lnum);
7537 if (lookfor != LOOKFOR_TERM)
7538 lookfor = LOOKFOR_UNTERM;
7539 }
7540 }
7541 }
7542 }
7543
7544 /*
7545 * Check if we are after a while (cond);
7546 * If so: Ignore until the matching "do".
7547 */
7548 /* XXX */
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007549 else if (cin_iswhileofdo_end(terminated, ind_maxparen,
7550 ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007551 {
7552 /*
7553 * Found an unterminated line after a while ();, line up
7554 * with the last one.
7555 * while (cond);
7556 * 100 + <- line up with this one
7557 * -> here;
7558 */
7559 if (lookfor == LOOKFOR_UNTERM
7560 || lookfor == LOOKFOR_ENUM_OR_INIT)
7561 {
7562 if (cont_amount > 0)
7563 amount = cont_amount;
7564 else
7565 amount += ind_continuation;
7566 break;
7567 }
7568
7569 if (whilelevel == 0)
7570 {
7571 lookfor = LOOKFOR_TERM;
7572 amount = get_indent(); /* XXX */
7573 if (theline[0] == '{')
7574 amount += ind_open_extra;
7575 }
7576 ++whilelevel;
7577 }
7578
7579 /*
7580 * We are after a "normal" statement.
7581 * If we had another statement we can stop now and use the
7582 * indent of that other statement.
7583 * Otherwise the indent of the current statement may be used,
7584 * search backwards for the next "normal" statement.
7585 */
7586 else
7587 {
7588 /*
7589 * Skip single break line, if before a switch label. It
7590 * may be lined up with the case label.
7591 */
7592 if (lookfor == LOOKFOR_NOBREAK
7593 && cin_isbreak(skipwhite(ml_get_curline())))
7594 {
7595 lookfor = LOOKFOR_ANY;
7596 continue;
7597 }
7598
7599 /*
7600 * Handle "do {" line.
7601 */
7602 if (whilelevel > 0)
7603 {
7604 l = cin_skipcomment(ml_get_curline());
7605 if (cin_isdo(l))
7606 {
7607 amount = get_indent(); /* XXX */
7608 --whilelevel;
7609 continue;
7610 }
7611 }
7612
7613 /*
7614 * Found a terminated line above an unterminated line. Add
7615 * the amount for a continuation line.
7616 * x = 1;
7617 * y = foo +
7618 * -> here;
7619 * or
7620 * int x = 1;
7621 * int foo,
7622 * -> here;
7623 */
7624 if (lookfor == LOOKFOR_UNTERM
7625 || lookfor == LOOKFOR_ENUM_OR_INIT)
7626 {
7627 if (cont_amount > 0)
7628 amount = cont_amount;
7629 else
7630 amount += ind_continuation;
7631 break;
7632 }
7633
7634 /*
7635 * Found a terminated line above a terminated line or "if"
7636 * etc. line. Use the amount of the line below us.
7637 * x = 1; x = 1;
7638 * if (asdf) y = 2;
7639 * while (asdf) ->here;
7640 * here;
7641 * ->foo;
7642 */
7643 if (lookfor == LOOKFOR_TERM)
7644 {
7645 if (!lookfor_break && whilelevel == 0)
7646 break;
7647 }
7648
7649 /*
7650 * First line above the one we're indenting is terminated.
7651 * To know what needs to be done look further backward for
7652 * a terminated line.
7653 */
7654 else
7655 {
7656 /*
7657 * position the cursor over the rightmost paren, so
7658 * that matching it will take us back to the start of
7659 * the line. Helps for:
7660 * func(asdr,
7661 * asdfasdf);
7662 * here;
7663 */
7664term_again:
7665 l = ml_get_curline();
7666 if (find_last_paren(l, '(', ')')
7667 && (trypos = find_match_paren(ind_maxparen,
7668 ind_maxcomment)) != NULL)
7669 {
7670 /*
7671 * Check if we are on a case label now. This is
7672 * handled above.
7673 * case xx: if ( asdf &&
7674 * asdf)
7675 */
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007676 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007677 l = ml_get_curline();
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007678 if (cin_iscase(l, FALSE) || cin_isscopedecl(l))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007679 {
7680 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007681 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007682 continue;
7683 }
7684 }
7685
7686 /* When aligning with the case statement, don't align
7687 * with a statement after it.
7688 * case 1: { <-- don't use this { position
7689 * stat;
7690 * }
7691 * case 2:
7692 * stat;
7693 * }
7694 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007695 iscase = (ind_keep_case_label && cin_iscase(l, FALSE));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007696
7697 /*
7698 * Get indent and pointer to text for current line,
7699 * ignoring any jump label.
7700 */
7701 amount = skip_label(curwin->w_cursor.lnum,
7702 &l, ind_maxcomment);
7703
7704 if (theline[0] == '{')
7705 amount += ind_open_extra;
7706 /* See remark above: "Only add ind_open_extra.." */
Bram Moolenaar18144c82006-04-12 21:52:12 +00007707 l = skipwhite(l);
7708 if (*l == '{')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007709 amount -= ind_open_extra;
7710 lookfor = iscase ? LOOKFOR_ANY : LOOKFOR_TERM;
7711
7712 /*
Bram Moolenaar18144c82006-04-12 21:52:12 +00007713 * When a terminated line starts with "else" skip to
7714 * the matching "if":
7715 * else 3;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00007716 * indent this;
Bram Moolenaar18144c82006-04-12 21:52:12 +00007717 * Need to use the scope of this "else". XXX
7718 * If whilelevel != 0 continue looking for a "do {".
7719 */
7720 if (lookfor == LOOKFOR_TERM
7721 && *l != '}'
7722 && cin_iselse(l)
7723 && whilelevel == 0)
7724 {
7725 if ((trypos = find_start_brace(ind_maxcomment))
7726 == NULL
7727 || find_match(LOOKFOR_IF, trypos->lnum,
7728 ind_maxparen, ind_maxcomment) == FAIL)
7729 break;
7730 continue;
7731 }
7732
7733 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007734 * If we're at the end of a block, skip to the start of
7735 * that block.
7736 */
7737 curwin->w_cursor.col = 0;
7738 if (*cin_skipcomment(l) == '}'
7739 && (trypos = find_start_brace(ind_maxcomment))
7740 != NULL) /* XXX */
7741 {
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007742 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007743 /* if not "else {" check for terminated again */
7744 /* but skip block for "} else {" */
7745 l = cin_skipcomment(ml_get_curline());
7746 if (*l == '}' || !cin_iselse(l))
7747 goto term_again;
7748 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007749 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007750 }
7751 }
7752 }
7753 }
7754 }
7755 }
7756
7757 /* add extra indent for a comment */
7758 if (cin_iscomment(theline))
7759 amount += ind_comment;
Bram Moolenaar02c707a2010-07-17 17:12:06 +02007760
7761 /* subtract extra left-shift for jump labels */
7762 if (ind_jump_label > 0 && original_line_islabel)
7763 amount -= ind_jump_label;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007764 }
7765
7766 /*
7767 * ok -- we're not inside any sort of structure at all!
7768 *
7769 * this means we're at the top level, and everything should
7770 * basically just match where the previous line is, except
7771 * for the lines immediately following a function declaration,
7772 * which are K&R-style parameters and need to be indented.
7773 */
7774 else
7775 {
7776 /*
7777 * if our line starts with an open brace, forget about any
7778 * prevailing indent and make sure it looks like the start
7779 * of a function
7780 */
7781
7782 if (theline[0] == '{')
7783 {
7784 amount = ind_first_open;
7785 }
7786
7787 /*
7788 * If the NEXT line is a function declaration, the current
7789 * line needs to be indented as a function type spec.
Bram Moolenaar1a89bbe2010-03-02 12:38:22 +01007790 * Don't do this if the current line looks like a comment or if the
7791 * current line is terminated, ie. ends in ';', or if the current line
7792 * contains { or }: "void f() {\n if (1)"
Bram Moolenaar071d4272004-06-13 20:20:40 +00007793 */
7794 else if (cur_curpos.lnum < curbuf->b_ml.ml_line_count
7795 && !cin_nocode(theline)
Bram Moolenaar1a89bbe2010-03-02 12:38:22 +01007796 && vim_strchr(theline, '{') == NULL
7797 && vim_strchr(theline, '}') == NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007798 && !cin_ends_in(theline, (char_u *)":", NULL)
7799 && !cin_ends_in(theline, (char_u *)",", NULL)
7800 && cin_isfuncdecl(NULL, cur_curpos.lnum + 1)
7801 && !cin_isterminated(theline, FALSE, TRUE))
7802 {
7803 amount = ind_func_type;
7804 }
7805 else
7806 {
7807 amount = 0;
7808 curwin->w_cursor = cur_curpos;
7809
7810 /* search backwards until we find something we recognize */
7811
7812 while (curwin->w_cursor.lnum > 1)
7813 {
7814 curwin->w_cursor.lnum--;
7815 curwin->w_cursor.col = 0;
7816
7817 l = ml_get_curline();
7818
7819 /*
7820 * If we're in a comment now, skip to the start of the comment.
7821 */ /* XXX */
7822 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
7823 {
7824 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007825 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007826 continue;
7827 }
7828
7829 /*
Bram Moolenaar18144c82006-04-12 21:52:12 +00007830 * Are we at the start of a cpp base class declaration or
7831 * constructor initialization?
Bram Moolenaar071d4272004-06-13 20:20:40 +00007832 */ /* XXX */
Bram Moolenaar18144c82006-04-12 21:52:12 +00007833 n = FALSE;
7834 if (ind_cpp_baseclass != 0 && theline[0] != '{')
7835 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00007836 n = cin_is_cpp_baseclass(&col);
Bram Moolenaar18144c82006-04-12 21:52:12 +00007837 l = ml_get_curline();
7838 }
7839 if (n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007840 {
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007841 /* XXX */
7842 amount = get_baseclass_amount(col, ind_maxparen,
7843 ind_maxcomment, ind_cpp_baseclass);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007844 break;
7845 }
7846
7847 /*
7848 * Skip preprocessor directives and blank lines.
7849 */
7850 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7851 continue;
7852
7853 if (cin_nocode(l))
7854 continue;
7855
7856 /*
7857 * If the previous line ends in ',', use one level of
7858 * indentation:
7859 * int foo,
7860 * bar;
7861 * do this before checking for '}' in case of eg.
7862 * enum foobar
7863 * {
7864 * ...
7865 * } foo,
7866 * bar;
7867 */
7868 n = 0;
7869 if (cin_ends_in(l, (char_u *)",", NULL)
7870 || (*l != NUL && (n = l[STRLEN(l) - 1]) == '\\'))
7871 {
7872 /* take us back to opening paren */
7873 if (find_last_paren(l, '(', ')')
7874 && (trypos = find_match_paren(ind_maxparen,
7875 ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007876 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007877
7878 /* For a line ending in ',' that is a continuation line go
7879 * back to the first line with a backslash:
7880 * char *foo = "bla\
7881 * bla",
7882 * here;
7883 */
7884 while (n == 0 && curwin->w_cursor.lnum > 1)
7885 {
7886 l = ml_get(curwin->w_cursor.lnum - 1);
7887 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
7888 break;
7889 --curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007890 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007891 }
7892
7893 amount = get_indent(); /* XXX */
7894
7895 if (amount == 0)
7896 amount = cin_first_id_amount();
7897 if (amount == 0)
7898 amount = ind_continuation;
7899 break;
7900 }
7901
7902 /*
7903 * If the line looks like a function declaration, and we're
7904 * not in a comment, put it the left margin.
7905 */
7906 if (cin_isfuncdecl(NULL, cur_curpos.lnum)) /* XXX */
7907 break;
7908 l = ml_get_curline();
7909
7910 /*
7911 * Finding the closing '}' of a previous function. Put
7912 * current line at the left margin. For when 'cino' has "fs".
7913 */
7914 if (*skipwhite(l) == '}')
7915 break;
7916
7917 /* (matching {)
7918 * If the previous line ends on '};' (maybe followed by
7919 * comments) align at column 0. For example:
7920 * char *string_array[] = { "foo",
7921 * / * x * / "b};ar" }; / * foobar * /
7922 */
7923 if (cin_ends_in(l, (char_u *)"};", NULL))
7924 break;
7925
7926 /*
7927 * If the PREVIOUS line is a function declaration, the current
7928 * line (and the ones that follow) needs to be indented as
7929 * parameters.
7930 */
7931 if (cin_isfuncdecl(&l, curwin->w_cursor.lnum))
7932 {
7933 amount = ind_param;
7934 break;
7935 }
7936
7937 /*
7938 * If the previous line ends in ';' and the line before the
7939 * previous line ends in ',' or '\', ident to column zero:
7940 * int foo,
7941 * bar;
7942 * indent_to_0 here;
7943 */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007944 if (cin_ends_in(l, (char_u *)";", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007945 {
7946 l = ml_get(curwin->w_cursor.lnum - 1);
7947 if (cin_ends_in(l, (char_u *)",", NULL)
7948 || (*l != NUL && l[STRLEN(l) - 1] == '\\'))
7949 break;
7950 l = ml_get_curline();
7951 }
7952
7953 /*
7954 * Doesn't look like anything interesting -- so just
7955 * use the indent of this line.
7956 *
7957 * Position the cursor over the rightmost paren, so that
7958 * matching it will take us back to the start of the line.
7959 */
7960 find_last_paren(l, '(', ')');
7961
7962 if ((trypos = find_match_paren(ind_maxparen,
7963 ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007964 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007965 amount = get_indent(); /* XXX */
7966 break;
7967 }
7968
7969 /* add extra indent for a comment */
7970 if (cin_iscomment(theline))
7971 amount += ind_comment;
7972
7973 /* add extra indent if the previous line ended in a backslash:
7974 * "asdfasdf\
7975 * here";
7976 * char *foo = "asdf\
7977 * here";
7978 */
7979 if (cur_curpos.lnum > 1)
7980 {
7981 l = ml_get(cur_curpos.lnum - 1);
7982 if (*l != NUL && l[STRLEN(l) - 1] == '\\')
7983 {
7984 cur_amount = cin_get_equal_amount(cur_curpos.lnum - 1);
7985 if (cur_amount > 0)
7986 amount = cur_amount;
7987 else if (cur_amount == 0)
7988 amount += ind_continuation;
7989 }
7990 }
7991 }
7992 }
7993
7994theend:
7995 /* put the cursor back where it belongs */
7996 curwin->w_cursor = cur_curpos;
7997
7998 vim_free(linecopy);
7999
8000 if (amount < 0)
8001 return 0;
8002 return amount;
8003}
8004
8005 static int
8006find_match(lookfor, ourscope, ind_maxparen, ind_maxcomment)
8007 int lookfor;
8008 linenr_T ourscope;
8009 int ind_maxparen;
8010 int ind_maxcomment;
8011{
8012 char_u *look;
8013 pos_T *theirscope;
8014 char_u *mightbeif;
8015 int elselevel;
8016 int whilelevel;
8017
8018 if (lookfor == LOOKFOR_IF)
8019 {
8020 elselevel = 1;
8021 whilelevel = 0;
8022 }
8023 else
8024 {
8025 elselevel = 0;
8026 whilelevel = 1;
8027 }
8028
8029 curwin->w_cursor.col = 0;
8030
8031 while (curwin->w_cursor.lnum > ourscope + 1)
8032 {
8033 curwin->w_cursor.lnum--;
8034 curwin->w_cursor.col = 0;
8035
8036 look = cin_skipcomment(ml_get_curline());
8037 if (cin_iselse(look)
8038 || cin_isif(look)
8039 || cin_isdo(look) /* XXX */
8040 || cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
8041 {
8042 /*
8043 * if we've gone outside the braces entirely,
8044 * we must be out of scope...
8045 */
8046 theirscope = find_start_brace(ind_maxcomment); /* XXX */
8047 if (theirscope == NULL)
8048 break;
8049
8050 /*
8051 * and if the brace enclosing this is further
8052 * back than the one enclosing the else, we're
8053 * out of luck too.
8054 */
8055 if (theirscope->lnum < ourscope)
8056 break;
8057
8058 /*
8059 * and if they're enclosed in a *deeper* brace,
8060 * then we can ignore it because it's in a
8061 * different scope...
8062 */
8063 if (theirscope->lnum > ourscope)
8064 continue;
8065
8066 /*
8067 * if it was an "else" (that's not an "else if")
8068 * then we need to go back to another if, so
8069 * increment elselevel
8070 */
8071 look = cin_skipcomment(ml_get_curline());
8072 if (cin_iselse(look))
8073 {
8074 mightbeif = cin_skipcomment(look + 4);
8075 if (!cin_isif(mightbeif))
8076 ++elselevel;
8077 continue;
8078 }
8079
8080 /*
8081 * if it was a "while" then we need to go back to
8082 * another "do", so increment whilelevel. XXX
8083 */
8084 if (cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
8085 {
8086 ++whilelevel;
8087 continue;
8088 }
8089
8090 /* If it's an "if" decrement elselevel */
8091 look = cin_skipcomment(ml_get_curline());
8092 if (cin_isif(look))
8093 {
8094 elselevel--;
8095 /*
8096 * When looking for an "if" ignore "while"s that
8097 * get in the way.
8098 */
8099 if (elselevel == 0 && lookfor == LOOKFOR_IF)
8100 whilelevel = 0;
8101 }
8102
8103 /* If it's a "do" decrement whilelevel */
8104 if (cin_isdo(look))
8105 whilelevel--;
8106
8107 /*
8108 * if we've used up all the elses, then
8109 * this must be the if that we want!
8110 * match the indent level of that if.
8111 */
8112 if (elselevel <= 0 && whilelevel <= 0)
8113 {
8114 return OK;
8115 }
8116 }
8117 }
8118 return FAIL;
8119}
8120
8121# if defined(FEAT_EVAL) || defined(PROTO)
8122/*
8123 * Get indent level from 'indentexpr'.
8124 */
8125 int
8126get_expr_indent()
8127{
8128 int indent;
8129 pos_T pos;
8130 int save_State;
Bram Moolenaard1f56e62006-02-22 21:25:37 +00008131 int use_sandbox = was_set_insecurely((char_u *)"indentexpr",
8132 OPT_LOCAL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008133
8134 pos = curwin->w_cursor;
8135 set_vim_var_nr(VV_LNUM, curwin->w_cursor.lnum);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00008136 if (use_sandbox)
8137 ++sandbox;
8138 ++textlock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008139 indent = eval_to_number(curbuf->b_p_inde);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00008140 if (use_sandbox)
8141 --sandbox;
8142 --textlock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008143
8144 /* Restore the cursor position so that 'indentexpr' doesn't need to.
8145 * Pretend to be in Insert mode, allow cursor past end of line for "o"
8146 * command. */
8147 save_State = State;
8148 State = INSERT;
8149 curwin->w_cursor = pos;
8150 check_cursor();
8151 State = save_State;
8152
8153 /* If there is an error, just keep the current indent. */
8154 if (indent < 0)
8155 indent = get_indent();
8156
8157 return indent;
8158}
8159# endif
8160
8161#endif /* FEAT_CINDENT */
8162
8163#if defined(FEAT_LISP) || defined(PROTO)
8164
8165static int lisp_match __ARGS((char_u *p));
8166
8167 static int
8168lisp_match(p)
8169 char_u *p;
8170{
8171 char_u buf[LSIZE];
8172 int len;
8173 char_u *word = p_lispwords;
8174
8175 while (*word != NUL)
8176 {
8177 (void)copy_option_part(&word, buf, LSIZE, ",");
8178 len = (int)STRLEN(buf);
8179 if (STRNCMP(buf, p, len) == 0 && p[len] == ' ')
8180 return TRUE;
8181 }
8182 return FALSE;
8183}
8184
8185/*
8186 * When 'p' is present in 'cpoptions, a Vi compatible method is used.
8187 * The incompatible newer method is quite a bit better at indenting
8188 * code in lisp-like languages than the traditional one; it's still
8189 * mostly heuristics however -- Dirk van Deun, dirk@rave.org
8190 *
8191 * TODO:
8192 * Findmatch() should be adapted for lisp, also to make showmatch
8193 * work correctly: now (v5.3) it seems all C/C++ oriented:
8194 * - it does not recognize the #\( and #\) notations as character literals
8195 * - it doesn't know about comments starting with a semicolon
8196 * - it incorrectly interprets '(' as a character literal
8197 * All this messes up get_lisp_indent in some rare cases.
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008198 * Update from Sergey Khorev:
8199 * I tried to fix the first two issues.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008200 */
8201 int
8202get_lisp_indent()
8203{
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008204 pos_T *pos, realpos, paren;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008205 int amount;
8206 char_u *that;
8207 colnr_T col;
8208 colnr_T firsttry;
8209 int parencount, quotecount;
8210 int vi_lisp;
8211
8212 /* Set vi_lisp to use the vi-compatible method */
8213 vi_lisp = (vim_strchr(p_cpo, CPO_LISP) != NULL);
8214
8215 realpos = curwin->w_cursor;
8216 curwin->w_cursor.col = 0;
8217
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008218 if ((pos = findmatch(NULL, '(')) == NULL)
8219 pos = findmatch(NULL, '[');
8220 else
8221 {
8222 paren = *pos;
8223 pos = findmatch(NULL, '[');
8224 if (pos == NULL || ltp(pos, &paren))
8225 pos = &paren;
8226 }
8227 if (pos != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008228 {
8229 /* Extra trick: Take the indent of the first previous non-white
8230 * line that is at the same () level. */
8231 amount = -1;
8232 parencount = 0;
8233
8234 while (--curwin->w_cursor.lnum >= pos->lnum)
8235 {
8236 if (linewhite(curwin->w_cursor.lnum))
8237 continue;
8238 for (that = ml_get_curline(); *that != NUL; ++that)
8239 {
8240 if (*that == ';')
8241 {
8242 while (*(that + 1) != NUL)
8243 ++that;
8244 continue;
8245 }
8246 if (*that == '\\')
8247 {
8248 if (*(that + 1) != NUL)
8249 ++that;
8250 continue;
8251 }
8252 if (*that == '"' && *(that + 1) != NUL)
8253 {
Bram Moolenaar15ff6c12006-09-15 18:18:09 +00008254 while (*++that && *that != '"')
8255 {
8256 /* skipping escaped characters in the string */
8257 if (*that == '\\')
8258 {
8259 if (*++that == NUL)
8260 break;
8261 if (that[1] == NUL)
8262 {
8263 ++that;
8264 break;
8265 }
8266 }
8267 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008268 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008269 if (*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008270 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008271 else if (*that == ')' || *that == ']')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008272 --parencount;
8273 }
8274 if (parencount == 0)
8275 {
8276 amount = get_indent();
8277 break;
8278 }
8279 }
8280
8281 if (amount == -1)
8282 {
8283 curwin->w_cursor.lnum = pos->lnum;
8284 curwin->w_cursor.col = pos->col;
8285 col = pos->col;
8286
8287 that = ml_get_curline();
8288
8289 if (vi_lisp && get_indent() == 0)
8290 amount = 2;
8291 else
8292 {
8293 amount = 0;
8294 while (*that && col)
8295 {
8296 amount += lbr_chartabsize_adv(&that, (colnr_T)amount);
8297 col--;
8298 }
8299
8300 /*
8301 * Some keywords require "body" indenting rules (the
8302 * non-standard-lisp ones are Scheme special forms):
8303 *
8304 * (let ((a 1)) instead (let ((a 1))
8305 * (...)) of (...))
8306 */
8307
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008308 if (!vi_lisp && (*that == '(' || *that == '[')
8309 && lisp_match(that + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008310 amount += 2;
8311 else
8312 {
8313 that++;
8314 amount++;
8315 firsttry = amount;
8316
8317 while (vim_iswhite(*that))
8318 {
8319 amount += lbr_chartabsize(that, (colnr_T)amount);
8320 ++that;
8321 }
8322
8323 if (*that && *that != ';') /* not a comment line */
8324 {
Bram Moolenaare21877a2008-02-13 09:58:14 +00008325 /* test *that != '(' to accommodate first let/do
Bram Moolenaar071d4272004-06-13 20:20:40 +00008326 * argument if it is more than one line */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008327 if (!vi_lisp && *that != '(' && *that != '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008328 firsttry++;
8329
8330 parencount = 0;
8331 quotecount = 0;
8332
8333 if (vi_lisp
8334 || (*that != '"'
8335 && *that != '\''
8336 && *that != '#'
8337 && (*that < '0' || *that > '9')))
8338 {
8339 while (*that
8340 && (!vim_iswhite(*that)
8341 || quotecount
8342 || parencount)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008343 && (!((*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008344 && !quotecount
8345 && !parencount
8346 && vi_lisp)))
8347 {
8348 if (*that == '"')
8349 quotecount = !quotecount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008350 if ((*that == '(' || *that == '[')
8351 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008352 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008353 if ((*that == ')' || *that == ']')
8354 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008355 --parencount;
8356 if (*that == '\\' && *(that+1) != NUL)
8357 amount += lbr_chartabsize_adv(&that,
8358 (colnr_T)amount);
8359 amount += lbr_chartabsize_adv(&that,
8360 (colnr_T)amount);
8361 }
8362 }
8363 while (vim_iswhite(*that))
8364 {
8365 amount += lbr_chartabsize(that, (colnr_T)amount);
8366 that++;
8367 }
8368 if (!*that || *that == ';')
8369 amount = firsttry;
8370 }
8371 }
8372 }
8373 }
8374 }
8375 else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008376 amount = 0; /* no matching '(' or '[' found, use zero indent */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008377
8378 curwin->w_cursor = realpos;
8379
8380 return amount;
8381}
8382#endif /* FEAT_LISP */
8383
8384 void
8385prepare_to_exit()
8386{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00008387#if defined(SIGHUP) && defined(SIG_IGN)
8388 /* Ignore SIGHUP, because a dropped connection causes a read error, which
8389 * makes Vim exit and then handling SIGHUP causes various reentrance
8390 * problems. */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00008391 signal(SIGHUP, SIG_IGN);
8392#endif
8393
Bram Moolenaar071d4272004-06-13 20:20:40 +00008394#ifdef FEAT_GUI
8395 if (gui.in_use)
8396 {
8397 gui.dying = TRUE;
8398 out_trash(); /* trash any pending output */
8399 }
8400 else
8401#endif
8402 {
8403 windgoto((int)Rows - 1, 0);
8404
8405 /*
8406 * Switch terminal mode back now, so messages end up on the "normal"
8407 * screen (if there are two screens).
8408 */
8409 settmode(TMODE_COOK);
8410#ifdef WIN3264
8411 if (can_end_termcap_mode(FALSE) == TRUE)
8412#endif
8413 stoptermcap();
8414 out_flush();
8415 }
8416}
8417
8418/*
8419 * Preserve files and exit.
8420 * When called IObuff must contain a message.
8421 */
8422 void
8423preserve_exit()
8424{
8425 buf_T *buf;
8426
8427 prepare_to_exit();
8428
Bram Moolenaar4770d092006-01-12 23:22:24 +00008429 /* Setting this will prevent free() calls. That avoids calling free()
8430 * recursively when free() was invoked with a bad pointer. */
8431 really_exiting = TRUE;
8432
Bram Moolenaar071d4272004-06-13 20:20:40 +00008433 out_str(IObuff);
8434 screen_start(); /* don't know where cursor is now */
8435 out_flush();
8436
8437 ml_close_notmod(); /* close all not-modified buffers */
8438
8439 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8440 {
8441 if (buf->b_ml.ml_mfp != NULL && buf->b_ml.ml_mfp->mf_fname != NULL)
8442 {
8443 OUT_STR(_("Vim: preserving files...\n"));
8444 screen_start(); /* don't know where cursor is now */
8445 out_flush();
8446 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
8447 break;
8448 }
8449 }
8450
8451 ml_close_all(FALSE); /* close all memfiles, without deleting */
8452
8453 OUT_STR(_("Vim: Finished.\n"));
8454
8455 getout(1);
8456}
8457
8458/*
8459 * return TRUE if "fname" exists.
8460 */
8461 int
8462vim_fexists(fname)
8463 char_u *fname;
8464{
8465 struct stat st;
8466
8467 if (mch_stat((char *)fname, &st))
8468 return FALSE;
8469 return TRUE;
8470}
8471
8472/*
8473 * Check for CTRL-C pressed, but only once in a while.
8474 * Should be used instead of ui_breakcheck() for functions that check for
8475 * each line in the file. Calling ui_breakcheck() each time takes too much
8476 * time, because it can be a system call.
8477 */
8478
8479#ifndef BREAKCHECK_SKIP
8480# ifdef FEAT_GUI /* assume the GUI only runs on fast computers */
8481# define BREAKCHECK_SKIP 200
8482# else
8483# define BREAKCHECK_SKIP 32
8484# endif
8485#endif
8486
8487static int breakcheck_count = 0;
8488
8489 void
8490line_breakcheck()
8491{
8492 if (++breakcheck_count >= BREAKCHECK_SKIP)
8493 {
8494 breakcheck_count = 0;
8495 ui_breakcheck();
8496 }
8497}
8498
8499/*
8500 * Like line_breakcheck() but check 10 times less often.
8501 */
8502 void
8503fast_breakcheck()
8504{
8505 if (++breakcheck_count >= BREAKCHECK_SKIP * 10)
8506 {
8507 breakcheck_count = 0;
8508 ui_breakcheck();
8509 }
8510}
8511
8512/*
Bram Moolenaard7834d32009-12-02 16:14:36 +00008513 * Invoke expand_wildcards() for one pattern.
8514 * Expand items like "%:h" before the expansion.
8515 * Returns OK or FAIL.
8516 */
8517 int
8518expand_wildcards_eval(pat, num_file, file, flags)
8519 char_u **pat; /* pointer to input pattern */
8520 int *num_file; /* resulting number of files */
8521 char_u ***file; /* array of resulting files */
8522 int flags; /* EW_DIR, etc. */
8523{
8524 int ret = FAIL;
8525 char_u *eval_pat = NULL;
8526 char_u *exp_pat = *pat;
8527 char_u *ignored_msg;
8528 int usedlen;
8529
8530 if (*exp_pat == '%' || *exp_pat == '#' || *exp_pat == '<')
8531 {
8532 ++emsg_off;
8533 eval_pat = eval_vars(exp_pat, exp_pat, &usedlen,
8534 NULL, &ignored_msg, NULL);
8535 --emsg_off;
8536 if (eval_pat != NULL)
8537 exp_pat = concat_str(eval_pat, exp_pat + usedlen);
8538 }
8539
8540 if (exp_pat != NULL)
8541 ret = expand_wildcards(1, &exp_pat, num_file, file, flags);
8542
8543 if (eval_pat != NULL)
8544 {
8545 vim_free(exp_pat);
8546 vim_free(eval_pat);
8547 }
8548
8549 return ret;
8550}
8551
8552/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008553 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching
8554 * 'wildignore'.
Bram Moolenaar9e193ac2010-07-19 23:11:27 +02008555 * Returns OK or FAIL. When FAIL then "num_file" won't be set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008556 */
8557 int
8558expand_wildcards(num_pat, pat, num_file, file, flags)
8559 int num_pat; /* number of input patterns */
8560 char_u **pat; /* array of input patterns */
8561 int *num_file; /* resulting number of files */
8562 char_u ***file; /* array of resulting files */
8563 int flags; /* EW_DIR, etc. */
8564{
8565 int retval;
8566 int i, j;
8567 char_u *p;
8568 int non_suf_match; /* number without matching suffix */
8569
8570 retval = gen_expand_wildcards(num_pat, pat, num_file, file, flags);
8571
8572 /* When keeping all matches, return here */
Bram Moolenaar9e193ac2010-07-19 23:11:27 +02008573 if ((flags & EW_KEEPALL) || retval == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008574 return retval;
8575
8576#ifdef FEAT_WILDIGN
8577 /*
8578 * Remove names that match 'wildignore'.
8579 */
8580 if (*p_wig)
8581 {
8582 char_u *ffname;
8583
8584 /* check all files in (*file)[] */
8585 for (i = 0; i < *num_file; ++i)
8586 {
8587 ffname = FullName_save((*file)[i], FALSE);
8588 if (ffname == NULL) /* out of memory */
8589 break;
8590# ifdef VMS
8591 vms_remove_version(ffname);
8592# endif
8593 if (match_file_list(p_wig, (*file)[i], ffname))
8594 {
8595 /* remove this matching file from the list */
8596 vim_free((*file)[i]);
8597 for (j = i; j + 1 < *num_file; ++j)
8598 (*file)[j] = (*file)[j + 1];
8599 --*num_file;
8600 --i;
8601 }
8602 vim_free(ffname);
8603 }
8604 }
8605#endif
8606
8607 /*
8608 * Move the names where 'suffixes' match to the end.
8609 */
8610 if (*num_file > 1)
8611 {
8612 non_suf_match = 0;
8613 for (i = 0; i < *num_file; ++i)
8614 {
8615 if (!match_suffix((*file)[i]))
8616 {
8617 /*
8618 * Move the name without matching suffix to the front
8619 * of the list.
8620 */
8621 p = (*file)[i];
8622 for (j = i; j > non_suf_match; --j)
8623 (*file)[j] = (*file)[j - 1];
8624 (*file)[non_suf_match++] = p;
8625 }
8626 }
8627 }
8628
8629 return retval;
8630}
8631
8632/*
8633 * Return TRUE if "fname" matches with an entry in 'suffixes'.
8634 */
8635 int
8636match_suffix(fname)
8637 char_u *fname;
8638{
8639 int fnamelen, setsuflen;
8640 char_u *setsuf;
8641#define MAXSUFLEN 30 /* maximum length of a file suffix */
8642 char_u suf_buf[MAXSUFLEN];
8643
8644 fnamelen = (int)STRLEN(fname);
8645 setsuflen = 0;
8646 for (setsuf = p_su; *setsuf; )
8647 {
8648 setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
Bram Moolenaar055a2ba2009-07-14 19:40:21 +00008649 if (setsuflen == 0)
8650 {
8651 char_u *tail = gettail(fname);
8652
8653 /* empty entry: match name without a '.' */
8654 if (vim_strchr(tail, '.') == NULL)
8655 {
8656 setsuflen = 1;
8657 break;
8658 }
8659 }
8660 else
8661 {
8662 if (fnamelen >= setsuflen
8663 && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
8664 (size_t)setsuflen) == 0)
8665 break;
8666 setsuflen = 0;
8667 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008668 }
8669 return (setsuflen != 0);
8670}
8671
8672#if !defined(NO_EXPANDPATH) || defined(PROTO)
8673
8674# ifdef VIM_BACKTICK
8675static int vim_backtick __ARGS((char_u *p));
8676static int expand_backtick __ARGS((garray_T *gap, char_u *pat, int flags));
8677# endif
8678
8679# if defined(MSDOS) || defined(FEAT_GUI_W16) || defined(WIN3264)
8680/*
8681 * File name expansion code for MS-DOS, Win16 and Win32. It's here because
8682 * it's shared between these systems.
8683 */
8684# if defined(DJGPP) || defined(PROTO)
8685# define _cdecl /* DJGPP doesn't have this */
8686# else
8687# ifdef __BORLANDC__
8688# define _cdecl _RTLENTRYF
8689# endif
8690# endif
8691
8692/*
8693 * comparison function for qsort in dos_expandpath()
8694 */
8695 static int _cdecl
8696pstrcmp(const void *a, const void *b)
8697{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00008698 return (pathcmp(*(char **)a, *(char **)b, -1));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008699}
8700
8701# ifndef WIN3264
8702 static void
8703namelowcpy(
8704 char_u *d,
8705 char_u *s)
8706{
8707# ifdef DJGPP
8708 if (USE_LONG_FNAME) /* don't lower case on Windows 95/NT systems */
8709 while (*s)
8710 *d++ = *s++;
8711 else
8712# endif
8713 while (*s)
8714 *d++ = TOLOWER_LOC(*s++);
8715 *d = NUL;
8716}
8717# endif
8718
8719/*
Bram Moolenaar231334e2005-07-25 20:46:57 +00008720 * Recursively expand one path component into all matching files and/or
8721 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008722 * Return the number of matches found.
8723 * "path" has backslashes before chars that are not to be expanded, starting
8724 * at "path[wildoff]".
Bram Moolenaar231334e2005-07-25 20:46:57 +00008725 * Return the number of matches found.
8726 * NOTE: much of this is identical to unix_expandpath(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00008727 */
8728 static int
8729dos_expandpath(
8730 garray_T *gap,
8731 char_u *path,
8732 int wildoff,
Bram Moolenaar231334e2005-07-25 20:46:57 +00008733 int flags, /* EW_* flags */
Bram Moolenaar25394022007-05-10 19:06:20 +00008734 int didstar) /* expanded "**" once already */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008735{
Bram Moolenaar231334e2005-07-25 20:46:57 +00008736 char_u *buf;
8737 char_u *path_end;
8738 char_u *p, *s, *e;
8739 int start_len = gap->ga_len;
8740 char_u *pat;
8741 regmatch_T regmatch;
8742 int starts_with_dot;
8743 int matches;
8744 int len;
8745 int starstar = FALSE;
8746 static int stardepth = 0; /* depth for "**" expansion */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008747#ifdef WIN3264
8748 WIN32_FIND_DATA fb;
8749 HANDLE hFind = (HANDLE)0;
8750# ifdef FEAT_MBYTE
8751 WIN32_FIND_DATAW wfb;
8752 WCHAR *wn = NULL; /* UCS-2 name, NULL when not used. */
8753# endif
8754#else
8755 struct ffblk fb;
8756#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008757 char_u *matchname;
Bram Moolenaar231334e2005-07-25 20:46:57 +00008758 int ok;
8759
8760 /* Expanding "**" may take a long time, check for CTRL-C. */
8761 if (stardepth > 0)
8762 {
8763 ui_breakcheck();
8764 if (got_int)
8765 return 0;
8766 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008767
8768 /* make room for file name */
Bram Moolenaar231334e2005-07-25 20:46:57 +00008769 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008770 if (buf == NULL)
8771 return 0;
8772
8773 /*
8774 * Find the first part in the path name that contains a wildcard or a ~1.
8775 * Copy it into buf, including the preceding characters.
8776 */
8777 p = buf;
8778 s = buf;
8779 e = NULL;
8780 path_end = path;
8781 while (*path_end != NUL)
8782 {
8783 /* May ignore a wildcard that has a backslash before it; it will
8784 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
8785 if (path_end >= path + wildoff && rem_backslash(path_end))
8786 *p++ = *path_end++;
8787 else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
8788 {
8789 if (e != NULL)
8790 break;
8791 s = p + 1;
8792 }
8793 else if (path_end >= path + wildoff
8794 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
8795 e = p;
8796#ifdef FEAT_MBYTE
8797 if (has_mbyte)
8798 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00008799 len = (*mb_ptr2len)(path_end);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008800 STRNCPY(p, path_end, len);
8801 p += len;
8802 path_end += len;
8803 }
8804 else
8805#endif
8806 *p++ = *path_end++;
8807 }
8808 e = p;
8809 *e = NUL;
8810
8811 /* now we have one wildcard component between s and e */
8812 /* Remove backslashes between "wildoff" and the start of the wildcard
8813 * component. */
8814 for (p = buf + wildoff; p < s; ++p)
8815 if (rem_backslash(p))
8816 {
Bram Moolenaar8c8de832008-06-24 22:58:06 +00008817 STRMOVE(p, p + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008818 --e;
8819 --s;
8820 }
8821
Bram Moolenaar231334e2005-07-25 20:46:57 +00008822 /* Check for "**" between "s" and "e". */
8823 for (p = s; p < e; ++p)
8824 if (p[0] == '*' && p[1] == '*')
8825 starstar = TRUE;
8826
Bram Moolenaar071d4272004-06-13 20:20:40 +00008827 starts_with_dot = (*s == '.');
8828 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
8829 if (pat == NULL)
8830 {
8831 vim_free(buf);
8832 return 0;
8833 }
8834
8835 /* compile the regexp into a program */
8836 regmatch.rm_ic = TRUE; /* Always ignore case */
8837 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
8838 vim_free(pat);
8839
8840 if (regmatch.regprog == NULL)
8841 {
8842 vim_free(buf);
8843 return 0;
8844 }
8845
8846 /* remember the pattern or file name being looked for */
8847 matchname = vim_strsave(s);
8848
Bram Moolenaar231334e2005-07-25 20:46:57 +00008849 /* If "**" is by itself, this is the first time we encounter it and more
8850 * is following then find matches without any directory. */
8851 if (!didstar && stardepth < 100 && starstar && e - s == 2
8852 && *path_end == '/')
8853 {
8854 STRCPY(s, path_end + 1);
8855 ++stardepth;
8856 (void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
8857 --stardepth;
8858 }
8859
Bram Moolenaar071d4272004-06-13 20:20:40 +00008860 /* Scan all files in the directory with "dir/ *.*" */
8861 STRCPY(s, "*.*");
8862#ifdef WIN3264
8863# ifdef FEAT_MBYTE
8864 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
8865 {
8866 /* The active codepage differs from 'encoding'. Attempt using the
8867 * wide function. If it fails because it is not implemented fall back
8868 * to the non-wide version (for Windows 98) */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00008869 wn = enc_to_utf16(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008870 if (wn != NULL)
8871 {
8872 hFind = FindFirstFileW(wn, &wfb);
8873 if (hFind == INVALID_HANDLE_VALUE
8874 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
8875 {
8876 vim_free(wn);
8877 wn = NULL;
8878 }
8879 }
8880 }
8881
8882 if (wn == NULL)
8883# endif
8884 hFind = FindFirstFile(buf, &fb);
8885 ok = (hFind != INVALID_HANDLE_VALUE);
8886#else
8887 /* If we are expanding wildcards we try both files and directories */
8888 ok = (findfirst((char *)buf, &fb,
8889 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
8890#endif
8891
8892 while (ok)
8893 {
8894#ifdef WIN3264
8895# ifdef FEAT_MBYTE
8896 if (wn != NULL)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00008897 p = utf16_to_enc(wfb.cFileName, NULL); /* p is allocated here */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008898 else
8899# endif
8900 p = (char_u *)fb.cFileName;
8901#else
8902 p = (char_u *)fb.ff_name;
8903#endif
8904 /* Ignore entries starting with a dot, unless when asked for. Accept
8905 * all entries found with "matchname". */
8906 if ((p[0] != '.' || starts_with_dot)
8907 && (matchname == NULL
8908 || vim_regexec(&regmatch, p, (colnr_T)0)))
8909 {
8910#ifdef WIN3264
8911 STRCPY(s, p);
8912#else
8913 namelowcpy(s, p);
8914#endif
8915 len = (int)STRLEN(buf);
Bram Moolenaar231334e2005-07-25 20:46:57 +00008916
8917 if (starstar && stardepth < 100)
8918 {
8919 /* For "**" in the pattern first go deeper in the tree to
8920 * find matches. */
8921 STRCPY(buf + len, "/**");
8922 STRCPY(buf + len + 3, path_end);
8923 ++stardepth;
8924 (void)dos_expandpath(gap, buf, len + 1, flags, TRUE);
8925 --stardepth;
8926 }
8927
Bram Moolenaar071d4272004-06-13 20:20:40 +00008928 STRCPY(buf + len, path_end);
8929 if (mch_has_exp_wildcard(path_end))
8930 {
8931 /* need to expand another component of the path */
8932 /* remove backslashes for the remaining components only */
Bram Moolenaar231334e2005-07-25 20:46:57 +00008933 (void)dos_expandpath(gap, buf, len + 1, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008934 }
8935 else
8936 {
8937 /* no more wildcards, check if there is a match */
8938 /* remove backslashes for the remaining components only */
8939 if (*path_end != 0)
8940 backslash_halve(buf + len + 1);
8941 if (mch_getperm(buf) >= 0) /* add existing file */
8942 addfile(gap, buf, flags);
8943 }
8944 }
8945
8946#ifdef WIN3264
8947# ifdef FEAT_MBYTE
8948 if (wn != NULL)
8949 {
8950 vim_free(p);
8951 ok = FindNextFileW(hFind, &wfb);
8952 }
8953 else
8954# endif
8955 ok = FindNextFile(hFind, &fb);
8956#else
8957 ok = (findnext(&fb) == 0);
8958#endif
8959
8960 /* If no more matches and no match was used, try expanding the name
8961 * itself. Finds the long name of a short filename. */
8962 if (!ok && matchname != NULL && gap->ga_len == start_len)
8963 {
8964 STRCPY(s, matchname);
8965#ifdef WIN3264
8966 FindClose(hFind);
8967# ifdef FEAT_MBYTE
8968 if (wn != NULL)
8969 {
8970 vim_free(wn);
Bram Moolenaar36f692d2008-11-20 16:10:17 +00008971 wn = enc_to_utf16(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008972 if (wn != NULL)
8973 hFind = FindFirstFileW(wn, &wfb);
8974 }
8975 if (wn == NULL)
8976# endif
8977 hFind = FindFirstFile(buf, &fb);
8978 ok = (hFind != INVALID_HANDLE_VALUE);
8979#else
8980 ok = (findfirst((char *)buf, &fb,
8981 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
8982#endif
8983 vim_free(matchname);
8984 matchname = NULL;
8985 }
8986 }
8987
8988#ifdef WIN3264
8989 FindClose(hFind);
8990# ifdef FEAT_MBYTE
8991 vim_free(wn);
8992# endif
8993#endif
8994 vim_free(buf);
8995 vim_free(regmatch.regprog);
8996 vim_free(matchname);
8997
8998 matches = gap->ga_len - start_len;
8999 if (matches > 0)
9000 qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
9001 sizeof(char_u *), pstrcmp);
9002 return matches;
9003}
9004
9005 int
9006mch_expandpath(
9007 garray_T *gap,
9008 char_u *path,
9009 int flags) /* EW_* flags */
9010{
Bram Moolenaar231334e2005-07-25 20:46:57 +00009011 return dos_expandpath(gap, path, 0, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009012}
9013# endif /* MSDOS || FEAT_GUI_W16 || WIN3264 */
9014
Bram Moolenaar231334e2005-07-25 20:46:57 +00009015#if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
9016 || defined(PROTO)
9017/*
9018 * Unix style wildcard expansion code.
9019 * It's here because it's used both for Unix and Mac.
9020 */
9021static int pstrcmp __ARGS((const void *, const void *));
9022
9023 static int
9024pstrcmp(a, b)
9025 const void *a, *b;
9026{
9027 return (pathcmp(*(char **)a, *(char **)b, -1));
9028}
9029
9030/*
9031 * Recursively expand one path component into all matching files and/or
9032 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
9033 * "path" has backslashes before chars that are not to be expanded, starting
9034 * at "path + wildoff".
9035 * Return the number of matches found.
9036 * NOTE: much of this is identical to dos_expandpath(), keep in sync!
9037 */
9038 int
9039unix_expandpath(gap, path, wildoff, flags, didstar)
9040 garray_T *gap;
9041 char_u *path;
9042 int wildoff;
9043 int flags; /* EW_* flags */
9044 int didstar; /* expanded "**" once already */
9045{
9046 char_u *buf;
9047 char_u *path_end;
9048 char_u *p, *s, *e;
9049 int start_len = gap->ga_len;
9050 char_u *pat;
9051 regmatch_T regmatch;
9052 int starts_with_dot;
9053 int matches;
9054 int len;
9055 int starstar = FALSE;
9056 static int stardepth = 0; /* depth for "**" expansion */
9057
9058 DIR *dirp;
9059 struct dirent *dp;
9060
9061 /* Expanding "**" may take a long time, check for CTRL-C. */
9062 if (stardepth > 0)
9063 {
9064 ui_breakcheck();
9065 if (got_int)
9066 return 0;
9067 }
9068
9069 /* make room for file name */
9070 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
9071 if (buf == NULL)
9072 return 0;
9073
9074 /*
9075 * Find the first part in the path name that contains a wildcard.
9076 * Copy it into "buf", including the preceding characters.
9077 */
9078 p = buf;
9079 s = buf;
9080 e = NULL;
9081 path_end = path;
9082 while (*path_end != NUL)
9083 {
9084 /* May ignore a wildcard that has a backslash before it; it will
9085 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
9086 if (path_end >= path + wildoff && rem_backslash(path_end))
9087 *p++ = *path_end++;
9088 else if (*path_end == '/')
9089 {
9090 if (e != NULL)
9091 break;
9092 s = p + 1;
9093 }
9094 else if (path_end >= path + wildoff
9095 && vim_strchr((char_u *)"*?[{~$", *path_end) != NULL)
9096 e = p;
9097#ifdef FEAT_MBYTE
9098 if (has_mbyte)
9099 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00009100 len = (*mb_ptr2len)(path_end);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009101 STRNCPY(p, path_end, len);
9102 p += len;
9103 path_end += len;
9104 }
9105 else
9106#endif
9107 *p++ = *path_end++;
9108 }
9109 e = p;
9110 *e = NUL;
9111
9112 /* now we have one wildcard component between "s" and "e" */
9113 /* Remove backslashes between "wildoff" and the start of the wildcard
9114 * component. */
9115 for (p = buf + wildoff; p < s; ++p)
9116 if (rem_backslash(p))
9117 {
Bram Moolenaar8c8de832008-06-24 22:58:06 +00009118 STRMOVE(p, p + 1);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009119 --e;
9120 --s;
9121 }
9122
9123 /* Check for "**" between "s" and "e". */
9124 for (p = s; p < e; ++p)
9125 if (p[0] == '*' && p[1] == '*')
9126 starstar = TRUE;
9127
9128 /* convert the file pattern to a regexp pattern */
9129 starts_with_dot = (*s == '.');
9130 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
9131 if (pat == NULL)
9132 {
9133 vim_free(buf);
9134 return 0;
9135 }
9136
9137 /* compile the regexp into a program */
Bram Moolenaarcc016f52005-12-10 20:23:46 +00009138#ifdef CASE_INSENSITIVE_FILENAME
Bram Moolenaar231334e2005-07-25 20:46:57 +00009139 regmatch.rm_ic = TRUE; /* Behave like Terminal.app */
9140#else
9141 regmatch.rm_ic = FALSE; /* Don't ever ignore case */
9142#endif
9143 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
9144 vim_free(pat);
9145
9146 if (regmatch.regprog == NULL)
9147 {
9148 vim_free(buf);
9149 return 0;
9150 }
9151
9152 /* If "**" is by itself, this is the first time we encounter it and more
9153 * is following then find matches without any directory. */
9154 if (!didstar && stardepth < 100 && starstar && e - s == 2
9155 && *path_end == '/')
9156 {
9157 STRCPY(s, path_end + 1);
9158 ++stardepth;
9159 (void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
9160 --stardepth;
9161 }
9162
9163 /* open the directory for scanning */
9164 *s = NUL;
9165 dirp = opendir(*buf == NUL ? "." : (char *)buf);
9166
9167 /* Find all matching entries */
9168 if (dirp != NULL)
9169 {
9170 for (;;)
9171 {
9172 dp = readdir(dirp);
9173 if (dp == NULL)
9174 break;
9175 if ((dp->d_name[0] != '.' || starts_with_dot)
9176 && vim_regexec(&regmatch, (char_u *)dp->d_name, (colnr_T)0))
9177 {
9178 STRCPY(s, dp->d_name);
9179 len = STRLEN(buf);
9180
9181 if (starstar && stardepth < 100)
9182 {
9183 /* For "**" in the pattern first go deeper in the tree to
9184 * find matches. */
9185 STRCPY(buf + len, "/**");
9186 STRCPY(buf + len + 3, path_end);
9187 ++stardepth;
9188 (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
9189 --stardepth;
9190 }
9191
9192 STRCPY(buf + len, path_end);
9193 if (mch_has_exp_wildcard(path_end)) /* handle more wildcards */
9194 {
9195 /* need to expand another component of the path */
9196 /* remove backslashes for the remaining components only */
9197 (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
9198 }
9199 else
9200 {
9201 /* no more wildcards, check if there is a match */
9202 /* remove backslashes for the remaining components only */
9203 if (*path_end != NUL)
9204 backslash_halve(buf + len + 1);
9205 if (mch_getperm(buf) >= 0) /* add existing file */
9206 {
Bram Moolenaar95e9b492006-03-15 23:04:43 +00009207#ifdef MACOS_CONVERT
Bram Moolenaar231334e2005-07-25 20:46:57 +00009208 size_t precomp_len = STRLEN(buf)+1;
9209 char_u *precomp_buf =
9210 mac_precompose_path(buf, precomp_len, &precomp_len);
Bram Moolenaar95e9b492006-03-15 23:04:43 +00009211
Bram Moolenaar231334e2005-07-25 20:46:57 +00009212 if (precomp_buf)
9213 {
9214 mch_memmove(buf, precomp_buf, precomp_len);
9215 vim_free(precomp_buf);
9216 }
9217#endif
9218 addfile(gap, buf, flags);
9219 }
9220 }
9221 }
9222 }
9223
9224 closedir(dirp);
9225 }
9226
9227 vim_free(buf);
9228 vim_free(regmatch.regprog);
9229
9230 matches = gap->ga_len - start_len;
9231 if (matches > 0)
9232 qsort(((char_u **)gap->ga_data) + start_len, matches,
9233 sizeof(char_u *), pstrcmp);
9234 return matches;
9235}
9236#endif
9237
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009238#if defined(FEAT_SEARCHPATH)
9239static int find_previous_pathsep __ARGS((char_u *path, char_u **psep));
9240static int is_unique __ARGS((char_u *maybe_unique, garray_T *gap, int i));
Bram Moolenaar162bd912010-07-28 22:29:10 +02009241static void expand_path_option __ARGS((char_u *curdir, garray_T *gap));
9242static char_u *get_path_cutoff __ARGS((char_u *fname, garray_T *gap));
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009243static void uniquefy_paths __ARGS((garray_T *gap, char_u *pattern));
9244static int expand_in_path __ARGS((garray_T *gap, char_u *pattern, int flags));
9245
9246/*
9247 * Moves psep to the previous path separator in path, starting from the
9248 * end of path.
9249 * Returns FAIL is psep ends up at the beginning of path.
9250 */
9251 static int
9252find_previous_pathsep(path, psep)
9253 char_u *path;
9254 char_u **psep;
9255{
9256 /* skip the current separator */
9257 if (*psep > path && vim_ispathsep(**psep))
9258 (*psep)--;
9259
9260 /* find the previous separator */
9261 while (*psep > path && !vim_ispathsep(**psep))
9262 (*psep)--;
9263
9264 if (*psep != path && vim_ispathsep(**psep))
9265 return OK;
9266
9267 return FAIL;
9268}
9269
9270/*
Bram Moolenaar162bd912010-07-28 22:29:10 +02009271 * Returns TRUE if "maybe_unique" is unique wrt other_paths in gap.
9272 * "maybe_unique" is the end portion of ((char_u **)gap->ga_data)[i].
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009273 */
9274 static int
9275is_unique(maybe_unique, gap, i)
9276 char_u *maybe_unique;
9277 garray_T *gap;
9278 int i;
9279{
9280 int j;
9281 int candidate_len;
9282 int other_path_len;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009283 char_u **other_paths = (char_u **)gap->ga_data;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009284
9285 for (j = 0; j < gap->ga_len && !got_int; j++)
9286 {
9287 ui_breakcheck();
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009288 if (j == i)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009289 continue; /* don't compare it with itself */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009290
Bram Moolenaar624c7aa2010-07-16 20:38:52 +02009291 candidate_len = (int)STRLEN(maybe_unique);
9292 other_path_len = (int)STRLEN(other_paths[j]);
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009293 if (other_path_len < candidate_len)
9294 continue; /* it's different */
9295
Bram Moolenaar162bd912010-07-28 22:29:10 +02009296 if (fnamecmp(maybe_unique, gettail(other_paths[j])) == 0)
9297 return FALSE; /* match */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009298 }
9299
Bram Moolenaar162bd912010-07-28 22:29:10 +02009300 return TRUE; /* no match found */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009301}
9302
9303/*
Bram Moolenaar1a509df2010-08-01 17:59:57 +02009304 * Split the 'path' option into an array of strings in garray_T. Relative
Bram Moolenaar162bd912010-07-28 22:29:10 +02009305 * paths are expanded to their equivalent fullpath. This includes the "."
9306 * (relative to current buffer directory) and empty path (relative to current
9307 * directory) notations.
9308 *
9309 * TODO: handle upward search (;) and path limiter (**N) notations by
9310 * expanding each into their equivalent path(s).
9311 */
9312 static void
9313expand_path_option(curdir, gap)
9314 char_u *curdir;
9315 garray_T *gap;
9316{
9317 char_u *path_option = *curbuf->b_p_path == NUL
9318 ? p_path : curbuf->b_p_path;
9319 char_u *buf;
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009320 char_u *p;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009321
9322 ga_init2(gap, (int)sizeof(char_u *), 1);
9323
9324 if ((buf = alloc((int)(MAXPATHL))) == NULL)
9325 return;
9326
9327 while (*path_option != NUL)
9328 {
9329 copy_option_part(&path_option, buf, MAXPATHL, " ,");
9330
9331 if (STRCMP(buf, ".") == 0) /* relative to current buffer */
9332 {
9333 if (curbuf->b_ffname == NULL)
9334 continue;
9335 STRCPY(buf, curbuf->b_ffname);
9336 *gettail(buf) = NUL;
9337 }
9338 else if (buf[0] == NUL) /* relative to current directory */
9339 STRCPY(buf, curdir);
9340 else if (!mch_isFullName(buf))
9341 {
9342 /* Expand relative path to their full path equivalent */
Bram Moolenaar30a86352010-07-29 23:10:40 +02009343 int curdir_len = (int)STRLEN(curdir);
9344 int buf_len = (int)STRLEN(buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009345
9346 if (curdir_len + buf_len + 3 > MAXPATHL)
9347 continue;
9348 STRMOVE(buf + curdir_len + 1, buf);
9349 STRCPY(buf, curdir);
Bram Moolenaar57adda12010-08-03 22:11:29 +02009350 buf[curdir_len] = PATHSEP;
9351 /*
9352 * 'path' may have "./baz" as one of the items.
9353 * If curdir is "/foo/bar", p will end up being "/foo/bar/./baz".
9354 * Simplify it.
9355 */
9356 simplify_filename(buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009357 }
9358
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009359 if (ga_grow(gap, 1) == FAIL)
9360 break;
9361 p = vim_strsave(buf);
9362 if (p == NULL)
9363 break;
9364 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009365 }
9366
9367 vim_free(buf);
9368}
9369
9370/*
9371 * Returns a pointer to the file or directory name in fname that matches the
9372 * longest path in gap, or NULL if there is no match. For example:
9373 *
9374 * path: /foo/bar/baz
9375 * fname: /foo/bar/baz/quux.txt
9376 * returns: ^this
9377 */
9378 static char_u *
9379get_path_cutoff(fname, gap)
9380 char_u *fname;
9381 garray_T *gap;
9382{
9383 int i;
9384 int maxlen = 0;
9385 char_u **path_part = (char_u **)gap->ga_data;
9386 char_u *cutoff = NULL;
9387
9388 for (i = 0; i < gap->ga_len; i++)
9389 {
9390 int j = 0;
9391
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009392 while ((fname[j] == path_part[i][j]
9393#if defined(WIN3264)
9394 || (vim_ispathsep(fname[j]) && vim_ispathsep(path_part[i][j]))
9395#endif
9396 ) && fname[j] != NUL && path_part[i][j] != NUL)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009397 j++;
9398 if (j > maxlen)
9399 {
9400 maxlen = j;
9401 cutoff = &fname[j];
9402 }
9403 }
9404
9405 /* Skip to the file or directory name */
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009406 if (cutoff != NULL)
9407 while (
9408#if defined(WIN3264)
9409 *cutoff == '/'
9410#else
9411 vim_ispathsep(*cutoff)
9412#endif
9413 )
9414 mb_ptr_adv(cutoff);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009415
9416 return cutoff;
9417}
9418
9419/*
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009420 * Sorts, removes duplicates and modifies all the fullpath names in gap so that
9421 * they are unique with respect to each other while conserving the part that
9422 * matches the pattern. Beware, this is at least O(n^2) wrt gap->ga_len.
9423 */
9424 static void
9425uniquefy_paths(gap, pattern)
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +02009426 garray_T *gap;
9427 char_u *pattern;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009428{
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +02009429 int i;
9430 int len;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009431 char_u **fnames = (char_u **)gap->ga_data;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009432 int sort_again = 0;
9433 char_u *pat;
9434 char_u *file_pattern;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009435 char_u *curdir = NULL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009436 regmatch_T regmatch;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009437 garray_T path_ga;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009438
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009439 sort_strings(fnames, gap->ga_len);
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +02009440 remove_duplicates(gap);
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009441
9442 /*
9443 * We need to prepend a '*' at the beginning of file_pattern so that the
9444 * regex matches anywhere in the path. FIXME: is this valid for all
Bram Moolenaarb31e4382010-07-24 16:01:56 +02009445 * possible patterns?
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009446 */
Bram Moolenaar624c7aa2010-07-16 20:38:52 +02009447 len = (int)STRLEN(pattern);
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009448 file_pattern = alloc(len + 2);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009449 if (file_pattern == NULL)
9450 return;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009451 file_pattern[0] = '*';
Bram Moolenaar162bd912010-07-28 22:29:10 +02009452 file_pattern[1] = NUL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009453 STRCAT(file_pattern, pattern);
9454 pat = file_pat_to_reg_pat(file_pattern, NULL, NULL, TRUE);
9455 vim_free(file_pattern);
Bram Moolenaarb31e4382010-07-24 16:01:56 +02009456 if (pat == NULL)
9457 return;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009458
Bram Moolenaarb31e4382010-07-24 16:01:56 +02009459 regmatch.rm_ic = TRUE; /* always ignore case */
9460 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
9461 vim_free(pat);
9462 if (regmatch.regprog == NULL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009463 return;
9464
Bram Moolenaar162bd912010-07-28 22:29:10 +02009465 if ((curdir = alloc((int)(MAXPATHL))) == NULL)
9466 return;
9467 mch_dirname(curdir, MAXPATHL);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009468
9469 expand_path_option(curdir, &path_ga);
9470
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009471 for (i = 0; i < gap->ga_len; i++)
9472 {
Bram Moolenaar162bd912010-07-28 22:29:10 +02009473 char_u *path = fnames[i];
9474 int is_in_curdir;
9475 char_u *dir_end = gettail(path);
9476
Bram Moolenaar624c7aa2010-07-16 20:38:52 +02009477 len = (int)STRLEN(path);
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009478 while (dir_end > path &&
9479#if defined(WIN3264)
9480 *dir_end != '/'
9481#else
9482 !vim_ispathsep(*dir_end)
9483#endif
9484 )
Bram Moolenaar162bd912010-07-28 22:29:10 +02009485 mb_ptr_back(path, dir_end);
9486 is_in_curdir = STRNCMP(curdir, path, dir_end - path) == 0
9487 && curdir[dir_end - path] == NUL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009488
Bram Moolenaar162bd912010-07-28 22:29:10 +02009489 /*
9490 * If the file is in the current directory,
9491 * and it is not unique,
9492 * reduce it to ./{filename}
9493 * FIXME ^ Is this portable?
9494 */
9495 if (is_in_curdir)
9496 {
9497 char_u *rel_path;
9498 char_u *short_name = shorten_fname(path, curdir);
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009499
Bram Moolenaar162bd912010-07-28 22:29:10 +02009500 if (short_name == NULL)
9501 short_name = path;
9502 if (is_unique(short_name, gap, i))
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009503 {
Bram Moolenaar162bd912010-07-28 22:29:10 +02009504 STRMOVE(path, short_name);
9505 continue;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009506 }
Bram Moolenaar162bd912010-07-28 22:29:10 +02009507
9508 rel_path = alloc((int)(STRLEN(short_name)
9509 + STRLEN(PATHSEPSTR) + 2));
9510 if (rel_path == NULL)
9511 goto theend;
9512
9513 /* FIXME Is "." a portable way of denoting the current directory? */
9514 STRCPY(rel_path, ".");
9515 add_pathsep(rel_path);
9516 STRCAT(rel_path, short_name);
9517
9518 if (len < (int)STRLEN(rel_path))
9519 {
9520 vim_free(fnames[i]);
9521 fnames[i] = alloc((int)(STRLEN(rel_path) + 1));
9522 if (fnames[i] == NULL)
9523 {
9524 vim_free(rel_path);
9525 goto theend;
9526 }
9527 }
9528
9529 STRCPY(fnames[i], rel_path);
9530 vim_free(rel_path);
9531 sort_again = 1;
9532 }
9533 else
9534 {
9535 /* Shorten the filename while maintaining its uniqueness */
9536 char_u *pathsep_p;
9537 char_u *path_cutoff = get_path_cutoff(path, &path_ga);
9538
9539 /* we start at the end of the path */
9540 pathsep_p = path + len - 1;
9541
9542 while (find_previous_pathsep(path, &pathsep_p))
9543 if (vim_regexec(&regmatch, pathsep_p + 1, (colnr_T)0)
9544 && is_unique(pathsep_p + 1, gap, i)
9545 && path_cutoff != NULL && pathsep_p + 1 >= path_cutoff)
9546 {
9547 sort_again = 1;
9548 mch_memmove(path, pathsep_p + 1, STRLEN(pathsep_p));
9549 break;
9550 }
9551 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009552 }
9553
Bram Moolenaar162bd912010-07-28 22:29:10 +02009554theend:
9555 vim_free(curdir);
9556 ga_clear_strings(&path_ga);
Bram Moolenaarb31e4382010-07-24 16:01:56 +02009557 vim_free(regmatch.regprog);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009558
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009559 if (sort_again)
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +02009560 {
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009561 sort_strings(fnames, gap->ga_len);
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +02009562 remove_duplicates(gap);
9563 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009564}
9565
9566/*
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009567 * Calls globpath() or mch_expandpath() with 'path' values for the given
9568 * pattern and stores the result in gap.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009569 * Returns the total number of matches.
9570 */
9571 static int
9572expand_in_path(gap, pattern, flags)
9573 garray_T *gap;
9574 char_u *pattern;
9575 int flags; /* EW_* flags */
9576{
Bram Moolenaar162bd912010-07-28 22:29:10 +02009577 char_u **path_list;
9578 char_u *curdir;
9579 garray_T path_ga;
9580 int i;
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009581# ifdef WIN3264
9582 char_u *file_pattern;
9583# else
9584 char_u *files = NULL;
9585 char_u *s; /* start */
9586 char_u *e; /* end */
9587 char_u *paths = NULL;
9588# endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009589
Bram Moolenaar7f0f6212010-08-03 22:21:00 +02009590 if ((curdir = alloc((unsigned)MAXPATHL)) == NULL)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009591 return 0;
9592 mch_dirname(curdir, MAXPATHL);
9593
9594 expand_path_option(curdir, &path_ga);
9595 vim_free(curdir);
9596 path_list = (char_u **)(path_ga.ga_data);
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009597# ifdef WIN3264
Bram Moolenaar7f0f6212010-08-03 22:21:00 +02009598 if ((file_pattern = alloc((unsigned)MAXPATHL)) == NULL)
9599 return 0;
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009600 for (i = 0; i < path_ga.ga_len; i++)
9601 {
9602 if (STRLEN(path_list[i]) + STRLEN(pattern) + 2 > MAXPATHL)
9603 continue;
9604 STRCPY(file_pattern, path_list[i]);
9605 STRCAT(file_pattern, "/");
9606 STRCAT(file_pattern, pattern);
9607 mch_expandpath(gap, file_pattern, EW_DIR|EW_ADDSLASH|EW_FILE);
9608 }
Bram Moolenaar7f0f6212010-08-03 22:21:00 +02009609 vim_free(file_pattern);
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009610# else
Bram Moolenaar162bd912010-07-28 22:29:10 +02009611 for (i = 0; i < path_ga.ga_len; i++)
9612 {
9613 if (paths == NULL)
9614 {
Bram Moolenaar7f0f6212010-08-03 22:21:00 +02009615 if ((paths = alloc((unsigned)(STRLEN(path_list[i]) + 1))) == NULL)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009616 return 0;
9617 STRCPY(paths, path_list[i]);
9618 }
9619 else
9620 {
9621 if ((paths = realloc(paths, (int)(STRLEN(paths)
9622 + STRLEN(path_list[i]) + 2))) == NULL)
9623 return 0;
9624 STRCAT(paths, ",");
9625 STRCAT(paths, path_list[i]);
9626 }
9627 }
9628
9629 files = globpath(paths, pattern, 0);
9630 vim_free(paths);
9631
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009632 if (files == NULL)
9633 return 0;
9634
9635 /* Copy each path in files into gap */
9636 s = e = files;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009637 while (*s != NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009638 {
Bram Moolenaar162bd912010-07-28 22:29:10 +02009639 while (*e != '\n' && *e != NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009640 e++;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009641 if (*e == NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009642 {
9643 addfile(gap, s, flags);
9644 break;
9645 }
9646 else
9647 {
9648 /* *e is '\n' */
Bram Moolenaar162bd912010-07-28 22:29:10 +02009649 *e = NUL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009650 addfile(gap, s, flags);
9651 e++;
9652 s = e;
9653 }
9654 }
9655
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009656 vim_free(files);
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009657# endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009658
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009659 return gap->ga_len;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009660}
9661#endif
9662
Bram Moolenaar1587a1e2010-07-29 20:59:59 +02009663#if defined(FEAT_SEARCHPATH) || defined(FEAT_CMDL_COMPL) || defined(PROTO)
9664/*
9665 * Remove adjacent duplicate entries from "gap", which is a list of file names
9666 * in allocated memory.
9667 */
9668 void
9669remove_duplicates(gap)
9670 garray_T *gap;
9671{
9672 int i;
9673 int j;
9674 char_u **fnames = (char_u **)gap->ga_data;
9675
9676 for (i = gap->ga_len - 1; i > 0; --i)
9677 if (fnamecmp(fnames[i - 1], fnames[i]) == 0)
9678 {
9679 vim_free(fnames[i]);
9680 for (j = i + 1; j < gap->ga_len; ++j)
9681 fnames[j - 1] = fnames[j];
9682 --gap->ga_len;
9683 }
9684}
9685#endif
9686
Bram Moolenaar071d4272004-06-13 20:20:40 +00009687/*
9688 * Generic wildcard expansion code.
9689 *
9690 * Characters in "pat" that should not be expanded must be preceded with a
9691 * backslash. E.g., "/path\ with\ spaces/my\*star*"
9692 *
9693 * Return FAIL when no single file was found. In this case "num_file" is not
9694 * set, and "file" may contain an error message.
9695 * Return OK when some files found. "num_file" is set to the number of
9696 * matches, "file" to the array of matches. Call FreeWild() later.
9697 */
9698 int
9699gen_expand_wildcards(num_pat, pat, num_file, file, flags)
9700 int num_pat; /* number of input patterns */
9701 char_u **pat; /* array of input patterns */
9702 int *num_file; /* resulting number of files */
9703 char_u ***file; /* array of resulting files */
9704 int flags; /* EW_* flags */
9705{
9706 int i;
9707 garray_T ga;
9708 char_u *p;
9709 static int recursive = FALSE;
9710 int add_pat;
9711
9712 /*
9713 * expand_env() is called to expand things like "~user". If this fails,
9714 * it calls ExpandOne(), which brings us back here. In this case, always
9715 * call the machine specific expansion function, if possible. Otherwise,
9716 * return FAIL.
9717 */
9718 if (recursive)
9719#ifdef SPECIAL_WILDCHAR
9720 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
9721#else
9722 return FAIL;
9723#endif
9724
9725#ifdef SPECIAL_WILDCHAR
9726 /*
9727 * If there are any special wildcard characters which we cannot handle
9728 * here, call machine specific function for all the expansion. This
9729 * avoids starting the shell for each argument separately.
9730 * For `=expr` do use the internal function.
9731 */
9732 for (i = 0; i < num_pat; i++)
9733 {
9734 if (vim_strpbrk(pat[i], (char_u *)SPECIAL_WILDCHAR) != NULL
9735# ifdef VIM_BACKTICK
9736 && !(vim_backtick(pat[i]) && pat[i][1] == '=')
9737# endif
9738 )
9739 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
9740 }
9741#endif
9742
9743 recursive = TRUE;
9744
9745 /*
9746 * The matching file names are stored in a growarray. Init it empty.
9747 */
9748 ga_init2(&ga, (int)sizeof(char_u *), 30);
9749
9750 for (i = 0; i < num_pat; ++i)
9751 {
9752 add_pat = -1;
9753 p = pat[i];
9754
9755#ifdef VIM_BACKTICK
9756 if (vim_backtick(p))
9757 add_pat = expand_backtick(&ga, p, flags);
9758 else
9759#endif
9760 {
9761 /*
9762 * First expand environment variables, "~/" and "~user/".
9763 */
9764 if (vim_strpbrk(p, (char_u *)"$~") != NULL)
9765 {
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00009766 p = expand_env_save_opt(p, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009767 if (p == NULL)
9768 p = pat[i];
9769#ifdef UNIX
9770 /*
9771 * On Unix, if expand_env() can't expand an environment
9772 * variable, use the shell to do that. Discard previously
9773 * found file names and start all over again.
9774 */
9775 else if (vim_strpbrk(p, (char_u *)"$~") != NULL)
9776 {
9777 vim_free(p);
Bram Moolenaar782027e2009-06-24 14:25:49 +00009778 ga_clear_strings(&ga);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009779 i = mch_expand_wildcards(num_pat, pat, num_file, file,
9780 flags);
9781 recursive = FALSE;
9782 return i;
9783 }
9784#endif
9785 }
9786
9787 /*
9788 * If there are wildcards: Expand file names and add each match to
9789 * the list. If there is no match, and EW_NOTFOUND is given, add
9790 * the pattern.
9791 * If there are no wildcards: Add the file name if it exists or
9792 * when EW_NOTFOUND is given.
9793 */
9794 if (mch_has_exp_wildcard(p))
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009795 {
9796#if defined(FEAT_SEARCHPATH)
9797 if (*p != '.' && !vim_ispathsep(*p) && (flags & EW_PATH))
9798 add_pat = expand_in_path(&ga, p, flags);
9799 else
9800#endif
9801 add_pat = mch_expandpath(&ga, p, flags);
9802 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009803 }
9804
9805 if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
9806 {
9807 char_u *t = backslash_halve_save(p);
9808
9809#if defined(MACOS_CLASSIC)
9810 slash_to_colon(t);
9811#endif
9812 /* When EW_NOTFOUND is used, always add files and dirs. Makes
9813 * "vim c:/" work. */
9814 if (flags & EW_NOTFOUND)
9815 addfile(&ga, t, flags | EW_DIR | EW_FILE);
9816 else if (mch_getperm(t) >= 0)
9817 addfile(&ga, t, flags);
9818 vim_free(t);
9819 }
9820
Bram Moolenaarb28ebbc2010-07-14 16:59:57 +02009821#if defined(FEAT_SEARCHPATH)
9822 if (flags & EW_PATH)
9823 uniquefy_paths(&ga, p);
9824#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009825 if (p != pat[i])
9826 vim_free(p);
9827 }
9828
9829 *num_file = ga.ga_len;
9830 *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data : (char_u **)"";
9831
9832 recursive = FALSE;
9833
9834 return (ga.ga_data != NULL) ? OK : FAIL;
9835}
9836
9837# ifdef VIM_BACKTICK
9838
9839/*
9840 * Return TRUE if we can expand this backtick thing here.
9841 */
9842 static int
9843vim_backtick(p)
9844 char_u *p;
9845{
9846 return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
9847}
9848
9849/*
9850 * Expand an item in `backticks` by executing it as a command.
9851 * Currently only works when pat[] starts and ends with a `.
9852 * Returns number of file names found.
9853 */
9854 static int
9855expand_backtick(gap, pat, flags)
9856 garray_T *gap;
9857 char_u *pat;
9858 int flags; /* EW_* flags */
9859{
9860 char_u *p;
9861 char_u *cmd;
9862 char_u *buffer;
9863 int cnt = 0;
9864 int i;
9865
9866 /* Create the command: lop off the backticks. */
9867 cmd = vim_strnsave(pat + 1, (int)STRLEN(pat) - 2);
9868 if (cmd == NULL)
9869 return 0;
9870
9871#ifdef FEAT_EVAL
9872 if (*cmd == '=') /* `={expr}`: Expand expression */
Bram Moolenaar362e1a32006-03-06 23:29:24 +00009873 buffer = eval_to_string(cmd + 1, &p, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009874 else
9875#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00009876 buffer = get_cmd_output(cmd, NULL,
9877 (flags & EW_SILENT) ? SHELL_SILENT : 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009878 vim_free(cmd);
9879 if (buffer == NULL)
9880 return 0;
9881
9882 cmd = buffer;
9883 while (*cmd != NUL)
9884 {
9885 cmd = skipwhite(cmd); /* skip over white space */
9886 p = cmd;
9887 while (*p != NUL && *p != '\r' && *p != '\n') /* skip over entry */
9888 ++p;
9889 /* add an entry if it is not empty */
9890 if (p > cmd)
9891 {
9892 i = *p;
9893 *p = NUL;
9894 addfile(gap, cmd, flags);
9895 *p = i;
9896 ++cnt;
9897 }
9898 cmd = p;
9899 while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
9900 ++cmd;
9901 }
9902
9903 vim_free(buffer);
9904 return cnt;
9905}
9906# endif /* VIM_BACKTICK */
9907
9908/*
9909 * Add a file to a file list. Accepted flags:
9910 * EW_DIR add directories
9911 * EW_FILE add files
Bram Moolenaar1f35bf92006-03-07 22:38:47 +00009912 * EW_EXEC add executable files
Bram Moolenaar071d4272004-06-13 20:20:40 +00009913 * EW_NOTFOUND add even when it doesn't exist
9914 * EW_ADDSLASH add slash after directory name
9915 */
9916 void
9917addfile(gap, f, flags)
9918 garray_T *gap;
9919 char_u *f; /* filename */
9920 int flags;
9921{
9922 char_u *p;
9923 int isdir;
9924
9925 /* if the file/dir doesn't exist, may not add it */
9926 if (!(flags & EW_NOTFOUND) && mch_getperm(f) < 0)
9927 return;
9928
9929#ifdef FNAME_ILLEGAL
9930 /* if the file/dir contains illegal characters, don't add it */
9931 if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
9932 return;
9933#endif
9934
9935 isdir = mch_isdir(f);
9936 if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
9937 return;
9938
Bram Moolenaar1f35bf92006-03-07 22:38:47 +00009939 /* If the file isn't executable, may not add it. Do accept directories. */
9940 if (!isdir && (flags & EW_EXEC) && !mch_can_exe(f))
9941 return;
9942
Bram Moolenaar071d4272004-06-13 20:20:40 +00009943 /* Make room for another item in the file list. */
9944 if (ga_grow(gap, 1) == FAIL)
9945 return;
9946
9947 p = alloc((unsigned)(STRLEN(f) + 1 + isdir));
9948 if (p == NULL)
9949 return;
9950
9951 STRCPY(p, f);
9952#ifdef BACKSLASH_IN_FILENAME
9953 slash_adjust(p);
9954#endif
9955 /*
9956 * Append a slash or backslash after directory names if none is present.
9957 */
9958#ifndef DONT_ADD_PATHSEP_TO_DIR
9959 if (isdir && (flags & EW_ADDSLASH))
9960 add_pathsep(p);
9961#endif
9962 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009963}
9964#endif /* !NO_EXPANDPATH */
9965
9966#if defined(VIM_BACKTICK) || defined(FEAT_EVAL) || defined(PROTO)
9967
9968#ifndef SEEK_SET
9969# define SEEK_SET 0
9970#endif
9971#ifndef SEEK_END
9972# define SEEK_END 2
9973#endif
9974
9975/*
9976 * Get the stdout of an external command.
9977 * Returns an allocated string, or NULL for error.
9978 */
9979 char_u *
Bram Moolenaarc0197e22004-09-13 20:26:32 +00009980get_cmd_output(cmd, infile, flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009981 char_u *cmd;
Bram Moolenaarc0197e22004-09-13 20:26:32 +00009982 char_u *infile; /* optional input file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009983 int flags; /* can be SHELL_SILENT */
9984{
9985 char_u *tempname;
9986 char_u *command;
9987 char_u *buffer = NULL;
9988 int len;
9989 int i = 0;
9990 FILE *fd;
9991
9992 if (check_restricted() || check_secure())
9993 return NULL;
9994
9995 /* get a name for the temp file */
9996 if ((tempname = vim_tempname('o')) == NULL)
9997 {
9998 EMSG(_(e_notmp));
9999 return NULL;
10000 }
10001
10002 /* Add the redirection stuff */
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010003 command = make_filter_cmd(cmd, infile, tempname);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010004 if (command == NULL)
10005 goto done;
10006
10007 /*
10008 * Call the shell to execute the command (errors are ignored).
10009 * Don't check timestamps here.
10010 */
10011 ++no_check_timestamps;
10012 call_shell(command, SHELL_DOOUT | SHELL_EXPAND | flags);
10013 --no_check_timestamps;
10014
10015 vim_free(command);
10016
10017 /*
10018 * read the names from the file into memory
10019 */
10020# ifdef VMS
Bram Moolenaar25394022007-05-10 19:06:20 +000010021 /* created temporary file is not always readable as binary */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010022 fd = mch_fopen((char *)tempname, "r");
10023# else
10024 fd = mch_fopen((char *)tempname, READBIN);
10025# endif
10026
10027 if (fd == NULL)
10028 {
10029 EMSG2(_(e_notopen), tempname);
10030 goto done;
10031 }
10032
10033 fseek(fd, 0L, SEEK_END);
10034 len = ftell(fd); /* get size of temp file */
10035 fseek(fd, 0L, SEEK_SET);
10036
10037 buffer = alloc(len + 1);
10038 if (buffer != NULL)
10039 i = (int)fread((char *)buffer, (size_t)1, (size_t)len, fd);
10040 fclose(fd);
10041 mch_remove(tempname);
10042 if (buffer == NULL)
10043 goto done;
10044#ifdef VMS
10045 len = i; /* VMS doesn't give us what we asked for... */
10046#endif
10047 if (i != len)
10048 {
10049 EMSG2(_(e_notread), tempname);
10050 vim_free(buffer);
10051 buffer = NULL;
10052 }
10053 else
Bram Moolenaar162bd912010-07-28 22:29:10 +020010054 buffer[len] = NUL; /* make sure the buffer is terminated */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010055
10056done:
10057 vim_free(tempname);
10058 return buffer;
10059}
10060#endif
10061
10062/*
10063 * Free the list of files returned by expand_wildcards() or other expansion
10064 * functions.
10065 */
10066 void
10067FreeWild(count, files)
10068 int count;
10069 char_u **files;
10070{
Bram Moolenaarfc1421e2006-04-20 22:17:20 +000010071 if (count <= 0 || files == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010072 return;
10073#if defined(__EMX__) && defined(__ALWAYS_HAS_TRAILING_NULL_POINTER) /* XXX */
10074 /*
10075 * Is this still OK for when other functions than expand_wildcards() have
10076 * been used???
10077 */
10078 _fnexplodefree((char **)files);
10079#else
10080 while (count--)
10081 vim_free(files[count]);
10082 vim_free(files);
10083#endif
10084}
10085
10086/*
Bram Moolenaara9dc3752010-07-11 20:46:53 +020010087 * Return TRUE when need to go to Insert mode because of 'insertmode'.
Bram Moolenaar071d4272004-06-13 20:20:40 +000010088 * Don't do this when still processing a command or a mapping.
10089 * Don't do this when inside a ":normal" command.
10090 */
10091 int
10092goto_im()
10093{
10094 return (p_im && stuff_empty() && typebuf_typed());
10095}