blob: 3f8a0442a991db5f730b3d6a1f95d586f85691c0 [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
2277 * care of notifiying 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/*
2470 * changed() is called when something in the current buffer is changed.
2471 *
2472 * Most often called through changed_bytes() and changed_lines(), which also
2473 * mark the area of the display to be redrawn.
2474 */
2475 void
2476changed()
2477{
2478#if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
2479 /* The text of the preediting area is inserted, but this doesn't
2480 * mean a change of the buffer yet. That is delayed until the
2481 * text is committed. (this means preedit becomes empty) */
2482 if (im_is_preediting() && !xim_changed_while_preediting)
2483 return;
2484 xim_changed_while_preediting = FALSE;
2485#endif
2486
2487 if (!curbuf->b_changed)
2488 {
2489 int save_msg_scroll = msg_scroll;
2490
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002491 /* Give a warning about changing a read-only file. This may also
2492 * check-out the file, thus change "curbuf"! */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002493 change_warning(0);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002494
Bram Moolenaar071d4272004-06-13 20:20:40 +00002495 /* Create a swap file if that is wanted.
2496 * Don't do this for "nofile" and "nowrite" buffer types. */
2497 if (curbuf->b_may_swap
2498#ifdef FEAT_QUICKFIX
2499 && !bt_dontwrite(curbuf)
2500#endif
2501 )
2502 {
2503 ml_open_file(curbuf);
2504
2505 /* The ml_open_file() can cause an ATTENTION message.
2506 * Wait two seconds, to make sure the user reads this unexpected
2507 * message. Since we could be anywhere, call wait_return() now,
2508 * and don't let the emsg() set msg_scroll. */
2509 if (need_wait_return && emsg_silent == 0)
2510 {
2511 out_flush();
2512 ui_delay(2000L, TRUE);
2513 wait_return(TRUE);
2514 msg_scroll = save_msg_scroll;
2515 }
2516 }
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02002517 changed_int();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002518 }
2519 ++curbuf->b_changedtick;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002520}
2521
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02002522/*
2523 * Internal part of changed(), no user interaction.
2524 */
2525 void
2526changed_int()
2527{
2528 curbuf->b_changed = TRUE;
2529 ml_setflags(curbuf);
2530#ifdef FEAT_WINDOWS
2531 check_status(curbuf);
2532 redraw_tabline = TRUE;
2533#endif
2534#ifdef FEAT_TITLE
2535 need_maketitle = TRUE; /* set window title later */
2536#endif
2537}
2538
Bram Moolenaardba8a912005-04-24 22:08:39 +00002539static void changedOneline __ARGS((buf_T *buf, linenr_T lnum));
2540static void changed_lines_buf __ARGS((buf_T *buf, linenr_T lnum, linenr_T lnume, long xtra));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002541static void changed_common __ARGS((linenr_T lnum, colnr_T col, linenr_T lnume, long xtra));
2542
2543/*
2544 * Changed bytes within a single line for the current buffer.
2545 * - marks the windows on this buffer to be redisplayed
2546 * - marks the buffer changed by calling changed()
2547 * - invalidates cached values
2548 */
2549 void
2550changed_bytes(lnum, col)
2551 linenr_T lnum;
2552 colnr_T col;
2553{
Bram Moolenaardba8a912005-04-24 22:08:39 +00002554 changedOneline(curbuf, lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002555 changed_common(lnum, col, lnum + 1, 0L);
Bram Moolenaardba8a912005-04-24 22:08:39 +00002556
2557#ifdef FEAT_DIFF
2558 /* Diff highlighting in other diff windows may need to be updated too. */
2559 if (curwin->w_p_diff)
2560 {
2561 win_T *wp;
2562 linenr_T wlnum;
2563
2564 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2565 if (wp->w_p_diff && wp != curwin)
2566 {
2567 redraw_win_later(wp, VALID);
2568 wlnum = diff_lnum_win(lnum, wp);
2569 if (wlnum > 0)
2570 changedOneline(wp->w_buffer, wlnum);
2571 }
2572 }
2573#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002574}
2575
2576 static void
Bram Moolenaardba8a912005-04-24 22:08:39 +00002577changedOneline(buf, lnum)
2578 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002579 linenr_T lnum;
2580{
Bram Moolenaardba8a912005-04-24 22:08:39 +00002581 if (buf->b_mod_set)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002582 {
2583 /* find the maximum area that must be redisplayed */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002584 if (lnum < buf->b_mod_top)
2585 buf->b_mod_top = lnum;
2586 else if (lnum >= buf->b_mod_bot)
2587 buf->b_mod_bot = lnum + 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002588 }
2589 else
2590 {
2591 /* set the area that must be redisplayed to one line */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002592 buf->b_mod_set = TRUE;
2593 buf->b_mod_top = lnum;
2594 buf->b_mod_bot = lnum + 1;
2595 buf->b_mod_xlines = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002596 }
2597}
2598
2599/*
2600 * Appended "count" lines below line "lnum" in the current buffer.
2601 * Must be called AFTER the change and after mark_adjust().
2602 * Takes care of marking the buffer to be redrawn and sets the changed flag.
2603 */
2604 void
2605appended_lines(lnum, count)
2606 linenr_T lnum;
2607 long count;
2608{
2609 changed_lines(lnum + 1, 0, lnum + 1, count);
2610}
2611
2612/*
2613 * Like appended_lines(), but adjust marks first.
2614 */
2615 void
2616appended_lines_mark(lnum, count)
2617 linenr_T lnum;
2618 long count;
2619{
2620 mark_adjust(lnum + 1, (linenr_T)MAXLNUM, count, 0L);
2621 changed_lines(lnum + 1, 0, lnum + 1, count);
2622}
2623
2624/*
2625 * Deleted "count" lines at line "lnum" in the current buffer.
2626 * Must be called AFTER the change and after mark_adjust().
2627 * Takes care of marking the buffer to be redrawn and sets the changed flag.
2628 */
2629 void
2630deleted_lines(lnum, count)
2631 linenr_T lnum;
2632 long count;
2633{
2634 changed_lines(lnum, 0, lnum + count, -count);
2635}
2636
2637/*
2638 * Like deleted_lines(), but adjust marks first.
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002639 * Make sure the cursor is on a valid line before calling, a GUI callback may
2640 * be triggered to display the cursor.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002641 */
2642 void
2643deleted_lines_mark(lnum, count)
2644 linenr_T lnum;
2645 long count;
2646{
2647 mark_adjust(lnum, (linenr_T)(lnum + count - 1), (long)MAXLNUM, -count);
2648 changed_lines(lnum, 0, lnum + count, -count);
2649}
2650
2651/*
2652 * Changed lines for the current buffer.
2653 * Must be called AFTER the change and after mark_adjust().
2654 * - mark the buffer changed by calling changed()
2655 * - mark the windows on this buffer to be redisplayed
2656 * - invalidate cached values
2657 * "lnum" is the first line that needs displaying, "lnume" the first line
2658 * below the changed lines (BEFORE the change).
2659 * When only inserting lines, "lnum" and "lnume" are equal.
2660 * Takes care of calling changed() and updating b_mod_*.
2661 */
2662 void
2663changed_lines(lnum, col, lnume, xtra)
2664 linenr_T lnum; /* first line with change */
2665 colnr_T col; /* column in first line with change */
2666 linenr_T lnume; /* line below last changed line */
2667 long xtra; /* number of extra lines (negative when deleting) */
2668{
Bram Moolenaardba8a912005-04-24 22:08:39 +00002669 changed_lines_buf(curbuf, lnum, lnume, xtra);
2670
2671#ifdef FEAT_DIFF
2672 if (xtra == 0 && curwin->w_p_diff)
2673 {
2674 /* When the number of lines doesn't change then mark_adjust() isn't
2675 * called and other diff buffers still need to be marked for
2676 * displaying. */
2677 win_T *wp;
2678 linenr_T wlnum;
2679
2680 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2681 if (wp->w_p_diff && wp != curwin)
2682 {
2683 redraw_win_later(wp, VALID);
2684 wlnum = diff_lnum_win(lnum, wp);
2685 if (wlnum > 0)
2686 changed_lines_buf(wp->w_buffer, wlnum,
2687 lnume - lnum + wlnum, 0L);
2688 }
2689 }
2690#endif
2691
2692 changed_common(lnum, col, lnume, xtra);
2693}
2694
2695 static void
2696changed_lines_buf(buf, lnum, lnume, xtra)
2697 buf_T *buf;
2698 linenr_T lnum; /* first line with change */
2699 linenr_T lnume; /* line below last changed line */
2700 long xtra; /* number of extra lines (negative when deleting) */
2701{
2702 if (buf->b_mod_set)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002703 {
2704 /* find the maximum area that must be redisplayed */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002705 if (lnum < buf->b_mod_top)
2706 buf->b_mod_top = lnum;
2707 if (lnum < buf->b_mod_bot)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002708 {
2709 /* adjust old bot position for xtra lines */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002710 buf->b_mod_bot += xtra;
2711 if (buf->b_mod_bot < lnum)
2712 buf->b_mod_bot = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002713 }
Bram Moolenaardba8a912005-04-24 22:08:39 +00002714 if (lnume + xtra > buf->b_mod_bot)
2715 buf->b_mod_bot = lnume + xtra;
2716 buf->b_mod_xlines += xtra;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002717 }
2718 else
2719 {
2720 /* set the area that must be redisplayed */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002721 buf->b_mod_set = TRUE;
2722 buf->b_mod_top = lnum;
2723 buf->b_mod_bot = lnume + xtra;
2724 buf->b_mod_xlines = xtra;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002725 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002726}
2727
2728 static void
2729changed_common(lnum, col, lnume, xtra)
2730 linenr_T lnum;
2731 colnr_T col;
2732 linenr_T lnume;
2733 long xtra;
2734{
2735 win_T *wp;
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00002736#ifdef FEAT_WINDOWS
2737 tabpage_T *tp;
2738#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002739 int i;
2740#ifdef FEAT_JUMPLIST
2741 int cols;
2742 pos_T *p;
2743 int add;
2744#endif
2745
2746 /* mark the buffer as modified */
2747 changed();
2748
2749 /* set the '. mark */
2750 if (!cmdmod.keepjumps)
2751 {
2752 curbuf->b_last_change.lnum = lnum;
2753 curbuf->b_last_change.col = col;
2754
2755#ifdef FEAT_JUMPLIST
2756 /* Create a new entry if a new undo-able change was started or we
2757 * don't have an entry yet. */
2758 if (curbuf->b_new_change || curbuf->b_changelistlen == 0)
2759 {
2760 if (curbuf->b_changelistlen == 0)
2761 add = TRUE;
2762 else
2763 {
2764 /* Don't create a new entry when the line number is the same
2765 * as the last one and the column is not too far away. Avoids
2766 * creating many entries for typing "xxxxx". */
2767 p = &curbuf->b_changelist[curbuf->b_changelistlen - 1];
2768 if (p->lnum != lnum)
2769 add = TRUE;
2770 else
2771 {
2772 cols = comp_textwidth(FALSE);
2773 if (cols == 0)
2774 cols = 79;
2775 add = (p->col + cols < col || col + cols < p->col);
2776 }
2777 }
2778 if (add)
2779 {
2780 /* This is the first of a new sequence of undo-able changes
2781 * and it's at some distance of the last change. Use a new
2782 * position in the changelist. */
2783 curbuf->b_new_change = FALSE;
2784
2785 if (curbuf->b_changelistlen == JUMPLISTSIZE)
2786 {
2787 /* changelist is full: remove oldest entry */
2788 curbuf->b_changelistlen = JUMPLISTSIZE - 1;
2789 mch_memmove(curbuf->b_changelist, curbuf->b_changelist + 1,
2790 sizeof(pos_T) * (JUMPLISTSIZE - 1));
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00002791 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002792 {
2793 /* Correct position in changelist for other windows on
2794 * this buffer. */
2795 if (wp->w_buffer == curbuf && wp->w_changelistidx > 0)
2796 --wp->w_changelistidx;
2797 }
2798 }
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00002799 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002800 {
2801 /* For other windows, if the position in the changelist is
2802 * at the end it stays at the end. */
2803 if (wp->w_buffer == curbuf
2804 && wp->w_changelistidx == curbuf->b_changelistlen)
2805 ++wp->w_changelistidx;
2806 }
2807 ++curbuf->b_changelistlen;
2808 }
2809 }
2810 curbuf->b_changelist[curbuf->b_changelistlen - 1] =
2811 curbuf->b_last_change;
2812 /* The current window is always after the last change, so that "g,"
2813 * takes you back to it. */
2814 curwin->w_changelistidx = curbuf->b_changelistlen;
2815#endif
2816 }
2817
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00002818 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002819 {
2820 if (wp->w_buffer == curbuf)
2821 {
2822 /* Mark this window to be redrawn later. */
2823 if (wp->w_redr_type < VALID)
2824 wp->w_redr_type = VALID;
2825
2826 /* Check if a change in the buffer has invalidated the cached
2827 * values for the cursor. */
2828#ifdef FEAT_FOLDING
2829 /*
2830 * Update the folds for this window. Can't postpone this, because
2831 * a following operator might work on the whole fold: ">>dd".
2832 */
2833 foldUpdate(wp, lnum, lnume + xtra - 1);
2834
2835 /* The change may cause lines above or below the change to become
2836 * included in a fold. Set lnum/lnume to the first/last line that
2837 * might be displayed differently.
2838 * Set w_cline_folded here as an efficient way to update it when
2839 * inserting lines just above a closed fold. */
2840 i = hasFoldingWin(wp, lnum, &lnum, NULL, FALSE, NULL);
2841 if (wp->w_cursor.lnum == lnum)
2842 wp->w_cline_folded = i;
2843 i = hasFoldingWin(wp, lnume, NULL, &lnume, FALSE, NULL);
2844 if (wp->w_cursor.lnum == lnume)
2845 wp->w_cline_folded = i;
2846
2847 /* If the changed line is in a range of previously folded lines,
2848 * compare with the first line in that range. */
2849 if (wp->w_cursor.lnum <= lnum)
2850 {
2851 i = find_wl_entry(wp, lnum);
2852 if (i >= 0 && wp->w_cursor.lnum > wp->w_lines[i].wl_lnum)
2853 changed_line_abv_curs_win(wp);
2854 }
2855#endif
2856
2857 if (wp->w_cursor.lnum > lnum)
2858 changed_line_abv_curs_win(wp);
2859 else if (wp->w_cursor.lnum == lnum && wp->w_cursor.col >= col)
2860 changed_cline_bef_curs_win(wp);
2861 if (wp->w_botline >= lnum)
2862 {
2863 /* Assume that botline doesn't change (inserted lines make
2864 * other lines scroll down below botline). */
2865 approximate_botline_win(wp);
2866 }
2867
2868 /* Check if any w_lines[] entries have become invalid.
2869 * For entries below the change: Correct the lnums for
2870 * inserted/deleted lines. Makes it possible to stop displaying
2871 * after the change. */
2872 for (i = 0; i < wp->w_lines_valid; ++i)
2873 if (wp->w_lines[i].wl_valid)
2874 {
2875 if (wp->w_lines[i].wl_lnum >= lnum)
2876 {
2877 if (wp->w_lines[i].wl_lnum < lnume)
2878 {
2879 /* line included in change */
2880 wp->w_lines[i].wl_valid = FALSE;
2881 }
2882 else if (xtra != 0)
2883 {
2884 /* line below change */
2885 wp->w_lines[i].wl_lnum += xtra;
2886#ifdef FEAT_FOLDING
2887 wp->w_lines[i].wl_lastlnum += xtra;
2888#endif
2889 }
2890 }
2891#ifdef FEAT_FOLDING
2892 else if (wp->w_lines[i].wl_lastlnum >= lnum)
2893 {
2894 /* change somewhere inside this range of folded lines,
2895 * may need to be redrawn */
2896 wp->w_lines[i].wl_valid = FALSE;
2897 }
2898#endif
2899 }
Bram Moolenaar3234cc62009-11-03 17:47:12 +00002900
2901#ifdef FEAT_FOLDING
2902 /* Take care of side effects for setting w_topline when folds have
2903 * changed. Esp. when the buffer was changed in another window. */
2904 if (hasAnyFolding(wp))
2905 set_topline(wp, wp->w_topline);
2906#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002907 }
2908 }
2909
2910 /* Call update_screen() later, which checks out what needs to be redrawn,
2911 * since it notices b_mod_set and then uses b_mod_*. */
2912 if (must_redraw < VALID)
2913 must_redraw = VALID;
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002914
2915#ifdef FEAT_AUTOCMD
2916 /* when the cursor line is changed always trigger CursorMoved */
Bram Moolenaare163f1c2006-10-17 09:12:21 +00002917 if (lnum <= curwin->w_cursor.lnum
2918 && lnume + (xtra < 0 ? -xtra : xtra) > curwin->w_cursor.lnum)
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002919 last_cursormoved.lnum = 0;
2920#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002921}
2922
2923/*
2924 * unchanged() is called when the changed flag must be reset for buffer 'buf'
2925 */
2926 void
2927unchanged(buf, ff)
2928 buf_T *buf;
2929 int ff; /* also reset 'fileformat' */
2930{
2931 if (buf->b_changed || (ff && file_ff_differs(buf)))
2932 {
2933 buf->b_changed = 0;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002934 ml_setflags(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002935 if (ff)
2936 save_file_ff(buf);
2937#ifdef FEAT_WINDOWS
2938 check_status(buf);
Bram Moolenaar997fb4b2006-02-17 21:53:23 +00002939 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002940#endif
2941#ifdef FEAT_TITLE
2942 need_maketitle = TRUE; /* set window title later */
2943#endif
2944 }
2945 ++buf->b_changedtick;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002946#ifdef FEAT_NETBEANS_INTG
2947 netbeans_unmodified(buf);
2948#endif
2949}
2950
2951#if defined(FEAT_WINDOWS) || defined(PROTO)
2952/*
2953 * check_status: called when the status bars for the buffer 'buf'
2954 * need to be updated
2955 */
2956 void
2957check_status(buf)
2958 buf_T *buf;
2959{
2960 win_T *wp;
2961
2962 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2963 if (wp->w_buffer == buf && wp->w_status_height)
2964 {
2965 wp->w_redr_status = TRUE;
2966 if (must_redraw < VALID)
2967 must_redraw = VALID;
2968 }
2969}
2970#endif
2971
2972/*
2973 * If the file is readonly, give a warning message with the first change.
2974 * Don't do this for autocommands.
2975 * Don't use emsg(), because it flushes the macro buffer.
Bram Moolenaard5cdbeb2005-10-10 20:59:28 +00002976 * If we have undone all changes b_changed will be FALSE, but "b_did_warn"
Bram Moolenaar071d4272004-06-13 20:20:40 +00002977 * will be TRUE.
2978 */
2979 void
2980change_warning(col)
2981 int col; /* column for message; non-zero when in insert
2982 mode and 'showmode' is on */
2983{
Bram Moolenaar496c5262009-03-18 14:42:00 +00002984 static char *w_readonly = N_("W10: Warning: Changing a readonly file");
2985
Bram Moolenaar071d4272004-06-13 20:20:40 +00002986 if (curbuf->b_did_warn == FALSE
2987 && curbufIsChanged() == 0
2988#ifdef FEAT_AUTOCMD
2989 && !autocmd_busy
2990#endif
2991 && curbuf->b_p_ro)
2992 {
2993#ifdef FEAT_AUTOCMD
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002994 ++curbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002995 apply_autocmds(EVENT_FILECHANGEDRO, NULL, NULL, FALSE, curbuf);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002996 --curbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002997 if (!curbuf->b_p_ro)
2998 return;
2999#endif
3000 /*
3001 * Do what msg() does, but with a column offset if the warning should
3002 * be after the mode message.
3003 */
3004 msg_start();
3005 if (msg_row == Rows - 1)
3006 msg_col = col;
Bram Moolenaar2df6dcc2004-07-12 15:53:54 +00003007 msg_source(hl_attr(HLF_W));
Bram Moolenaar496c5262009-03-18 14:42:00 +00003008 MSG_PUTS_ATTR(_(w_readonly), hl_attr(HLF_W) | MSG_HIST);
3009#ifdef FEAT_EVAL
3010 set_vim_var_string(VV_WARNINGMSG, (char_u *)_(w_readonly), -1);
3011#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003012 msg_clr_eos();
3013 (void)msg_end();
3014 if (msg_silent == 0 && !silent_mode)
3015 {
3016 out_flush();
3017 ui_delay(1000L, TRUE); /* give the user time to think about it */
3018 }
3019 curbuf->b_did_warn = TRUE;
3020 redraw_cmdline = FALSE; /* don't redraw and erase the message */
3021 if (msg_row < Rows - 1)
3022 showmode();
3023 }
3024}
3025
3026/*
3027 * Ask for a reply from the user, a 'y' or a 'n'.
3028 * No other characters are accepted, the message is repeated until a valid
3029 * reply is entered or CTRL-C is hit.
3030 * If direct is TRUE, don't use vgetc() but ui_inchar(), don't get characters
3031 * from any buffers but directly from the user.
3032 *
3033 * return the 'y' or 'n'
3034 */
3035 int
3036ask_yesno(str, direct)
3037 char_u *str;
3038 int direct;
3039{
3040 int r = ' ';
3041 int save_State = State;
3042
3043 if (exiting) /* put terminal in raw mode for this question */
3044 settmode(TMODE_RAW);
3045 ++no_wait_return;
3046#ifdef USE_ON_FLY_SCROLL
3047 dont_scroll = TRUE; /* disallow scrolling here */
3048#endif
3049 State = CONFIRM; /* mouse behaves like with :confirm */
3050#ifdef FEAT_MOUSE
3051 setmouse(); /* disables mouse for xterm */
3052#endif
3053 ++no_mapping;
3054 ++allow_keys; /* no mapping here, but recognize keys */
3055
3056 while (r != 'y' && r != 'n')
3057 {
3058 /* same highlighting as for wait_return */
3059 smsg_attr(hl_attr(HLF_R), (char_u *)"%s (y/n)?", str);
3060 if (direct)
3061 r = get_keystroke();
3062 else
Bram Moolenaar913626c2008-01-03 11:43:42 +00003063 r = plain_vgetc();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003064 if (r == Ctrl_C || r == ESC)
3065 r = 'n';
3066 msg_putchar(r); /* show what you typed */
3067 out_flush();
3068 }
3069 --no_wait_return;
3070 State = save_State;
3071#ifdef FEAT_MOUSE
3072 setmouse();
3073#endif
3074 --no_mapping;
3075 --allow_keys;
3076
3077 return r;
3078}
3079
3080/*
3081 * Get a key stroke directly from the user.
3082 * Ignores mouse clicks and scrollbar events, except a click for the left
3083 * button (used at the more prompt).
3084 * Doesn't use vgetc(), because it syncs undo and eats mapped characters.
3085 * Disadvantage: typeahead is ignored.
3086 * Translates the interrupt character for unix to ESC.
3087 */
3088 int
3089get_keystroke()
3090{
3091#define CBUFLEN 151
3092 char_u buf[CBUFLEN];
3093 int len = 0;
3094 int n;
3095 int save_mapped_ctrl_c = mapped_ctrl_c;
Bram Moolenaar4395a712006-09-05 18:57:57 +00003096 int waited = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003097
3098 mapped_ctrl_c = FALSE; /* mappings are not used here */
3099 for (;;)
3100 {
3101 cursor_on();
3102 out_flush();
3103
3104 /* First time: blocking wait. Second time: wait up to 100ms for a
3105 * terminal code to complete. Leave some room for check_termcode() to
3106 * insert a key code into (max 5 chars plus NUL). And
3107 * fix_input_buffer() can triple the number of bytes. */
3108 n = ui_inchar(buf + len, (CBUFLEN - 6 - len) / 3,
3109 len == 0 ? -1L : 100L, 0);
3110 if (n > 0)
3111 {
3112 /* Replace zero and CSI by a special key code. */
3113 n = fix_input_buffer(buf + len, n, FALSE);
3114 len += n;
Bram Moolenaar4395a712006-09-05 18:57:57 +00003115 waited = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003116 }
Bram Moolenaar4395a712006-09-05 18:57:57 +00003117 else if (len > 0)
3118 ++waited; /* keep track of the waiting time */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003119
Bram Moolenaar4395a712006-09-05 18:57:57 +00003120 /* Incomplete termcode and not timed out yet: get more characters */
3121 if ((n = check_termcode(1, buf, len)) < 0
3122 && (!p_ttimeout || waited * 100L < (p_ttm < 0 ? p_tm : p_ttm)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003123 continue;
Bram Moolenaar4395a712006-09-05 18:57:57 +00003124
Bram Moolenaar071d4272004-06-13 20:20:40 +00003125 /* found a termcode: adjust length */
3126 if (n > 0)
3127 len = n;
3128 if (len == 0) /* nothing typed yet */
3129 continue;
3130
3131 /* Handle modifier and/or special key code. */
3132 n = buf[0];
3133 if (n == K_SPECIAL)
3134 {
3135 n = TO_SPECIAL(buf[1], buf[2]);
3136 if (buf[1] == KS_MODIFIER
3137 || n == K_IGNORE
3138#ifdef FEAT_MOUSE
3139 || n == K_LEFTMOUSE_NM
3140 || n == K_LEFTDRAG
3141 || n == K_LEFTRELEASE
3142 || n == K_LEFTRELEASE_NM
3143 || n == K_MIDDLEMOUSE
3144 || n == K_MIDDLEDRAG
3145 || n == K_MIDDLERELEASE
3146 || n == K_RIGHTMOUSE
3147 || n == K_RIGHTDRAG
3148 || n == K_RIGHTRELEASE
3149 || n == K_MOUSEDOWN
3150 || n == K_MOUSEUP
3151 || n == K_X1MOUSE
3152 || n == K_X1DRAG
3153 || n == K_X1RELEASE
3154 || n == K_X2MOUSE
3155 || n == K_X2DRAG
3156 || n == K_X2RELEASE
3157# ifdef FEAT_GUI
3158 || n == K_VER_SCROLLBAR
3159 || n == K_HOR_SCROLLBAR
3160# endif
3161#endif
3162 )
3163 {
3164 if (buf[1] == KS_MODIFIER)
3165 mod_mask = buf[2];
3166 len -= 3;
3167 if (len > 0)
3168 mch_memmove(buf, buf + 3, (size_t)len);
3169 continue;
3170 }
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00003171 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003172 }
3173#ifdef FEAT_MBYTE
3174 if (has_mbyte)
3175 {
3176 if (MB_BYTE2LEN(n) > len)
3177 continue; /* more bytes to get */
3178 buf[len >= CBUFLEN ? CBUFLEN - 1 : len] = NUL;
3179 n = (*mb_ptr2char)(buf);
3180 }
3181#endif
3182#ifdef UNIX
3183 if (n == intr_char)
3184 n = ESC;
3185#endif
3186 break;
3187 }
3188
3189 mapped_ctrl_c = save_mapped_ctrl_c;
3190 return n;
3191}
3192
3193/*
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003194 * Get a number from the user.
3195 * When "mouse_used" is not NULL allow using the mouse.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003196 */
3197 int
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003198get_number(colon, mouse_used)
3199 int colon; /* allow colon to abort */
3200 int *mouse_used;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003201{
3202 int n = 0;
3203 int c;
Bram Moolenaar3991dab2006-03-27 17:01:56 +00003204 int typed = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003205
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003206 if (mouse_used != NULL)
3207 *mouse_used = FALSE;
3208
Bram Moolenaar071d4272004-06-13 20:20:40 +00003209 /* When not printing messages, the user won't know what to type, return a
3210 * zero (as if CR was hit). */
3211 if (msg_silent != 0)
3212 return 0;
3213
3214#ifdef USE_ON_FLY_SCROLL
3215 dont_scroll = TRUE; /* disallow scrolling here */
3216#endif
3217 ++no_mapping;
3218 ++allow_keys; /* no mapping here, but recognize keys */
3219 for (;;)
3220 {
3221 windgoto(msg_row, msg_col);
3222 c = safe_vgetc();
3223 if (VIM_ISDIGIT(c))
3224 {
3225 n = n * 10 + c - '0';
3226 msg_putchar(c);
Bram Moolenaar3991dab2006-03-27 17:01:56 +00003227 ++typed;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003228 }
3229 else if (c == K_DEL || c == K_KDEL || c == K_BS || c == Ctrl_H)
3230 {
Bram Moolenaar3991dab2006-03-27 17:01:56 +00003231 if (typed > 0)
3232 {
3233 MSG_PUTS("\b \b");
3234 --typed;
3235 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003236 n /= 10;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003237 }
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003238#ifdef FEAT_MOUSE
3239 else if (mouse_used != NULL && c == K_LEFTMOUSE)
3240 {
3241 *mouse_used = TRUE;
3242 n = mouse_row + 1;
3243 break;
3244 }
3245#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003246 else if (n == 0 && c == ':' && colon)
3247 {
3248 stuffcharReadbuff(':');
3249 if (!exmode_active)
3250 cmdline_row = msg_row;
3251 skip_redraw = TRUE; /* skip redraw once */
3252 do_redraw = FALSE;
3253 break;
3254 }
3255 else if (c == CAR || c == NL || c == Ctrl_C || c == ESC)
3256 break;
3257 }
3258 --no_mapping;
3259 --allow_keys;
3260 return n;
3261}
3262
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003263/*
3264 * Ask the user to enter a number.
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003265 * When "mouse_used" is not NULL allow using the mouse and in that case return
3266 * the line number.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003267 */
3268 int
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003269prompt_for_number(mouse_used)
3270 int *mouse_used;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003271{
3272 int i;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003273 int save_cmdline_row;
3274 int save_State;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003275
3276 /* When using ":silent" assume that <CR> was entered. */
Bram Moolenaar42eeac32005-06-29 22:40:58 +00003277 if (mouse_used != NULL)
Bram Moolenaard812df62008-11-09 12:46:09 +00003278 MSG_PUTS(_("Type number and <Enter> or click with mouse (empty cancels): "));
Bram Moolenaar42eeac32005-06-29 22:40:58 +00003279 else
Bram Moolenaard812df62008-11-09 12:46:09 +00003280 MSG_PUTS(_("Type number and <Enter> (empty cancels): "));
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003281
Bram Moolenaar203335e2006-09-03 14:35:42 +00003282 /* Set the state such that text can be selected/copied/pasted and we still
3283 * get mouse events. */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003284 save_cmdline_row = cmdline_row;
Bram Moolenaar203335e2006-09-03 14:35:42 +00003285 cmdline_row = 0;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003286 save_State = State;
Bram Moolenaar203335e2006-09-03 14:35:42 +00003287 State = CMDLINE;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003288
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003289 i = get_number(TRUE, mouse_used);
3290 if (KeyTyped)
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003291 {
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003292 /* don't call wait_return() now */
3293 /* msg_putchar('\n'); */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003294 cmdline_row = msg_row - 1;
3295 need_wait_return = FALSE;
3296 msg_didany = FALSE;
Bram Moolenaarb2450162009-07-22 09:04:20 +00003297 msg_didout = FALSE;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003298 }
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003299 else
3300 cmdline_row = save_cmdline_row;
3301 State = save_State;
3302
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003303 return i;
3304}
3305
Bram Moolenaar071d4272004-06-13 20:20:40 +00003306 void
3307msgmore(n)
3308 long n;
3309{
3310 long pn;
3311
3312 if (global_busy /* no messages now, wait until global is finished */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003313 || !messaging()) /* 'lazyredraw' set, don't do messages now */
3314 return;
3315
Bram Moolenaar7df2d662005-01-25 22:18:08 +00003316 /* We don't want to overwrite another important message, but do overwrite
3317 * a previous "more lines" or "fewer lines" message, so that "5dd" and
3318 * then "put" reports the last action. */
3319 if (keep_msg != NULL && !keep_msg_more)
3320 return;
3321
Bram Moolenaar071d4272004-06-13 20:20:40 +00003322 if (n > 0)
3323 pn = n;
3324 else
3325 pn = -n;
3326
3327 if (pn > p_report)
3328 {
3329 if (pn == 1)
3330 {
3331 if (n > 0)
3332 STRCPY(msg_buf, _("1 more line"));
3333 else
3334 STRCPY(msg_buf, _("1 line less"));
3335 }
3336 else
3337 {
3338 if (n > 0)
3339 sprintf((char *)msg_buf, _("%ld more lines"), pn);
3340 else
3341 sprintf((char *)msg_buf, _("%ld fewer lines"), pn);
3342 }
3343 if (got_int)
3344 STRCAT(msg_buf, _(" (Interrupted)"));
3345 if (msg(msg_buf))
3346 {
Bram Moolenaar238a5642006-02-21 22:12:05 +00003347 set_keep_msg(msg_buf, 0);
Bram Moolenaar7df2d662005-01-25 22:18:08 +00003348 keep_msg_more = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003349 }
3350 }
3351}
3352
3353/*
3354 * flush map and typeahead buffers and give a warning for an error
3355 */
3356 void
3357beep_flush()
3358{
3359 if (emsg_silent == 0)
3360 {
3361 flush_buffers(FALSE);
3362 vim_beep();
3363 }
3364}
3365
3366/*
3367 * give a warning for an error
3368 */
3369 void
3370vim_beep()
3371{
3372 if (emsg_silent == 0)
3373 {
3374 if (p_vb
3375#ifdef FEAT_GUI
3376 /* While the GUI is starting up the termcap is set for the GUI
3377 * but the output still goes to a terminal. */
3378 && !(gui.in_use && gui.starting)
3379#endif
3380 )
3381 {
3382 out_str(T_VB);
3383 }
3384 else
3385 {
3386#ifdef MSDOS
3387 /*
3388 * The number of beeps outputted is reduced to avoid having to wait
3389 * for all the beeps to finish. This is only a problem on systems
3390 * where the beeps don't overlap.
3391 */
3392 if (beep_count == 0 || beep_count == 10)
3393 {
3394 out_char(BELL);
3395 beep_count = 1;
3396 }
3397 else
3398 ++beep_count;
3399#else
3400 out_char(BELL);
3401#endif
3402 }
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003403
3404 /* When 'verbose' is set and we are sourcing a script or executing a
3405 * function give the user a hint where the beep comes from. */
3406 if (vim_strchr(p_debug, 'e') != NULL)
3407 {
3408 msg_source(hl_attr(HLF_W));
3409 msg_attr((char_u *)_("Beep!"), hl_attr(HLF_W));
3410 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003411 }
3412}
3413
3414/*
3415 * To get the "real" home directory:
3416 * - get value of $HOME
3417 * For Unix:
3418 * - go to that directory
3419 * - do mch_dirname() to get the real name of that directory.
3420 * This also works with mounts and links.
3421 * Don't do this for MS-DOS, it will change the "current dir" for a drive.
3422 */
3423static char_u *homedir = NULL;
3424
3425 void
3426init_homedir()
3427{
3428 char_u *var;
3429
Bram Moolenaar05159a02005-02-26 23:04:13 +00003430 /* In case we are called a second time (when 'encoding' changes). */
3431 vim_free(homedir);
3432 homedir = NULL;
3433
Bram Moolenaar071d4272004-06-13 20:20:40 +00003434#ifdef VMS
3435 var = mch_getenv((char_u *)"SYS$LOGIN");
3436#else
3437 var = mch_getenv((char_u *)"HOME");
3438#endif
3439
3440 if (var != NULL && *var == NUL) /* empty is same as not set */
3441 var = NULL;
3442
3443#ifdef WIN3264
3444 /*
3445 * Weird but true: $HOME may contain an indirect reference to another
3446 * variable, esp. "%USERPROFILE%". Happens when $USERPROFILE isn't set
3447 * when $HOME is being set.
3448 */
3449 if (var != NULL && *var == '%')
3450 {
3451 char_u *p;
3452 char_u *exp;
3453
3454 p = vim_strchr(var + 1, '%');
3455 if (p != NULL)
3456 {
Bram Moolenaarce0842a2005-07-18 21:58:11 +00003457 vim_strncpy(NameBuff, var + 1, p - (var + 1));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003458 exp = mch_getenv(NameBuff);
3459 if (exp != NULL && *exp != NUL
3460 && STRLEN(exp) + STRLEN(p) < MAXPATHL)
3461 {
Bram Moolenaar555b2802005-05-19 21:08:39 +00003462 vim_snprintf((char *)NameBuff, MAXPATHL, "%s%s", exp, p + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003463 var = NameBuff;
3464 /* Also set $HOME, it's needed for _viminfo. */
3465 vim_setenv((char_u *)"HOME", NameBuff);
3466 }
3467 }
3468 }
3469
3470 /*
3471 * Typically, $HOME is not defined on Windows, unless the user has
3472 * specifically defined it for Vim's sake. However, on Windows NT
3473 * platforms, $HOMEDRIVE and $HOMEPATH are automatically defined for
3474 * each user. Try constructing $HOME from these.
3475 */
3476 if (var == NULL)
3477 {
3478 char_u *homedrive, *homepath;
3479
3480 homedrive = mch_getenv((char_u *)"HOMEDRIVE");
3481 homepath = mch_getenv((char_u *)"HOMEPATH");
Bram Moolenaar6f977012010-01-06 17:53:38 +01003482 if (homepath == NULL || *homepath == NUL)
3483 homepath = "\\";
3484 if (homedrive != NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00003485 && STRLEN(homedrive) + STRLEN(homepath) < MAXPATHL)
3486 {
3487 sprintf((char *)NameBuff, "%s%s", homedrive, homepath);
3488 if (NameBuff[0] != NUL)
3489 {
3490 var = NameBuff;
3491 /* Also set $HOME, it's needed for _viminfo. */
3492 vim_setenv((char_u *)"HOME", NameBuff);
3493 }
3494 }
3495 }
Bram Moolenaar05159a02005-02-26 23:04:13 +00003496
3497# if defined(FEAT_MBYTE)
3498 if (enc_utf8 && var != NULL)
3499 {
3500 int len;
3501 char_u *pp;
3502
3503 /* Convert from active codepage to UTF-8. Other conversions are
3504 * not done, because they would fail for non-ASCII characters. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003505 acp_to_enc(var, (int)STRLEN(var), &pp, &len);
Bram Moolenaar05159a02005-02-26 23:04:13 +00003506 if (pp != NULL)
3507 {
3508 homedir = pp;
3509 return;
3510 }
3511 }
3512# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003513#endif
3514
3515#if defined(OS2) || defined(MSDOS) || defined(MSWIN)
3516 /*
3517 * Default home dir is C:/
3518 * Best assumption we can make in such a situation.
3519 */
3520 if (var == NULL)
3521 var = "C:/";
3522#endif
3523 if (var != NULL)
3524 {
3525#ifdef UNIX
3526 /*
3527 * Change to the directory and get the actual path. This resolves
3528 * links. Don't do it when we can't return.
3529 */
3530 if (mch_dirname(NameBuff, MAXPATHL) == OK
3531 && mch_chdir((char *)NameBuff) == 0)
3532 {
3533 if (!mch_chdir((char *)var) && mch_dirname(IObuff, IOSIZE) == OK)
3534 var = IObuff;
3535 if (mch_chdir((char *)NameBuff) != 0)
3536 EMSG(_(e_prev_dir));
3537 }
3538#endif
3539 homedir = vim_strsave(var);
3540 }
3541}
3542
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003543#if defined(EXITFREE) || defined(PROTO)
3544 void
3545free_homedir()
3546{
3547 vim_free(homedir);
3548}
3549#endif
3550
Bram Moolenaar071d4272004-06-13 20:20:40 +00003551/*
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003552 * Call expand_env() and store the result in an allocated string.
3553 * This is not very memory efficient, this expects the result to be freed
3554 * again soon.
3555 */
3556 char_u *
3557expand_env_save(src)
3558 char_u *src;
3559{
3560 return expand_env_save_opt(src, FALSE);
3561}
3562
3563/*
3564 * Idem, but when "one" is TRUE handle the string as one file name, only
3565 * expand "~" at the start.
3566 */
3567 char_u *
3568expand_env_save_opt(src, one)
3569 char_u *src;
3570 int one;
3571{
3572 char_u *p;
3573
3574 p = alloc(MAXPATHL);
3575 if (p != NULL)
3576 expand_env_esc(src, p, MAXPATHL, FALSE, one, NULL);
3577 return p;
3578}
3579
3580/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003581 * Expand environment variable with path name.
3582 * "~/" is also expanded, using $HOME. For Unix "~user/" is expanded.
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003583 * Skips over "\ ", "\~" and "\$" (not for Win32 though).
Bram Moolenaar071d4272004-06-13 20:20:40 +00003584 * If anything fails no expansion is done and dst equals src.
3585 */
3586 void
3587expand_env(src, dst, dstlen)
3588 char_u *src; /* input string e.g. "$HOME/vim.hlp" */
3589 char_u *dst; /* where to put the result */
3590 int dstlen; /* maximum length of the result */
3591{
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003592 expand_env_esc(src, dst, dstlen, FALSE, FALSE, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003593}
3594
3595 void
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003596expand_env_esc(srcp, dst, dstlen, esc, one, startstr)
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003597 char_u *srcp; /* input string e.g. "$HOME/vim.hlp" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003598 char_u *dst; /* where to put the result */
3599 int dstlen; /* maximum length of the result */
3600 int esc; /* escape spaces in expanded variables */
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003601 int one; /* "srcp" is one file name */
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003602 char_u *startstr; /* start again after this (can be NULL) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003603{
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003604 char_u *src;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003605 char_u *tail;
3606 int c;
3607 char_u *var;
3608 int copy_char;
3609 int mustfree; /* var was allocated, need to free it later */
3610 int at_start = TRUE; /* at start of a name */
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003611 int startstr_len = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003612
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003613 if (startstr != NULL)
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003614 startstr_len = (int)STRLEN(startstr);
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003615
3616 src = skipwhite(srcp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003617 --dstlen; /* leave one char space for "\," */
3618 while (*src && dstlen > 0)
3619 {
3620 copy_char = TRUE;
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003621 if ((*src == '$'
3622#ifdef VMS
3623 && at_start
3624#endif
3625 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003626#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3627 || *src == '%'
3628#endif
3629 || (*src == '~' && at_start))
3630 {
3631 mustfree = FALSE;
3632
3633 /*
3634 * The variable name is copied into dst temporarily, because it may
3635 * be a string in read-only memory and a NUL needs to be appended.
3636 */
3637 if (*src != '~') /* environment var */
3638 {
3639 tail = src + 1;
3640 var = dst;
3641 c = dstlen - 1;
3642
3643#ifdef UNIX
3644 /* Unix has ${var-name} type environment vars */
3645 if (*tail == '{' && !vim_isIDc('{'))
3646 {
3647 tail++; /* ignore '{' */
3648 while (c-- > 0 && *tail && *tail != '}')
3649 *var++ = *tail++;
3650 }
3651 else
3652#endif
3653 {
3654 while (c-- > 0 && *tail != NUL && ((vim_isIDc(*tail))
3655#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3656 || (*src == '%' && *tail != '%')
3657#endif
3658 ))
3659 {
3660#ifdef OS2 /* env vars only in uppercase */
3661 *var++ = TOUPPER_LOC(*tail);
3662 tail++; /* toupper() may be a macro! */
3663#else
3664 *var++ = *tail++;
3665#endif
3666 }
3667 }
3668
3669#if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
3670# ifdef UNIX
3671 if (src[1] == '{' && *tail != '}')
3672# else
3673 if (*src == '%' && *tail != '%')
3674# endif
3675 var = NULL;
3676 else
3677 {
3678# ifdef UNIX
3679 if (src[1] == '{')
3680# else
3681 if (*src == '%')
3682#endif
3683 ++tail;
3684#endif
3685 *var = NUL;
3686 var = vim_getenv(dst, &mustfree);
3687#if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
3688 }
3689#endif
3690 }
3691 /* home directory */
3692 else if ( src[1] == NUL
3693 || vim_ispathsep(src[1])
3694 || vim_strchr((char_u *)" ,\t\n", src[1]) != NULL)
3695 {
3696 var = homedir;
3697 tail = src + 1;
3698 }
3699 else /* user directory */
3700 {
3701#if defined(UNIX) || (defined(VMS) && defined(USER_HOME))
3702 /*
3703 * Copy ~user to dst[], so we can put a NUL after it.
3704 */
3705 tail = src;
3706 var = dst;
3707 c = dstlen - 1;
3708 while ( c-- > 0
3709 && *tail
3710 && vim_isfilec(*tail)
3711 && !vim_ispathsep(*tail))
3712 *var++ = *tail++;
3713 *var = NUL;
3714# ifdef UNIX
3715 /*
3716 * If the system supports getpwnam(), use it.
3717 * Otherwise, or if getpwnam() fails, the shell is used to
3718 * expand ~user. This is slower and may fail if the shell
3719 * does not support ~user (old versions of /bin/sh).
3720 */
3721# if defined(HAVE_GETPWNAM) && defined(HAVE_PWD_H)
3722 {
3723 struct passwd *pw;
3724
Bram Moolenaara40ceaf2006-01-13 22:35:40 +00003725 /* Note: memory allocated by getpwnam() is never freed.
3726 * Calling endpwent() apparently doesn't help. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003727 pw = getpwnam((char *)dst + 1);
3728 if (pw != NULL)
3729 var = (char_u *)pw->pw_dir;
3730 else
3731 var = NULL;
3732 }
3733 if (var == NULL)
3734# endif
3735 {
3736 expand_T xpc;
3737
3738 ExpandInit(&xpc);
3739 xpc.xp_context = EXPAND_FILES;
3740 var = ExpandOne(&xpc, dst, NULL,
3741 WILD_ADD_SLASH|WILD_SILENT, WILD_EXPAND_FREE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003742 mustfree = TRUE;
3743 }
3744
3745# else /* !UNIX, thus VMS */
3746 /*
3747 * USER_HOME is a comma-separated list of
3748 * directories to search for the user account in.
3749 */
3750 {
3751 char_u test[MAXPATHL], paths[MAXPATHL];
3752 char_u *path, *next_path, *ptr;
3753 struct stat st;
3754
3755 STRCPY(paths, USER_HOME);
3756 next_path = paths;
3757 while (*next_path)
3758 {
3759 for (path = next_path; *next_path && *next_path != ',';
3760 next_path++);
3761 if (*next_path)
3762 *next_path++ = NUL;
3763 STRCPY(test, path);
3764 STRCAT(test, "/");
3765 STRCAT(test, dst + 1);
3766 if (mch_stat(test, &st) == 0)
3767 {
3768 var = alloc(STRLEN(test) + 1);
3769 STRCPY(var, test);
3770 mustfree = TRUE;
3771 break;
3772 }
3773 }
3774 }
3775# endif /* UNIX */
3776#else
3777 /* cannot expand user's home directory, so don't try */
3778 var = NULL;
3779 tail = (char_u *)""; /* for gcc */
3780#endif /* UNIX || VMS */
3781 }
3782
3783#ifdef BACKSLASH_IN_FILENAME
3784 /* If 'shellslash' is set change backslashes to forward slashes.
3785 * Can't use slash_adjust(), p_ssl may be set temporarily. */
3786 if (p_ssl && var != NULL && vim_strchr(var, '\\') != NULL)
3787 {
3788 char_u *p = vim_strsave(var);
3789
3790 if (p != NULL)
3791 {
3792 if (mustfree)
3793 vim_free(var);
3794 var = p;
3795 mustfree = TRUE;
3796 forward_slash(var);
3797 }
3798 }
3799#endif
3800
3801 /* If "var" contains white space, escape it with a backslash.
3802 * Required for ":e ~/tt" when $HOME includes a space. */
3803 if (esc && var != NULL && vim_strpbrk(var, (char_u *)" \t") != NULL)
3804 {
3805 char_u *p = vim_strsave_escaped(var, (char_u *)" \t");
3806
3807 if (p != NULL)
3808 {
3809 if (mustfree)
3810 vim_free(var);
3811 var = p;
3812 mustfree = TRUE;
3813 }
3814 }
3815
3816 if (var != NULL && *var != NUL
3817 && (STRLEN(var) + STRLEN(tail) + 1 < (unsigned)dstlen))
3818 {
3819 STRCPY(dst, var);
3820 dstlen -= (int)STRLEN(var);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003821 c = (int)STRLEN(var);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003822 /* if var[] ends in a path separator and tail[] starts
3823 * with it, skip a character */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003824 if (*var != NUL && after_pathsep(dst, dst + c)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003825#if defined(BACKSLASH_IN_FILENAME) || defined(AMIGA)
3826 && dst[-1] != ':'
3827#endif
3828 && vim_ispathsep(*tail))
3829 ++tail;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003830 dst += c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003831 src = tail;
3832 copy_char = FALSE;
3833 }
3834 if (mustfree)
3835 vim_free(var);
3836 }
3837
3838 if (copy_char) /* copy at least one char */
3839 {
3840 /*
Bram Moolenaar25394022007-05-10 19:06:20 +00003841 * Recognize the start of a new name, for '~'.
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003842 * Don't do this when "one" is TRUE, to avoid expanding "~" in
3843 * ":edit foo ~ foo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00003844 */
3845 at_start = FALSE;
3846 if (src[0] == '\\' && src[1] != NUL)
3847 {
3848 *dst++ = *src++;
3849 --dstlen;
3850 }
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003851 else if ((src[0] == ' ' || src[0] == ',') && !one)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003852 at_start = TRUE;
3853 *dst++ = *src++;
3854 --dstlen;
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003855
3856 if (startstr != NULL && src - startstr_len >= srcp
3857 && STRNCMP(src - startstr_len, startstr, startstr_len) == 0)
3858 at_start = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003859 }
3860 }
3861 *dst = NUL;
3862}
3863
3864/*
3865 * Vim's version of getenv().
3866 * Special handling of $HOME, $VIM and $VIMRUNTIME.
Bram Moolenaar2f6b0b82005-03-08 22:43:10 +00003867 * Also does ACP to 'enc' conversion for Win32.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003868 */
3869 char_u *
3870vim_getenv(name, mustfree)
3871 char_u *name;
3872 int *mustfree; /* set to TRUE when returned is allocated */
3873{
3874 char_u *p;
3875 char_u *pend;
3876 int vimruntime;
3877
3878#if defined(OS2) || defined(MSDOS) || defined(MSWIN)
3879 /* use "C:/" when $HOME is not set */
3880 if (STRCMP(name, "HOME") == 0)
3881 return homedir;
3882#endif
3883
3884 p = mch_getenv(name);
3885 if (p != NULL && *p == NUL) /* empty is the same as not set */
3886 p = NULL;
3887
3888 if (p != NULL)
Bram Moolenaar05159a02005-02-26 23:04:13 +00003889 {
3890#if defined(FEAT_MBYTE) && defined(WIN3264)
3891 if (enc_utf8)
3892 {
3893 int len;
3894 char_u *pp;
3895
3896 /* Convert from active codepage to UTF-8. Other conversions are
3897 * not done, because they would fail for non-ASCII characters. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003898 acp_to_enc(p, (int)STRLEN(p), &pp, &len);
Bram Moolenaar05159a02005-02-26 23:04:13 +00003899 if (pp != NULL)
3900 {
3901 p = pp;
3902 *mustfree = TRUE;
3903 }
3904 }
3905#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003906 return p;
Bram Moolenaar05159a02005-02-26 23:04:13 +00003907 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003908
3909 vimruntime = (STRCMP(name, "VIMRUNTIME") == 0);
3910 if (!vimruntime && STRCMP(name, "VIM") != 0)
3911 return NULL;
3912
3913 /*
3914 * When expanding $VIMRUNTIME fails, try using $VIM/vim<version> or $VIM.
3915 * Don't do this when default_vimruntime_dir is non-empty.
3916 */
3917 if (vimruntime
3918#ifdef HAVE_PATHDEF
3919 && *default_vimruntime_dir == NUL
3920#endif
3921 )
3922 {
3923 p = mch_getenv((char_u *)"VIM");
3924 if (p != NULL && *p == NUL) /* empty is the same as not set */
3925 p = NULL;
3926 if (p != NULL)
3927 {
3928 p = vim_version_dir(p);
3929 if (p != NULL)
3930 *mustfree = TRUE;
3931 else
3932 p = mch_getenv((char_u *)"VIM");
Bram Moolenaar05159a02005-02-26 23:04:13 +00003933
3934#if defined(FEAT_MBYTE) && defined(WIN3264)
3935 if (enc_utf8)
3936 {
3937 int len;
3938 char_u *pp;
3939
3940 /* Convert from active codepage to UTF-8. Other conversions
3941 * are not done, because they would fail for non-ASCII
3942 * characters. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003943 acp_to_enc(p, (int)STRLEN(p), &pp, &len);
Bram Moolenaar05159a02005-02-26 23:04:13 +00003944 if (pp != NULL)
3945 {
3946 if (mustfree)
3947 vim_free(p);
3948 p = pp;
3949 *mustfree = TRUE;
3950 }
3951 }
3952#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003953 }
3954 }
3955
3956 /*
3957 * When expanding $VIM or $VIMRUNTIME fails, try using:
3958 * - the directory name from 'helpfile' (unless it contains '$')
3959 * - the executable name from argv[0]
3960 */
3961 if (p == NULL)
3962 {
3963 if (p_hf != NULL && vim_strchr(p_hf, '$') == NULL)
3964 p = p_hf;
3965#ifdef USE_EXE_NAME
3966 /*
3967 * Use the name of the executable, obtained from argv[0].
3968 */
3969 else
3970 p = exe_name;
3971#endif
3972 if (p != NULL)
3973 {
3974 /* remove the file name */
3975 pend = gettail(p);
3976
3977 /* remove "doc/" from 'helpfile', if present */
3978 if (p == p_hf)
3979 pend = remove_tail(p, pend, (char_u *)"doc");
3980
3981#ifdef USE_EXE_NAME
3982# ifdef MACOS_X
Bram Moolenaar95e9b492006-03-15 23:04:43 +00003983 /* remove "MacOS" from exe_name and add "Resources/vim" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003984 if (p == exe_name)
3985 {
3986 char_u *pend1;
Bram Moolenaar95e9b492006-03-15 23:04:43 +00003987 char_u *pnew;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003988
Bram Moolenaar95e9b492006-03-15 23:04:43 +00003989 pend1 = remove_tail(p, pend, (char_u *)"MacOS");
3990 if (pend1 != pend)
3991 {
3992 pnew = alloc((unsigned)(pend1 - p) + 15);
3993 if (pnew != NULL)
3994 {
3995 STRNCPY(pnew, p, (pend1 - p));
3996 STRCPY(pnew + (pend1 - p), "Resources/vim");
3997 p = pnew;
3998 pend = p + STRLEN(p);
3999 }
4000 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004001 }
4002# endif
4003 /* remove "src/" from exe_name, if present */
4004 if (p == exe_name)
4005 pend = remove_tail(p, pend, (char_u *)"src");
4006#endif
4007
4008 /* for $VIM, remove "runtime/" or "vim54/", if present */
4009 if (!vimruntime)
4010 {
4011 pend = remove_tail(p, pend, (char_u *)RUNTIME_DIRNAME);
4012 pend = remove_tail(p, pend, (char_u *)VIM_VERSION_NODOT);
4013 }
4014
4015 /* remove trailing path separator */
4016#ifndef MACOS_CLASSIC
4017 /* With MacOS path (with colons) the final colon is required */
Bram Moolenaare21877a2008-02-13 09:58:14 +00004018 /* to avoid confusion between absolute and relative path */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004019 if (pend > p && after_pathsep(p, pend))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004020 --pend;
4021#endif
4022
Bram Moolenaar95e9b492006-03-15 23:04:43 +00004023#ifdef MACOS_X
4024 if (p == exe_name || p == p_hf)
4025#endif
4026 /* check that the result is a directory name */
4027 p = vim_strnsave(p, (int)(pend - p));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004028
4029 if (p != NULL && !mch_isdir(p))
4030 {
4031 vim_free(p);
4032 p = NULL;
4033 }
4034 else
4035 {
4036#ifdef USE_EXE_NAME
4037 /* may add "/vim54" or "/runtime" if it exists */
4038 if (vimruntime && (pend = vim_version_dir(p)) != NULL)
4039 {
4040 vim_free(p);
4041 p = pend;
4042 }
4043#endif
4044 *mustfree = TRUE;
4045 }
4046 }
4047 }
4048
4049#ifdef HAVE_PATHDEF
4050 /* When there is a pathdef.c file we can use default_vim_dir and
4051 * default_vimruntime_dir */
4052 if (p == NULL)
4053 {
4054 /* Only use default_vimruntime_dir when it is not empty */
4055 if (vimruntime && *default_vimruntime_dir != NUL)
4056 {
4057 p = default_vimruntime_dir;
4058 *mustfree = FALSE;
4059 }
4060 else if (*default_vim_dir != NUL)
4061 {
4062 if (vimruntime && (p = vim_version_dir(default_vim_dir)) != NULL)
4063 *mustfree = TRUE;
4064 else
4065 {
4066 p = default_vim_dir;
4067 *mustfree = FALSE;
4068 }
4069 }
4070 }
4071#endif
4072
4073 /*
4074 * Set the environment variable, so that the new value can be found fast
4075 * next time, and others can also use it (e.g. Perl).
4076 */
4077 if (p != NULL)
4078 {
4079 if (vimruntime)
4080 {
4081 vim_setenv((char_u *)"VIMRUNTIME", p);
4082 didset_vimruntime = TRUE;
4083#ifdef FEAT_GETTEXT
4084 {
Bram Moolenaard6754642005-01-17 22:18:45 +00004085 char_u *buf = concat_str(p, (char_u *)"/lang");
Bram Moolenaar071d4272004-06-13 20:20:40 +00004086
4087 if (buf != NULL)
4088 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004089 bindtextdomain(VIMPACKAGE, (char *)buf);
4090 vim_free(buf);
4091 }
4092 }
4093#endif
4094 }
4095 else
4096 {
4097 vim_setenv((char_u *)"VIM", p);
4098 didset_vim = TRUE;
4099 }
4100 }
4101 return p;
4102}
4103
4104/*
4105 * Check if the directory "vimdir/<version>" or "vimdir/runtime" exists.
4106 * Return NULL if not, return its name in allocated memory otherwise.
4107 */
4108 static char_u *
4109vim_version_dir(vimdir)
4110 char_u *vimdir;
4111{
4112 char_u *p;
4113
4114 if (vimdir == NULL || *vimdir == NUL)
4115 return NULL;
4116 p = concat_fnames(vimdir, (char_u *)VIM_VERSION_NODOT, TRUE);
4117 if (p != NULL && mch_isdir(p))
4118 return p;
4119 vim_free(p);
4120 p = concat_fnames(vimdir, (char_u *)RUNTIME_DIRNAME, TRUE);
4121 if (p != NULL && mch_isdir(p))
4122 return p;
4123 vim_free(p);
4124 return NULL;
4125}
4126
4127/*
4128 * If the string between "p" and "pend" ends in "name/", return "pend" minus
4129 * the length of "name/". Otherwise return "pend".
4130 */
4131 static char_u *
4132remove_tail(p, pend, name)
4133 char_u *p;
4134 char_u *pend;
4135 char_u *name;
4136{
4137 int len = (int)STRLEN(name) + 1;
4138 char_u *newend = pend - len;
4139
4140 if (newend >= p
4141 && fnamencmp(newend, name, len - 1) == 0
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004142 && (newend == p || after_pathsep(p, newend)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004143 return newend;
4144 return pend;
4145}
4146
Bram Moolenaar071d4272004-06-13 20:20:40 +00004147/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004148 * Our portable version of setenv.
4149 */
4150 void
4151vim_setenv(name, val)
4152 char_u *name;
4153 char_u *val;
4154{
4155#ifdef HAVE_SETENV
4156 mch_setenv((char *)name, (char *)val, 1);
4157#else
4158 char_u *envbuf;
4159
4160 /*
4161 * Putenv does not copy the string, it has to remain
4162 * valid. The allocated memory will never be freed.
4163 */
4164 envbuf = alloc((unsigned)(STRLEN(name) + STRLEN(val) + 2));
4165 if (envbuf != NULL)
4166 {
4167 sprintf((char *)envbuf, "%s=%s", name, val);
4168 putenv((char *)envbuf);
4169 }
4170#endif
4171}
4172
4173#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
4174/*
4175 * Function given to ExpandGeneric() to obtain an environment variable name.
4176 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004177 char_u *
4178get_env_name(xp, idx)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00004179 expand_T *xp UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004180 int idx;
4181{
4182# if defined(AMIGA) || defined(__MRC__) || defined(__SC__)
4183 /*
4184 * No environ[] on the Amiga and on the Mac (using MPW).
4185 */
4186 return NULL;
4187# else
4188# ifndef __WIN32__
4189 /* Borland C++ 5.2 has this in a header file. */
4190 extern char **environ;
4191# endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00004192# define ENVNAMELEN 100
4193 static char_u name[ENVNAMELEN];
Bram Moolenaar071d4272004-06-13 20:20:40 +00004194 char_u *str;
4195 int n;
4196
4197 str = (char_u *)environ[idx];
4198 if (str == NULL)
4199 return NULL;
4200
Bram Moolenaar21cf8232004-07-16 20:18:37 +00004201 for (n = 0; n < ENVNAMELEN - 1; ++n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004202 {
4203 if (str[n] == '=' || str[n] == NUL)
4204 break;
4205 name[n] = str[n];
4206 }
4207 name[n] = NUL;
4208 return name;
4209# endif
4210}
4211#endif
4212
4213/*
4214 * Replace home directory by "~" in each space or comma separated file name in
4215 * 'src'.
4216 * If anything fails (except when out of space) dst equals src.
4217 */
4218 void
4219home_replace(buf, src, dst, dstlen, one)
4220 buf_T *buf; /* when not NULL, check for help files */
4221 char_u *src; /* input file name */
4222 char_u *dst; /* where to put the result */
4223 int dstlen; /* maximum length of the result */
4224 int one; /* if TRUE, only replace one file name, include
4225 spaces and commas in the file name. */
4226{
4227 size_t dirlen = 0, envlen = 0;
4228 size_t len;
4229 char_u *homedir_env;
4230 char_u *p;
4231
4232 if (src == NULL)
4233 {
4234 *dst = NUL;
4235 return;
4236 }
4237
4238 /*
4239 * If the file is a help file, remove the path completely.
4240 */
4241 if (buf != NULL && buf->b_help)
4242 {
4243 STRCPY(dst, gettail(src));
4244 return;
4245 }
4246
4247 /*
4248 * We check both the value of the $HOME environment variable and the
4249 * "real" home directory.
4250 */
4251 if (homedir != NULL)
4252 dirlen = STRLEN(homedir);
4253
4254#ifdef VMS
4255 homedir_env = mch_getenv((char_u *)"SYS$LOGIN");
4256#else
4257 homedir_env = mch_getenv((char_u *)"HOME");
4258#endif
4259
4260 if (homedir_env != NULL && *homedir_env == NUL)
4261 homedir_env = NULL;
4262 if (homedir_env != NULL)
4263 envlen = STRLEN(homedir_env);
4264
4265 if (!one)
4266 src = skipwhite(src);
4267 while (*src && dstlen > 0)
4268 {
4269 /*
4270 * Here we are at the beginning of a file name.
4271 * First, check to see if the beginning of the file name matches
4272 * $HOME or the "real" home directory. Check that there is a '/'
4273 * after the match (so that if e.g. the file is "/home/pieter/bla",
4274 * and the home directory is "/home/piet", the file does not end up
4275 * as "~er/bla" (which would seem to indicate the file "bla" in user
4276 * er's home directory)).
4277 */
4278 p = homedir;
4279 len = dirlen;
4280 for (;;)
4281 {
4282 if ( len
4283 && fnamencmp(src, p, len) == 0
4284 && (vim_ispathsep(src[len])
4285 || (!one && (src[len] == ',' || src[len] == ' '))
4286 || src[len] == NUL))
4287 {
4288 src += len;
4289 if (--dstlen > 0)
4290 *dst++ = '~';
4291
4292 /*
4293 * If it's just the home directory, add "/".
4294 */
4295 if (!vim_ispathsep(src[0]) && --dstlen > 0)
4296 *dst++ = '/';
4297 break;
4298 }
4299 if (p == homedir_env)
4300 break;
4301 p = homedir_env;
4302 len = envlen;
4303 }
4304
4305 /* if (!one) skip to separator: space or comma */
4306 while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
4307 *dst++ = *src++;
4308 /* skip separator */
4309 while ((*src == ' ' || *src == ',') && --dstlen > 0)
4310 *dst++ = *src++;
4311 }
4312 /* if (dstlen == 0) out of space, what to do??? */
4313
4314 *dst = NUL;
4315}
4316
4317/*
4318 * Like home_replace, store the replaced string in allocated memory.
4319 * When something fails, NULL is returned.
4320 */
4321 char_u *
4322home_replace_save(buf, src)
4323 buf_T *buf; /* when not NULL, check for help files */
4324 char_u *src; /* input file name */
4325{
4326 char_u *dst;
4327 unsigned len;
4328
4329 len = 3; /* space for "~/" and trailing NUL */
4330 if (src != NULL) /* just in case */
4331 len += (unsigned)STRLEN(src);
4332 dst = alloc(len);
4333 if (dst != NULL)
4334 home_replace(buf, src, dst, len, TRUE);
4335 return dst;
4336}
4337
4338/*
4339 * Compare two file names and return:
4340 * FPC_SAME if they both exist and are the same file.
4341 * FPC_SAMEX if they both don't exist and have the same file name.
4342 * FPC_DIFF if they both exist and are different files.
4343 * FPC_NOTX if they both don't exist.
4344 * FPC_DIFFX if one of them doesn't exist.
4345 * For the first name environment variables are expanded
4346 */
4347 int
4348fullpathcmp(s1, s2, checkname)
4349 char_u *s1, *s2;
4350 int checkname; /* when both don't exist, check file names */
4351{
4352#ifdef UNIX
4353 char_u exp1[MAXPATHL];
4354 char_u full1[MAXPATHL];
4355 char_u full2[MAXPATHL];
4356 struct stat st1, st2;
4357 int r1, r2;
4358
4359 expand_env(s1, exp1, MAXPATHL);
4360 r1 = mch_stat((char *)exp1, &st1);
4361 r2 = mch_stat((char *)s2, &st2);
4362 if (r1 != 0 && r2 != 0)
4363 {
4364 /* if mch_stat() doesn't work, may compare the names */
4365 if (checkname)
4366 {
4367 if (fnamecmp(exp1, s2) == 0)
4368 return FPC_SAMEX;
4369 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4370 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4371 if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
4372 return FPC_SAMEX;
4373 }
4374 return FPC_NOTX;
4375 }
4376 if (r1 != 0 || r2 != 0)
4377 return FPC_DIFFX;
4378 if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
4379 return FPC_SAME;
4380 return FPC_DIFF;
4381#else
4382 char_u *exp1; /* expanded s1 */
4383 char_u *full1; /* full path of s1 */
4384 char_u *full2; /* full path of s2 */
4385 int retval = FPC_DIFF;
4386 int r1, r2;
4387
4388 /* allocate one buffer to store three paths (alloc()/free() is slow!) */
4389 if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
4390 {
4391 full1 = exp1 + MAXPATHL;
4392 full2 = full1 + MAXPATHL;
4393
4394 expand_env(s1, exp1, MAXPATHL);
4395 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4396 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4397
4398 /* If vim_FullName() fails, the file probably doesn't exist. */
4399 if (r1 != OK && r2 != OK)
4400 {
4401 if (checkname && fnamecmp(exp1, s2) == 0)
4402 retval = FPC_SAMEX;
4403 else
4404 retval = FPC_NOTX;
4405 }
4406 else if (r1 != OK || r2 != OK)
4407 retval = FPC_DIFFX;
4408 else if (fnamecmp(full1, full2))
4409 retval = FPC_DIFF;
4410 else
4411 retval = FPC_SAME;
4412 vim_free(exp1);
4413 }
4414 return retval;
4415#endif
4416}
4417
4418/*
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004419 * Get the tail of a path: the file name.
4420 * Fail safe: never returns NULL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004421 */
4422 char_u *
4423gettail(fname)
4424 char_u *fname;
4425{
4426 char_u *p1, *p2;
4427
4428 if (fname == NULL)
4429 return (char_u *)"";
4430 for (p1 = p2 = fname; *p2; ) /* find last part of path */
4431 {
4432 if (vim_ispathsep(*p2))
4433 p1 = p2 + 1;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004434 mb_ptr_adv(p2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004435 }
4436 return p1;
4437}
4438
4439/*
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004440 * Get pointer to tail of "fname", including path separators. Putting a NUL
4441 * here leaves the directory name. Takes care of "c:/" and "//".
4442 * Always returns a valid pointer.
4443 */
4444 char_u *
4445gettail_sep(fname)
4446 char_u *fname;
4447{
4448 char_u *p;
4449 char_u *t;
4450
4451 p = get_past_head(fname); /* don't remove the '/' from "c:/file" */
4452 t = gettail(fname);
4453 while (t > p && after_pathsep(fname, t))
4454 --t;
4455#ifdef VMS
4456 /* path separator is part of the path */
4457 ++t;
4458#endif
4459 return t;
4460}
4461
4462/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004463 * get the next path component (just after the next path separator).
4464 */
4465 char_u *
4466getnextcomp(fname)
4467 char_u *fname;
4468{
4469 while (*fname && !vim_ispathsep(*fname))
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004470 mb_ptr_adv(fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004471 if (*fname)
4472 ++fname;
4473 return fname;
4474}
4475
Bram Moolenaar071d4272004-06-13 20:20:40 +00004476/*
4477 * Get a pointer to one character past the head of a path name.
4478 * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
4479 * If there is no head, path is returned.
4480 */
4481 char_u *
4482get_past_head(path)
4483 char_u *path;
4484{
4485 char_u *retval;
4486
4487#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
4488 /* may skip "c:" */
4489 if (isalpha(path[0]) && path[1] == ':')
4490 retval = path + 2;
4491 else
4492 retval = path;
4493#else
4494# if defined(AMIGA)
4495 /* may skip "label:" */
4496 retval = vim_strchr(path, ':');
4497 if (retval == NULL)
4498 retval = path;
4499# else /* Unix */
4500 retval = path;
4501# endif
4502#endif
4503
4504 while (vim_ispathsep(*retval))
4505 ++retval;
4506
4507 return retval;
4508}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004509
4510/*
4511 * return TRUE if 'c' is a path separator.
4512 */
4513 int
4514vim_ispathsep(c)
4515 int c;
4516{
4517#ifdef RISCOS
4518 return (c == '.' || c == ':');
4519#else
4520# ifdef UNIX
4521 return (c == '/'); /* UNIX has ':' inside file names */
4522# else
4523# ifdef BACKSLASH_IN_FILENAME
4524 return (c == ':' || c == '/' || c == '\\');
4525# else
4526# ifdef VMS
4527 /* server"user passwd"::device:[full.path.name]fname.extension;version" */
4528 return (c == ':' || c == '[' || c == ']' || c == '/'
4529 || c == '<' || c == '>' || c == '"' );
Bram Moolenaar1056d982006-03-09 22:37:52 +00004530# else /* Amiga */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004531 return (c == ':' || c == '/');
Bram Moolenaar071d4272004-06-13 20:20:40 +00004532# endif /* VMS */
4533# endif
4534# endif
4535#endif /* RISC OS */
4536}
4537
4538#if defined(FEAT_SEARCHPATH) || defined(PROTO)
4539/*
4540 * return TRUE if 'c' is a path list separator.
4541 */
4542 int
4543vim_ispathlistsep(c)
4544 int c;
4545{
4546#ifdef UNIX
4547 return (c == ':');
4548#else
Bram Moolenaar25394022007-05-10 19:06:20 +00004549 return (c == ';'); /* might not be right for every system... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004550#endif
4551}
4552#endif
4553
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004554#if defined(FEAT_GUI_TABLINE) || defined(FEAT_WINDOWS) \
4555 || defined(FEAT_EVAL) || defined(PROTO)
4556/*
4557 * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
4558 * It's done in-place.
4559 */
4560 void
4561shorten_dir(str)
4562 char_u *str;
4563{
4564 char_u *tail, *s, *d;
4565 int skip = FALSE;
4566
4567 tail = gettail(str);
4568 d = str;
4569 for (s = str; ; ++s)
4570 {
4571 if (s >= tail) /* copy the whole tail */
4572 {
4573 *d++ = *s;
4574 if (*s == NUL)
4575 break;
4576 }
4577 else if (vim_ispathsep(*s)) /* copy '/' and next char */
4578 {
4579 *d++ = *s;
4580 skip = FALSE;
4581 }
4582 else if (!skip)
4583 {
4584 *d++ = *s; /* copy next char */
4585 if (*s != '~' && *s != '.') /* and leading "~" and "." */
4586 skip = TRUE;
4587# ifdef FEAT_MBYTE
4588 if (has_mbyte)
4589 {
4590 int l = mb_ptr2len(s);
4591
4592 while (--l > 0)
Bram Moolenaarb6baca52006-08-15 20:24:14 +00004593 *d++ = *++s;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004594 }
4595# endif
4596 }
4597 }
4598}
4599#endif
4600
Bram Moolenaar900b4d72005-12-12 22:05:50 +00004601/*
4602 * Return TRUE if the directory of "fname" exists, FALSE otherwise.
4603 * Also returns TRUE if there is no directory name.
4604 * "fname" must be writable!.
4605 */
4606 int
4607dir_of_file_exists(fname)
4608 char_u *fname;
4609{
4610 char_u *p;
4611 int c;
4612 int retval;
4613
4614 p = gettail_sep(fname);
4615 if (p == fname)
4616 return TRUE;
4617 c = *p;
4618 *p = NUL;
4619 retval = mch_isdir(fname);
4620 *p = c;
4621 return retval;
4622}
4623
Bram Moolenaar071d4272004-06-13 20:20:40 +00004624#if (defined(CASE_INSENSITIVE_FILENAME) && defined(BACKSLASH_IN_FILENAME)) \
4625 || defined(PROTO)
4626/*
4627 * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally.
4628 */
4629 int
4630vim_fnamecmp(x, y)
4631 char_u *x, *y;
4632{
4633 return vim_fnamencmp(x, y, MAXPATHL);
4634}
4635
4636 int
4637vim_fnamencmp(x, y, len)
4638 char_u *x, *y;
4639 size_t len;
4640{
4641 while (len > 0 && *x && *y)
4642 {
4643 if (TOLOWER_LOC(*x) != TOLOWER_LOC(*y)
4644 && !(*x == '/' && *y == '\\')
4645 && !(*x == '\\' && *y == '/'))
4646 break;
4647 ++x;
4648 ++y;
4649 --len;
4650 }
4651 if (len == 0)
4652 return 0;
4653 return (*x - *y);
4654}
4655#endif
4656
4657/*
4658 * Concatenate file names fname1 and fname2 into allocated memory.
Bram Moolenaar25394022007-05-10 19:06:20 +00004659 * Only add a '/' or '\\' when 'sep' is TRUE and it is necessary.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004660 */
4661 char_u *
4662concat_fnames(fname1, fname2, sep)
4663 char_u *fname1;
4664 char_u *fname2;
4665 int sep;
4666{
4667 char_u *dest;
4668
4669 dest = alloc((unsigned)(STRLEN(fname1) + STRLEN(fname2) + 3));
4670 if (dest != NULL)
4671 {
4672 STRCPY(dest, fname1);
4673 if (sep)
4674 add_pathsep(dest);
4675 STRCAT(dest, fname2);
4676 }
4677 return dest;
4678}
4679
Bram Moolenaard6754642005-01-17 22:18:45 +00004680/*
4681 * Concatenate two strings and return the result in allocated memory.
4682 * Returns NULL when out of memory.
4683 */
4684 char_u *
4685concat_str(str1, str2)
4686 char_u *str1;
4687 char_u *str2;
4688{
4689 char_u *dest;
4690 size_t l = STRLEN(str1);
4691
4692 dest = alloc((unsigned)(l + STRLEN(str2) + 1L));
4693 if (dest != NULL)
4694 {
4695 STRCPY(dest, str1);
4696 STRCPY(dest + l, str2);
4697 }
4698 return dest;
4699}
Bram Moolenaard6754642005-01-17 22:18:45 +00004700
Bram Moolenaar071d4272004-06-13 20:20:40 +00004701/*
4702 * Add a path separator to a file name, unless it already ends in a path
4703 * separator.
4704 */
4705 void
4706add_pathsep(p)
4707 char_u *p;
4708{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004709 if (*p != NUL && !after_pathsep(p, p + STRLEN(p)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004710 STRCAT(p, PATHSEPSTR);
4711}
4712
4713/*
4714 * FullName_save - Make an allocated copy of a full file name.
4715 * Returns NULL when out of memory.
4716 */
4717 char_u *
4718FullName_save(fname, force)
4719 char_u *fname;
4720 int force; /* force expansion, even when it already looks
4721 like a full path name */
4722{
4723 char_u *buf;
4724 char_u *new_fname = NULL;
4725
4726 if (fname == NULL)
4727 return NULL;
4728
4729 buf = alloc((unsigned)MAXPATHL);
4730 if (buf != NULL)
4731 {
4732 if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
4733 new_fname = vim_strsave(buf);
4734 else
4735 new_fname = vim_strsave(fname);
4736 vim_free(buf);
4737 }
4738 return new_fname;
4739}
4740
4741#if defined(FEAT_CINDENT) || defined(FEAT_SYN_HL)
4742
4743static char_u *skip_string __ARGS((char_u *p));
4744
4745/*
4746 * Find the start of a comment, not knowing if we are in a comment right now.
4747 * Search starts at w_cursor.lnum and goes backwards.
4748 */
4749 pos_T *
4750find_start_comment(ind_maxcomment) /* XXX */
4751 int ind_maxcomment;
4752{
4753 pos_T *pos;
4754 char_u *line;
4755 char_u *p;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00004756 int cur_maxcomment = ind_maxcomment;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004757
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00004758 for (;;)
4759 {
4760 pos = findmatchlimit(NULL, '*', FM_BACKWARD, cur_maxcomment);
4761 if (pos == NULL)
4762 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004763
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00004764 /*
4765 * Check if the comment start we found is inside a string.
4766 * If it is then restrict the search to below this line and try again.
4767 */
4768 line = ml_get(pos->lnum);
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00004769 for (p = line; *p && (colnr_T)(p - line) < pos->col; ++p)
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00004770 p = skip_string(p);
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00004771 if ((colnr_T)(p - line) <= pos->col)
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00004772 break;
4773 cur_maxcomment = curwin->w_cursor.lnum - pos->lnum - 1;
4774 if (cur_maxcomment <= 0)
4775 {
4776 pos = NULL;
4777 break;
4778 }
4779 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004780 return pos;
4781}
4782
4783/*
4784 * Skip to the end of a "string" and a 'c' character.
4785 * If there is no string or character, return argument unmodified.
4786 */
4787 static char_u *
4788skip_string(p)
4789 char_u *p;
4790{
4791 int i;
4792
4793 /*
4794 * We loop, because strings may be concatenated: "date""time".
4795 */
4796 for ( ; ; ++p)
4797 {
4798 if (p[0] == '\'') /* 'c' or '\n' or '\000' */
4799 {
4800 if (!p[1]) /* ' at end of line */
4801 break;
4802 i = 2;
4803 if (p[1] == '\\') /* '\n' or '\000' */
4804 {
4805 ++i;
4806 while (vim_isdigit(p[i - 1])) /* '\000' */
4807 ++i;
4808 }
4809 if (p[i] == '\'') /* check for trailing ' */
4810 {
4811 p += i;
4812 continue;
4813 }
4814 }
4815 else if (p[0] == '"') /* start of string */
4816 {
4817 for (++p; p[0]; ++p)
4818 {
4819 if (p[0] == '\\' && p[1] != NUL)
4820 ++p;
4821 else if (p[0] == '"') /* end of string */
4822 break;
4823 }
4824 if (p[0] == '"')
4825 continue;
4826 }
4827 break; /* no string found */
4828 }
4829 if (!*p)
4830 --p; /* backup from NUL */
4831 return p;
4832}
4833#endif /* FEAT_CINDENT || FEAT_SYN_HL */
4834
4835#if defined(FEAT_CINDENT) || defined(PROTO)
4836
4837/*
4838 * Do C or expression indenting on the current line.
4839 */
4840 void
4841do_c_expr_indent()
4842{
4843# ifdef FEAT_EVAL
4844 if (*curbuf->b_p_inde != NUL)
4845 fixthisline(get_expr_indent);
4846 else
4847# endif
4848 fixthisline(get_c_indent);
4849}
4850
4851/*
4852 * Functions for C-indenting.
4853 * Most of this originally comes from Eric Fischer.
4854 */
4855/*
4856 * Below "XXX" means that this function may unlock the current line.
4857 */
4858
4859static char_u *cin_skipcomment __ARGS((char_u *));
4860static int cin_nocode __ARGS((char_u *));
4861static pos_T *find_line_comment __ARGS((void));
4862static int cin_islabel_skip __ARGS((char_u **));
4863static int cin_isdefault __ARGS((char_u *));
4864static char_u *after_label __ARGS((char_u *l));
4865static int get_indent_nolabel __ARGS((linenr_T lnum));
4866static int skip_label __ARGS((linenr_T, char_u **pp, int ind_maxcomment));
4867static int cin_first_id_amount __ARGS((void));
4868static int cin_get_equal_amount __ARGS((linenr_T lnum));
4869static int cin_ispreproc __ARGS((char_u *));
4870static int cin_ispreproc_cont __ARGS((char_u **pp, linenr_T *lnump));
4871static int cin_iscomment __ARGS((char_u *));
4872static int cin_islinecomment __ARGS((char_u *));
4873static int cin_isterminated __ARGS((char_u *, int, int));
4874static int cin_isinit __ARGS((void));
4875static int cin_isfuncdecl __ARGS((char_u **, linenr_T));
4876static int cin_isif __ARGS((char_u *));
4877static int cin_iselse __ARGS((char_u *));
4878static int cin_isdo __ARGS((char_u *));
4879static int cin_iswhileofdo __ARGS((char_u *, linenr_T, int));
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00004880static int cin_iswhileofdo_end __ARGS((int terminated, int ind_maxparen, int ind_maxcomment));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004881static int cin_isbreak __ARGS((char_u *));
Bram Moolenaare7c56862007-08-04 10:14:52 +00004882static int cin_is_cpp_baseclass __ARGS((colnr_T *col));
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00004883static int get_baseclass_amount __ARGS((int col, int ind_maxparen, int ind_maxcomment, int ind_cpp_baseclass));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004884static int cin_ends_in __ARGS((char_u *, char_u *, char_u *));
4885static int cin_skip2pos __ARGS((pos_T *trypos));
4886static pos_T *find_start_brace __ARGS((int));
4887static pos_T *find_match_paren __ARGS((int, int));
4888static int corr_ind_maxparen __ARGS((int ind_maxparen, pos_T *startpos));
4889static int find_last_paren __ARGS((char_u *l, int start, int end));
4890static int find_match __ARGS((int lookfor, linenr_T ourscope, int ind_maxparen, int ind_maxcomment));
4891
Bram Moolenaar39353fd2007-03-27 09:02:11 +00004892static int ind_hash_comment = 0; /* # starts a comment */
4893
Bram Moolenaar071d4272004-06-13 20:20:40 +00004894/*
4895 * Skip over white space and C comments within the line.
Bram Moolenaar39353fd2007-03-27 09:02:11 +00004896 * Also skip over Perl/shell comments if desired.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004897 */
4898 static char_u *
4899cin_skipcomment(s)
4900 char_u *s;
4901{
4902 while (*s)
4903 {
Bram Moolenaar39353fd2007-03-27 09:02:11 +00004904 char_u *prev_s = s;
4905
Bram Moolenaar071d4272004-06-13 20:20:40 +00004906 s = skipwhite(s);
Bram Moolenaar39353fd2007-03-27 09:02:11 +00004907
4908 /* Perl/shell # comment comment continues until eol. Require a space
4909 * before # to avoid recognizing $#array. */
4910 if (ind_hash_comment != 0 && s != prev_s && *s == '#')
4911 {
4912 s += STRLEN(s);
4913 break;
4914 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004915 if (*s != '/')
4916 break;
4917 ++s;
4918 if (*s == '/') /* slash-slash comment continues till eol */
4919 {
4920 s += STRLEN(s);
4921 break;
4922 }
4923 if (*s != '*')
4924 break;
4925 for (++s; *s; ++s) /* skip slash-star comment */
4926 if (s[0] == '*' && s[1] == '/')
4927 {
4928 s += 2;
4929 break;
4930 }
4931 }
4932 return s;
4933}
4934
4935/*
4936 * Return TRUE if there there is no code at *s. White space and comments are
4937 * not considered code.
4938 */
4939 static int
4940cin_nocode(s)
4941 char_u *s;
4942{
4943 return *cin_skipcomment(s) == NUL;
4944}
4945
4946/*
4947 * Check previous lines for a "//" line comment, skipping over blank lines.
4948 */
4949 static pos_T *
4950find_line_comment() /* XXX */
4951{
4952 static pos_T pos;
4953 char_u *line;
4954 char_u *p;
4955
4956 pos = curwin->w_cursor;
4957 while (--pos.lnum > 0)
4958 {
4959 line = ml_get(pos.lnum);
4960 p = skipwhite(line);
4961 if (cin_islinecomment(p))
4962 {
4963 pos.col = (int)(p - line);
4964 return &pos;
4965 }
4966 if (*p != NUL)
4967 break;
4968 }
4969 return NULL;
4970}
4971
4972/*
4973 * Check if string matches "label:"; move to character after ':' if true.
4974 */
4975 static int
4976cin_islabel_skip(s)
4977 char_u **s;
4978{
4979 if (!vim_isIDc(**s)) /* need at least one ID character */
4980 return FALSE;
4981
4982 while (vim_isIDc(**s))
4983 (*s)++;
4984
4985 *s = cin_skipcomment(*s);
4986
4987 /* "::" is not a label, it's C++ */
4988 return (**s == ':' && *++*s != ':');
4989}
4990
4991/*
4992 * Recognize a label: "label:".
4993 * Note: curwin->w_cursor must be where we are looking for the label.
4994 */
4995 int
4996cin_islabel(ind_maxcomment) /* XXX */
4997 int ind_maxcomment;
4998{
4999 char_u *s;
5000
5001 s = cin_skipcomment(ml_get_curline());
5002
5003 /*
5004 * Exclude "default" from labels, since it should be indented
5005 * like a switch label. Same for C++ scope declarations.
5006 */
5007 if (cin_isdefault(s))
5008 return FALSE;
5009 if (cin_isscopedecl(s))
5010 return FALSE;
5011
5012 if (cin_islabel_skip(&s))
5013 {
5014 /*
5015 * Only accept a label if the previous line is terminated or is a case
5016 * label.
5017 */
5018 pos_T cursor_save;
5019 pos_T *trypos;
5020 char_u *line;
5021
5022 cursor_save = curwin->w_cursor;
5023 while (curwin->w_cursor.lnum > 1)
5024 {
5025 --curwin->w_cursor.lnum;
5026
5027 /*
5028 * If we're in a comment now, skip to the start of the comment.
5029 */
5030 curwin->w_cursor.col = 0;
5031 if ((trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
5032 curwin->w_cursor = *trypos;
5033
5034 line = ml_get_curline();
5035 if (cin_ispreproc(line)) /* ignore #defines, #if, etc. */
5036 continue;
5037 if (*(line = cin_skipcomment(line)) == NUL)
5038 continue;
5039
5040 curwin->w_cursor = cursor_save;
5041 if (cin_isterminated(line, TRUE, FALSE)
5042 || cin_isscopedecl(line)
5043 || cin_iscase(line)
5044 || (cin_islabel_skip(&line) && cin_nocode(line)))
5045 return TRUE;
5046 return FALSE;
5047 }
5048 curwin->w_cursor = cursor_save;
5049 return TRUE; /* label at start of file??? */
5050 }
5051 return FALSE;
5052}
5053
5054/*
5055 * Recognize structure initialization and enumerations.
5056 * Q&D-Implementation:
5057 * check for "=" at end or "[typedef] enum" at beginning of line.
5058 */
5059 static int
5060cin_isinit(void)
5061{
5062 char_u *s;
5063
5064 s = cin_skipcomment(ml_get_curline());
5065
5066 if (STRNCMP(s, "typedef", 7) == 0 && !vim_isIDc(s[7]))
5067 s = cin_skipcomment(s + 7);
5068
5069 if (STRNCMP(s, "enum", 4) == 0 && !vim_isIDc(s[4]))
5070 return TRUE;
5071
5072 if (cin_ends_in(s, (char_u *)"=", (char_u *)"{"))
5073 return TRUE;
5074
5075 return FALSE;
5076}
5077
5078/*
5079 * Recognize a switch label: "case .*:" or "default:".
5080 */
5081 int
5082cin_iscase(s)
5083 char_u *s;
5084{
5085 s = cin_skipcomment(s);
5086 if (STRNCMP(s, "case", 4) == 0 && !vim_isIDc(s[4]))
5087 {
5088 for (s += 4; *s; ++s)
5089 {
5090 s = cin_skipcomment(s);
5091 if (*s == ':')
5092 {
5093 if (s[1] == ':') /* skip over "::" for C++ */
5094 ++s;
5095 else
5096 return TRUE;
5097 }
5098 if (*s == '\'' && s[1] && s[2] == '\'')
5099 s += 2; /* skip over '.' */
5100 else if (*s == '/' && (s[1] == '*' || s[1] == '/'))
5101 return FALSE; /* stop at comment */
5102 else if (*s == '"')
5103 return FALSE; /* stop at string */
5104 }
5105 return FALSE;
5106 }
5107
5108 if (cin_isdefault(s))
5109 return TRUE;
5110 return FALSE;
5111}
5112
5113/*
5114 * Recognize a "default" switch label.
5115 */
5116 static int
5117cin_isdefault(s)
5118 char_u *s;
5119{
5120 return (STRNCMP(s, "default", 7) == 0
5121 && *(s = cin_skipcomment(s + 7)) == ':'
5122 && s[1] != ':');
5123}
5124
5125/*
5126 * Recognize a "public/private/proctected" scope declaration label.
5127 */
5128 int
5129cin_isscopedecl(s)
5130 char_u *s;
5131{
5132 int i;
5133
5134 s = cin_skipcomment(s);
5135 if (STRNCMP(s, "public", 6) == 0)
5136 i = 6;
5137 else if (STRNCMP(s, "protected", 9) == 0)
5138 i = 9;
5139 else if (STRNCMP(s, "private", 7) == 0)
5140 i = 7;
5141 else
5142 return FALSE;
5143 return (*(s = cin_skipcomment(s + i)) == ':' && s[1] != ':');
5144}
5145
5146/*
5147 * Return a pointer to the first non-empty non-comment character after a ':'.
5148 * Return NULL if not found.
5149 * case 234: a = b;
5150 * ^
5151 */
5152 static char_u *
5153after_label(l)
5154 char_u *l;
5155{
5156 for ( ; *l; ++l)
5157 {
5158 if (*l == ':')
5159 {
5160 if (l[1] == ':') /* skip over "::" for C++ */
5161 ++l;
5162 else if (!cin_iscase(l + 1))
5163 break;
5164 }
5165 else if (*l == '\'' && l[1] && l[2] == '\'')
5166 l += 2; /* skip over 'x' */
5167 }
5168 if (*l == NUL)
5169 return NULL;
5170 l = cin_skipcomment(l + 1);
5171 if (*l == NUL)
5172 return NULL;
5173 return l;
5174}
5175
5176/*
5177 * Get indent of line "lnum", skipping a label.
5178 * Return 0 if there is nothing after the label.
5179 */
5180 static int
5181get_indent_nolabel(lnum) /* XXX */
5182 linenr_T lnum;
5183{
5184 char_u *l;
5185 pos_T fp;
5186 colnr_T col;
5187 char_u *p;
5188
5189 l = ml_get(lnum);
5190 p = after_label(l);
5191 if (p == NULL)
5192 return 0;
5193
5194 fp.col = (colnr_T)(p - l);
5195 fp.lnum = lnum;
5196 getvcol(curwin, &fp, &col, NULL, NULL);
5197 return (int)col;
5198}
5199
5200/*
5201 * Find indent for line "lnum", ignoring any case or jump label.
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005202 * Also return a pointer to the text (after the label) in "pp".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005203 * label: if (asdf && asdfasdf)
5204 * ^
5205 */
5206 static int
5207skip_label(lnum, pp, ind_maxcomment)
5208 linenr_T lnum;
5209 char_u **pp;
5210 int ind_maxcomment;
5211{
5212 char_u *l;
5213 int amount;
5214 pos_T cursor_save;
5215
5216 cursor_save = curwin->w_cursor;
5217 curwin->w_cursor.lnum = lnum;
5218 l = ml_get_curline();
5219 /* XXX */
5220 if (cin_iscase(l) || cin_isscopedecl(l) || cin_islabel(ind_maxcomment))
5221 {
5222 amount = get_indent_nolabel(lnum);
5223 l = after_label(ml_get_curline());
5224 if (l == NULL) /* just in case */
5225 l = ml_get_curline();
5226 }
5227 else
5228 {
5229 amount = get_indent();
5230 l = ml_get_curline();
5231 }
5232 *pp = l;
5233
5234 curwin->w_cursor = cursor_save;
5235 return amount;
5236}
5237
5238/*
5239 * Return the indent of the first variable name after a type in a declaration.
5240 * int a, indent of "a"
5241 * static struct foo b, indent of "b"
5242 * enum bla c, indent of "c"
5243 * Returns zero when it doesn't look like a declaration.
5244 */
5245 static int
5246cin_first_id_amount()
5247{
5248 char_u *line, *p, *s;
5249 int len;
5250 pos_T fp;
5251 colnr_T col;
5252
5253 line = ml_get_curline();
5254 p = skipwhite(line);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005255 len = (int)(skiptowhite(p) - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005256 if (len == 6 && STRNCMP(p, "static", 6) == 0)
5257 {
5258 p = skipwhite(p + 6);
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00005259 len = (int)(skiptowhite(p) - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005260 }
5261 if (len == 6 && STRNCMP(p, "struct", 6) == 0)
5262 p = skipwhite(p + 6);
5263 else if (len == 4 && STRNCMP(p, "enum", 4) == 0)
5264 p = skipwhite(p + 4);
5265 else if ((len == 8 && STRNCMP(p, "unsigned", 8) == 0)
5266 || (len == 6 && STRNCMP(p, "signed", 6) == 0))
5267 {
5268 s = skipwhite(p + len);
5269 if ((STRNCMP(s, "int", 3) == 0 && vim_iswhite(s[3]))
5270 || (STRNCMP(s, "long", 4) == 0 && vim_iswhite(s[4]))
5271 || (STRNCMP(s, "short", 5) == 0 && vim_iswhite(s[5]))
5272 || (STRNCMP(s, "char", 4) == 0 && vim_iswhite(s[4])))
5273 p = s;
5274 }
5275 for (len = 0; vim_isIDc(p[len]); ++len)
5276 ;
5277 if (len == 0 || !vim_iswhite(p[len]) || cin_nocode(p))
5278 return 0;
5279
5280 p = skipwhite(p + len);
5281 fp.lnum = curwin->w_cursor.lnum;
5282 fp.col = (colnr_T)(p - line);
5283 getvcol(curwin, &fp, &col, NULL, NULL);
5284 return (int)col;
5285}
5286
5287/*
5288 * Return the indent of the first non-blank after an equal sign.
5289 * char *foo = "here";
5290 * Return zero if no (useful) equal sign found.
5291 * Return -1 if the line above "lnum" ends in a backslash.
5292 * foo = "asdf\
5293 * asdf\
5294 * here";
5295 */
5296 static int
5297cin_get_equal_amount(lnum)
5298 linenr_T lnum;
5299{
5300 char_u *line;
5301 char_u *s;
5302 colnr_T col;
5303 pos_T fp;
5304
5305 if (lnum > 1)
5306 {
5307 line = ml_get(lnum - 1);
5308 if (*line != NUL && line[STRLEN(line) - 1] == '\\')
5309 return -1;
5310 }
5311
5312 line = s = ml_get(lnum);
5313 while (*s != NUL && vim_strchr((char_u *)"=;{}\"'", *s) == NULL)
5314 {
5315 if (cin_iscomment(s)) /* ignore comments */
5316 s = cin_skipcomment(s);
5317 else
5318 ++s;
5319 }
5320 if (*s != '=')
5321 return 0;
5322
5323 s = skipwhite(s + 1);
5324 if (cin_nocode(s))
5325 return 0;
5326
5327 if (*s == '"') /* nice alignment for continued strings */
5328 ++s;
5329
5330 fp.lnum = lnum;
5331 fp.col = (colnr_T)(s - line);
5332 getvcol(curwin, &fp, &col, NULL, NULL);
5333 return (int)col;
5334}
5335
5336/*
5337 * Recognize a preprocessor statement: Any line that starts with '#'.
5338 */
5339 static int
5340cin_ispreproc(s)
5341 char_u *s;
5342{
5343 s = skipwhite(s);
5344 if (*s == '#')
5345 return TRUE;
5346 return FALSE;
5347}
5348
5349/*
5350 * Return TRUE if line "*pp" at "*lnump" is a preprocessor statement or a
5351 * continuation line of a preprocessor statement. Decrease "*lnump" to the
5352 * start and return the line in "*pp".
5353 */
5354 static int
5355cin_ispreproc_cont(pp, lnump)
5356 char_u **pp;
5357 linenr_T *lnump;
5358{
5359 char_u *line = *pp;
5360 linenr_T lnum = *lnump;
5361 int retval = FALSE;
5362
Bram Moolenaard8e9bb22005-07-09 21:14:46 +00005363 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005364 {
5365 if (cin_ispreproc(line))
5366 {
5367 retval = TRUE;
5368 *lnump = lnum;
5369 break;
5370 }
5371 if (lnum == 1)
5372 break;
5373 line = ml_get(--lnum);
5374 if (*line == NUL || line[STRLEN(line) - 1] != '\\')
5375 break;
5376 }
5377
5378 if (lnum != *lnump)
5379 *pp = ml_get(*lnump);
5380 return retval;
5381}
5382
5383/*
5384 * Recognize the start of a C or C++ comment.
5385 */
5386 static int
5387cin_iscomment(p)
5388 char_u *p;
5389{
5390 return (p[0] == '/' && (p[1] == '*' || p[1] == '/'));
5391}
5392
5393/*
5394 * Recognize the start of a "//" comment.
5395 */
5396 static int
5397cin_islinecomment(p)
5398 char_u *p;
5399{
5400 return (p[0] == '/' && p[1] == '/');
5401}
5402
5403/*
5404 * Recognize a line that starts with '{' or '}', or ends with ';', '{' or '}'.
5405 * Don't consider "} else" a terminated line.
5406 * Return the character terminating the line (ending char's have precedence if
5407 * both apply in order to determine initializations).
5408 */
5409 static int
5410cin_isterminated(s, incl_open, incl_comma)
5411 char_u *s;
5412 int incl_open; /* include '{' at the end as terminator */
5413 int incl_comma; /* recognize a trailing comma */
5414{
5415 char_u found_start = 0;
5416
5417 s = cin_skipcomment(s);
5418
5419 if (*s == '{' || (*s == '}' && !cin_iselse(s)))
5420 found_start = *s;
5421
5422 while (*s)
5423 {
5424 /* skip over comments, "" strings and 'c'haracters */
5425 s = skip_string(cin_skipcomment(s));
5426 if ((*s == ';' || (incl_open && *s == '{') || *s == '}'
5427 || (incl_comma && *s == ','))
5428 && cin_nocode(s + 1))
5429 return *s;
5430
5431 if (*s)
5432 s++;
5433 }
5434 return found_start;
5435}
5436
5437/*
5438 * Recognize the basic picture of a function declaration -- it needs to
5439 * have an open paren somewhere and a close paren at the end of the line and
5440 * no semicolons anywhere.
5441 * When a line ends in a comma we continue looking in the next line.
5442 * "sp" points to a string with the line. When looking at other lines it must
5443 * be restored to the line. When it's NULL fetch lines here.
5444 * "lnum" is where we start looking.
5445 */
5446 static int
5447cin_isfuncdecl(sp, first_lnum)
5448 char_u **sp;
5449 linenr_T first_lnum;
5450{
5451 char_u *s;
5452 linenr_T lnum = first_lnum;
5453 int retval = FALSE;
5454
5455 if (sp == NULL)
5456 s = ml_get(lnum);
5457 else
5458 s = *sp;
5459
5460 while (*s && *s != '(' && *s != ';' && *s != '\'' && *s != '"')
5461 {
5462 if (cin_iscomment(s)) /* ignore comments */
5463 s = cin_skipcomment(s);
5464 else
5465 ++s;
5466 }
5467 if (*s != '(')
5468 return FALSE; /* ';', ' or " before any () or no '(' */
5469
5470 while (*s && *s != ';' && *s != '\'' && *s != '"')
5471 {
5472 if (*s == ')' && cin_nocode(s + 1))
5473 {
5474 /* ')' at the end: may have found a match
5475 * Check for he previous line not to end in a backslash:
5476 * #if defined(x) && \
5477 * defined(y)
5478 */
5479 lnum = first_lnum - 1;
5480 s = ml_get(lnum);
5481 if (*s == NUL || s[STRLEN(s) - 1] != '\\')
5482 retval = TRUE;
5483 goto done;
5484 }
5485 if (*s == ',' && cin_nocode(s + 1))
5486 {
5487 /* ',' at the end: continue looking in the next line */
5488 if (lnum >= curbuf->b_ml.ml_line_count)
5489 break;
5490
5491 s = ml_get(++lnum);
5492 }
5493 else if (cin_iscomment(s)) /* ignore comments */
5494 s = cin_skipcomment(s);
5495 else
5496 ++s;
5497 }
5498
5499done:
5500 if (lnum != first_lnum && sp != NULL)
5501 *sp = ml_get(first_lnum);
5502
5503 return retval;
5504}
5505
5506 static int
5507cin_isif(p)
5508 char_u *p;
5509{
5510 return (STRNCMP(p, "if", 2) == 0 && !vim_isIDc(p[2]));
5511}
5512
5513 static int
5514cin_iselse(p)
5515 char_u *p;
5516{
5517 if (*p == '}') /* accept "} else" */
5518 p = cin_skipcomment(p + 1);
5519 return (STRNCMP(p, "else", 4) == 0 && !vim_isIDc(p[4]));
5520}
5521
5522 static int
5523cin_isdo(p)
5524 char_u *p;
5525{
5526 return (STRNCMP(p, "do", 2) == 0 && !vim_isIDc(p[2]));
5527}
5528
5529/*
5530 * Check if this is a "while" that should have a matching "do".
5531 * We only accept a "while (condition) ;", with only white space between the
5532 * ')' and ';'. The condition may be spread over several lines.
5533 */
5534 static int
5535cin_iswhileofdo(p, lnum, ind_maxparen) /* XXX */
5536 char_u *p;
5537 linenr_T lnum;
5538 int ind_maxparen;
5539{
5540 pos_T cursor_save;
5541 pos_T *trypos;
5542 int retval = FALSE;
5543
5544 p = cin_skipcomment(p);
5545 if (*p == '}') /* accept "} while (cond);" */
5546 p = cin_skipcomment(p + 1);
5547 if (STRNCMP(p, "while", 5) == 0 && !vim_isIDc(p[5]))
5548 {
5549 cursor_save = curwin->w_cursor;
5550 curwin->w_cursor.lnum = lnum;
5551 curwin->w_cursor.col = 0;
5552 p = ml_get_curline();
5553 while (*p && *p != 'w') /* skip any '}', until the 'w' of the "while" */
5554 {
5555 ++p;
5556 ++curwin->w_cursor.col;
5557 }
5558 if ((trypos = findmatchlimit(NULL, 0, 0, ind_maxparen)) != NULL
5559 && *cin_skipcomment(ml_get_pos(trypos) + 1) == ';')
5560 retval = TRUE;
5561 curwin->w_cursor = cursor_save;
5562 }
5563 return retval;
5564}
5565
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005566/*
5567 * Return TRUE if we are at the end of a do-while.
5568 * do
5569 * nothing;
5570 * while (foo
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00005571 * && bar); <-- here
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005572 * Adjust the cursor to the line with "while".
5573 */
5574 static int
5575cin_iswhileofdo_end(terminated, ind_maxparen, ind_maxcomment)
5576 int terminated;
5577 int ind_maxparen;
5578 int ind_maxcomment;
5579{
5580 char_u *line;
5581 char_u *p;
5582 char_u *s;
5583 pos_T *trypos;
5584 int i;
5585
5586 if (terminated != ';') /* there must be a ';' at the end */
5587 return FALSE;
5588
5589 p = line = ml_get_curline();
5590 while (*p != NUL)
5591 {
5592 p = cin_skipcomment(p);
5593 if (*p == ')')
5594 {
5595 s = skipwhite(p + 1);
5596 if (*s == ';' && cin_nocode(s + 1))
5597 {
5598 /* Found ");" at end of the line, now check there is "while"
5599 * before the matching '('. XXX */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005600 i = (int)(p - line);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005601 curwin->w_cursor.col = i;
5602 trypos = find_match_paren(ind_maxparen, ind_maxcomment);
5603 if (trypos != NULL)
5604 {
5605 s = cin_skipcomment(ml_get(trypos->lnum));
5606 if (*s == '}') /* accept "} while (cond);" */
5607 s = cin_skipcomment(s + 1);
5608 if (STRNCMP(s, "while", 5) == 0 && !vim_isIDc(s[5]))
5609 {
5610 curwin->w_cursor.lnum = trypos->lnum;
5611 return TRUE;
5612 }
5613 }
5614
5615 /* Searching may have made "line" invalid, get it again. */
5616 line = ml_get_curline();
5617 p = line + i;
5618 }
5619 }
5620 if (*p != NUL)
5621 ++p;
5622 }
5623 return FALSE;
5624}
5625
Bram Moolenaar071d4272004-06-13 20:20:40 +00005626 static int
5627cin_isbreak(p)
5628 char_u *p;
5629{
5630 return (STRNCMP(p, "break", 5) == 0 && !vim_isIDc(p[5]));
5631}
5632
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005633/*
5634 * Find the position of a C++ base-class declaration or
Bram Moolenaar071d4272004-06-13 20:20:40 +00005635 * constructor-initialization. eg:
5636 *
5637 * class MyClass :
5638 * baseClass <-- here
5639 * class MyClass : public baseClass,
5640 * anotherBaseClass <-- here (should probably lineup ??)
5641 * MyClass::MyClass(...) :
5642 * baseClass(...) <-- here (constructor-initialization)
Bram Moolenaar18144c82006-04-12 21:52:12 +00005643 *
5644 * This is a lot of guessing. Watch out for "cond ? func() : foo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005645 */
5646 static int
Bram Moolenaare7c56862007-08-04 10:14:52 +00005647cin_is_cpp_baseclass(col)
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005648 colnr_T *col; /* return: column to align with */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005649{
5650 char_u *s;
5651 int class_or_struct, lookfor_ctor_init, cpp_base_class;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005652 linenr_T lnum = curwin->w_cursor.lnum;
Bram Moolenaare7c56862007-08-04 10:14:52 +00005653 char_u *line = ml_get_curline();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005654
5655 *col = 0;
5656
Bram Moolenaar21cf8232004-07-16 20:18:37 +00005657 s = skipwhite(line);
5658 if (*s == '#') /* skip #define FOO x ? (x) : x */
5659 return FALSE;
5660 s = cin_skipcomment(s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005661 if (*s == NUL)
5662 return FALSE;
5663
5664 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
5665
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005666 /* Search for a line starting with '#', empty, ending in ';' or containing
5667 * '{' or '}' and start below it. This handles the following situations:
5668 * a = cond ?
5669 * func() :
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00005670 * asdf;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005671 * func::foo()
5672 * : something
5673 * {}
5674 * Foo::Foo (int one, int two)
5675 * : something(4),
5676 * somethingelse(3)
5677 * {}
5678 */
5679 while (lnum > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005680 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00005681 line = ml_get(lnum - 1);
5682 s = skipwhite(line);
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005683 if (*s == '#' || *s == NUL)
5684 break;
5685 while (*s != NUL)
5686 {
5687 s = cin_skipcomment(s);
5688 if (*s == '{' || *s == '}'
5689 || (*s == ';' && cin_nocode(s + 1)))
5690 break;
5691 if (*s != NUL)
5692 ++s;
5693 }
5694 if (*s != NUL)
5695 break;
5696 --lnum;
5697 }
5698
Bram Moolenaare7c56862007-08-04 10:14:52 +00005699 line = ml_get(lnum);
5700 s = cin_skipcomment(line);
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005701 for (;;)
5702 {
5703 if (*s == NUL)
5704 {
5705 if (lnum == curwin->w_cursor.lnum)
5706 break;
5707 /* Continue in the cursor line. */
Bram Moolenaare7c56862007-08-04 10:14:52 +00005708 line = ml_get(++lnum);
5709 s = cin_skipcomment(line);
5710 if (*s == NUL)
5711 continue;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005712 }
5713
Bram Moolenaar071d4272004-06-13 20:20:40 +00005714 if (s[0] == ':')
5715 {
5716 if (s[1] == ':')
5717 {
5718 /* skip double colon. It can't be a constructor
5719 * initialization any more */
5720 lookfor_ctor_init = FALSE;
5721 s = cin_skipcomment(s + 2);
5722 }
5723 else if (lookfor_ctor_init || class_or_struct)
5724 {
5725 /* we have something found, that looks like the start of
Bram Moolenaare21877a2008-02-13 09:58:14 +00005726 * cpp-base-class-declaration or constructor-initialization */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005727 cpp_base_class = TRUE;
5728 lookfor_ctor_init = class_or_struct = FALSE;
5729 *col = 0;
5730 s = cin_skipcomment(s + 1);
5731 }
5732 else
5733 s = cin_skipcomment(s + 1);
5734 }
5735 else if ((STRNCMP(s, "class", 5) == 0 && !vim_isIDc(s[5]))
5736 || (STRNCMP(s, "struct", 6) == 0 && !vim_isIDc(s[6])))
5737 {
5738 class_or_struct = TRUE;
5739 lookfor_ctor_init = FALSE;
5740
5741 if (*s == 'c')
5742 s = cin_skipcomment(s + 5);
5743 else
5744 s = cin_skipcomment(s + 6);
5745 }
5746 else
5747 {
5748 if (s[0] == '{' || s[0] == '}' || s[0] == ';')
5749 {
5750 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
5751 }
5752 else if (s[0] == ')')
5753 {
5754 /* Constructor-initialization is assumed if we come across
5755 * something like "):" */
5756 class_or_struct = FALSE;
5757 lookfor_ctor_init = TRUE;
5758 }
Bram Moolenaar18144c82006-04-12 21:52:12 +00005759 else if (s[0] == '?')
5760 {
5761 /* Avoid seeing '() :' after '?' as constructor init. */
5762 return FALSE;
5763 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005764 else if (!vim_isIDc(s[0]))
5765 {
5766 /* if it is not an identifier, we are wrong */
5767 class_or_struct = FALSE;
5768 lookfor_ctor_init = FALSE;
5769 }
5770 else if (*col == 0)
5771 {
5772 /* it can't be a constructor-initialization any more */
5773 lookfor_ctor_init = FALSE;
5774
5775 /* the first statement starts here: lineup with this one... */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005776 if (cpp_base_class)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005777 *col = (colnr_T)(s - line);
5778 }
5779
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005780 /* When the line ends in a comma don't align with it. */
5781 if (lnum == curwin->w_cursor.lnum && *s == ',' && cin_nocode(s + 1))
5782 *col = 0;
5783
Bram Moolenaar071d4272004-06-13 20:20:40 +00005784 s = cin_skipcomment(s + 1);
5785 }
5786 }
5787
5788 return cpp_base_class;
5789}
5790
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005791 static int
5792get_baseclass_amount(col, ind_maxparen, ind_maxcomment, ind_cpp_baseclass)
5793 int col;
5794 int ind_maxparen;
5795 int ind_maxcomment;
5796 int ind_cpp_baseclass;
5797{
5798 int amount;
5799 colnr_T vcol;
5800 pos_T *trypos;
5801
5802 if (col == 0)
5803 {
5804 amount = get_indent();
5805 if (find_last_paren(ml_get_curline(), '(', ')')
5806 && (trypos = find_match_paren(ind_maxparen,
5807 ind_maxcomment)) != NULL)
5808 amount = get_indent_lnum(trypos->lnum); /* XXX */
5809 if (!cin_ends_in(ml_get_curline(), (char_u *)",", NULL))
5810 amount += ind_cpp_baseclass;
5811 }
5812 else
5813 {
5814 curwin->w_cursor.col = col;
5815 getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
5816 amount = (int)vcol;
5817 }
5818 if (amount < ind_cpp_baseclass)
5819 amount = ind_cpp_baseclass;
5820 return amount;
5821}
5822
Bram Moolenaar071d4272004-06-13 20:20:40 +00005823/*
5824 * Return TRUE if string "s" ends with the string "find", possibly followed by
5825 * white space and comments. Skip strings and comments.
5826 * Ignore "ignore" after "find" if it's not NULL.
5827 */
5828 static int
5829cin_ends_in(s, find, ignore)
5830 char_u *s;
5831 char_u *find;
5832 char_u *ignore;
5833{
5834 char_u *p = s;
5835 char_u *r;
5836 int len = (int)STRLEN(find);
5837
5838 while (*p != NUL)
5839 {
5840 p = cin_skipcomment(p);
5841 if (STRNCMP(p, find, len) == 0)
5842 {
5843 r = skipwhite(p + len);
5844 if (ignore != NULL && STRNCMP(r, ignore, STRLEN(ignore)) == 0)
5845 r = skipwhite(r + STRLEN(ignore));
5846 if (cin_nocode(r))
5847 return TRUE;
5848 }
5849 if (*p != NUL)
5850 ++p;
5851 }
5852 return FALSE;
5853}
5854
5855/*
5856 * Skip strings, chars and comments until at or past "trypos".
5857 * Return the column found.
5858 */
5859 static int
5860cin_skip2pos(trypos)
5861 pos_T *trypos;
5862{
5863 char_u *line;
5864 char_u *p;
5865
5866 p = line = ml_get(trypos->lnum);
5867 while (*p && (colnr_T)(p - line) < trypos->col)
5868 {
5869 if (cin_iscomment(p))
5870 p = cin_skipcomment(p);
5871 else
5872 {
5873 p = skip_string(p);
5874 ++p;
5875 }
5876 }
5877 return (int)(p - line);
5878}
5879
5880/*
5881 * Find the '{' at the start of the block we are in.
5882 * Return NULL if no match found.
5883 * Ignore a '{' that is in a comment, makes indenting the next three lines
5884 * work. */
5885/* foo() */
5886/* { */
5887/* } */
5888
5889 static pos_T *
5890find_start_brace(ind_maxcomment) /* XXX */
5891 int ind_maxcomment;
5892{
5893 pos_T cursor_save;
5894 pos_T *trypos;
5895 pos_T *pos;
5896 static pos_T pos_copy;
5897
5898 cursor_save = curwin->w_cursor;
5899 while ((trypos = findmatchlimit(NULL, '{', FM_BLOCKSTOP, 0)) != NULL)
5900 {
5901 pos_copy = *trypos; /* copy pos_T, next findmatch will change it */
5902 trypos = &pos_copy;
5903 curwin->w_cursor = *trypos;
5904 pos = NULL;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005905 /* ignore the { if it's in a // or / * * / comment */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005906 if ((colnr_T)cin_skip2pos(trypos) == trypos->col
5907 && (pos = find_start_comment(ind_maxcomment)) == NULL) /* XXX */
5908 break;
5909 if (pos != NULL)
5910 curwin->w_cursor.lnum = pos->lnum;
5911 }
5912 curwin->w_cursor = cursor_save;
5913 return trypos;
5914}
5915
5916/*
5917 * Find the matching '(', failing if it is in a comment.
5918 * Return NULL of no match found.
5919 */
5920 static pos_T *
5921find_match_paren(ind_maxparen, ind_maxcomment) /* XXX */
5922 int ind_maxparen;
5923 int ind_maxcomment;
5924{
5925 pos_T cursor_save;
5926 pos_T *trypos;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005927 static pos_T pos_copy;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005928
5929 cursor_save = curwin->w_cursor;
5930 if ((trypos = findmatchlimit(NULL, '(', 0, ind_maxparen)) != NULL)
5931 {
5932 /* check if the ( is in a // comment */
5933 if ((colnr_T)cin_skip2pos(trypos) > trypos->col)
5934 trypos = NULL;
5935 else
5936 {
5937 pos_copy = *trypos; /* copy trypos, findmatch will change it */
5938 trypos = &pos_copy;
5939 curwin->w_cursor = *trypos;
5940 if (find_start_comment(ind_maxcomment) != NULL) /* XXX */
5941 trypos = NULL;
5942 }
5943 }
5944 curwin->w_cursor = cursor_save;
5945 return trypos;
5946}
5947
5948/*
5949 * Return ind_maxparen corrected for the difference in line number between the
5950 * cursor position and "startpos". This makes sure that searching for a
5951 * matching paren above the cursor line doesn't find a match because of
5952 * looking a few lines further.
5953 */
5954 static int
5955corr_ind_maxparen(ind_maxparen, startpos)
5956 int ind_maxparen;
5957 pos_T *startpos;
5958{
5959 long n = (long)startpos->lnum - (long)curwin->w_cursor.lnum;
5960
5961 if (n > 0 && n < ind_maxparen / 2)
5962 return ind_maxparen - (int)n;
5963 return ind_maxparen;
5964}
5965
5966/*
5967 * Set w_cursor.col to the column number of the last unmatched ')' or '{' in
5968 * line "l".
5969 */
5970 static int
5971find_last_paren(l, start, end)
5972 char_u *l;
5973 int start, end;
5974{
5975 int i;
5976 int retval = FALSE;
5977 int open_count = 0;
5978
5979 curwin->w_cursor.col = 0; /* default is start of line */
5980
5981 for (i = 0; l[i]; i++)
5982 {
5983 i = (int)(cin_skipcomment(l + i) - l); /* ignore parens in comments */
5984 i = (int)(skip_string(l + i) - l); /* ignore parens in quotes */
5985 if (l[i] == start)
5986 ++open_count;
5987 else if (l[i] == end)
5988 {
5989 if (open_count > 0)
5990 --open_count;
5991 else
5992 {
5993 curwin->w_cursor.col = i;
5994 retval = TRUE;
5995 }
5996 }
5997 }
5998 return retval;
5999}
6000
6001 int
6002get_c_indent()
6003{
6004 /*
6005 * spaces from a block's opening brace the prevailing indent for that
6006 * block should be
6007 */
6008 int ind_level = curbuf->b_p_sw;
6009
6010 /*
6011 * spaces from the edge of the line an open brace that's at the end of a
6012 * line is imagined to be.
6013 */
6014 int ind_open_imag = 0;
6015
6016 /*
6017 * spaces from the prevailing indent for a line that is not precededof by
6018 * an opening brace.
6019 */
6020 int ind_no_brace = 0;
6021
6022 /*
6023 * column where the first { of a function should be located }
6024 */
6025 int ind_first_open = 0;
6026
6027 /*
6028 * spaces from the prevailing indent a leftmost open brace should be
6029 * located
6030 */
6031 int ind_open_extra = 0;
6032
6033 /*
6034 * spaces from the matching open brace (real location for one at the left
6035 * edge; imaginary location from one that ends a line) the matching close
6036 * brace should be located
6037 */
6038 int ind_close_extra = 0;
6039
6040 /*
6041 * spaces from the edge of the line an open brace sitting in the leftmost
6042 * column is imagined to be
6043 */
6044 int ind_open_left_imag = 0;
6045
6046 /*
6047 * spaces from the switch() indent a "case xx" label should be located
6048 */
6049 int ind_case = curbuf->b_p_sw;
6050
6051 /*
6052 * spaces from the "case xx:" code after a switch() should be located
6053 */
6054 int ind_case_code = curbuf->b_p_sw;
6055
6056 /*
6057 * lineup break at end of case in switch() with case label
6058 */
6059 int ind_case_break = 0;
6060
6061 /*
6062 * spaces from the class declaration indent a scope declaration label
6063 * should be located
6064 */
6065 int ind_scopedecl = curbuf->b_p_sw;
6066
6067 /*
6068 * spaces from the scope declaration label code should be located
6069 */
6070 int ind_scopedecl_code = curbuf->b_p_sw;
6071
6072 /*
6073 * amount K&R-style parameters should be indented
6074 */
6075 int ind_param = curbuf->b_p_sw;
6076
6077 /*
6078 * amount a function type spec should be indented
6079 */
6080 int ind_func_type = curbuf->b_p_sw;
6081
6082 /*
6083 * amount a cpp base class declaration or constructor initialization
6084 * should be indented
6085 */
6086 int ind_cpp_baseclass = curbuf->b_p_sw;
6087
6088 /*
6089 * additional spaces beyond the prevailing indent a continuation line
6090 * should be located
6091 */
6092 int ind_continuation = curbuf->b_p_sw;
6093
6094 /*
6095 * spaces from the indent of the line with an unclosed parentheses
6096 */
6097 int ind_unclosed = curbuf->b_p_sw * 2;
6098
6099 /*
6100 * spaces from the indent of the line with an unclosed parentheses, which
6101 * itself is also unclosed
6102 */
6103 int ind_unclosed2 = curbuf->b_p_sw;
6104
6105 /*
6106 * suppress ignoring spaces from the indent of a line starting with an
6107 * unclosed parentheses.
6108 */
6109 int ind_unclosed_noignore = 0;
6110
6111 /*
6112 * If the opening paren is the last nonwhite character on the line, and
6113 * ind_unclosed_wrapped is nonzero, use this indent relative to the outer
6114 * context (for very long lines).
6115 */
6116 int ind_unclosed_wrapped = 0;
6117
6118 /*
6119 * suppress ignoring white space when lining up with the character after
6120 * an unclosed parentheses.
6121 */
6122 int ind_unclosed_whiteok = 0;
6123
6124 /*
6125 * indent a closing parentheses under the line start of the matching
6126 * opening parentheses.
6127 */
6128 int ind_matching_paren = 0;
6129
6130 /*
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006131 * indent a closing parentheses under the previous line.
6132 */
6133 int ind_paren_prev = 0;
6134
6135 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006136 * Extra indent for comments.
6137 */
6138 int ind_comment = 0;
6139
6140 /*
6141 * spaces from the comment opener when there is nothing after it.
6142 */
6143 int ind_in_comment = 3;
6144
6145 /*
6146 * boolean: if non-zero, use ind_in_comment even if there is something
6147 * after the comment opener.
6148 */
6149 int ind_in_comment2 = 0;
6150
6151 /*
6152 * max lines to search for an open paren
6153 */
6154 int ind_maxparen = 20;
6155
6156 /*
6157 * max lines to search for an open comment
6158 */
6159 int ind_maxcomment = 70;
6160
6161 /*
6162 * handle braces for java code
6163 */
6164 int ind_java = 0;
6165
6166 /*
6167 * handle blocked cases correctly
6168 */
6169 int ind_keep_case_label = 0;
6170
6171 pos_T cur_curpos;
6172 int amount;
6173 int scope_amount;
Bram Moolenaarb21e5842006-04-16 18:30:08 +00006174 int cur_amount = MAXCOL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006175 colnr_T col;
6176 char_u *theline;
6177 char_u *linecopy;
6178 pos_T *trypos;
6179 pos_T *tryposBrace = NULL;
6180 pos_T our_paren_pos;
6181 char_u *start;
6182 int start_brace;
Bram Moolenaare21877a2008-02-13 09:58:14 +00006183#define BRACE_IN_COL0 1 /* '{' is in column 0 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006184#define BRACE_AT_START 2 /* '{' is at start of line */
6185#define BRACE_AT_END 3 /* '{' is at end of line */
6186 linenr_T ourscope;
6187 char_u *l;
6188 char_u *look;
6189 char_u terminated;
6190 int lookfor;
6191#define LOOKFOR_INITIAL 0
6192#define LOOKFOR_IF 1
6193#define LOOKFOR_DO 2
6194#define LOOKFOR_CASE 3
6195#define LOOKFOR_ANY 4
6196#define LOOKFOR_TERM 5
6197#define LOOKFOR_UNTERM 6
6198#define LOOKFOR_SCOPEDECL 7
6199#define LOOKFOR_NOBREAK 8
6200#define LOOKFOR_CPP_BASECLASS 9
6201#define LOOKFOR_ENUM_OR_INIT 10
6202
6203 int whilelevel;
6204 linenr_T lnum;
6205 char_u *options;
6206 int fraction = 0; /* init for GCC */
6207 int divider;
6208 int n;
6209 int iscase;
6210 int lookfor_break;
6211 int cont_amount = 0; /* amount for continuation line */
6212
6213 for (options = curbuf->b_p_cino; *options; )
6214 {
6215 l = options++;
6216 if (*options == '-')
6217 ++options;
6218 n = getdigits(&options);
6219 divider = 0;
6220 if (*options == '.') /* ".5s" means a fraction */
6221 {
6222 fraction = atol((char *)++options);
6223 while (VIM_ISDIGIT(*options))
6224 {
6225 ++options;
6226 if (divider)
6227 divider *= 10;
6228 else
6229 divider = 10;
6230 }
6231 }
6232 if (*options == 's') /* "2s" means two times 'shiftwidth' */
6233 {
6234 if (n == 0 && fraction == 0)
6235 n = curbuf->b_p_sw; /* just "s" is one 'shiftwidth' */
6236 else
6237 {
6238 n *= curbuf->b_p_sw;
6239 if (divider)
6240 n += (curbuf->b_p_sw * fraction + divider / 2) / divider;
6241 }
6242 ++options;
6243 }
6244 if (l[1] == '-')
6245 n = -n;
6246 /* When adding an entry here, also update the default 'cinoptions' in
Bram Moolenaar39353fd2007-03-27 09:02:11 +00006247 * doc/indent.txt, and add explanation for it! */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006248 switch (*l)
6249 {
6250 case '>': ind_level = n; break;
6251 case 'e': ind_open_imag = n; break;
6252 case 'n': ind_no_brace = n; break;
6253 case 'f': ind_first_open = n; break;
6254 case '{': ind_open_extra = n; break;
6255 case '}': ind_close_extra = n; break;
6256 case '^': ind_open_left_imag = n; break;
6257 case ':': ind_case = n; break;
6258 case '=': ind_case_code = n; break;
6259 case 'b': ind_case_break = n; break;
6260 case 'p': ind_param = n; break;
6261 case 't': ind_func_type = n; break;
6262 case '/': ind_comment = n; break;
6263 case 'c': ind_in_comment = n; break;
6264 case 'C': ind_in_comment2 = n; break;
6265 case 'i': ind_cpp_baseclass = n; break;
6266 case '+': ind_continuation = n; break;
6267 case '(': ind_unclosed = n; break;
6268 case 'u': ind_unclosed2 = n; break;
6269 case 'U': ind_unclosed_noignore = n; break;
6270 case 'W': ind_unclosed_wrapped = n; break;
6271 case 'w': ind_unclosed_whiteok = n; break;
6272 case 'm': ind_matching_paren = n; break;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006273 case 'M': ind_paren_prev = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006274 case ')': ind_maxparen = n; break;
6275 case '*': ind_maxcomment = n; break;
6276 case 'g': ind_scopedecl = n; break;
6277 case 'h': ind_scopedecl_code = n; break;
6278 case 'j': ind_java = n; break;
6279 case 'l': ind_keep_case_label = n; break;
Bram Moolenaar39353fd2007-03-27 09:02:11 +00006280 case '#': ind_hash_comment = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006281 }
Bram Moolenaardfdf3c42010-03-23 18:22:46 +01006282 if (*options == ',')
6283 ++options;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006284 }
6285
6286 /* remember where the cursor was when we started */
6287 cur_curpos = curwin->w_cursor;
6288
6289 /* Get a copy of the current contents of the line.
6290 * This is required, because only the most recent line obtained with
6291 * ml_get is valid! */
6292 linecopy = vim_strsave(ml_get(cur_curpos.lnum));
6293 if (linecopy == NULL)
6294 return 0;
6295
6296 /*
6297 * In insert mode and the cursor is on a ')' truncate the line at the
6298 * cursor position. We don't want to line up with the matching '(' when
6299 * inserting new stuff.
6300 * For unknown reasons the cursor might be past the end of the line, thus
6301 * check for that.
6302 */
6303 if ((State & INSERT)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006304 && curwin->w_cursor.col < (colnr_T)STRLEN(linecopy)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006305 && linecopy[curwin->w_cursor.col] == ')')
6306 linecopy[curwin->w_cursor.col] = NUL;
6307
6308 theline = skipwhite(linecopy);
6309
6310 /* move the cursor to the start of the line */
6311
6312 curwin->w_cursor.col = 0;
6313
6314 /*
6315 * #defines and so on always go at the left when included in 'cinkeys'.
6316 */
6317 if (*theline == '#' && (*linecopy == '#' || in_cinkeys('#', ' ', TRUE)))
6318 {
6319 amount = 0;
6320 }
6321
6322 /*
6323 * Is it a non-case label? Then that goes at the left margin too.
6324 */
6325 else if (cin_islabel(ind_maxcomment)) /* XXX */
6326 {
6327 amount = 0;
6328 }
6329
6330 /*
6331 * If we're inside a "//" comment and there is a "//" comment in a
6332 * previous line, lineup with that one.
6333 */
6334 else if (cin_islinecomment(theline)
6335 && (trypos = find_line_comment()) != NULL) /* XXX */
6336 {
6337 /* find how indented the line beginning the comment is */
6338 getvcol(curwin, trypos, &col, NULL, NULL);
6339 amount = col;
6340 }
6341
6342 /*
6343 * If we're inside a comment and not looking at the start of the
6344 * comment, try using the 'comments' option.
6345 */
6346 else if (!cin_iscomment(theline)
6347 && (trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
6348 {
6349 int lead_start_len = 2;
6350 int lead_middle_len = 1;
6351 char_u lead_start[COM_MAX_LEN]; /* start-comment string */
6352 char_u lead_middle[COM_MAX_LEN]; /* middle-comment string */
6353 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
6354 char_u *p;
6355 int start_align = 0;
6356 int start_off = 0;
6357 int done = FALSE;
6358
6359 /* find how indented the line beginning the comment is */
6360 getvcol(curwin, trypos, &col, NULL, NULL);
6361 amount = col;
6362
6363 p = curbuf->b_p_com;
6364 while (*p != NUL)
6365 {
6366 int align = 0;
6367 int off = 0;
6368 int what = 0;
6369
6370 while (*p != NUL && *p != ':')
6371 {
6372 if (*p == COM_START || *p == COM_END || *p == COM_MIDDLE)
6373 what = *p++;
6374 else if (*p == COM_LEFT || *p == COM_RIGHT)
6375 align = *p++;
6376 else if (VIM_ISDIGIT(*p) || *p == '-')
6377 off = getdigits(&p);
6378 else
6379 ++p;
6380 }
6381
6382 if (*p == ':')
6383 ++p;
6384 (void)copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
6385 if (what == COM_START)
6386 {
6387 STRCPY(lead_start, lead_end);
6388 lead_start_len = (int)STRLEN(lead_start);
6389 start_off = off;
6390 start_align = align;
6391 }
6392 else if (what == COM_MIDDLE)
6393 {
6394 STRCPY(lead_middle, lead_end);
6395 lead_middle_len = (int)STRLEN(lead_middle);
6396 }
6397 else if (what == COM_END)
6398 {
6399 /* If our line starts with the middle comment string, line it
6400 * up with the comment opener per the 'comments' option. */
6401 if (STRNCMP(theline, lead_middle, lead_middle_len) == 0
6402 && STRNCMP(theline, lead_end, STRLEN(lead_end)) != 0)
6403 {
6404 done = TRUE;
6405 if (curwin->w_cursor.lnum > 1)
6406 {
6407 /* If the start comment string matches in the previous
Bram Moolenaare21877a2008-02-13 09:58:14 +00006408 * line, use the indent of that line plus offset. If
Bram Moolenaar071d4272004-06-13 20:20:40 +00006409 * the middle comment string matches in the previous
6410 * line, use the indent of that line. XXX */
6411 look = skipwhite(ml_get(curwin->w_cursor.lnum - 1));
6412 if (STRNCMP(look, lead_start, lead_start_len) == 0)
6413 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6414 else if (STRNCMP(look, lead_middle,
6415 lead_middle_len) == 0)
6416 {
6417 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6418 break;
6419 }
6420 /* If the start comment string doesn't match with the
6421 * start of the comment, skip this entry. XXX */
6422 else if (STRNCMP(ml_get(trypos->lnum) + trypos->col,
6423 lead_start, lead_start_len) != 0)
6424 continue;
6425 }
6426 if (start_off != 0)
6427 amount += start_off;
6428 else if (start_align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006429 amount += vim_strsize(lead_start)
6430 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006431 break;
6432 }
6433
6434 /* If our line starts with the end comment string, line it up
6435 * with the middle comment */
6436 if (STRNCMP(theline, lead_middle, lead_middle_len) != 0
6437 && STRNCMP(theline, lead_end, STRLEN(lead_end)) == 0)
6438 {
6439 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6440 /* XXX */
6441 if (off != 0)
6442 amount += off;
6443 else if (align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006444 amount += vim_strsize(lead_start)
6445 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006446 done = TRUE;
6447 break;
6448 }
6449 }
6450 }
6451
6452 /* If our line starts with an asterisk, line up with the
6453 * asterisk in the comment opener; otherwise, line up
6454 * with the first character of the comment text.
6455 */
6456 if (done)
6457 ;
6458 else if (theline[0] == '*')
6459 amount += 1;
6460 else
6461 {
6462 /*
6463 * If we are more than one line away from the comment opener, take
6464 * the indent of the previous non-empty line. If 'cino' has "CO"
6465 * and we are just below the comment opener and there are any
6466 * white characters after it line up with the text after it;
6467 * otherwise, add the amount specified by "c" in 'cino'
6468 */
6469 amount = -1;
6470 for (lnum = cur_curpos.lnum - 1; lnum > trypos->lnum; --lnum)
6471 {
6472 if (linewhite(lnum)) /* skip blank lines */
6473 continue;
6474 amount = get_indent_lnum(lnum); /* XXX */
6475 break;
6476 }
6477 if (amount == -1) /* use the comment opener */
6478 {
6479 if (!ind_in_comment2)
6480 {
6481 start = ml_get(trypos->lnum);
6482 look = start + trypos->col + 2; /* skip / and * */
6483 if (*look != NUL) /* if something after it */
6484 trypos->col = (colnr_T)(skipwhite(look) - start);
6485 }
6486 getvcol(curwin, trypos, &col, NULL, NULL);
6487 amount = col;
6488 if (ind_in_comment2 || *look == NUL)
6489 amount += ind_in_comment;
6490 }
6491 }
6492 }
6493
6494 /*
6495 * Are we inside parentheses or braces?
6496 */ /* XXX */
6497 else if (((trypos = find_match_paren(ind_maxparen, ind_maxcomment)) != NULL
6498 && ind_java == 0)
6499 || (tryposBrace = find_start_brace(ind_maxcomment)) != NULL
6500 || trypos != NULL)
6501 {
6502 if (trypos != NULL && tryposBrace != NULL)
6503 {
6504 /* Both an unmatched '(' and '{' is found. Use the one which is
6505 * closer to the current cursor position, set the other to NULL. */
6506 if (trypos->lnum != tryposBrace->lnum
6507 ? trypos->lnum < tryposBrace->lnum
6508 : trypos->col < tryposBrace->col)
6509 trypos = NULL;
6510 else
6511 tryposBrace = NULL;
6512 }
6513
6514 if (trypos != NULL)
6515 {
6516 /*
6517 * If the matching paren is more than one line away, use the indent of
6518 * a previous non-empty line that matches the same paren.
6519 */
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006520 if (theline[0] == ')' && ind_paren_prev)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006521 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006522 /* Line up with the start of the matching paren line. */
6523 amount = get_indent_lnum(curwin->w_cursor.lnum - 1); /* XXX */
6524 }
6525 else
6526 {
6527 amount = -1;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006528 our_paren_pos = *trypos;
6529 for (lnum = cur_curpos.lnum - 1; lnum > our_paren_pos.lnum; --lnum)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006530 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006531 l = skipwhite(ml_get(lnum));
6532 if (cin_nocode(l)) /* skip comment lines */
6533 continue;
6534 if (cin_ispreproc_cont(&l, &lnum))
6535 continue; /* ignore #define, #if, etc. */
6536 curwin->w_cursor.lnum = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006537
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006538 /* Skip a comment. XXX */
6539 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
6540 {
6541 lnum = trypos->lnum + 1;
6542 continue;
6543 }
6544
6545 /* XXX */
6546 if ((trypos = find_match_paren(
6547 corr_ind_maxparen(ind_maxparen, &cur_curpos),
Bram Moolenaar071d4272004-06-13 20:20:40 +00006548 ind_maxcomment)) != NULL
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006549 && trypos->lnum == our_paren_pos.lnum
6550 && trypos->col == our_paren_pos.col)
6551 {
6552 amount = get_indent_lnum(lnum); /* XXX */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006553
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006554 if (theline[0] == ')')
6555 {
6556 if (our_paren_pos.lnum != lnum
6557 && cur_amount > amount)
6558 cur_amount = amount;
6559 amount = -1;
6560 }
6561 break;
6562 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006563 }
6564 }
6565
6566 /*
6567 * Line up with line where the matching paren is. XXX
6568 * If the line starts with a '(' or the indent for unclosed
6569 * parentheses is zero, line up with the unclosed parentheses.
6570 */
6571 if (amount == -1)
6572 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006573 int ignore_paren_col = 0;
6574
Bram Moolenaar071d4272004-06-13 20:20:40 +00006575 amount = skip_label(our_paren_pos.lnum, &look, ind_maxcomment);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006576 look = skipwhite(look);
6577 if (*look == '(')
6578 {
6579 linenr_T save_lnum = curwin->w_cursor.lnum;
6580 char_u *line;
6581 int look_col;
6582
6583 /* Ignore a '(' in front of the line that has a match before
6584 * our matching '('. */
6585 curwin->w_cursor.lnum = our_paren_pos.lnum;
6586 line = ml_get_curline();
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006587 look_col = (int)(look - line);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006588 curwin->w_cursor.col = look_col + 1;
6589 if ((trypos = findmatchlimit(NULL, ')', 0, ind_maxparen))
6590 != NULL
6591 && trypos->lnum == our_paren_pos.lnum
6592 && trypos->col < our_paren_pos.col)
6593 ignore_paren_col = trypos->col + 1;
6594
6595 curwin->w_cursor.lnum = save_lnum;
6596 look = ml_get(our_paren_pos.lnum) + look_col;
6597 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006598 if (theline[0] == ')' || ind_unclosed == 0
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006599 || (!ind_unclosed_noignore && *look == '('
6600 && ignore_paren_col == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006601 {
6602 /*
6603 * If we're looking at a close paren, line up right there;
6604 * otherwise, line up with the next (non-white) character.
6605 * When ind_unclosed_wrapped is set and the matching paren is
6606 * the last nonwhite character of the line, use either the
6607 * indent of the current line or the indentation of the next
6608 * outer paren and add ind_unclosed_wrapped (for very long
6609 * lines).
6610 */
6611 if (theline[0] != ')')
6612 {
6613 cur_amount = MAXCOL;
6614 l = ml_get(our_paren_pos.lnum);
6615 if (ind_unclosed_wrapped
6616 && cin_ends_in(l, (char_u *)"(", NULL))
6617 {
6618 /* look for opening unmatched paren, indent one level
6619 * for each additional level */
6620 n = 1;
6621 for (col = 0; col < our_paren_pos.col; ++col)
6622 {
6623 switch (l[col])
6624 {
6625 case '(':
6626 case '{': ++n;
6627 break;
6628
6629 case ')':
6630 case '}': if (n > 1)
6631 --n;
6632 break;
6633 }
6634 }
6635
6636 our_paren_pos.col = 0;
6637 amount += n * ind_unclosed_wrapped;
6638 }
6639 else if (ind_unclosed_whiteok)
6640 our_paren_pos.col++;
6641 else
6642 {
6643 col = our_paren_pos.col + 1;
6644 while (vim_iswhite(l[col]))
6645 col++;
6646 if (l[col] != NUL) /* In case of trailing space */
6647 our_paren_pos.col = col;
6648 else
6649 our_paren_pos.col++;
6650 }
6651 }
6652
6653 /*
6654 * Find how indented the paren is, or the character after it
6655 * if we did the above "if".
6656 */
6657 if (our_paren_pos.col > 0)
6658 {
6659 getvcol(curwin, &our_paren_pos, &col, NULL, NULL);
6660 if (cur_amount > (int)col)
6661 cur_amount = col;
6662 }
6663 }
6664
6665 if (theline[0] == ')' && ind_matching_paren)
6666 {
6667 /* Line up with the start of the matching paren line. */
6668 }
6669 else if (ind_unclosed == 0 || (!ind_unclosed_noignore
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006670 && *look == '(' && ignore_paren_col == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006671 {
6672 if (cur_amount != MAXCOL)
6673 amount = cur_amount;
6674 }
6675 else
6676 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006677 /* Add ind_unclosed2 for each '(' before our matching one, but
6678 * ignore (void) before the line (ignore_paren_col). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006679 col = our_paren_pos.col;
Bram Moolenaarb21e5842006-04-16 18:30:08 +00006680 while ((int)our_paren_pos.col > ignore_paren_col)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006681 {
6682 --our_paren_pos.col;
6683 switch (*ml_get_pos(&our_paren_pos))
6684 {
6685 case '(': amount += ind_unclosed2;
6686 col = our_paren_pos.col;
6687 break;
6688 case ')': amount -= ind_unclosed2;
6689 col = MAXCOL;
6690 break;
6691 }
6692 }
6693
6694 /* Use ind_unclosed once, when the first '(' is not inside
6695 * braces */
6696 if (col == MAXCOL)
6697 amount += ind_unclosed;
6698 else
6699 {
6700 curwin->w_cursor.lnum = our_paren_pos.lnum;
6701 curwin->w_cursor.col = col;
6702 if ((trypos = find_match_paren(ind_maxparen,
6703 ind_maxcomment)) != NULL)
6704 amount += ind_unclosed2;
6705 else
6706 amount += ind_unclosed;
6707 }
6708 /*
6709 * For a line starting with ')' use the minimum of the two
6710 * positions, to avoid giving it more indent than the previous
6711 * lines:
6712 * func_long_name( if (x
6713 * arg && yy
6714 * ) ^ not here ) ^ not here
6715 */
6716 if (cur_amount < amount)
6717 amount = cur_amount;
6718 }
6719 }
6720
6721 /* add extra indent for a comment */
6722 if (cin_iscomment(theline))
6723 amount += ind_comment;
6724 }
6725
6726 /*
6727 * Are we at least inside braces, then?
6728 */
6729 else
6730 {
6731 trypos = tryposBrace;
6732
6733 ourscope = trypos->lnum;
6734 start = ml_get(ourscope);
6735
6736 /*
6737 * Now figure out how indented the line is in general.
6738 * If the brace was at the start of the line, we use that;
6739 * otherwise, check out the indentation of the line as
6740 * a whole and then add the "imaginary indent" to that.
6741 */
6742 look = skipwhite(start);
6743 if (*look == '{')
6744 {
6745 getvcol(curwin, trypos, &col, NULL, NULL);
6746 amount = col;
6747 if (*start == '{')
6748 start_brace = BRACE_IN_COL0;
6749 else
6750 start_brace = BRACE_AT_START;
6751 }
6752 else
6753 {
6754 /*
6755 * that opening brace might have been on a continuation
6756 * line. if so, find the start of the line.
6757 */
6758 curwin->w_cursor.lnum = ourscope;
6759
6760 /*
6761 * position the cursor over the rightmost paren, so that
6762 * matching it will take us back to the start of the line.
6763 */
6764 lnum = ourscope;
6765 if (find_last_paren(start, '(', ')')
6766 && (trypos = find_match_paren(ind_maxparen,
6767 ind_maxcomment)) != NULL)
6768 lnum = trypos->lnum;
6769
6770 /*
6771 * It could have been something like
6772 * case 1: if (asdf &&
6773 * ldfd) {
6774 * }
6775 */
6776 if (ind_keep_case_label && cin_iscase(skipwhite(ml_get_curline())))
6777 amount = get_indent();
6778 else
6779 amount = skip_label(lnum, &l, ind_maxcomment);
6780
6781 start_brace = BRACE_AT_END;
6782 }
6783
6784 /*
6785 * if we're looking at a closing brace, that's where
6786 * we want to be. otherwise, add the amount of room
6787 * that an indent is supposed to be.
6788 */
6789 if (theline[0] == '}')
6790 {
6791 /*
6792 * they may want closing braces to line up with something
6793 * other than the open brace. indulge them, if so.
6794 */
6795 amount += ind_close_extra;
6796 }
6797 else
6798 {
6799 /*
6800 * If we're looking at an "else", try to find an "if"
6801 * to match it with.
6802 * If we're looking at a "while", try to find a "do"
6803 * to match it with.
6804 */
6805 lookfor = LOOKFOR_INITIAL;
6806 if (cin_iselse(theline))
6807 lookfor = LOOKFOR_IF;
6808 else if (cin_iswhileofdo(theline, cur_curpos.lnum, ind_maxparen))
6809 /* XXX */
6810 lookfor = LOOKFOR_DO;
6811 if (lookfor != LOOKFOR_INITIAL)
6812 {
6813 curwin->w_cursor.lnum = cur_curpos.lnum;
6814 if (find_match(lookfor, ourscope, ind_maxparen,
6815 ind_maxcomment) == OK)
6816 {
6817 amount = get_indent(); /* XXX */
6818 goto theend;
6819 }
6820 }
6821
6822 /*
6823 * We get here if we are not on an "while-of-do" or "else" (or
6824 * failed to find a matching "if").
6825 * Search backwards for something to line up with.
6826 * First set amount for when we don't find anything.
6827 */
6828
6829 /*
6830 * if the '{' is _really_ at the left margin, use the imaginary
6831 * location of a left-margin brace. Otherwise, correct the
6832 * location for ind_open_extra.
6833 */
6834
6835 if (start_brace == BRACE_IN_COL0) /* '{' is in column 0 */
6836 {
6837 amount = ind_open_left_imag;
6838 }
6839 else
6840 {
6841 if (start_brace == BRACE_AT_END) /* '{' is at end of line */
6842 amount += ind_open_imag;
6843 else
6844 {
6845 /* Compensate for adding ind_open_extra later. */
6846 amount -= ind_open_extra;
6847 if (amount < 0)
6848 amount = 0;
6849 }
6850 }
6851
6852 lookfor_break = FALSE;
6853
6854 if (cin_iscase(theline)) /* it's a switch() label */
6855 {
6856 lookfor = LOOKFOR_CASE; /* find a previous switch() label */
6857 amount += ind_case;
6858 }
6859 else if (cin_isscopedecl(theline)) /* private:, ... */
6860 {
6861 lookfor = LOOKFOR_SCOPEDECL; /* class decl is this block */
6862 amount += ind_scopedecl;
6863 }
6864 else
6865 {
6866 if (ind_case_break && cin_isbreak(theline)) /* break; ... */
6867 lookfor_break = TRUE;
6868
6869 lookfor = LOOKFOR_INITIAL;
6870 amount += ind_level; /* ind_level from start of block */
6871 }
6872 scope_amount = amount;
6873 whilelevel = 0;
6874
6875 /*
6876 * Search backwards. If we find something we recognize, line up
6877 * with that.
6878 *
6879 * if we're looking at an open brace, indent
6880 * the usual amount relative to the conditional
6881 * that opens the block.
6882 */
6883 curwin->w_cursor = cur_curpos;
6884 for (;;)
6885 {
6886 curwin->w_cursor.lnum--;
6887 curwin->w_cursor.col = 0;
6888
6889 /*
6890 * If we went all the way back to the start of our scope, line
6891 * up with it.
6892 */
6893 if (curwin->w_cursor.lnum <= ourscope)
6894 {
6895 /* we reached end of scope:
6896 * if looking for a enum or structure initialization
6897 * go further back:
6898 * if it is an initializer (enum xxx or xxx =), then
6899 * don't add ind_continuation, otherwise it is a variable
6900 * declaration:
6901 * int x,
6902 * here; <-- add ind_continuation
6903 */
6904 if (lookfor == LOOKFOR_ENUM_OR_INIT)
6905 {
6906 if (curwin->w_cursor.lnum == 0
6907 || curwin->w_cursor.lnum
6908 < ourscope - ind_maxparen)
6909 {
6910 /* nothing found (abuse ind_maxparen as limit)
6911 * assume terminated line (i.e. a variable
6912 * initialization) */
6913 if (cont_amount > 0)
6914 amount = cont_amount;
6915 else
6916 amount += ind_continuation;
6917 break;
6918 }
6919
6920 l = ml_get_curline();
6921
6922 /*
6923 * If we're in a comment now, skip to the start of the
6924 * comment.
6925 */
6926 trypos = find_start_comment(ind_maxcomment);
6927 if (trypos != NULL)
6928 {
6929 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00006930 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006931 continue;
6932 }
6933
6934 /*
6935 * Skip preprocessor directives and blank lines.
6936 */
6937 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
6938 continue;
6939
6940 if (cin_nocode(l))
6941 continue;
6942
6943 terminated = cin_isterminated(l, FALSE, TRUE);
6944
6945 /*
6946 * If we are at top level and the line looks like a
6947 * function declaration, we are done
6948 * (it's a variable declaration).
6949 */
6950 if (start_brace != BRACE_IN_COL0
6951 || !cin_isfuncdecl(&l, curwin->w_cursor.lnum))
6952 {
6953 /* if the line is terminated with another ','
6954 * it is a continued variable initialization.
6955 * don't add extra indent.
6956 * TODO: does not work, if a function
6957 * declaration is split over multiple lines:
6958 * cin_isfuncdecl returns FALSE then.
6959 */
6960 if (terminated == ',')
6961 break;
6962
6963 /* if it es a enum declaration or an assignment,
6964 * we are done.
6965 */
6966 if (terminated != ';' && cin_isinit())
6967 break;
6968
6969 /* nothing useful found */
6970 if (terminated == 0 || terminated == '{')
6971 continue;
6972 }
6973
6974 if (terminated != ';')
6975 {
6976 /* Skip parens and braces. Position the cursor
6977 * over the rightmost paren, so that matching it
6978 * will take us back to the start of the line.
6979 */ /* XXX */
6980 trypos = NULL;
6981 if (find_last_paren(l, '(', ')'))
6982 trypos = find_match_paren(ind_maxparen,
6983 ind_maxcomment);
6984
6985 if (trypos == NULL && find_last_paren(l, '{', '}'))
6986 trypos = find_start_brace(ind_maxcomment);
6987
6988 if (trypos != NULL)
6989 {
6990 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00006991 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006992 continue;
6993 }
6994 }
6995
6996 /* it's a variable declaration, add indentation
6997 * like in
6998 * int a,
6999 * b;
7000 */
7001 if (cont_amount > 0)
7002 amount = cont_amount;
7003 else
7004 amount += ind_continuation;
7005 }
7006 else if (lookfor == LOOKFOR_UNTERM)
7007 {
7008 if (cont_amount > 0)
7009 amount = cont_amount;
7010 else
7011 amount += ind_continuation;
7012 }
7013 else if (lookfor != LOOKFOR_TERM
7014 && lookfor != LOOKFOR_CPP_BASECLASS)
7015 {
7016 amount = scope_amount;
7017 if (theline[0] == '{')
7018 amount += ind_open_extra;
7019 }
7020 break;
7021 }
7022
7023 /*
7024 * If we're in a comment now, skip to the start of the comment.
7025 */ /* XXX */
7026 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
7027 {
7028 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007029 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007030 continue;
7031 }
7032
7033 l = ml_get_curline();
7034
7035 /*
7036 * If this is a switch() label, may line up relative to that.
Bram Moolenaar18144c82006-04-12 21:52:12 +00007037 * If this is a C++ scope declaration, do the same.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007038 */
7039 iscase = cin_iscase(l);
7040 if (iscase || cin_isscopedecl(l))
7041 {
7042 /* we are only looking for cpp base class
7043 * declaration/initialization any longer */
7044 if (lookfor == LOOKFOR_CPP_BASECLASS)
7045 break;
7046
7047 /* When looking for a "do" we are not interested in
7048 * labels. */
7049 if (whilelevel > 0)
7050 continue;
7051
7052 /*
7053 * case xx:
7054 * c = 99 + <- this indent plus continuation
7055 *-> here;
7056 */
7057 if (lookfor == LOOKFOR_UNTERM
7058 || lookfor == LOOKFOR_ENUM_OR_INIT)
7059 {
7060 if (cont_amount > 0)
7061 amount = cont_amount;
7062 else
7063 amount += ind_continuation;
7064 break;
7065 }
7066
7067 /*
7068 * case xx: <- line up with this case
7069 * x = 333;
7070 * case yy:
7071 */
7072 if ( (iscase && lookfor == LOOKFOR_CASE)
7073 || (iscase && lookfor_break)
7074 || (!iscase && lookfor == LOOKFOR_SCOPEDECL))
7075 {
7076 /*
7077 * Check that this case label is not for another
7078 * switch()
7079 */ /* XXX */
7080 if ((trypos = find_start_brace(ind_maxcomment)) ==
7081 NULL || trypos->lnum == ourscope)
7082 {
7083 amount = get_indent(); /* XXX */
7084 break;
7085 }
7086 continue;
7087 }
7088
7089 n = get_indent_nolabel(curwin->w_cursor.lnum); /* XXX */
7090
7091 /*
7092 * case xx: if (cond) <- line up with this if
7093 * y = y + 1;
7094 * -> s = 99;
7095 *
7096 * case xx:
7097 * if (cond) <- line up with this line
7098 * y = y + 1;
7099 * -> s = 99;
7100 */
7101 if (lookfor == LOOKFOR_TERM)
7102 {
7103 if (n)
7104 amount = n;
7105
7106 if (!lookfor_break)
7107 break;
7108 }
7109
7110 /*
7111 * case xx: x = x + 1; <- line up with this x
7112 * -> y = y + 1;
7113 *
7114 * case xx: if (cond) <- line up with this if
7115 * -> y = y + 1;
7116 */
7117 if (n)
7118 {
7119 amount = n;
7120 l = after_label(ml_get_curline());
7121 if (l != NULL && cin_is_cinword(l))
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007122 {
7123 if (theline[0] == '{')
7124 amount += ind_open_extra;
7125 else
7126 amount += ind_level + ind_no_brace;
7127 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007128 break;
7129 }
7130
7131 /*
7132 * Try to get the indent of a statement before the switch
7133 * label. If nothing is found, line up relative to the
7134 * switch label.
7135 * break; <- may line up with this line
7136 * case xx:
7137 * -> y = 1;
7138 */
7139 scope_amount = get_indent() + (iscase /* XXX */
7140 ? ind_case_code : ind_scopedecl_code);
7141 lookfor = ind_case_break ? LOOKFOR_NOBREAK : LOOKFOR_ANY;
7142 continue;
7143 }
7144
7145 /*
7146 * Looking for a switch() label or C++ scope declaration,
7147 * ignore other lines, skip {}-blocks.
7148 */
7149 if (lookfor == LOOKFOR_CASE || lookfor == LOOKFOR_SCOPEDECL)
7150 {
7151 if (find_last_paren(l, '{', '}') && (trypos =
7152 find_start_brace(ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007153 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007154 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007155 curwin->w_cursor.col = 0;
7156 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007157 continue;
7158 }
7159
7160 /*
7161 * Ignore jump labels with nothing after them.
7162 */
7163 if (cin_islabel(ind_maxcomment))
7164 {
7165 l = after_label(ml_get_curline());
7166 if (l == NULL || cin_nocode(l))
7167 continue;
7168 }
7169
7170 /*
7171 * Ignore #defines, #if, etc.
7172 * Ignore comment and empty lines.
7173 * (need to get the line again, cin_islabel() may have
7174 * unlocked it)
7175 */
7176 l = ml_get_curline();
7177 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum)
7178 || cin_nocode(l))
7179 continue;
7180
7181 /*
7182 * Are we at the start of a cpp base class declaration or
7183 * constructor initialization?
7184 */ /* XXX */
Bram Moolenaar18144c82006-04-12 21:52:12 +00007185 n = FALSE;
7186 if (lookfor != LOOKFOR_TERM && ind_cpp_baseclass > 0)
7187 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00007188 n = cin_is_cpp_baseclass(&col);
Bram Moolenaar18144c82006-04-12 21:52:12 +00007189 l = ml_get_curline();
7190 }
7191 if (n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007192 {
7193 if (lookfor == LOOKFOR_UNTERM)
7194 {
7195 if (cont_amount > 0)
7196 amount = cont_amount;
7197 else
7198 amount += ind_continuation;
7199 }
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007200 else if (theline[0] == '{')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007201 {
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007202 /* Need to find start of the declaration. */
7203 lookfor = LOOKFOR_UNTERM;
7204 ind_continuation = 0;
7205 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007206 }
7207 else
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007208 /* XXX */
7209 amount = get_baseclass_amount(col, ind_maxparen,
7210 ind_maxcomment, ind_cpp_baseclass);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007211 break;
7212 }
7213 else if (lookfor == LOOKFOR_CPP_BASECLASS)
7214 {
7215 /* only look, whether there is a cpp base class
Bram Moolenaar18144c82006-04-12 21:52:12 +00007216 * declaration or initialization before the opening brace.
7217 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007218 if (cin_isterminated(l, TRUE, FALSE))
7219 break;
7220 else
7221 continue;
7222 }
7223
7224 /*
7225 * What happens next depends on the line being terminated.
7226 * If terminated with a ',' only consider it terminating if
Bram Moolenaar25394022007-05-10 19:06:20 +00007227 * there is another unterminated statement behind, eg:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007228 * 123,
7229 * sizeof
7230 * here
7231 * Otherwise check whether it is a enumeration or structure
7232 * initialisation (not indented) or a variable declaration
7233 * (indented).
7234 */
7235 terminated = cin_isterminated(l, FALSE, TRUE);
7236
7237 if (terminated == 0 || (lookfor != LOOKFOR_UNTERM
7238 && terminated == ','))
7239 {
7240 /*
7241 * if we're in the middle of a paren thing,
7242 * go back to the line that starts it so
7243 * we can get the right prevailing indent
7244 * if ( foo &&
7245 * bar )
7246 */
7247 /*
7248 * position the cursor over the rightmost paren, so that
7249 * matching it will take us back to the start of the line.
7250 */
7251 (void)find_last_paren(l, '(', ')');
7252 trypos = find_match_paren(
7253 corr_ind_maxparen(ind_maxparen, &cur_curpos),
7254 ind_maxcomment);
7255
7256 /*
7257 * If we are looking for ',', we also look for matching
7258 * braces.
7259 */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007260 if (trypos == NULL && terminated == ','
7261 && find_last_paren(l, '{', '}'))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007262 trypos = find_start_brace(ind_maxcomment);
7263
7264 if (trypos != NULL)
7265 {
7266 /*
7267 * Check if we are on a case label now. This is
7268 * handled above.
7269 * case xx: if ( asdf &&
7270 * asdf)
7271 */
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007272 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007273 l = ml_get_curline();
7274 if (cin_iscase(l) || cin_isscopedecl(l))
7275 {
7276 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007277 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007278 continue;
7279 }
7280 }
7281
7282 /*
7283 * Skip over continuation lines to find the one to get the
7284 * indent from
7285 * char *usethis = "bla\
7286 * bla",
7287 * here;
7288 */
7289 if (terminated == ',')
7290 {
7291 while (curwin->w_cursor.lnum > 1)
7292 {
7293 l = ml_get(curwin->w_cursor.lnum - 1);
7294 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
7295 break;
7296 --curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007297 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007298 }
7299 }
7300
7301 /*
7302 * Get indent and pointer to text for current line,
7303 * ignoring any jump label. XXX
7304 */
7305 cur_amount = skip_label(curwin->w_cursor.lnum,
7306 &l, ind_maxcomment);
7307
7308 /*
7309 * If this is just above the line we are indenting, and it
7310 * starts with a '{', line it up with this line.
7311 * while (not)
7312 * -> {
7313 * }
7314 */
7315 if (terminated != ',' && lookfor != LOOKFOR_TERM
7316 && theline[0] == '{')
7317 {
7318 amount = cur_amount;
7319 /*
7320 * Only add ind_open_extra when the current line
7321 * doesn't start with a '{', which must have a match
7322 * in the same line (scope is the same). Probably:
7323 * { 1, 2 },
7324 * -> { 3, 4 }
7325 */
7326 if (*skipwhite(l) != '{')
7327 amount += ind_open_extra;
7328
7329 if (ind_cpp_baseclass)
7330 {
7331 /* have to look back, whether it is a cpp base
7332 * class declaration or initialization */
7333 lookfor = LOOKFOR_CPP_BASECLASS;
7334 continue;
7335 }
7336 break;
7337 }
7338
7339 /*
7340 * Check if we are after an "if", "while", etc.
7341 * Also allow " } else".
7342 */
7343 if (cin_is_cinword(l) || cin_iselse(skipwhite(l)))
7344 {
7345 /*
7346 * Found an unterminated line after an if (), line up
7347 * with the last one.
7348 * if (cond)
7349 * 100 +
7350 * -> here;
7351 */
7352 if (lookfor == LOOKFOR_UNTERM
7353 || lookfor == LOOKFOR_ENUM_OR_INIT)
7354 {
7355 if (cont_amount > 0)
7356 amount = cont_amount;
7357 else
7358 amount += ind_continuation;
7359 break;
7360 }
7361
7362 /*
7363 * If this is just above the line we are indenting, we
7364 * are finished.
7365 * while (not)
7366 * -> here;
7367 * Otherwise this indent can be used when the line
7368 * before this is terminated.
7369 * yyy;
7370 * if (stat)
7371 * while (not)
7372 * xxx;
7373 * -> here;
7374 */
7375 amount = cur_amount;
7376 if (theline[0] == '{')
7377 amount += ind_open_extra;
7378 if (lookfor != LOOKFOR_TERM)
7379 {
7380 amount += ind_level + ind_no_brace;
7381 break;
7382 }
7383
7384 /*
7385 * Special trick: when expecting the while () after a
7386 * do, line up with the while()
7387 * do
7388 * x = 1;
7389 * -> here
7390 */
7391 l = skipwhite(ml_get_curline());
7392 if (cin_isdo(l))
7393 {
7394 if (whilelevel == 0)
7395 break;
7396 --whilelevel;
7397 }
7398
7399 /*
7400 * When searching for a terminated line, don't use the
7401 * one between the "if" and the "else".
7402 * Need to use the scope of this "else". XXX
7403 * If whilelevel != 0 continue looking for a "do {".
7404 */
7405 if (cin_iselse(l)
7406 && whilelevel == 0
7407 && ((trypos = find_start_brace(ind_maxcomment))
7408 == NULL
7409 || find_match(LOOKFOR_IF, trypos->lnum,
7410 ind_maxparen, ind_maxcomment) == FAIL))
7411 break;
7412 }
7413
7414 /*
7415 * If we're below an unterminated line that is not an
7416 * "if" or something, we may line up with this line or
Bram Moolenaar25394022007-05-10 19:06:20 +00007417 * add something for a continuation line, depending on
Bram Moolenaar071d4272004-06-13 20:20:40 +00007418 * the line before this one.
7419 */
7420 else
7421 {
7422 /*
7423 * Found two unterminated lines on a row, line up with
7424 * the last one.
7425 * c = 99 +
7426 * 100 +
7427 * -> here;
7428 */
7429 if (lookfor == LOOKFOR_UNTERM)
7430 {
7431 /* When line ends in a comma add extra indent */
7432 if (terminated == ',')
7433 amount += ind_continuation;
7434 break;
7435 }
7436
7437 if (lookfor == LOOKFOR_ENUM_OR_INIT)
7438 {
7439 /* Found two lines ending in ',', lineup with the
7440 * lowest one, but check for cpp base class
7441 * declaration/initialization, if it is an
7442 * opening brace or we are looking just for
7443 * enumerations/initializations. */
7444 if (terminated == ',')
7445 {
7446 if (ind_cpp_baseclass == 0)
7447 break;
7448
7449 lookfor = LOOKFOR_CPP_BASECLASS;
7450 continue;
7451 }
7452
7453 /* Ignore unterminated lines in between, but
7454 * reduce indent. */
7455 if (amount > cur_amount)
7456 amount = cur_amount;
7457 }
7458 else
7459 {
7460 /*
7461 * Found first unterminated line on a row, may
7462 * line up with this line, remember its indent
7463 * 100 +
7464 * -> here;
7465 */
7466 amount = cur_amount;
7467
7468 /*
7469 * If previous line ends in ',', check whether we
7470 * are in an initialization or enum
7471 * struct xxx =
7472 * {
7473 * sizeof a,
7474 * 124 };
7475 * or a normal possible continuation line.
7476 * but only, of no other statement has been found
7477 * yet.
7478 */
7479 if (lookfor == LOOKFOR_INITIAL && terminated == ',')
7480 {
7481 lookfor = LOOKFOR_ENUM_OR_INIT;
7482 cont_amount = cin_first_id_amount();
7483 }
7484 else
7485 {
7486 if (lookfor == LOOKFOR_INITIAL
7487 && *l != NUL
7488 && l[STRLEN(l) - 1] == '\\')
7489 /* XXX */
7490 cont_amount = cin_get_equal_amount(
7491 curwin->w_cursor.lnum);
7492 if (lookfor != LOOKFOR_TERM)
7493 lookfor = LOOKFOR_UNTERM;
7494 }
7495 }
7496 }
7497 }
7498
7499 /*
7500 * Check if we are after a while (cond);
7501 * If so: Ignore until the matching "do".
7502 */
7503 /* XXX */
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007504 else if (cin_iswhileofdo_end(terminated, ind_maxparen,
7505 ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007506 {
7507 /*
7508 * Found an unterminated line after a while ();, line up
7509 * with the last one.
7510 * while (cond);
7511 * 100 + <- line up with this one
7512 * -> here;
7513 */
7514 if (lookfor == LOOKFOR_UNTERM
7515 || lookfor == LOOKFOR_ENUM_OR_INIT)
7516 {
7517 if (cont_amount > 0)
7518 amount = cont_amount;
7519 else
7520 amount += ind_continuation;
7521 break;
7522 }
7523
7524 if (whilelevel == 0)
7525 {
7526 lookfor = LOOKFOR_TERM;
7527 amount = get_indent(); /* XXX */
7528 if (theline[0] == '{')
7529 amount += ind_open_extra;
7530 }
7531 ++whilelevel;
7532 }
7533
7534 /*
7535 * We are after a "normal" statement.
7536 * If we had another statement we can stop now and use the
7537 * indent of that other statement.
7538 * Otherwise the indent of the current statement may be used,
7539 * search backwards for the next "normal" statement.
7540 */
7541 else
7542 {
7543 /*
7544 * Skip single break line, if before a switch label. It
7545 * may be lined up with the case label.
7546 */
7547 if (lookfor == LOOKFOR_NOBREAK
7548 && cin_isbreak(skipwhite(ml_get_curline())))
7549 {
7550 lookfor = LOOKFOR_ANY;
7551 continue;
7552 }
7553
7554 /*
7555 * Handle "do {" line.
7556 */
7557 if (whilelevel > 0)
7558 {
7559 l = cin_skipcomment(ml_get_curline());
7560 if (cin_isdo(l))
7561 {
7562 amount = get_indent(); /* XXX */
7563 --whilelevel;
7564 continue;
7565 }
7566 }
7567
7568 /*
7569 * Found a terminated line above an unterminated line. Add
7570 * the amount for a continuation line.
7571 * x = 1;
7572 * y = foo +
7573 * -> here;
7574 * or
7575 * int x = 1;
7576 * int foo,
7577 * -> here;
7578 */
7579 if (lookfor == LOOKFOR_UNTERM
7580 || lookfor == LOOKFOR_ENUM_OR_INIT)
7581 {
7582 if (cont_amount > 0)
7583 amount = cont_amount;
7584 else
7585 amount += ind_continuation;
7586 break;
7587 }
7588
7589 /*
7590 * Found a terminated line above a terminated line or "if"
7591 * etc. line. Use the amount of the line below us.
7592 * x = 1; x = 1;
7593 * if (asdf) y = 2;
7594 * while (asdf) ->here;
7595 * here;
7596 * ->foo;
7597 */
7598 if (lookfor == LOOKFOR_TERM)
7599 {
7600 if (!lookfor_break && whilelevel == 0)
7601 break;
7602 }
7603
7604 /*
7605 * First line above the one we're indenting is terminated.
7606 * To know what needs to be done look further backward for
7607 * a terminated line.
7608 */
7609 else
7610 {
7611 /*
7612 * position the cursor over the rightmost paren, so
7613 * that matching it will take us back to the start of
7614 * the line. Helps for:
7615 * func(asdr,
7616 * asdfasdf);
7617 * here;
7618 */
7619term_again:
7620 l = ml_get_curline();
7621 if (find_last_paren(l, '(', ')')
7622 && (trypos = find_match_paren(ind_maxparen,
7623 ind_maxcomment)) != NULL)
7624 {
7625 /*
7626 * Check if we are on a case label now. This is
7627 * handled above.
7628 * case xx: if ( asdf &&
7629 * asdf)
7630 */
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007631 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007632 l = ml_get_curline();
7633 if (cin_iscase(l) || cin_isscopedecl(l))
7634 {
7635 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007636 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007637 continue;
7638 }
7639 }
7640
7641 /* When aligning with the case statement, don't align
7642 * with a statement after it.
7643 * case 1: { <-- don't use this { position
7644 * stat;
7645 * }
7646 * case 2:
7647 * stat;
7648 * }
7649 */
7650 iscase = (ind_keep_case_label && cin_iscase(l));
7651
7652 /*
7653 * Get indent and pointer to text for current line,
7654 * ignoring any jump label.
7655 */
7656 amount = skip_label(curwin->w_cursor.lnum,
7657 &l, ind_maxcomment);
7658
7659 if (theline[0] == '{')
7660 amount += ind_open_extra;
7661 /* See remark above: "Only add ind_open_extra.." */
Bram Moolenaar18144c82006-04-12 21:52:12 +00007662 l = skipwhite(l);
7663 if (*l == '{')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007664 amount -= ind_open_extra;
7665 lookfor = iscase ? LOOKFOR_ANY : LOOKFOR_TERM;
7666
7667 /*
Bram Moolenaar18144c82006-04-12 21:52:12 +00007668 * When a terminated line starts with "else" skip to
7669 * the matching "if":
7670 * else 3;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00007671 * indent this;
Bram Moolenaar18144c82006-04-12 21:52:12 +00007672 * Need to use the scope of this "else". XXX
7673 * If whilelevel != 0 continue looking for a "do {".
7674 */
7675 if (lookfor == LOOKFOR_TERM
7676 && *l != '}'
7677 && cin_iselse(l)
7678 && whilelevel == 0)
7679 {
7680 if ((trypos = find_start_brace(ind_maxcomment))
7681 == NULL
7682 || find_match(LOOKFOR_IF, trypos->lnum,
7683 ind_maxparen, ind_maxcomment) == FAIL)
7684 break;
7685 continue;
7686 }
7687
7688 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007689 * If we're at the end of a block, skip to the start of
7690 * that block.
7691 */
7692 curwin->w_cursor.col = 0;
7693 if (*cin_skipcomment(l) == '}'
7694 && (trypos = find_start_brace(ind_maxcomment))
7695 != NULL) /* XXX */
7696 {
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007697 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007698 /* if not "else {" check for terminated again */
7699 /* but skip block for "} else {" */
7700 l = cin_skipcomment(ml_get_curline());
7701 if (*l == '}' || !cin_iselse(l))
7702 goto term_again;
7703 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007704 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007705 }
7706 }
7707 }
7708 }
7709 }
7710 }
7711
7712 /* add extra indent for a comment */
7713 if (cin_iscomment(theline))
7714 amount += ind_comment;
7715 }
7716
7717 /*
7718 * ok -- we're not inside any sort of structure at all!
7719 *
7720 * this means we're at the top level, and everything should
7721 * basically just match where the previous line is, except
7722 * for the lines immediately following a function declaration,
7723 * which are K&R-style parameters and need to be indented.
7724 */
7725 else
7726 {
7727 /*
7728 * if our line starts with an open brace, forget about any
7729 * prevailing indent and make sure it looks like the start
7730 * of a function
7731 */
7732
7733 if (theline[0] == '{')
7734 {
7735 amount = ind_first_open;
7736 }
7737
7738 /*
7739 * If the NEXT line is a function declaration, the current
7740 * line needs to be indented as a function type spec.
Bram Moolenaar1a89bbe2010-03-02 12:38:22 +01007741 * Don't do this if the current line looks like a comment or if the
7742 * current line is terminated, ie. ends in ';', or if the current line
7743 * contains { or }: "void f() {\n if (1)"
Bram Moolenaar071d4272004-06-13 20:20:40 +00007744 */
7745 else if (cur_curpos.lnum < curbuf->b_ml.ml_line_count
7746 && !cin_nocode(theline)
Bram Moolenaar1a89bbe2010-03-02 12:38:22 +01007747 && vim_strchr(theline, '{') == NULL
7748 && vim_strchr(theline, '}') == NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007749 && !cin_ends_in(theline, (char_u *)":", NULL)
7750 && !cin_ends_in(theline, (char_u *)",", NULL)
7751 && cin_isfuncdecl(NULL, cur_curpos.lnum + 1)
7752 && !cin_isterminated(theline, FALSE, TRUE))
7753 {
7754 amount = ind_func_type;
7755 }
7756 else
7757 {
7758 amount = 0;
7759 curwin->w_cursor = cur_curpos;
7760
7761 /* search backwards until we find something we recognize */
7762
7763 while (curwin->w_cursor.lnum > 1)
7764 {
7765 curwin->w_cursor.lnum--;
7766 curwin->w_cursor.col = 0;
7767
7768 l = ml_get_curline();
7769
7770 /*
7771 * If we're in a comment now, skip to the start of the comment.
7772 */ /* XXX */
7773 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
7774 {
7775 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007776 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007777 continue;
7778 }
7779
7780 /*
Bram Moolenaar18144c82006-04-12 21:52:12 +00007781 * Are we at the start of a cpp base class declaration or
7782 * constructor initialization?
Bram Moolenaar071d4272004-06-13 20:20:40 +00007783 */ /* XXX */
Bram Moolenaar18144c82006-04-12 21:52:12 +00007784 n = FALSE;
7785 if (ind_cpp_baseclass != 0 && theline[0] != '{')
7786 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00007787 n = cin_is_cpp_baseclass(&col);
Bram Moolenaar18144c82006-04-12 21:52:12 +00007788 l = ml_get_curline();
7789 }
7790 if (n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007791 {
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007792 /* XXX */
7793 amount = get_baseclass_amount(col, ind_maxparen,
7794 ind_maxcomment, ind_cpp_baseclass);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007795 break;
7796 }
7797
7798 /*
7799 * Skip preprocessor directives and blank lines.
7800 */
7801 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7802 continue;
7803
7804 if (cin_nocode(l))
7805 continue;
7806
7807 /*
7808 * If the previous line ends in ',', use one level of
7809 * indentation:
7810 * int foo,
7811 * bar;
7812 * do this before checking for '}' in case of eg.
7813 * enum foobar
7814 * {
7815 * ...
7816 * } foo,
7817 * bar;
7818 */
7819 n = 0;
7820 if (cin_ends_in(l, (char_u *)",", NULL)
7821 || (*l != NUL && (n = l[STRLEN(l) - 1]) == '\\'))
7822 {
7823 /* take us back to opening paren */
7824 if (find_last_paren(l, '(', ')')
7825 && (trypos = find_match_paren(ind_maxparen,
7826 ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007827 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007828
7829 /* For a line ending in ',' that is a continuation line go
7830 * back to the first line with a backslash:
7831 * char *foo = "bla\
7832 * bla",
7833 * here;
7834 */
7835 while (n == 0 && curwin->w_cursor.lnum > 1)
7836 {
7837 l = ml_get(curwin->w_cursor.lnum - 1);
7838 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
7839 break;
7840 --curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007841 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007842 }
7843
7844 amount = get_indent(); /* XXX */
7845
7846 if (amount == 0)
7847 amount = cin_first_id_amount();
7848 if (amount == 0)
7849 amount = ind_continuation;
7850 break;
7851 }
7852
7853 /*
7854 * If the line looks like a function declaration, and we're
7855 * not in a comment, put it the left margin.
7856 */
7857 if (cin_isfuncdecl(NULL, cur_curpos.lnum)) /* XXX */
7858 break;
7859 l = ml_get_curline();
7860
7861 /*
7862 * Finding the closing '}' of a previous function. Put
7863 * current line at the left margin. For when 'cino' has "fs".
7864 */
7865 if (*skipwhite(l) == '}')
7866 break;
7867
7868 /* (matching {)
7869 * If the previous line ends on '};' (maybe followed by
7870 * comments) align at column 0. For example:
7871 * char *string_array[] = { "foo",
7872 * / * x * / "b};ar" }; / * foobar * /
7873 */
7874 if (cin_ends_in(l, (char_u *)"};", NULL))
7875 break;
7876
7877 /*
7878 * If the PREVIOUS line is a function declaration, the current
7879 * line (and the ones that follow) needs to be indented as
7880 * parameters.
7881 */
7882 if (cin_isfuncdecl(&l, curwin->w_cursor.lnum))
7883 {
7884 amount = ind_param;
7885 break;
7886 }
7887
7888 /*
7889 * If the previous line ends in ';' and the line before the
7890 * previous line ends in ',' or '\', ident to column zero:
7891 * int foo,
7892 * bar;
7893 * indent_to_0 here;
7894 */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007895 if (cin_ends_in(l, (char_u *)";", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007896 {
7897 l = ml_get(curwin->w_cursor.lnum - 1);
7898 if (cin_ends_in(l, (char_u *)",", NULL)
7899 || (*l != NUL && l[STRLEN(l) - 1] == '\\'))
7900 break;
7901 l = ml_get_curline();
7902 }
7903
7904 /*
7905 * Doesn't look like anything interesting -- so just
7906 * use the indent of this line.
7907 *
7908 * Position the cursor over the rightmost paren, so that
7909 * matching it will take us back to the start of the line.
7910 */
7911 find_last_paren(l, '(', ')');
7912
7913 if ((trypos = find_match_paren(ind_maxparen,
7914 ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007915 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007916 amount = get_indent(); /* XXX */
7917 break;
7918 }
7919
7920 /* add extra indent for a comment */
7921 if (cin_iscomment(theline))
7922 amount += ind_comment;
7923
7924 /* add extra indent if the previous line ended in a backslash:
7925 * "asdfasdf\
7926 * here";
7927 * char *foo = "asdf\
7928 * here";
7929 */
7930 if (cur_curpos.lnum > 1)
7931 {
7932 l = ml_get(cur_curpos.lnum - 1);
7933 if (*l != NUL && l[STRLEN(l) - 1] == '\\')
7934 {
7935 cur_amount = cin_get_equal_amount(cur_curpos.lnum - 1);
7936 if (cur_amount > 0)
7937 amount = cur_amount;
7938 else if (cur_amount == 0)
7939 amount += ind_continuation;
7940 }
7941 }
7942 }
7943 }
7944
7945theend:
7946 /* put the cursor back where it belongs */
7947 curwin->w_cursor = cur_curpos;
7948
7949 vim_free(linecopy);
7950
7951 if (amount < 0)
7952 return 0;
7953 return amount;
7954}
7955
7956 static int
7957find_match(lookfor, ourscope, ind_maxparen, ind_maxcomment)
7958 int lookfor;
7959 linenr_T ourscope;
7960 int ind_maxparen;
7961 int ind_maxcomment;
7962{
7963 char_u *look;
7964 pos_T *theirscope;
7965 char_u *mightbeif;
7966 int elselevel;
7967 int whilelevel;
7968
7969 if (lookfor == LOOKFOR_IF)
7970 {
7971 elselevel = 1;
7972 whilelevel = 0;
7973 }
7974 else
7975 {
7976 elselevel = 0;
7977 whilelevel = 1;
7978 }
7979
7980 curwin->w_cursor.col = 0;
7981
7982 while (curwin->w_cursor.lnum > ourscope + 1)
7983 {
7984 curwin->w_cursor.lnum--;
7985 curwin->w_cursor.col = 0;
7986
7987 look = cin_skipcomment(ml_get_curline());
7988 if (cin_iselse(look)
7989 || cin_isif(look)
7990 || cin_isdo(look) /* XXX */
7991 || cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
7992 {
7993 /*
7994 * if we've gone outside the braces entirely,
7995 * we must be out of scope...
7996 */
7997 theirscope = find_start_brace(ind_maxcomment); /* XXX */
7998 if (theirscope == NULL)
7999 break;
8000
8001 /*
8002 * and if the brace enclosing this is further
8003 * back than the one enclosing the else, we're
8004 * out of luck too.
8005 */
8006 if (theirscope->lnum < ourscope)
8007 break;
8008
8009 /*
8010 * and if they're enclosed in a *deeper* brace,
8011 * then we can ignore it because it's in a
8012 * different scope...
8013 */
8014 if (theirscope->lnum > ourscope)
8015 continue;
8016
8017 /*
8018 * if it was an "else" (that's not an "else if")
8019 * then we need to go back to another if, so
8020 * increment elselevel
8021 */
8022 look = cin_skipcomment(ml_get_curline());
8023 if (cin_iselse(look))
8024 {
8025 mightbeif = cin_skipcomment(look + 4);
8026 if (!cin_isif(mightbeif))
8027 ++elselevel;
8028 continue;
8029 }
8030
8031 /*
8032 * if it was a "while" then we need to go back to
8033 * another "do", so increment whilelevel. XXX
8034 */
8035 if (cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
8036 {
8037 ++whilelevel;
8038 continue;
8039 }
8040
8041 /* If it's an "if" decrement elselevel */
8042 look = cin_skipcomment(ml_get_curline());
8043 if (cin_isif(look))
8044 {
8045 elselevel--;
8046 /*
8047 * When looking for an "if" ignore "while"s that
8048 * get in the way.
8049 */
8050 if (elselevel == 0 && lookfor == LOOKFOR_IF)
8051 whilelevel = 0;
8052 }
8053
8054 /* If it's a "do" decrement whilelevel */
8055 if (cin_isdo(look))
8056 whilelevel--;
8057
8058 /*
8059 * if we've used up all the elses, then
8060 * this must be the if that we want!
8061 * match the indent level of that if.
8062 */
8063 if (elselevel <= 0 && whilelevel <= 0)
8064 {
8065 return OK;
8066 }
8067 }
8068 }
8069 return FAIL;
8070}
8071
8072# if defined(FEAT_EVAL) || defined(PROTO)
8073/*
8074 * Get indent level from 'indentexpr'.
8075 */
8076 int
8077get_expr_indent()
8078{
8079 int indent;
8080 pos_T pos;
8081 int save_State;
Bram Moolenaard1f56e62006-02-22 21:25:37 +00008082 int use_sandbox = was_set_insecurely((char_u *)"indentexpr",
8083 OPT_LOCAL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008084
8085 pos = curwin->w_cursor;
8086 set_vim_var_nr(VV_LNUM, curwin->w_cursor.lnum);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00008087 if (use_sandbox)
8088 ++sandbox;
8089 ++textlock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008090 indent = eval_to_number(curbuf->b_p_inde);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00008091 if (use_sandbox)
8092 --sandbox;
8093 --textlock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008094
8095 /* Restore the cursor position so that 'indentexpr' doesn't need to.
8096 * Pretend to be in Insert mode, allow cursor past end of line for "o"
8097 * command. */
8098 save_State = State;
8099 State = INSERT;
8100 curwin->w_cursor = pos;
8101 check_cursor();
8102 State = save_State;
8103
8104 /* If there is an error, just keep the current indent. */
8105 if (indent < 0)
8106 indent = get_indent();
8107
8108 return indent;
8109}
8110# endif
8111
8112#endif /* FEAT_CINDENT */
8113
8114#if defined(FEAT_LISP) || defined(PROTO)
8115
8116static int lisp_match __ARGS((char_u *p));
8117
8118 static int
8119lisp_match(p)
8120 char_u *p;
8121{
8122 char_u buf[LSIZE];
8123 int len;
8124 char_u *word = p_lispwords;
8125
8126 while (*word != NUL)
8127 {
8128 (void)copy_option_part(&word, buf, LSIZE, ",");
8129 len = (int)STRLEN(buf);
8130 if (STRNCMP(buf, p, len) == 0 && p[len] == ' ')
8131 return TRUE;
8132 }
8133 return FALSE;
8134}
8135
8136/*
8137 * When 'p' is present in 'cpoptions, a Vi compatible method is used.
8138 * The incompatible newer method is quite a bit better at indenting
8139 * code in lisp-like languages than the traditional one; it's still
8140 * mostly heuristics however -- Dirk van Deun, dirk@rave.org
8141 *
8142 * TODO:
8143 * Findmatch() should be adapted for lisp, also to make showmatch
8144 * work correctly: now (v5.3) it seems all C/C++ oriented:
8145 * - it does not recognize the #\( and #\) notations as character literals
8146 * - it doesn't know about comments starting with a semicolon
8147 * - it incorrectly interprets '(' as a character literal
8148 * All this messes up get_lisp_indent in some rare cases.
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008149 * Update from Sergey Khorev:
8150 * I tried to fix the first two issues.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008151 */
8152 int
8153get_lisp_indent()
8154{
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008155 pos_T *pos, realpos, paren;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008156 int amount;
8157 char_u *that;
8158 colnr_T col;
8159 colnr_T firsttry;
8160 int parencount, quotecount;
8161 int vi_lisp;
8162
8163 /* Set vi_lisp to use the vi-compatible method */
8164 vi_lisp = (vim_strchr(p_cpo, CPO_LISP) != NULL);
8165
8166 realpos = curwin->w_cursor;
8167 curwin->w_cursor.col = 0;
8168
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008169 if ((pos = findmatch(NULL, '(')) == NULL)
8170 pos = findmatch(NULL, '[');
8171 else
8172 {
8173 paren = *pos;
8174 pos = findmatch(NULL, '[');
8175 if (pos == NULL || ltp(pos, &paren))
8176 pos = &paren;
8177 }
8178 if (pos != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008179 {
8180 /* Extra trick: Take the indent of the first previous non-white
8181 * line that is at the same () level. */
8182 amount = -1;
8183 parencount = 0;
8184
8185 while (--curwin->w_cursor.lnum >= pos->lnum)
8186 {
8187 if (linewhite(curwin->w_cursor.lnum))
8188 continue;
8189 for (that = ml_get_curline(); *that != NUL; ++that)
8190 {
8191 if (*that == ';')
8192 {
8193 while (*(that + 1) != NUL)
8194 ++that;
8195 continue;
8196 }
8197 if (*that == '\\')
8198 {
8199 if (*(that + 1) != NUL)
8200 ++that;
8201 continue;
8202 }
8203 if (*that == '"' && *(that + 1) != NUL)
8204 {
Bram Moolenaar15ff6c12006-09-15 18:18:09 +00008205 while (*++that && *that != '"')
8206 {
8207 /* skipping escaped characters in the string */
8208 if (*that == '\\')
8209 {
8210 if (*++that == NUL)
8211 break;
8212 if (that[1] == NUL)
8213 {
8214 ++that;
8215 break;
8216 }
8217 }
8218 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008219 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008220 if (*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008221 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008222 else if (*that == ')' || *that == ']')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008223 --parencount;
8224 }
8225 if (parencount == 0)
8226 {
8227 amount = get_indent();
8228 break;
8229 }
8230 }
8231
8232 if (amount == -1)
8233 {
8234 curwin->w_cursor.lnum = pos->lnum;
8235 curwin->w_cursor.col = pos->col;
8236 col = pos->col;
8237
8238 that = ml_get_curline();
8239
8240 if (vi_lisp && get_indent() == 0)
8241 amount = 2;
8242 else
8243 {
8244 amount = 0;
8245 while (*that && col)
8246 {
8247 amount += lbr_chartabsize_adv(&that, (colnr_T)amount);
8248 col--;
8249 }
8250
8251 /*
8252 * Some keywords require "body" indenting rules (the
8253 * non-standard-lisp ones are Scheme special forms):
8254 *
8255 * (let ((a 1)) instead (let ((a 1))
8256 * (...)) of (...))
8257 */
8258
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008259 if (!vi_lisp && (*that == '(' || *that == '[')
8260 && lisp_match(that + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008261 amount += 2;
8262 else
8263 {
8264 that++;
8265 amount++;
8266 firsttry = amount;
8267
8268 while (vim_iswhite(*that))
8269 {
8270 amount += lbr_chartabsize(that, (colnr_T)amount);
8271 ++that;
8272 }
8273
8274 if (*that && *that != ';') /* not a comment line */
8275 {
Bram Moolenaare21877a2008-02-13 09:58:14 +00008276 /* test *that != '(' to accommodate first let/do
Bram Moolenaar071d4272004-06-13 20:20:40 +00008277 * argument if it is more than one line */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008278 if (!vi_lisp && *that != '(' && *that != '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008279 firsttry++;
8280
8281 parencount = 0;
8282 quotecount = 0;
8283
8284 if (vi_lisp
8285 || (*that != '"'
8286 && *that != '\''
8287 && *that != '#'
8288 && (*that < '0' || *that > '9')))
8289 {
8290 while (*that
8291 && (!vim_iswhite(*that)
8292 || quotecount
8293 || parencount)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008294 && (!((*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008295 && !quotecount
8296 && !parencount
8297 && vi_lisp)))
8298 {
8299 if (*that == '"')
8300 quotecount = !quotecount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008301 if ((*that == '(' || *that == '[')
8302 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008303 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008304 if ((*that == ')' || *that == ']')
8305 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008306 --parencount;
8307 if (*that == '\\' && *(that+1) != NUL)
8308 amount += lbr_chartabsize_adv(&that,
8309 (colnr_T)amount);
8310 amount += lbr_chartabsize_adv(&that,
8311 (colnr_T)amount);
8312 }
8313 }
8314 while (vim_iswhite(*that))
8315 {
8316 amount += lbr_chartabsize(that, (colnr_T)amount);
8317 that++;
8318 }
8319 if (!*that || *that == ';')
8320 amount = firsttry;
8321 }
8322 }
8323 }
8324 }
8325 }
8326 else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008327 amount = 0; /* no matching '(' or '[' found, use zero indent */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008328
8329 curwin->w_cursor = realpos;
8330
8331 return amount;
8332}
8333#endif /* FEAT_LISP */
8334
8335 void
8336prepare_to_exit()
8337{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00008338#if defined(SIGHUP) && defined(SIG_IGN)
8339 /* Ignore SIGHUP, because a dropped connection causes a read error, which
8340 * makes Vim exit and then handling SIGHUP causes various reentrance
8341 * problems. */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00008342 signal(SIGHUP, SIG_IGN);
8343#endif
8344
Bram Moolenaar071d4272004-06-13 20:20:40 +00008345#ifdef FEAT_GUI
8346 if (gui.in_use)
8347 {
8348 gui.dying = TRUE;
8349 out_trash(); /* trash any pending output */
8350 }
8351 else
8352#endif
8353 {
8354 windgoto((int)Rows - 1, 0);
8355
8356 /*
8357 * Switch terminal mode back now, so messages end up on the "normal"
8358 * screen (if there are two screens).
8359 */
8360 settmode(TMODE_COOK);
8361#ifdef WIN3264
8362 if (can_end_termcap_mode(FALSE) == TRUE)
8363#endif
8364 stoptermcap();
8365 out_flush();
8366 }
8367}
8368
8369/*
8370 * Preserve files and exit.
8371 * When called IObuff must contain a message.
8372 */
8373 void
8374preserve_exit()
8375{
8376 buf_T *buf;
8377
8378 prepare_to_exit();
8379
Bram Moolenaar4770d092006-01-12 23:22:24 +00008380 /* Setting this will prevent free() calls. That avoids calling free()
8381 * recursively when free() was invoked with a bad pointer. */
8382 really_exiting = TRUE;
8383
Bram Moolenaar071d4272004-06-13 20:20:40 +00008384 out_str(IObuff);
8385 screen_start(); /* don't know where cursor is now */
8386 out_flush();
8387
8388 ml_close_notmod(); /* close all not-modified buffers */
8389
8390 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8391 {
8392 if (buf->b_ml.ml_mfp != NULL && buf->b_ml.ml_mfp->mf_fname != NULL)
8393 {
8394 OUT_STR(_("Vim: preserving files...\n"));
8395 screen_start(); /* don't know where cursor is now */
8396 out_flush();
8397 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
8398 break;
8399 }
8400 }
8401
8402 ml_close_all(FALSE); /* close all memfiles, without deleting */
8403
8404 OUT_STR(_("Vim: Finished.\n"));
8405
8406 getout(1);
8407}
8408
8409/*
8410 * return TRUE if "fname" exists.
8411 */
8412 int
8413vim_fexists(fname)
8414 char_u *fname;
8415{
8416 struct stat st;
8417
8418 if (mch_stat((char *)fname, &st))
8419 return FALSE;
8420 return TRUE;
8421}
8422
8423/*
8424 * Check for CTRL-C pressed, but only once in a while.
8425 * Should be used instead of ui_breakcheck() for functions that check for
8426 * each line in the file. Calling ui_breakcheck() each time takes too much
8427 * time, because it can be a system call.
8428 */
8429
8430#ifndef BREAKCHECK_SKIP
8431# ifdef FEAT_GUI /* assume the GUI only runs on fast computers */
8432# define BREAKCHECK_SKIP 200
8433# else
8434# define BREAKCHECK_SKIP 32
8435# endif
8436#endif
8437
8438static int breakcheck_count = 0;
8439
8440 void
8441line_breakcheck()
8442{
8443 if (++breakcheck_count >= BREAKCHECK_SKIP)
8444 {
8445 breakcheck_count = 0;
8446 ui_breakcheck();
8447 }
8448}
8449
8450/*
8451 * Like line_breakcheck() but check 10 times less often.
8452 */
8453 void
8454fast_breakcheck()
8455{
8456 if (++breakcheck_count >= BREAKCHECK_SKIP * 10)
8457 {
8458 breakcheck_count = 0;
8459 ui_breakcheck();
8460 }
8461}
8462
8463/*
Bram Moolenaard7834d32009-12-02 16:14:36 +00008464 * Invoke expand_wildcards() for one pattern.
8465 * Expand items like "%:h" before the expansion.
8466 * Returns OK or FAIL.
8467 */
8468 int
8469expand_wildcards_eval(pat, num_file, file, flags)
8470 char_u **pat; /* pointer to input pattern */
8471 int *num_file; /* resulting number of files */
8472 char_u ***file; /* array of resulting files */
8473 int flags; /* EW_DIR, etc. */
8474{
8475 int ret = FAIL;
8476 char_u *eval_pat = NULL;
8477 char_u *exp_pat = *pat;
8478 char_u *ignored_msg;
8479 int usedlen;
8480
8481 if (*exp_pat == '%' || *exp_pat == '#' || *exp_pat == '<')
8482 {
8483 ++emsg_off;
8484 eval_pat = eval_vars(exp_pat, exp_pat, &usedlen,
8485 NULL, &ignored_msg, NULL);
8486 --emsg_off;
8487 if (eval_pat != NULL)
8488 exp_pat = concat_str(eval_pat, exp_pat + usedlen);
8489 }
8490
8491 if (exp_pat != NULL)
8492 ret = expand_wildcards(1, &exp_pat, num_file, file, flags);
8493
8494 if (eval_pat != NULL)
8495 {
8496 vim_free(exp_pat);
8497 vim_free(eval_pat);
8498 }
8499
8500 return ret;
8501}
8502
8503/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008504 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching
8505 * 'wildignore'.
Bram Moolenaar362e1a32006-03-06 23:29:24 +00008506 * Returns OK or FAIL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008507 */
8508 int
8509expand_wildcards(num_pat, pat, num_file, file, flags)
8510 int num_pat; /* number of input patterns */
8511 char_u **pat; /* array of input patterns */
8512 int *num_file; /* resulting number of files */
8513 char_u ***file; /* array of resulting files */
8514 int flags; /* EW_DIR, etc. */
8515{
8516 int retval;
8517 int i, j;
8518 char_u *p;
8519 int non_suf_match; /* number without matching suffix */
8520
8521 retval = gen_expand_wildcards(num_pat, pat, num_file, file, flags);
8522
8523 /* When keeping all matches, return here */
8524 if (flags & EW_KEEPALL)
8525 return retval;
8526
8527#ifdef FEAT_WILDIGN
8528 /*
8529 * Remove names that match 'wildignore'.
8530 */
8531 if (*p_wig)
8532 {
8533 char_u *ffname;
8534
8535 /* check all files in (*file)[] */
8536 for (i = 0; i < *num_file; ++i)
8537 {
8538 ffname = FullName_save((*file)[i], FALSE);
8539 if (ffname == NULL) /* out of memory */
8540 break;
8541# ifdef VMS
8542 vms_remove_version(ffname);
8543# endif
8544 if (match_file_list(p_wig, (*file)[i], ffname))
8545 {
8546 /* remove this matching file from the list */
8547 vim_free((*file)[i]);
8548 for (j = i; j + 1 < *num_file; ++j)
8549 (*file)[j] = (*file)[j + 1];
8550 --*num_file;
8551 --i;
8552 }
8553 vim_free(ffname);
8554 }
8555 }
8556#endif
8557
8558 /*
8559 * Move the names where 'suffixes' match to the end.
8560 */
8561 if (*num_file > 1)
8562 {
8563 non_suf_match = 0;
8564 for (i = 0; i < *num_file; ++i)
8565 {
8566 if (!match_suffix((*file)[i]))
8567 {
8568 /*
8569 * Move the name without matching suffix to the front
8570 * of the list.
8571 */
8572 p = (*file)[i];
8573 for (j = i; j > non_suf_match; --j)
8574 (*file)[j] = (*file)[j - 1];
8575 (*file)[non_suf_match++] = p;
8576 }
8577 }
8578 }
8579
8580 return retval;
8581}
8582
8583/*
8584 * Return TRUE if "fname" matches with an entry in 'suffixes'.
8585 */
8586 int
8587match_suffix(fname)
8588 char_u *fname;
8589{
8590 int fnamelen, setsuflen;
8591 char_u *setsuf;
8592#define MAXSUFLEN 30 /* maximum length of a file suffix */
8593 char_u suf_buf[MAXSUFLEN];
8594
8595 fnamelen = (int)STRLEN(fname);
8596 setsuflen = 0;
8597 for (setsuf = p_su; *setsuf; )
8598 {
8599 setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
Bram Moolenaar055a2ba2009-07-14 19:40:21 +00008600 if (setsuflen == 0)
8601 {
8602 char_u *tail = gettail(fname);
8603
8604 /* empty entry: match name without a '.' */
8605 if (vim_strchr(tail, '.') == NULL)
8606 {
8607 setsuflen = 1;
8608 break;
8609 }
8610 }
8611 else
8612 {
8613 if (fnamelen >= setsuflen
8614 && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
8615 (size_t)setsuflen) == 0)
8616 break;
8617 setsuflen = 0;
8618 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008619 }
8620 return (setsuflen != 0);
8621}
8622
8623#if !defined(NO_EXPANDPATH) || defined(PROTO)
8624
8625# ifdef VIM_BACKTICK
8626static int vim_backtick __ARGS((char_u *p));
8627static int expand_backtick __ARGS((garray_T *gap, char_u *pat, int flags));
8628# endif
8629
8630# if defined(MSDOS) || defined(FEAT_GUI_W16) || defined(WIN3264)
8631/*
8632 * File name expansion code for MS-DOS, Win16 and Win32. It's here because
8633 * it's shared between these systems.
8634 */
8635# if defined(DJGPP) || defined(PROTO)
8636# define _cdecl /* DJGPP doesn't have this */
8637# else
8638# ifdef __BORLANDC__
8639# define _cdecl _RTLENTRYF
8640# endif
8641# endif
8642
8643/*
8644 * comparison function for qsort in dos_expandpath()
8645 */
8646 static int _cdecl
8647pstrcmp(const void *a, const void *b)
8648{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00008649 return (pathcmp(*(char **)a, *(char **)b, -1));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008650}
8651
8652# ifndef WIN3264
8653 static void
8654namelowcpy(
8655 char_u *d,
8656 char_u *s)
8657{
8658# ifdef DJGPP
8659 if (USE_LONG_FNAME) /* don't lower case on Windows 95/NT systems */
8660 while (*s)
8661 *d++ = *s++;
8662 else
8663# endif
8664 while (*s)
8665 *d++ = TOLOWER_LOC(*s++);
8666 *d = NUL;
8667}
8668# endif
8669
8670/*
Bram Moolenaar231334e2005-07-25 20:46:57 +00008671 * Recursively expand one path component into all matching files and/or
8672 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008673 * Return the number of matches found.
8674 * "path" has backslashes before chars that are not to be expanded, starting
8675 * at "path[wildoff]".
Bram Moolenaar231334e2005-07-25 20:46:57 +00008676 * Return the number of matches found.
8677 * NOTE: much of this is identical to unix_expandpath(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00008678 */
8679 static int
8680dos_expandpath(
8681 garray_T *gap,
8682 char_u *path,
8683 int wildoff,
Bram Moolenaar231334e2005-07-25 20:46:57 +00008684 int flags, /* EW_* flags */
Bram Moolenaar25394022007-05-10 19:06:20 +00008685 int didstar) /* expanded "**" once already */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008686{
Bram Moolenaar231334e2005-07-25 20:46:57 +00008687 char_u *buf;
8688 char_u *path_end;
8689 char_u *p, *s, *e;
8690 int start_len = gap->ga_len;
8691 char_u *pat;
8692 regmatch_T regmatch;
8693 int starts_with_dot;
8694 int matches;
8695 int len;
8696 int starstar = FALSE;
8697 static int stardepth = 0; /* depth for "**" expansion */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008698#ifdef WIN3264
8699 WIN32_FIND_DATA fb;
8700 HANDLE hFind = (HANDLE)0;
8701# ifdef FEAT_MBYTE
8702 WIN32_FIND_DATAW wfb;
8703 WCHAR *wn = NULL; /* UCS-2 name, NULL when not used. */
8704# endif
8705#else
8706 struct ffblk fb;
8707#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008708 char_u *matchname;
Bram Moolenaar231334e2005-07-25 20:46:57 +00008709 int ok;
8710
8711 /* Expanding "**" may take a long time, check for CTRL-C. */
8712 if (stardepth > 0)
8713 {
8714 ui_breakcheck();
8715 if (got_int)
8716 return 0;
8717 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008718
8719 /* make room for file name */
Bram Moolenaar231334e2005-07-25 20:46:57 +00008720 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008721 if (buf == NULL)
8722 return 0;
8723
8724 /*
8725 * Find the first part in the path name that contains a wildcard or a ~1.
8726 * Copy it into buf, including the preceding characters.
8727 */
8728 p = buf;
8729 s = buf;
8730 e = NULL;
8731 path_end = path;
8732 while (*path_end != NUL)
8733 {
8734 /* May ignore a wildcard that has a backslash before it; it will
8735 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
8736 if (path_end >= path + wildoff && rem_backslash(path_end))
8737 *p++ = *path_end++;
8738 else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
8739 {
8740 if (e != NULL)
8741 break;
8742 s = p + 1;
8743 }
8744 else if (path_end >= path + wildoff
8745 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
8746 e = p;
8747#ifdef FEAT_MBYTE
8748 if (has_mbyte)
8749 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00008750 len = (*mb_ptr2len)(path_end);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008751 STRNCPY(p, path_end, len);
8752 p += len;
8753 path_end += len;
8754 }
8755 else
8756#endif
8757 *p++ = *path_end++;
8758 }
8759 e = p;
8760 *e = NUL;
8761
8762 /* now we have one wildcard component between s and e */
8763 /* Remove backslashes between "wildoff" and the start of the wildcard
8764 * component. */
8765 for (p = buf + wildoff; p < s; ++p)
8766 if (rem_backslash(p))
8767 {
Bram Moolenaar8c8de832008-06-24 22:58:06 +00008768 STRMOVE(p, p + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008769 --e;
8770 --s;
8771 }
8772
Bram Moolenaar231334e2005-07-25 20:46:57 +00008773 /* Check for "**" between "s" and "e". */
8774 for (p = s; p < e; ++p)
8775 if (p[0] == '*' && p[1] == '*')
8776 starstar = TRUE;
8777
Bram Moolenaar071d4272004-06-13 20:20:40 +00008778 starts_with_dot = (*s == '.');
8779 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
8780 if (pat == NULL)
8781 {
8782 vim_free(buf);
8783 return 0;
8784 }
8785
8786 /* compile the regexp into a program */
8787 regmatch.rm_ic = TRUE; /* Always ignore case */
8788 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
8789 vim_free(pat);
8790
8791 if (regmatch.regprog == NULL)
8792 {
8793 vim_free(buf);
8794 return 0;
8795 }
8796
8797 /* remember the pattern or file name being looked for */
8798 matchname = vim_strsave(s);
8799
Bram Moolenaar231334e2005-07-25 20:46:57 +00008800 /* If "**" is by itself, this is the first time we encounter it and more
8801 * is following then find matches without any directory. */
8802 if (!didstar && stardepth < 100 && starstar && e - s == 2
8803 && *path_end == '/')
8804 {
8805 STRCPY(s, path_end + 1);
8806 ++stardepth;
8807 (void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
8808 --stardepth;
8809 }
8810
Bram Moolenaar071d4272004-06-13 20:20:40 +00008811 /* Scan all files in the directory with "dir/ *.*" */
8812 STRCPY(s, "*.*");
8813#ifdef WIN3264
8814# ifdef FEAT_MBYTE
8815 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
8816 {
8817 /* The active codepage differs from 'encoding'. Attempt using the
8818 * wide function. If it fails because it is not implemented fall back
8819 * to the non-wide version (for Windows 98) */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00008820 wn = enc_to_utf16(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008821 if (wn != NULL)
8822 {
8823 hFind = FindFirstFileW(wn, &wfb);
8824 if (hFind == INVALID_HANDLE_VALUE
8825 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
8826 {
8827 vim_free(wn);
8828 wn = NULL;
8829 }
8830 }
8831 }
8832
8833 if (wn == NULL)
8834# endif
8835 hFind = FindFirstFile(buf, &fb);
8836 ok = (hFind != INVALID_HANDLE_VALUE);
8837#else
8838 /* If we are expanding wildcards we try both files and directories */
8839 ok = (findfirst((char *)buf, &fb,
8840 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
8841#endif
8842
8843 while (ok)
8844 {
8845#ifdef WIN3264
8846# ifdef FEAT_MBYTE
8847 if (wn != NULL)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00008848 p = utf16_to_enc(wfb.cFileName, NULL); /* p is allocated here */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008849 else
8850# endif
8851 p = (char_u *)fb.cFileName;
8852#else
8853 p = (char_u *)fb.ff_name;
8854#endif
8855 /* Ignore entries starting with a dot, unless when asked for. Accept
8856 * all entries found with "matchname". */
8857 if ((p[0] != '.' || starts_with_dot)
8858 && (matchname == NULL
8859 || vim_regexec(&regmatch, p, (colnr_T)0)))
8860 {
8861#ifdef WIN3264
8862 STRCPY(s, p);
8863#else
8864 namelowcpy(s, p);
8865#endif
8866 len = (int)STRLEN(buf);
Bram Moolenaar231334e2005-07-25 20:46:57 +00008867
8868 if (starstar && stardepth < 100)
8869 {
8870 /* For "**" in the pattern first go deeper in the tree to
8871 * find matches. */
8872 STRCPY(buf + len, "/**");
8873 STRCPY(buf + len + 3, path_end);
8874 ++stardepth;
8875 (void)dos_expandpath(gap, buf, len + 1, flags, TRUE);
8876 --stardepth;
8877 }
8878
Bram Moolenaar071d4272004-06-13 20:20:40 +00008879 STRCPY(buf + len, path_end);
8880 if (mch_has_exp_wildcard(path_end))
8881 {
8882 /* need to expand another component of the path */
8883 /* remove backslashes for the remaining components only */
Bram Moolenaar231334e2005-07-25 20:46:57 +00008884 (void)dos_expandpath(gap, buf, len + 1, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008885 }
8886 else
8887 {
8888 /* no more wildcards, check if there is a match */
8889 /* remove backslashes for the remaining components only */
8890 if (*path_end != 0)
8891 backslash_halve(buf + len + 1);
8892 if (mch_getperm(buf) >= 0) /* add existing file */
8893 addfile(gap, buf, flags);
8894 }
8895 }
8896
8897#ifdef WIN3264
8898# ifdef FEAT_MBYTE
8899 if (wn != NULL)
8900 {
8901 vim_free(p);
8902 ok = FindNextFileW(hFind, &wfb);
8903 }
8904 else
8905# endif
8906 ok = FindNextFile(hFind, &fb);
8907#else
8908 ok = (findnext(&fb) == 0);
8909#endif
8910
8911 /* If no more matches and no match was used, try expanding the name
8912 * itself. Finds the long name of a short filename. */
8913 if (!ok && matchname != NULL && gap->ga_len == start_len)
8914 {
8915 STRCPY(s, matchname);
8916#ifdef WIN3264
8917 FindClose(hFind);
8918# ifdef FEAT_MBYTE
8919 if (wn != NULL)
8920 {
8921 vim_free(wn);
Bram Moolenaar36f692d2008-11-20 16:10:17 +00008922 wn = enc_to_utf16(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008923 if (wn != NULL)
8924 hFind = FindFirstFileW(wn, &wfb);
8925 }
8926 if (wn == NULL)
8927# endif
8928 hFind = FindFirstFile(buf, &fb);
8929 ok = (hFind != INVALID_HANDLE_VALUE);
8930#else
8931 ok = (findfirst((char *)buf, &fb,
8932 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
8933#endif
8934 vim_free(matchname);
8935 matchname = NULL;
8936 }
8937 }
8938
8939#ifdef WIN3264
8940 FindClose(hFind);
8941# ifdef FEAT_MBYTE
8942 vim_free(wn);
8943# endif
8944#endif
8945 vim_free(buf);
8946 vim_free(regmatch.regprog);
8947 vim_free(matchname);
8948
8949 matches = gap->ga_len - start_len;
8950 if (matches > 0)
8951 qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
8952 sizeof(char_u *), pstrcmp);
8953 return matches;
8954}
8955
8956 int
8957mch_expandpath(
8958 garray_T *gap,
8959 char_u *path,
8960 int flags) /* EW_* flags */
8961{
Bram Moolenaar231334e2005-07-25 20:46:57 +00008962 return dos_expandpath(gap, path, 0, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008963}
8964# endif /* MSDOS || FEAT_GUI_W16 || WIN3264 */
8965
Bram Moolenaar231334e2005-07-25 20:46:57 +00008966#if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
8967 || defined(PROTO)
8968/*
8969 * Unix style wildcard expansion code.
8970 * It's here because it's used both for Unix and Mac.
8971 */
8972static int pstrcmp __ARGS((const void *, const void *));
8973
8974 static int
8975pstrcmp(a, b)
8976 const void *a, *b;
8977{
8978 return (pathcmp(*(char **)a, *(char **)b, -1));
8979}
8980
8981/*
8982 * Recursively expand one path component into all matching files and/or
8983 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
8984 * "path" has backslashes before chars that are not to be expanded, starting
8985 * at "path + wildoff".
8986 * Return the number of matches found.
8987 * NOTE: much of this is identical to dos_expandpath(), keep in sync!
8988 */
8989 int
8990unix_expandpath(gap, path, wildoff, flags, didstar)
8991 garray_T *gap;
8992 char_u *path;
8993 int wildoff;
8994 int flags; /* EW_* flags */
8995 int didstar; /* expanded "**" once already */
8996{
8997 char_u *buf;
8998 char_u *path_end;
8999 char_u *p, *s, *e;
9000 int start_len = gap->ga_len;
9001 char_u *pat;
9002 regmatch_T regmatch;
9003 int starts_with_dot;
9004 int matches;
9005 int len;
9006 int starstar = FALSE;
9007 static int stardepth = 0; /* depth for "**" expansion */
9008
9009 DIR *dirp;
9010 struct dirent *dp;
9011
9012 /* Expanding "**" may take a long time, check for CTRL-C. */
9013 if (stardepth > 0)
9014 {
9015 ui_breakcheck();
9016 if (got_int)
9017 return 0;
9018 }
9019
9020 /* make room for file name */
9021 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
9022 if (buf == NULL)
9023 return 0;
9024
9025 /*
9026 * Find the first part in the path name that contains a wildcard.
9027 * Copy it into "buf", including the preceding characters.
9028 */
9029 p = buf;
9030 s = buf;
9031 e = NULL;
9032 path_end = path;
9033 while (*path_end != NUL)
9034 {
9035 /* May ignore a wildcard that has a backslash before it; it will
9036 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
9037 if (path_end >= path + wildoff && rem_backslash(path_end))
9038 *p++ = *path_end++;
9039 else if (*path_end == '/')
9040 {
9041 if (e != NULL)
9042 break;
9043 s = p + 1;
9044 }
9045 else if (path_end >= path + wildoff
9046 && vim_strchr((char_u *)"*?[{~$", *path_end) != NULL)
9047 e = p;
9048#ifdef FEAT_MBYTE
9049 if (has_mbyte)
9050 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00009051 len = (*mb_ptr2len)(path_end);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009052 STRNCPY(p, path_end, len);
9053 p += len;
9054 path_end += len;
9055 }
9056 else
9057#endif
9058 *p++ = *path_end++;
9059 }
9060 e = p;
9061 *e = NUL;
9062
9063 /* now we have one wildcard component between "s" and "e" */
9064 /* Remove backslashes between "wildoff" and the start of the wildcard
9065 * component. */
9066 for (p = buf + wildoff; p < s; ++p)
9067 if (rem_backslash(p))
9068 {
Bram Moolenaar8c8de832008-06-24 22:58:06 +00009069 STRMOVE(p, p + 1);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009070 --e;
9071 --s;
9072 }
9073
9074 /* Check for "**" between "s" and "e". */
9075 for (p = s; p < e; ++p)
9076 if (p[0] == '*' && p[1] == '*')
9077 starstar = TRUE;
9078
9079 /* convert the file pattern to a regexp pattern */
9080 starts_with_dot = (*s == '.');
9081 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
9082 if (pat == NULL)
9083 {
9084 vim_free(buf);
9085 return 0;
9086 }
9087
9088 /* compile the regexp into a program */
Bram Moolenaarcc016f52005-12-10 20:23:46 +00009089#ifdef CASE_INSENSITIVE_FILENAME
Bram Moolenaar231334e2005-07-25 20:46:57 +00009090 regmatch.rm_ic = TRUE; /* Behave like Terminal.app */
9091#else
9092 regmatch.rm_ic = FALSE; /* Don't ever ignore case */
9093#endif
9094 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
9095 vim_free(pat);
9096
9097 if (regmatch.regprog == NULL)
9098 {
9099 vim_free(buf);
9100 return 0;
9101 }
9102
9103 /* If "**" is by itself, this is the first time we encounter it and more
9104 * is following then find matches without any directory. */
9105 if (!didstar && stardepth < 100 && starstar && e - s == 2
9106 && *path_end == '/')
9107 {
9108 STRCPY(s, path_end + 1);
9109 ++stardepth;
9110 (void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
9111 --stardepth;
9112 }
9113
9114 /* open the directory for scanning */
9115 *s = NUL;
9116 dirp = opendir(*buf == NUL ? "." : (char *)buf);
9117
9118 /* Find all matching entries */
9119 if (dirp != NULL)
9120 {
9121 for (;;)
9122 {
9123 dp = readdir(dirp);
9124 if (dp == NULL)
9125 break;
9126 if ((dp->d_name[0] != '.' || starts_with_dot)
9127 && vim_regexec(&regmatch, (char_u *)dp->d_name, (colnr_T)0))
9128 {
9129 STRCPY(s, dp->d_name);
9130 len = STRLEN(buf);
9131
9132 if (starstar && stardepth < 100)
9133 {
9134 /* For "**" in the pattern first go deeper in the tree to
9135 * find matches. */
9136 STRCPY(buf + len, "/**");
9137 STRCPY(buf + len + 3, path_end);
9138 ++stardepth;
9139 (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
9140 --stardepth;
9141 }
9142
9143 STRCPY(buf + len, path_end);
9144 if (mch_has_exp_wildcard(path_end)) /* handle more wildcards */
9145 {
9146 /* need to expand another component of the path */
9147 /* remove backslashes for the remaining components only */
9148 (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
9149 }
9150 else
9151 {
9152 /* no more wildcards, check if there is a match */
9153 /* remove backslashes for the remaining components only */
9154 if (*path_end != NUL)
9155 backslash_halve(buf + len + 1);
9156 if (mch_getperm(buf) >= 0) /* add existing file */
9157 {
Bram Moolenaar95e9b492006-03-15 23:04:43 +00009158#ifdef MACOS_CONVERT
Bram Moolenaar231334e2005-07-25 20:46:57 +00009159 size_t precomp_len = STRLEN(buf)+1;
9160 char_u *precomp_buf =
9161 mac_precompose_path(buf, precomp_len, &precomp_len);
Bram Moolenaar95e9b492006-03-15 23:04:43 +00009162
Bram Moolenaar231334e2005-07-25 20:46:57 +00009163 if (precomp_buf)
9164 {
9165 mch_memmove(buf, precomp_buf, precomp_len);
9166 vim_free(precomp_buf);
9167 }
9168#endif
9169 addfile(gap, buf, flags);
9170 }
9171 }
9172 }
9173 }
9174
9175 closedir(dirp);
9176 }
9177
9178 vim_free(buf);
9179 vim_free(regmatch.regprog);
9180
9181 matches = gap->ga_len - start_len;
9182 if (matches > 0)
9183 qsort(((char_u **)gap->ga_data) + start_len, matches,
9184 sizeof(char_u *), pstrcmp);
9185 return matches;
9186}
9187#endif
9188
Bram Moolenaar071d4272004-06-13 20:20:40 +00009189/*
9190 * Generic wildcard expansion code.
9191 *
9192 * Characters in "pat" that should not be expanded must be preceded with a
9193 * backslash. E.g., "/path\ with\ spaces/my\*star*"
9194 *
9195 * Return FAIL when no single file was found. In this case "num_file" is not
9196 * set, and "file" may contain an error message.
9197 * Return OK when some files found. "num_file" is set to the number of
9198 * matches, "file" to the array of matches. Call FreeWild() later.
9199 */
9200 int
9201gen_expand_wildcards(num_pat, pat, num_file, file, flags)
9202 int num_pat; /* number of input patterns */
9203 char_u **pat; /* array of input patterns */
9204 int *num_file; /* resulting number of files */
9205 char_u ***file; /* array of resulting files */
9206 int flags; /* EW_* flags */
9207{
9208 int i;
9209 garray_T ga;
9210 char_u *p;
9211 static int recursive = FALSE;
9212 int add_pat;
9213
9214 /*
9215 * expand_env() is called to expand things like "~user". If this fails,
9216 * it calls ExpandOne(), which brings us back here. In this case, always
9217 * call the machine specific expansion function, if possible. Otherwise,
9218 * return FAIL.
9219 */
9220 if (recursive)
9221#ifdef SPECIAL_WILDCHAR
9222 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
9223#else
9224 return FAIL;
9225#endif
9226
9227#ifdef SPECIAL_WILDCHAR
9228 /*
9229 * If there are any special wildcard characters which we cannot handle
9230 * here, call machine specific function for all the expansion. This
9231 * avoids starting the shell for each argument separately.
9232 * For `=expr` do use the internal function.
9233 */
9234 for (i = 0; i < num_pat; i++)
9235 {
9236 if (vim_strpbrk(pat[i], (char_u *)SPECIAL_WILDCHAR) != NULL
9237# ifdef VIM_BACKTICK
9238 && !(vim_backtick(pat[i]) && pat[i][1] == '=')
9239# endif
9240 )
9241 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
9242 }
9243#endif
9244
9245 recursive = TRUE;
9246
9247 /*
9248 * The matching file names are stored in a growarray. Init it empty.
9249 */
9250 ga_init2(&ga, (int)sizeof(char_u *), 30);
9251
9252 for (i = 0; i < num_pat; ++i)
9253 {
9254 add_pat = -1;
9255 p = pat[i];
9256
9257#ifdef VIM_BACKTICK
9258 if (vim_backtick(p))
9259 add_pat = expand_backtick(&ga, p, flags);
9260 else
9261#endif
9262 {
9263 /*
9264 * First expand environment variables, "~/" and "~user/".
9265 */
9266 if (vim_strpbrk(p, (char_u *)"$~") != NULL)
9267 {
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00009268 p = expand_env_save_opt(p, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009269 if (p == NULL)
9270 p = pat[i];
9271#ifdef UNIX
9272 /*
9273 * On Unix, if expand_env() can't expand an environment
9274 * variable, use the shell to do that. Discard previously
9275 * found file names and start all over again.
9276 */
9277 else if (vim_strpbrk(p, (char_u *)"$~") != NULL)
9278 {
9279 vim_free(p);
Bram Moolenaar782027e2009-06-24 14:25:49 +00009280 ga_clear_strings(&ga);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009281 i = mch_expand_wildcards(num_pat, pat, num_file, file,
9282 flags);
9283 recursive = FALSE;
9284 return i;
9285 }
9286#endif
9287 }
9288
9289 /*
9290 * If there are wildcards: Expand file names and add each match to
9291 * the list. If there is no match, and EW_NOTFOUND is given, add
9292 * the pattern.
9293 * If there are no wildcards: Add the file name if it exists or
9294 * when EW_NOTFOUND is given.
9295 */
9296 if (mch_has_exp_wildcard(p))
9297 add_pat = mch_expandpath(&ga, p, flags);
9298 }
9299
9300 if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
9301 {
9302 char_u *t = backslash_halve_save(p);
9303
9304#if defined(MACOS_CLASSIC)
9305 slash_to_colon(t);
9306#endif
9307 /* When EW_NOTFOUND is used, always add files and dirs. Makes
9308 * "vim c:/" work. */
9309 if (flags & EW_NOTFOUND)
9310 addfile(&ga, t, flags | EW_DIR | EW_FILE);
9311 else if (mch_getperm(t) >= 0)
9312 addfile(&ga, t, flags);
9313 vim_free(t);
9314 }
9315
9316 if (p != pat[i])
9317 vim_free(p);
9318 }
9319
9320 *num_file = ga.ga_len;
9321 *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data : (char_u **)"";
9322
9323 recursive = FALSE;
9324
9325 return (ga.ga_data != NULL) ? OK : FAIL;
9326}
9327
9328# ifdef VIM_BACKTICK
9329
9330/*
9331 * Return TRUE if we can expand this backtick thing here.
9332 */
9333 static int
9334vim_backtick(p)
9335 char_u *p;
9336{
9337 return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
9338}
9339
9340/*
9341 * Expand an item in `backticks` by executing it as a command.
9342 * Currently only works when pat[] starts and ends with a `.
9343 * Returns number of file names found.
9344 */
9345 static int
9346expand_backtick(gap, pat, flags)
9347 garray_T *gap;
9348 char_u *pat;
9349 int flags; /* EW_* flags */
9350{
9351 char_u *p;
9352 char_u *cmd;
9353 char_u *buffer;
9354 int cnt = 0;
9355 int i;
9356
9357 /* Create the command: lop off the backticks. */
9358 cmd = vim_strnsave(pat + 1, (int)STRLEN(pat) - 2);
9359 if (cmd == NULL)
9360 return 0;
9361
9362#ifdef FEAT_EVAL
9363 if (*cmd == '=') /* `={expr}`: Expand expression */
Bram Moolenaar362e1a32006-03-06 23:29:24 +00009364 buffer = eval_to_string(cmd + 1, &p, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009365 else
9366#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00009367 buffer = get_cmd_output(cmd, NULL,
9368 (flags & EW_SILENT) ? SHELL_SILENT : 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009369 vim_free(cmd);
9370 if (buffer == NULL)
9371 return 0;
9372
9373 cmd = buffer;
9374 while (*cmd != NUL)
9375 {
9376 cmd = skipwhite(cmd); /* skip over white space */
9377 p = cmd;
9378 while (*p != NUL && *p != '\r' && *p != '\n') /* skip over entry */
9379 ++p;
9380 /* add an entry if it is not empty */
9381 if (p > cmd)
9382 {
9383 i = *p;
9384 *p = NUL;
9385 addfile(gap, cmd, flags);
9386 *p = i;
9387 ++cnt;
9388 }
9389 cmd = p;
9390 while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
9391 ++cmd;
9392 }
9393
9394 vim_free(buffer);
9395 return cnt;
9396}
9397# endif /* VIM_BACKTICK */
9398
9399/*
9400 * Add a file to a file list. Accepted flags:
9401 * EW_DIR add directories
9402 * EW_FILE add files
Bram Moolenaar1f35bf92006-03-07 22:38:47 +00009403 * EW_EXEC add executable files
Bram Moolenaar071d4272004-06-13 20:20:40 +00009404 * EW_NOTFOUND add even when it doesn't exist
9405 * EW_ADDSLASH add slash after directory name
9406 */
9407 void
9408addfile(gap, f, flags)
9409 garray_T *gap;
9410 char_u *f; /* filename */
9411 int flags;
9412{
9413 char_u *p;
9414 int isdir;
9415
9416 /* if the file/dir doesn't exist, may not add it */
9417 if (!(flags & EW_NOTFOUND) && mch_getperm(f) < 0)
9418 return;
9419
9420#ifdef FNAME_ILLEGAL
9421 /* if the file/dir contains illegal characters, don't add it */
9422 if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
9423 return;
9424#endif
9425
9426 isdir = mch_isdir(f);
9427 if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
9428 return;
9429
Bram Moolenaar1f35bf92006-03-07 22:38:47 +00009430 /* If the file isn't executable, may not add it. Do accept directories. */
9431 if (!isdir && (flags & EW_EXEC) && !mch_can_exe(f))
9432 return;
9433
Bram Moolenaar071d4272004-06-13 20:20:40 +00009434 /* Make room for another item in the file list. */
9435 if (ga_grow(gap, 1) == FAIL)
9436 return;
9437
9438 p = alloc((unsigned)(STRLEN(f) + 1 + isdir));
9439 if (p == NULL)
9440 return;
9441
9442 STRCPY(p, f);
9443#ifdef BACKSLASH_IN_FILENAME
9444 slash_adjust(p);
9445#endif
9446 /*
9447 * Append a slash or backslash after directory names if none is present.
9448 */
9449#ifndef DONT_ADD_PATHSEP_TO_DIR
9450 if (isdir && (flags & EW_ADDSLASH))
9451 add_pathsep(p);
9452#endif
9453 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009454}
9455#endif /* !NO_EXPANDPATH */
9456
9457#if defined(VIM_BACKTICK) || defined(FEAT_EVAL) || defined(PROTO)
9458
9459#ifndef SEEK_SET
9460# define SEEK_SET 0
9461#endif
9462#ifndef SEEK_END
9463# define SEEK_END 2
9464#endif
9465
9466/*
9467 * Get the stdout of an external command.
9468 * Returns an allocated string, or NULL for error.
9469 */
9470 char_u *
Bram Moolenaarc0197e22004-09-13 20:26:32 +00009471get_cmd_output(cmd, infile, flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009472 char_u *cmd;
Bram Moolenaarc0197e22004-09-13 20:26:32 +00009473 char_u *infile; /* optional input file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009474 int flags; /* can be SHELL_SILENT */
9475{
9476 char_u *tempname;
9477 char_u *command;
9478 char_u *buffer = NULL;
9479 int len;
9480 int i = 0;
9481 FILE *fd;
9482
9483 if (check_restricted() || check_secure())
9484 return NULL;
9485
9486 /* get a name for the temp file */
9487 if ((tempname = vim_tempname('o')) == NULL)
9488 {
9489 EMSG(_(e_notmp));
9490 return NULL;
9491 }
9492
9493 /* Add the redirection stuff */
Bram Moolenaarc0197e22004-09-13 20:26:32 +00009494 command = make_filter_cmd(cmd, infile, tempname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009495 if (command == NULL)
9496 goto done;
9497
9498 /*
9499 * Call the shell to execute the command (errors are ignored).
9500 * Don't check timestamps here.
9501 */
9502 ++no_check_timestamps;
9503 call_shell(command, SHELL_DOOUT | SHELL_EXPAND | flags);
9504 --no_check_timestamps;
9505
9506 vim_free(command);
9507
9508 /*
9509 * read the names from the file into memory
9510 */
9511# ifdef VMS
Bram Moolenaar25394022007-05-10 19:06:20 +00009512 /* created temporary file is not always readable as binary */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009513 fd = mch_fopen((char *)tempname, "r");
9514# else
9515 fd = mch_fopen((char *)tempname, READBIN);
9516# endif
9517
9518 if (fd == NULL)
9519 {
9520 EMSG2(_(e_notopen), tempname);
9521 goto done;
9522 }
9523
9524 fseek(fd, 0L, SEEK_END);
9525 len = ftell(fd); /* get size of temp file */
9526 fseek(fd, 0L, SEEK_SET);
9527
9528 buffer = alloc(len + 1);
9529 if (buffer != NULL)
9530 i = (int)fread((char *)buffer, (size_t)1, (size_t)len, fd);
9531 fclose(fd);
9532 mch_remove(tempname);
9533 if (buffer == NULL)
9534 goto done;
9535#ifdef VMS
9536 len = i; /* VMS doesn't give us what we asked for... */
9537#endif
9538 if (i != len)
9539 {
9540 EMSG2(_(e_notread), tempname);
9541 vim_free(buffer);
9542 buffer = NULL;
9543 }
9544 else
9545 buffer[len] = '\0'; /* make sure the buffer is terminated */
9546
9547done:
9548 vim_free(tempname);
9549 return buffer;
9550}
9551#endif
9552
9553/*
9554 * Free the list of files returned by expand_wildcards() or other expansion
9555 * functions.
9556 */
9557 void
9558FreeWild(count, files)
9559 int count;
9560 char_u **files;
9561{
Bram Moolenaarfc1421e2006-04-20 22:17:20 +00009562 if (count <= 0 || files == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009563 return;
9564#if defined(__EMX__) && defined(__ALWAYS_HAS_TRAILING_NULL_POINTER) /* XXX */
9565 /*
9566 * Is this still OK for when other functions than expand_wildcards() have
9567 * been used???
9568 */
9569 _fnexplodefree((char **)files);
9570#else
9571 while (count--)
9572 vim_free(files[count]);
9573 vim_free(files);
9574#endif
9575}
9576
9577/*
9578 * return TRUE when need to go to Insert mode because of 'insertmode'.
9579 * Don't do this when still processing a command or a mapping.
9580 * Don't do this when inside a ":normal" command.
9581 */
9582 int
9583goto_im()
9584{
9585 return (p_im && stuff_empty() && typebuf_typed());
9586}