blob: f86a16781fd23242b13b5f7729dac5e6e07a6f09 [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
1029 for (p = lead_flags; *p && *p != ':'; ++p)
1030 {
1031 if (*p == COM_RIGHT || *p == COM_LEFT)
1032 c = *p;
1033 else if (VIM_ISDIGIT(*p) || *p == '-')
1034 off = getdigits(&p);
1035 }
1036 if (c == COM_RIGHT) /* right adjusted leader */
1037 {
1038 /* find last non-white in the leader to line up with */
1039 for (p = leader + lead_len - 1; p > leader
1040 && vim_iswhite(*p); --p)
1041 ;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001042 ++p;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001043
1044#ifdef FEAT_MBYTE
1045 /* Compute the length of the replaced characters in
1046 * screen characters, not bytes. */
1047 {
1048 int repl_size = vim_strnsize(lead_repl,
1049 lead_repl_len);
1050 int old_size = 0;
1051 char_u *endp = p;
1052 int l;
1053
1054 while (old_size < repl_size && p > leader)
1055 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001056 mb_ptr_back(leader, p);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001057 old_size += ptr2cells(p);
1058 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001059 l = lead_repl_len - (int)(endp - p);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001060 if (l != 0)
1061 mch_memmove(endp + l, endp,
1062 (size_t)((leader + lead_len) - endp));
1063 lead_len += l;
1064 }
1065#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001066 if (p < leader + lead_repl_len)
1067 p = leader;
1068 else
1069 p -= lead_repl_len;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001070#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001071 mch_memmove(p, lead_repl, (size_t)lead_repl_len);
1072 if (p + lead_repl_len > leader + lead_len)
1073 p[lead_repl_len] = NUL;
1074
1075 /* blank-out any other chars from the old leader. */
1076 while (--p >= leader)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001077 {
1078#ifdef FEAT_MBYTE
1079 int l = mb_head_off(leader, p);
1080
1081 if (l > 1)
1082 {
1083 p -= l;
1084 if (ptr2cells(p) > 1)
1085 {
1086 p[1] = ' ';
1087 --l;
1088 }
1089 mch_memmove(p + 1, p + l + 1,
1090 (size_t)((leader + lead_len) - (p + l + 1)));
1091 lead_len -= l;
1092 *p = ' ';
1093 }
1094 else
1095#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001096 if (!vim_iswhite(*p))
1097 *p = ' ';
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001098 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001099 }
1100 else /* left adjusted leader */
1101 {
1102 p = skipwhite(leader);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001103#ifdef FEAT_MBYTE
1104 /* Compute the length of the replaced characters in
1105 * screen characters, not bytes. Move the part that is
1106 * not to be overwritten. */
1107 {
1108 int repl_size = vim_strnsize(lead_repl,
1109 lead_repl_len);
1110 int i;
1111 int l;
1112
1113 for (i = 0; p[i] != NUL && i < lead_len; i += l)
1114 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00001115 l = (*mb_ptr2len)(p + i);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001116 if (vim_strnsize(p, i + l) > repl_size)
1117 break;
1118 }
1119 if (i != lead_repl_len)
1120 {
1121 mch_memmove(p + lead_repl_len, p + i,
1122 (size_t)(lead_len - i - (leader - p)));
1123 lead_len += lead_repl_len - i;
1124 }
1125 }
1126#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001127 mch_memmove(p, lead_repl, (size_t)lead_repl_len);
1128
1129 /* Replace any remaining non-white chars in the old
1130 * leader by spaces. Keep Tabs, the indent must
1131 * remain the same. */
1132 for (p += lead_repl_len; p < leader + lead_len; ++p)
1133 if (!vim_iswhite(*p))
1134 {
1135 /* Don't put a space before a TAB. */
1136 if (p + 1 < leader + lead_len && p[1] == TAB)
1137 {
1138 --lead_len;
1139 mch_memmove(p, p + 1,
1140 (leader + lead_len) - p);
1141 }
1142 else
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001143 {
1144#ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00001145 int l = (*mb_ptr2len)(p);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001146
1147 if (l > 1)
1148 {
1149 if (ptr2cells(p) > 1)
1150 {
1151 /* Replace a double-wide char with
1152 * two spaces */
1153 --l;
1154 *p++ = ' ';
1155 }
1156 mch_memmove(p + 1, p + l,
1157 (leader + lead_len) - p);
1158 lead_len -= l - 1;
1159 }
1160#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001161 *p = ' ';
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001162 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001163 }
1164 *p = NUL;
1165 }
1166
1167 /* Recompute the indent, it may have changed. */
1168 if (curbuf->b_p_ai
1169#ifdef FEAT_SMARTINDENT
1170 || do_si
1171#endif
1172 )
1173 newindent = get_indent_str(leader, (int)curbuf->b_p_ts);
1174
1175 /* Add the indent offset */
1176 if (newindent + off < 0)
1177 {
1178 off = -newindent;
1179 newindent = 0;
1180 }
1181 else
1182 newindent += off;
1183
1184 /* Correct trailing spaces for the shift, so that
1185 * alignment remains equal. */
1186 while (off > 0 && lead_len > 0
1187 && leader[lead_len - 1] == ' ')
1188 {
1189 /* Don't do it when there is a tab before the space */
1190 if (vim_strchr(skipwhite(leader), '\t') != NULL)
1191 break;
1192 --lead_len;
1193 --off;
1194 }
1195
1196 /* If the leader ends in white space, don't add an
1197 * extra space */
1198 if (lead_len > 0 && vim_iswhite(leader[lead_len - 1]))
1199 extra_space = FALSE;
1200 leader[lead_len] = NUL;
1201 }
1202
1203 if (extra_space)
1204 {
1205 leader[lead_len++] = ' ';
1206 leader[lead_len] = NUL;
1207 }
1208
1209 newcol = lead_len;
1210
1211 /*
1212 * if a new indent will be set below, remove the indent that
1213 * is in the comment leader
1214 */
1215 if (newindent
1216#ifdef FEAT_SMARTINDENT
1217 || did_si
1218#endif
1219 )
1220 {
1221 while (lead_len && vim_iswhite(*leader))
1222 {
1223 --lead_len;
1224 --newcol;
1225 ++leader;
1226 }
1227 }
1228
1229 }
1230#ifdef FEAT_SMARTINDENT
1231 did_si = can_si = FALSE;
1232#endif
1233 }
1234 else if (comment_end != NULL)
1235 {
1236 /*
1237 * We have finished a comment, so we don't use the leader.
1238 * If this was a C-comment and 'ai' or 'si' is set do a normal
1239 * indent to align with the line containing the start of the
1240 * comment.
1241 */
1242 if (comment_end[0] == '*' && comment_end[1] == '/' &&
1243 (curbuf->b_p_ai
1244#ifdef FEAT_SMARTINDENT
1245 || do_si
1246#endif
1247 ))
1248 {
1249 old_cursor = curwin->w_cursor;
1250 curwin->w_cursor.col = (colnr_T)(comment_end - saved_line);
1251 if ((pos = findmatch(NULL, NUL)) != NULL)
1252 {
1253 curwin->w_cursor.lnum = pos->lnum;
1254 newindent = get_indent();
1255 }
1256 curwin->w_cursor = old_cursor;
1257 }
1258 }
1259 }
1260#endif
1261
1262 /* (State == INSERT || State == REPLACE), only when dir == FORWARD */
1263 if (p_extra != NULL)
1264 {
1265 *p_extra = saved_char; /* restore char that NUL replaced */
1266
1267 /*
1268 * When 'ai' set or "flags" has OPENLINE_DELSPACES, skip to the first
1269 * non-blank.
1270 *
1271 * When in REPLACE mode, put the deleted blanks on the replace stack,
1272 * preceded by a NUL, so they can be put back when a BS is entered.
1273 */
1274 if (REPLACE_NORMAL(State))
1275 replace_push(NUL); /* end of extra blanks */
1276 if (curbuf->b_p_ai || (flags & OPENLINE_DELSPACES))
1277 {
1278 while ((*p_extra == ' ' || *p_extra == '\t')
1279#ifdef FEAT_MBYTE
1280 && (!enc_utf8
1281 || !utf_iscomposing(utf_ptr2char(p_extra + 1)))
1282#endif
1283 )
1284 {
1285 if (REPLACE_NORMAL(State))
1286 replace_push(*p_extra);
1287 ++p_extra;
1288 ++less_cols_off;
1289 }
1290 }
1291 if (*p_extra != NUL)
1292 did_ai = FALSE; /* append some text, don't truncate now */
1293
1294 /* columns for marks adjusted for removed columns */
1295 less_cols = (int)(p_extra - saved_line);
1296 }
1297
1298 if (p_extra == NULL)
1299 p_extra = (char_u *)""; /* append empty line */
1300
1301#ifdef FEAT_COMMENTS
1302 /* concatenate leader and p_extra, if there is a leader */
1303 if (lead_len)
1304 {
1305 STRCAT(leader, p_extra);
1306 p_extra = leader;
1307 did_ai = TRUE; /* So truncating blanks works with comments */
1308 less_cols -= lead_len;
1309 }
1310 else
1311 end_comment_pending = NUL; /* turns out there was no leader */
1312#endif
1313
1314 old_cursor = curwin->w_cursor;
1315 if (dir == BACKWARD)
1316 --curwin->w_cursor.lnum;
1317#ifdef FEAT_VREPLACE
1318 if (!(State & VREPLACE_FLAG) || old_cursor.lnum >= orig_line_count)
1319#endif
1320 {
1321 if (ml_append(curwin->w_cursor.lnum, p_extra, (colnr_T)0, FALSE)
1322 == FAIL)
1323 goto theend;
1324 /* Postpone calling changed_lines(), because it would mess up folding
1325 * with markers. */
1326 mark_adjust(curwin->w_cursor.lnum + 1, (linenr_T)MAXLNUM, 1L, 0L);
1327 did_append = TRUE;
1328 }
1329#ifdef FEAT_VREPLACE
1330 else
1331 {
1332 /*
1333 * In VREPLACE mode we are starting to replace the next line.
1334 */
1335 curwin->w_cursor.lnum++;
1336 if (curwin->w_cursor.lnum >= Insstart.lnum + vr_lines_changed)
1337 {
1338 /* In case we NL to a new line, BS to the previous one, and NL
1339 * again, we don't want to save the new line for undo twice.
1340 */
1341 (void)u_save_cursor(); /* errors are ignored! */
1342 vr_lines_changed++;
1343 }
1344 ml_replace(curwin->w_cursor.lnum, p_extra, TRUE);
1345 changed_bytes(curwin->w_cursor.lnum, 0);
1346 curwin->w_cursor.lnum--;
1347 did_append = FALSE;
1348 }
1349#endif
1350
1351 if (newindent
1352#ifdef FEAT_SMARTINDENT
1353 || did_si
1354#endif
1355 )
1356 {
1357 ++curwin->w_cursor.lnum;
1358#ifdef FEAT_SMARTINDENT
1359 if (did_si)
1360 {
1361 if (p_sr)
1362 newindent -= newindent % (int)curbuf->b_p_sw;
1363 newindent += (int)curbuf->b_p_sw;
1364 }
1365#endif
Bram Moolenaar5002c292007-07-24 13:26:15 +00001366 /* Copy the indent */
1367 if (curbuf->b_p_ci)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001368 {
1369 (void)copy_indent(newindent, saved_line);
1370
1371 /*
1372 * Set the 'preserveindent' option so that any further screwing
1373 * with the line doesn't entirely destroy our efforts to preserve
1374 * it. It gets restored at the function end.
1375 */
1376 curbuf->b_p_pi = TRUE;
1377 }
1378 else
1379 (void)set_indent(newindent, SIN_INSERT);
1380 less_cols -= curwin->w_cursor.col;
1381
1382 ai_col = curwin->w_cursor.col;
1383
1384 /*
1385 * In REPLACE mode, for each character in the new indent, there must
1386 * be a NUL on the replace stack, for when it is deleted with BS
1387 */
1388 if (REPLACE_NORMAL(State))
1389 for (n = 0; n < (int)curwin->w_cursor.col; ++n)
1390 replace_push(NUL);
1391 newcol += curwin->w_cursor.col;
1392#ifdef FEAT_SMARTINDENT
1393 if (no_si)
1394 did_si = FALSE;
1395#endif
1396 }
1397
1398#ifdef FEAT_COMMENTS
1399 /*
1400 * In REPLACE mode, for each character in the extra leader, there must be
1401 * a NUL on the replace stack, for when it is deleted with BS.
1402 */
1403 if (REPLACE_NORMAL(State))
1404 while (lead_len-- > 0)
1405 replace_push(NUL);
1406#endif
1407
1408 curwin->w_cursor = old_cursor;
1409
1410 if (dir == FORWARD)
1411 {
1412 if (trunc_line || (State & INSERT))
1413 {
1414 /* truncate current line at cursor */
1415 saved_line[curwin->w_cursor.col] = NUL;
1416 /* Remove trailing white space, unless OPENLINE_KEEPTRAIL used. */
1417 if (trunc_line && !(flags & OPENLINE_KEEPTRAIL))
1418 truncate_spaces(saved_line);
1419 ml_replace(curwin->w_cursor.lnum, saved_line, FALSE);
1420 saved_line = NULL;
1421 if (did_append)
1422 {
1423 changed_lines(curwin->w_cursor.lnum, curwin->w_cursor.col,
1424 curwin->w_cursor.lnum + 1, 1L);
1425 did_append = FALSE;
1426
1427 /* Move marks after the line break to the new line. */
1428 if (flags & OPENLINE_MARKFIX)
1429 mark_col_adjust(curwin->w_cursor.lnum,
1430 curwin->w_cursor.col + less_cols_off,
1431 1L, (long)-less_cols);
1432 }
1433 else
1434 changed_bytes(curwin->w_cursor.lnum, curwin->w_cursor.col);
1435 }
1436
1437 /*
1438 * Put the cursor on the new line. Careful: the scrollup() above may
1439 * have moved w_cursor, we must use old_cursor.
1440 */
1441 curwin->w_cursor.lnum = old_cursor.lnum + 1;
1442 }
1443 if (did_append)
1444 changed_lines(curwin->w_cursor.lnum, 0, curwin->w_cursor.lnum, 1L);
1445
1446 curwin->w_cursor.col = newcol;
1447#ifdef FEAT_VIRTUALEDIT
1448 curwin->w_cursor.coladd = 0;
1449#endif
1450
1451#if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
1452 /*
1453 * In VREPLACE mode, we are handling the replace stack ourselves, so stop
1454 * fixthisline() from doing it (via change_indent()) by telling it we're in
1455 * normal INSERT mode.
1456 */
1457 if (State & VREPLACE_FLAG)
1458 {
1459 vreplace_mode = State; /* So we know to put things right later */
1460 State = INSERT;
1461 }
1462 else
1463 vreplace_mode = 0;
1464#endif
1465#ifdef FEAT_LISP
1466 /*
1467 * May do lisp indenting.
1468 */
1469 if (!p_paste
1470# ifdef FEAT_COMMENTS
1471 && leader == NULL
1472# endif
1473 && curbuf->b_p_lisp
1474 && curbuf->b_p_ai)
1475 {
1476 fixthisline(get_lisp_indent);
1477 p = ml_get_curline();
1478 ai_col = (colnr_T)(skipwhite(p) - p);
1479 }
1480#endif
1481#ifdef FEAT_CINDENT
1482 /*
1483 * May do indenting after opening a new line.
1484 */
1485 if (!p_paste
1486 && (curbuf->b_p_cin
1487# ifdef FEAT_EVAL
1488 || *curbuf->b_p_inde != NUL
1489# endif
1490 )
1491 && in_cinkeys(dir == FORWARD
1492 ? KEY_OPEN_FORW
1493 : KEY_OPEN_BACK, ' ', linewhite(curwin->w_cursor.lnum)))
1494 {
1495 do_c_expr_indent();
1496 p = ml_get_curline();
1497 ai_col = (colnr_T)(skipwhite(p) - p);
1498 }
1499#endif
1500#if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
1501 if (vreplace_mode != 0)
1502 State = vreplace_mode;
1503#endif
1504
1505#ifdef FEAT_VREPLACE
1506 /*
1507 * Finally, VREPLACE gets the stuff on the new line, then puts back the
1508 * original line, and inserts the new stuff char by char, pushing old stuff
1509 * onto the replace stack (via ins_char()).
1510 */
1511 if (State & VREPLACE_FLAG)
1512 {
1513 /* Put new line in p_extra */
1514 p_extra = vim_strsave(ml_get_curline());
1515 if (p_extra == NULL)
1516 goto theend;
1517
1518 /* Put back original line */
1519 ml_replace(curwin->w_cursor.lnum, next_line, FALSE);
1520
1521 /* Insert new stuff into line again */
1522 curwin->w_cursor.col = 0;
1523#ifdef FEAT_VIRTUALEDIT
1524 curwin->w_cursor.coladd = 0;
1525#endif
1526 ins_bytes(p_extra); /* will call changed_bytes() */
1527 vim_free(p_extra);
1528 next_line = NULL;
1529 }
1530#endif
1531
1532 retval = TRUE; /* success! */
1533theend:
1534 curbuf->b_p_pi = saved_pi;
1535 vim_free(saved_line);
1536 vim_free(next_line);
1537 vim_free(allocated);
1538 return retval;
1539}
1540
1541#if defined(FEAT_COMMENTS) || defined(PROTO)
1542/*
1543 * get_leader_len() returns the length of the prefix of the given string
1544 * which introduces a comment. If this string is not a comment then 0 is
1545 * returned.
1546 * When "flags" is not NULL, it is set to point to the flags of the recognized
1547 * comment leader.
1548 * "backward" must be true for the "O" command.
1549 */
1550 int
1551get_leader_len(line, flags, backward)
1552 char_u *line;
1553 char_u **flags;
1554 int backward;
1555{
1556 int i, j;
1557 int got_com = FALSE;
1558 int found_one;
1559 char_u part_buf[COM_MAX_LEN]; /* buffer for one option part */
1560 char_u *string; /* pointer to comment string */
1561 char_u *list;
1562
1563 i = 0;
1564 while (vim_iswhite(line[i])) /* leading white space is ignored */
1565 ++i;
1566
1567 /*
1568 * Repeat to match several nested comment strings.
1569 */
1570 while (line[i])
1571 {
1572 /*
1573 * scan through the 'comments' option for a match
1574 */
1575 found_one = FALSE;
1576 for (list = curbuf->b_p_com; *list; )
1577 {
1578 /*
1579 * Get one option part into part_buf[]. Advance list to next one.
1580 * put string at start of string.
1581 */
1582 if (!got_com && flags != NULL) /* remember where flags started */
1583 *flags = list;
1584 (void)copy_option_part(&list, part_buf, COM_MAX_LEN, ",");
1585 string = vim_strchr(part_buf, ':');
1586 if (string == NULL) /* missing ':', ignore this part */
1587 continue;
1588 *string++ = NUL; /* isolate flags from string */
1589
1590 /*
1591 * When already found a nested comment, only accept further
1592 * nested comments.
1593 */
1594 if (got_com && vim_strchr(part_buf, COM_NEST) == NULL)
1595 continue;
1596
1597 /* When 'O' flag used don't use for "O" command */
1598 if (backward && vim_strchr(part_buf, COM_NOBACK) != NULL)
1599 continue;
1600
1601 /*
1602 * Line contents and string must match.
1603 * When string starts with white space, must have some white space
1604 * (but the amount does not need to match, there might be a mix of
1605 * TABs and spaces).
1606 */
1607 if (vim_iswhite(string[0]))
1608 {
1609 if (i == 0 || !vim_iswhite(line[i - 1]))
1610 continue;
1611 while (vim_iswhite(string[0]))
1612 ++string;
1613 }
1614 for (j = 0; string[j] != NUL && string[j] == line[i + j]; ++j)
1615 ;
1616 if (string[j] != NUL)
1617 continue;
1618
1619 /*
1620 * When 'b' flag used, there must be white space or an
1621 * end-of-line after the string in the line.
1622 */
1623 if (vim_strchr(part_buf, COM_BLANK) != NULL
1624 && !vim_iswhite(line[i + j]) && line[i + j] != NUL)
1625 continue;
1626
1627 /*
1628 * We have found a match, stop searching.
1629 */
1630 i += j;
1631 got_com = TRUE;
1632 found_one = TRUE;
1633 break;
1634 }
1635
1636 /*
1637 * No match found, stop scanning.
1638 */
1639 if (!found_one)
1640 break;
1641
1642 /*
1643 * Include any trailing white space.
1644 */
1645 while (vim_iswhite(line[i]))
1646 ++i;
1647
1648 /*
1649 * If this comment doesn't nest, stop here.
1650 */
1651 if (vim_strchr(part_buf, COM_NEST) == NULL)
1652 break;
1653 }
1654 return (got_com ? i : 0);
1655}
1656#endif
1657
1658/*
1659 * Return the number of window lines occupied by buffer line "lnum".
1660 */
1661 int
1662plines(lnum)
1663 linenr_T lnum;
1664{
1665 return plines_win(curwin, lnum, TRUE);
1666}
1667
1668 int
1669plines_win(wp, lnum, winheight)
1670 win_T *wp;
1671 linenr_T lnum;
1672 int winheight; /* when TRUE limit to window height */
1673{
1674#if defined(FEAT_DIFF) || defined(PROTO)
1675 /* Check for filler lines above this buffer line. When folded the result
1676 * is one line anyway. */
1677 return plines_win_nofill(wp, lnum, winheight) + diff_check_fill(wp, lnum);
1678}
1679
1680 int
1681plines_nofill(lnum)
1682 linenr_T lnum;
1683{
1684 return plines_win_nofill(curwin, lnum, TRUE);
1685}
1686
1687 int
1688plines_win_nofill(wp, lnum, winheight)
1689 win_T *wp;
1690 linenr_T lnum;
1691 int winheight; /* when TRUE limit to window height */
1692{
1693#endif
1694 int lines;
1695
1696 if (!wp->w_p_wrap)
1697 return 1;
1698
1699#ifdef FEAT_VERTSPLIT
1700 if (wp->w_width == 0)
1701 return 1;
1702#endif
1703
1704#ifdef FEAT_FOLDING
1705 /* A folded lines is handled just like an empty line. */
1706 /* NOTE: Caller must handle lines that are MAYBE folded. */
1707 if (lineFolded(wp, lnum) == TRUE)
1708 return 1;
1709#endif
1710
1711 lines = plines_win_nofold(wp, lnum);
1712 if (winheight > 0 && lines > wp->w_height)
1713 return (int)wp->w_height;
1714 return lines;
1715}
1716
1717/*
1718 * Return number of window lines physical line "lnum" will occupy in window
1719 * "wp". Does not care about folding, 'wrap' or 'diff'.
1720 */
1721 int
1722plines_win_nofold(wp, lnum)
1723 win_T *wp;
1724 linenr_T lnum;
1725{
1726 char_u *s;
1727 long col;
1728 int width;
1729
1730 s = ml_get_buf(wp->w_buffer, lnum, FALSE);
1731 if (*s == NUL) /* empty line */
1732 return 1;
1733 col = win_linetabsize(wp, s, (colnr_T)MAXCOL);
1734
1735 /*
1736 * If list mode is on, then the '$' at the end of the line may take up one
1737 * extra column.
1738 */
1739 if (wp->w_p_list && lcs_eol != NUL)
1740 col += 1;
1741
1742 /*
1743 * Add column offset for 'number' and 'foldcolumn'.
1744 */
1745 width = W_WIDTH(wp) - win_col_off(wp);
1746 if (width <= 0)
1747 return 32000;
1748 if (col <= width)
1749 return 1;
1750 col -= width;
1751 width += win_col_off2(wp);
1752 return (col + (width - 1)) / width + 1;
1753}
1754
1755/*
1756 * Like plines_win(), but only reports the number of physical screen lines
1757 * used from the start of the line to the given column number.
1758 */
1759 int
1760plines_win_col(wp, lnum, column)
1761 win_T *wp;
1762 linenr_T lnum;
1763 long column;
1764{
1765 long col;
1766 char_u *s;
1767 int lines = 0;
1768 int width;
1769
1770#ifdef FEAT_DIFF
1771 /* Check for filler lines above this buffer line. When folded the result
1772 * is one line anyway. */
1773 lines = diff_check_fill(wp, lnum);
1774#endif
1775
1776 if (!wp->w_p_wrap)
1777 return lines + 1;
1778
1779#ifdef FEAT_VERTSPLIT
1780 if (wp->w_width == 0)
1781 return lines + 1;
1782#endif
1783
1784 s = ml_get_buf(wp->w_buffer, lnum, FALSE);
1785
1786 col = 0;
1787 while (*s != NUL && --column >= 0)
1788 {
1789 col += win_lbr_chartabsize(wp, s, (colnr_T)col, NULL);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001790 mb_ptr_adv(s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001791 }
1792
1793 /*
1794 * If *s is a TAB, and the TAB is not displayed as ^I, and we're not in
1795 * INSERT mode, then col must be adjusted so that it represents the last
1796 * screen position of the TAB. This only fixes an error when the TAB wraps
1797 * from one screen line to the next (when 'columns' is not a multiple of
1798 * 'ts') -- webb.
1799 */
1800 if (*s == TAB && (State & NORMAL) && (!wp->w_p_list || lcs_tab1))
1801 col += win_lbr_chartabsize(wp, s, (colnr_T)col, NULL) - 1;
1802
1803 /*
1804 * Add column offset for 'number', 'foldcolumn', etc.
1805 */
1806 width = W_WIDTH(wp) - win_col_off(wp);
Bram Moolenaar26470632006-10-24 19:12:40 +00001807 if (width <= 0)
1808 return 9999;
1809
1810 lines += 1;
1811 if (col > width)
1812 lines += (col - width) / (width + win_col_off2(wp)) + 1;
1813 return lines;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001814}
1815
1816 int
1817plines_m_win(wp, first, last)
1818 win_T *wp;
1819 linenr_T first, last;
1820{
1821 int count = 0;
1822
1823 while (first <= last)
1824 {
1825#ifdef FEAT_FOLDING
1826 int x;
1827
1828 /* Check if there are any really folded lines, but also included lines
1829 * that are maybe folded. */
1830 x = foldedCount(wp, first, NULL);
1831 if (x > 0)
1832 {
1833 ++count; /* count 1 for "+-- folded" line */
1834 first += x;
1835 }
1836 else
1837#endif
1838 {
1839#ifdef FEAT_DIFF
1840 if (first == wp->w_topline)
1841 count += plines_win_nofill(wp, first, TRUE) + wp->w_topfill;
1842 else
1843#endif
1844 count += plines_win(wp, first, TRUE);
1845 ++first;
1846 }
1847 }
1848 return (count);
1849}
1850
1851#if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) || defined(PROTO)
1852/*
1853 * Insert string "p" at the cursor position. Stops at a NUL byte.
1854 * Handles Replace mode and multi-byte characters.
1855 */
1856 void
1857ins_bytes(p)
1858 char_u *p;
1859{
1860 ins_bytes_len(p, (int)STRLEN(p));
1861}
1862#endif
1863
1864#if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) \
1865 || defined(FEAT_COMMENTS) || defined(FEAT_MBYTE) || defined(PROTO)
1866/*
1867 * Insert string "p" with length "len" at the cursor position.
1868 * Handles Replace mode and multi-byte characters.
1869 */
1870 void
1871ins_bytes_len(p, len)
1872 char_u *p;
1873 int len;
1874{
1875 int i;
1876# ifdef FEAT_MBYTE
1877 int n;
1878
Bram Moolenaar176dd1e2008-06-21 14:30:28 +00001879 if (has_mbyte)
1880 for (i = 0; i < len; i += n)
1881 {
1882 if (enc_utf8)
1883 /* avoid reading past p[len] */
1884 n = utfc_ptr2len_len(p + i, len - i);
1885 else
1886 n = (*mb_ptr2len)(p + i);
1887 ins_char_bytes(p + i, n);
1888 }
1889 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001890# endif
Bram Moolenaar176dd1e2008-06-21 14:30:28 +00001891 for (i = 0; i < len; ++i)
1892 ins_char(p[i]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001893}
1894#endif
1895
1896/*
1897 * Insert or replace a single character at the cursor position.
1898 * When in REPLACE or VREPLACE mode, replace any existing character.
1899 * Caller must have prepared for undo.
1900 * For multi-byte characters we get the whole character, the caller must
1901 * convert bytes to a character.
1902 */
1903 void
1904ins_char(c)
1905 int c;
1906{
1907#if defined(FEAT_MBYTE) || defined(PROTO)
1908 char_u buf[MB_MAXBYTES];
1909 int n;
1910
1911 n = (*mb_char2bytes)(c, buf);
1912
1913 /* When "c" is 0x100, 0x200, etc. we don't want to insert a NUL byte.
1914 * Happens for CTRL-Vu9900. */
1915 if (buf[0] == 0)
1916 buf[0] = '\n';
1917
1918 ins_char_bytes(buf, n);
1919}
1920
1921 void
1922ins_char_bytes(buf, charlen)
1923 char_u *buf;
1924 int charlen;
1925{
1926 int c = buf[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001927#endif
1928 int newlen; /* nr of bytes inserted */
1929 int oldlen; /* nr of bytes deleted (0 when not replacing) */
1930 char_u *p;
1931 char_u *newp;
1932 char_u *oldp;
1933 int linelen; /* length of old line including NUL */
1934 colnr_T col;
1935 linenr_T lnum = curwin->w_cursor.lnum;
1936 int i;
1937
1938#ifdef FEAT_VIRTUALEDIT
1939 /* Break tabs if needed. */
1940 if (virtual_active() && curwin->w_cursor.coladd > 0)
1941 coladvance_force(getviscol());
1942#endif
1943
1944 col = curwin->w_cursor.col;
1945 oldp = ml_get(lnum);
1946 linelen = (int)STRLEN(oldp) + 1;
1947
1948 /* The lengths default to the values for when not replacing. */
1949 oldlen = 0;
1950#ifdef FEAT_MBYTE
1951 newlen = charlen;
1952#else
1953 newlen = 1;
1954#endif
1955
1956 if (State & REPLACE_FLAG)
1957 {
1958#ifdef FEAT_VREPLACE
1959 if (State & VREPLACE_FLAG)
1960 {
1961 colnr_T new_vcol = 0; /* init for GCC */
1962 colnr_T vcol;
1963 int old_list;
1964#ifndef FEAT_MBYTE
1965 char_u buf[2];
1966#endif
1967
1968 /*
1969 * Disable 'list' temporarily, unless 'cpo' contains the 'L' flag.
1970 * Returns the old value of list, so when finished,
1971 * curwin->w_p_list should be set back to this.
1972 */
1973 old_list = curwin->w_p_list;
1974 if (old_list && vim_strchr(p_cpo, CPO_LISTWM) == NULL)
1975 curwin->w_p_list = FALSE;
1976
1977 /*
1978 * In virtual replace mode each character may replace one or more
1979 * characters (zero if it's a TAB). Count the number of bytes to
1980 * be deleted to make room for the new character, counting screen
1981 * cells. May result in adding spaces to fill a gap.
1982 */
1983 getvcol(curwin, &curwin->w_cursor, NULL, &vcol, NULL);
1984#ifndef FEAT_MBYTE
1985 buf[0] = c;
1986 buf[1] = NUL;
1987#endif
1988 new_vcol = vcol + chartabsize(buf, vcol);
1989 while (oldp[col + oldlen] != NUL && vcol < new_vcol)
1990 {
1991 vcol += chartabsize(oldp + col + oldlen, vcol);
1992 /* Don't need to remove a TAB that takes us to the right
1993 * position. */
1994 if (vcol > new_vcol && oldp[col + oldlen] == TAB)
1995 break;
1996#ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00001997 oldlen += (*mb_ptr2len)(oldp + col + oldlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001998#else
1999 ++oldlen;
2000#endif
2001 /* Deleted a bit too much, insert spaces. */
2002 if (vcol > new_vcol)
2003 newlen += vcol - new_vcol;
2004 }
2005 curwin->w_p_list = old_list;
2006 }
2007 else
2008#endif
2009 if (oldp[col] != NUL)
2010 {
2011 /* normal replace */
2012#ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002013 oldlen = (*mb_ptr2len)(oldp + col);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002014#else
2015 oldlen = 1;
2016#endif
2017 }
2018
2019
2020 /* Push the replaced bytes onto the replace stack, so that they can be
2021 * put back when BS is used. The bytes of a multi-byte character are
2022 * done the other way around, so that the first byte is popped off
2023 * first (it tells the byte length of the character). */
2024 replace_push(NUL);
2025 for (i = 0; i < oldlen; ++i)
2026 {
2027#ifdef FEAT_MBYTE
Bram Moolenaar2c994e82008-01-02 16:49:36 +00002028 if (has_mbyte)
2029 i += replace_push_mb(oldp + col + i) - 1;
2030 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002031#endif
Bram Moolenaar2c994e82008-01-02 16:49:36 +00002032 replace_push(oldp[col + i]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002033 }
2034 }
2035
2036 newp = alloc_check((unsigned)(linelen + newlen - oldlen));
2037 if (newp == NULL)
2038 return;
2039
2040 /* Copy bytes before the cursor. */
2041 if (col > 0)
2042 mch_memmove(newp, oldp, (size_t)col);
2043
2044 /* Copy bytes after the changed character(s). */
2045 p = newp + col;
2046 mch_memmove(p + newlen, oldp + col + oldlen,
2047 (size_t)(linelen - col - oldlen));
2048
2049 /* Insert or overwrite the new character. */
2050#ifdef FEAT_MBYTE
2051 mch_memmove(p, buf, charlen);
2052 i = charlen;
2053#else
2054 *p = c;
2055 i = 1;
2056#endif
2057
2058 /* Fill with spaces when necessary. */
2059 while (i < newlen)
2060 p[i++] = ' ';
2061
2062 /* Replace the line in the buffer. */
2063 ml_replace(lnum, newp, FALSE);
2064
2065 /* mark the buffer as changed and prepare for displaying */
2066 changed_bytes(lnum, col);
2067
2068 /*
2069 * If we're in Insert or Replace mode and 'showmatch' is set, then briefly
2070 * show the match for right parens and braces.
2071 */
2072 if (p_sm && (State & INSERT)
2073 && msg_silent == 0
2074#ifdef FEAT_MBYTE
2075 && charlen == 1
2076#endif
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00002077#ifdef FEAT_INS_EXPAND
2078 && !ins_compl_active()
2079#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002080 )
2081 showmatch(c);
2082
2083#ifdef FEAT_RIGHTLEFT
2084 if (!p_ri || (State & REPLACE_FLAG))
2085#endif
2086 {
2087 /* Normal insert: move cursor right */
2088#ifdef FEAT_MBYTE
2089 curwin->w_cursor.col += charlen;
2090#else
2091 ++curwin->w_cursor.col;
2092#endif
2093 }
2094 /*
2095 * TODO: should try to update w_row here, to avoid recomputing it later.
2096 */
2097}
2098
2099/*
2100 * Insert a string at the cursor position.
2101 * Note: Does NOT handle Replace mode.
2102 * Caller must have prepared for undo.
2103 */
2104 void
2105ins_str(s)
2106 char_u *s;
2107{
2108 char_u *oldp, *newp;
2109 int newlen = (int)STRLEN(s);
2110 int oldlen;
2111 colnr_T col;
2112 linenr_T lnum = curwin->w_cursor.lnum;
2113
2114#ifdef FEAT_VIRTUALEDIT
2115 if (virtual_active() && curwin->w_cursor.coladd > 0)
2116 coladvance_force(getviscol());
2117#endif
2118
2119 col = curwin->w_cursor.col;
2120 oldp = ml_get(lnum);
2121 oldlen = (int)STRLEN(oldp);
2122
2123 newp = alloc_check((unsigned)(oldlen + newlen + 1));
2124 if (newp == NULL)
2125 return;
2126 if (col > 0)
2127 mch_memmove(newp, oldp, (size_t)col);
2128 mch_memmove(newp + col, s, (size_t)newlen);
2129 mch_memmove(newp + col + newlen, oldp + col, (size_t)(oldlen - col + 1));
2130 ml_replace(lnum, newp, FALSE);
2131 changed_bytes(lnum, col);
2132 curwin->w_cursor.col += newlen;
2133}
2134
2135/*
2136 * Delete one character under the cursor.
2137 * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
2138 * Caller must have prepared for undo.
2139 *
2140 * return FAIL for failure, OK otherwise
2141 */
2142 int
2143del_char(fixpos)
2144 int fixpos;
2145{
2146#ifdef FEAT_MBYTE
2147 if (has_mbyte)
2148 {
2149 /* Make sure the cursor is at the start of a character. */
2150 mb_adjust_cursor();
2151 if (*ml_get_cursor() == NUL)
2152 return FAIL;
2153 return del_chars(1L, fixpos);
2154 }
2155#endif
Bram Moolenaare3226be2005-12-18 22:10:00 +00002156 return del_bytes(1L, fixpos, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002157}
2158
2159#if defined(FEAT_MBYTE) || defined(PROTO)
2160/*
2161 * Like del_bytes(), but delete characters instead of bytes.
2162 */
2163 int
2164del_chars(count, fixpos)
2165 long count;
2166 int fixpos;
2167{
2168 long bytes = 0;
2169 long i;
2170 char_u *p;
2171 int l;
2172
2173 p = ml_get_cursor();
2174 for (i = 0; i < count && *p != NUL; ++i)
2175 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002176 l = (*mb_ptr2len)(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002177 bytes += l;
2178 p += l;
2179 }
Bram Moolenaare3226be2005-12-18 22:10:00 +00002180 return del_bytes(bytes, fixpos, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002181}
2182#endif
2183
2184/*
2185 * Delete "count" bytes under the cursor.
2186 * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
2187 * Caller must have prepared for undo.
2188 *
2189 * return FAIL for failure, OK otherwise
2190 */
2191 int
Bram Moolenaarca003e12006-03-17 23:19:38 +00002192del_bytes(count, fixpos_arg, use_delcombine)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002193 long count;
Bram Moolenaarca003e12006-03-17 23:19:38 +00002194 int fixpos_arg;
Bram Moolenaar78a15312009-05-15 19:33:18 +00002195 int use_delcombine UNUSED; /* 'delcombine' option applies */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002196{
2197 char_u *oldp, *newp;
2198 colnr_T oldlen;
2199 linenr_T lnum = curwin->w_cursor.lnum;
2200 colnr_T col = curwin->w_cursor.col;
2201 int was_alloced;
2202 long movelen;
Bram Moolenaarca003e12006-03-17 23:19:38 +00002203 int fixpos = fixpos_arg;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002204
2205 oldp = ml_get(lnum);
2206 oldlen = (int)STRLEN(oldp);
2207
2208 /*
2209 * Can't do anything when the cursor is on the NUL after the line.
2210 */
2211 if (col >= oldlen)
2212 return FAIL;
2213
2214#ifdef FEAT_MBYTE
2215 /* If 'delcombine' is set and deleting (less than) one character, only
2216 * delete the last combining character. */
Bram Moolenaare3226be2005-12-18 22:10:00 +00002217 if (p_deco && use_delcombine && enc_utf8
2218 && utfc_ptr2len(oldp + col) >= count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002219 {
Bram Moolenaar362e1a32006-03-06 23:29:24 +00002220 int cc[MAX_MCO];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002221 int n;
2222
Bram Moolenaar362e1a32006-03-06 23:29:24 +00002223 (void)utfc_ptr2char(oldp + col, cc);
2224 if (cc[0] != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002225 {
2226 /* Find the last composing char, there can be several. */
2227 n = col;
2228 do
2229 {
2230 col = n;
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002231 count = utf_ptr2len(oldp + n);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002232 n += count;
2233 } while (UTF_COMPOSINGLIKE(oldp + col, oldp + n));
2234 fixpos = 0;
2235 }
2236 }
2237#endif
2238
2239 /*
2240 * When count is too big, reduce it.
2241 */
2242 movelen = (long)oldlen - (long)col - count + 1; /* includes trailing NUL */
2243 if (movelen <= 1)
2244 {
2245 /*
2246 * If we just took off the last character of a non-blank line, and
Bram Moolenaarca003e12006-03-17 23:19:38 +00002247 * fixpos is TRUE, we don't want to end up positioned at the NUL,
2248 * unless "restart_edit" is set or 'virtualedit' contains "onemore".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002249 */
Bram Moolenaarca003e12006-03-17 23:19:38 +00002250 if (col > 0 && fixpos && restart_edit == 0
2251#ifdef FEAT_VIRTUALEDIT
2252 && (ve_flags & VE_ONEMORE) == 0
2253#endif
2254 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00002255 {
2256 --curwin->w_cursor.col;
2257#ifdef FEAT_VIRTUALEDIT
2258 curwin->w_cursor.coladd = 0;
2259#endif
2260#ifdef FEAT_MBYTE
2261 if (has_mbyte)
2262 curwin->w_cursor.col -=
2263 (*mb_head_off)(oldp, oldp + curwin->w_cursor.col);
2264#endif
2265 }
2266 count = oldlen - col;
2267 movelen = 1;
2268 }
2269
2270 /*
2271 * If the old line has been allocated the deletion can be done in the
2272 * existing line. Otherwise a new line has to be allocated
Bram Moolenaare21877a2008-02-13 09:58:14 +00002273 * Can't do this when using Netbeans, because we would need to invoke
2274 * netbeans_removed(), which deallocates the line. Let ml_replace() take
2275 * care of notifiying Netbeans.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002276 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002277#ifdef FEAT_NETBEANS_INTG
Bram Moolenaare21877a2008-02-13 09:58:14 +00002278 if (usingNetbeans)
2279 was_alloced = FALSE;
2280 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002281#endif
Bram Moolenaare21877a2008-02-13 09:58:14 +00002282 was_alloced = ml_line_alloced(); /* check if oldp was allocated */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002283 if (was_alloced)
2284 newp = oldp; /* use same allocated memory */
2285 else
2286 { /* need to allocate a new line */
2287 newp = alloc((unsigned)(oldlen + 1 - count));
2288 if (newp == NULL)
2289 return FAIL;
2290 mch_memmove(newp, oldp, (size_t)col);
2291 }
2292 mch_memmove(newp + col, oldp + col + count, (size_t)movelen);
2293 if (!was_alloced)
2294 ml_replace(lnum, newp, FALSE);
2295
2296 /* mark the buffer as changed and prepare for displaying */
2297 changed_bytes(lnum, curwin->w_cursor.col);
2298
2299 return OK;
2300}
2301
2302/*
2303 * Delete from cursor to end of line.
2304 * Caller must have prepared for undo.
2305 *
2306 * return FAIL for failure, OK otherwise
2307 */
2308 int
2309truncate_line(fixpos)
2310 int fixpos; /* if TRUE fix the cursor position when done */
2311{
2312 char_u *newp;
2313 linenr_T lnum = curwin->w_cursor.lnum;
2314 colnr_T col = curwin->w_cursor.col;
2315
2316 if (col == 0)
2317 newp = vim_strsave((char_u *)"");
2318 else
2319 newp = vim_strnsave(ml_get(lnum), col);
2320
2321 if (newp == NULL)
2322 return FAIL;
2323
2324 ml_replace(lnum, newp, FALSE);
2325
2326 /* mark the buffer as changed and prepare for displaying */
2327 changed_bytes(lnum, curwin->w_cursor.col);
2328
2329 /*
2330 * If "fixpos" is TRUE we don't want to end up positioned at the NUL.
2331 */
2332 if (fixpos && curwin->w_cursor.col > 0)
2333 --curwin->w_cursor.col;
2334
2335 return OK;
2336}
2337
2338/*
2339 * Delete "nlines" lines at the cursor.
2340 * Saves the lines for undo first if "undo" is TRUE.
2341 */
2342 void
2343del_lines(nlines, undo)
2344 long nlines; /* number of lines to delete */
2345 int undo; /* if TRUE, prepare for undo */
2346{
2347 long n;
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002348 linenr_T first = curwin->w_cursor.lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002349
2350 if (nlines <= 0)
2351 return;
2352
2353 /* save the deleted lines for undo */
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002354 if (undo && u_savedel(first, nlines) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002355 return;
2356
2357 for (n = 0; n < nlines; )
2358 {
2359 if (curbuf->b_ml.ml_flags & ML_EMPTY) /* nothing to delete */
2360 break;
2361
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002362 ml_delete(first, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002363 ++n;
2364
2365 /* If we delete the last line in the file, stop */
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002366 if (first > curbuf->b_ml.ml_line_count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002367 break;
2368 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002369
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002370 /* Correct the cursor position before calling deleted_lines_mark(), it may
2371 * trigger a callback to display the cursor. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002372 curwin->w_cursor.col = 0;
2373 check_cursor_lnum();
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002374
2375 /* adjust marks, mark the buffer as changed and prepare for displaying */
2376 deleted_lines_mark(first, n);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002377}
2378
2379 int
2380gchar_pos(pos)
2381 pos_T *pos;
2382{
2383 char_u *ptr = ml_get_pos(pos);
2384
2385#ifdef FEAT_MBYTE
2386 if (has_mbyte)
2387 return (*mb_ptr2char)(ptr);
2388#endif
2389 return (int)*ptr;
2390}
2391
2392 int
2393gchar_cursor()
2394{
2395#ifdef FEAT_MBYTE
2396 if (has_mbyte)
2397 return (*mb_ptr2char)(ml_get_cursor());
2398#endif
2399 return (int)*ml_get_cursor();
2400}
2401
2402/*
2403 * Write a character at the current cursor position.
2404 * It is directly written into the block.
2405 */
2406 void
2407pchar_cursor(c)
2408 int c;
2409{
2410 *(ml_get_buf(curbuf, curwin->w_cursor.lnum, TRUE)
2411 + curwin->w_cursor.col) = c;
2412}
2413
2414#if 0 /* not used */
2415/*
2416 * Put *pos at end of current buffer
2417 */
2418 void
2419goto_endofbuf(pos)
2420 pos_T *pos;
2421{
2422 char_u *p;
2423
2424 pos->lnum = curbuf->b_ml.ml_line_count;
2425 pos->col = 0;
2426 p = ml_get(pos->lnum);
2427 while (*p++)
2428 ++pos->col;
2429}
2430#endif
2431
2432/*
2433 * When extra == 0: Return TRUE if the cursor is before or on the first
2434 * non-blank in the line.
2435 * When extra == 1: Return TRUE if the cursor is before the first non-blank in
2436 * the line.
2437 */
2438 int
2439inindent(extra)
2440 int extra;
2441{
2442 char_u *ptr;
2443 colnr_T col;
2444
2445 for (col = 0, ptr = ml_get_curline(); vim_iswhite(*ptr); ++col)
2446 ++ptr;
2447 if (col >= curwin->w_cursor.col + extra)
2448 return TRUE;
2449 else
2450 return FALSE;
2451}
2452
2453/*
2454 * Skip to next part of an option argument: Skip space and comma.
2455 */
2456 char_u *
2457skip_to_option_part(p)
2458 char_u *p;
2459{
2460 if (*p == ',')
2461 ++p;
2462 while (*p == ' ')
2463 ++p;
2464 return p;
2465}
2466
2467/*
2468 * changed() is called when something in the current buffer is changed.
2469 *
2470 * Most often called through changed_bytes() and changed_lines(), which also
2471 * mark the area of the display to be redrawn.
2472 */
2473 void
2474changed()
2475{
2476#if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
2477 /* The text of the preediting area is inserted, but this doesn't
2478 * mean a change of the buffer yet. That is delayed until the
2479 * text is committed. (this means preedit becomes empty) */
2480 if (im_is_preediting() && !xim_changed_while_preediting)
2481 return;
2482 xim_changed_while_preediting = FALSE;
2483#endif
2484
2485 if (!curbuf->b_changed)
2486 {
2487 int save_msg_scroll = msg_scroll;
2488
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002489 /* Give a warning about changing a read-only file. This may also
2490 * check-out the file, thus change "curbuf"! */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002491 change_warning(0);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002492
Bram Moolenaar071d4272004-06-13 20:20:40 +00002493 /* Create a swap file if that is wanted.
2494 * Don't do this for "nofile" and "nowrite" buffer types. */
2495 if (curbuf->b_may_swap
2496#ifdef FEAT_QUICKFIX
2497 && !bt_dontwrite(curbuf)
2498#endif
2499 )
2500 {
2501 ml_open_file(curbuf);
2502
2503 /* The ml_open_file() can cause an ATTENTION message.
2504 * Wait two seconds, to make sure the user reads this unexpected
2505 * message. Since we could be anywhere, call wait_return() now,
2506 * and don't let the emsg() set msg_scroll. */
2507 if (need_wait_return && emsg_silent == 0)
2508 {
2509 out_flush();
2510 ui_delay(2000L, TRUE);
2511 wait_return(TRUE);
2512 msg_scroll = save_msg_scroll;
2513 }
2514 }
2515 curbuf->b_changed = TRUE;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002516 ml_setflags(curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002517#ifdef FEAT_WINDOWS
2518 check_status(curbuf);
Bram Moolenaar997fb4b2006-02-17 21:53:23 +00002519 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002520#endif
2521#ifdef FEAT_TITLE
2522 need_maketitle = TRUE; /* set window title later */
2523#endif
2524 }
2525 ++curbuf->b_changedtick;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002526}
2527
Bram Moolenaardba8a912005-04-24 22:08:39 +00002528static void changedOneline __ARGS((buf_T *buf, linenr_T lnum));
2529static void changed_lines_buf __ARGS((buf_T *buf, linenr_T lnum, linenr_T lnume, long xtra));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002530static void changed_common __ARGS((linenr_T lnum, colnr_T col, linenr_T lnume, long xtra));
2531
2532/*
2533 * Changed bytes within a single line for the current buffer.
2534 * - marks the windows on this buffer to be redisplayed
2535 * - marks the buffer changed by calling changed()
2536 * - invalidates cached values
2537 */
2538 void
2539changed_bytes(lnum, col)
2540 linenr_T lnum;
2541 colnr_T col;
2542{
Bram Moolenaardba8a912005-04-24 22:08:39 +00002543 changedOneline(curbuf, lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002544 changed_common(lnum, col, lnum + 1, 0L);
Bram Moolenaardba8a912005-04-24 22:08:39 +00002545
2546#ifdef FEAT_DIFF
2547 /* Diff highlighting in other diff windows may need to be updated too. */
2548 if (curwin->w_p_diff)
2549 {
2550 win_T *wp;
2551 linenr_T wlnum;
2552
2553 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2554 if (wp->w_p_diff && wp != curwin)
2555 {
2556 redraw_win_later(wp, VALID);
2557 wlnum = diff_lnum_win(lnum, wp);
2558 if (wlnum > 0)
2559 changedOneline(wp->w_buffer, wlnum);
2560 }
2561 }
2562#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002563}
2564
2565 static void
Bram Moolenaardba8a912005-04-24 22:08:39 +00002566changedOneline(buf, lnum)
2567 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002568 linenr_T lnum;
2569{
Bram Moolenaardba8a912005-04-24 22:08:39 +00002570 if (buf->b_mod_set)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002571 {
2572 /* find the maximum area that must be redisplayed */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002573 if (lnum < buf->b_mod_top)
2574 buf->b_mod_top = lnum;
2575 else if (lnum >= buf->b_mod_bot)
2576 buf->b_mod_bot = lnum + 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002577 }
2578 else
2579 {
2580 /* set the area that must be redisplayed to one line */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002581 buf->b_mod_set = TRUE;
2582 buf->b_mod_top = lnum;
2583 buf->b_mod_bot = lnum + 1;
2584 buf->b_mod_xlines = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002585 }
2586}
2587
2588/*
2589 * Appended "count" lines below line "lnum" in the current buffer.
2590 * Must be called AFTER the change and after mark_adjust().
2591 * Takes care of marking the buffer to be redrawn and sets the changed flag.
2592 */
2593 void
2594appended_lines(lnum, count)
2595 linenr_T lnum;
2596 long count;
2597{
2598 changed_lines(lnum + 1, 0, lnum + 1, count);
2599}
2600
2601/*
2602 * Like appended_lines(), but adjust marks first.
2603 */
2604 void
2605appended_lines_mark(lnum, count)
2606 linenr_T lnum;
2607 long count;
2608{
2609 mark_adjust(lnum + 1, (linenr_T)MAXLNUM, count, 0L);
2610 changed_lines(lnum + 1, 0, lnum + 1, count);
2611}
2612
2613/*
2614 * Deleted "count" lines at line "lnum" in the current buffer.
2615 * Must be called AFTER the change and after mark_adjust().
2616 * Takes care of marking the buffer to be redrawn and sets the changed flag.
2617 */
2618 void
2619deleted_lines(lnum, count)
2620 linenr_T lnum;
2621 long count;
2622{
2623 changed_lines(lnum, 0, lnum + count, -count);
2624}
2625
2626/*
2627 * Like deleted_lines(), but adjust marks first.
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002628 * Make sure the cursor is on a valid line before calling, a GUI callback may
2629 * be triggered to display the cursor.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002630 */
2631 void
2632deleted_lines_mark(lnum, count)
2633 linenr_T lnum;
2634 long count;
2635{
2636 mark_adjust(lnum, (linenr_T)(lnum + count - 1), (long)MAXLNUM, -count);
2637 changed_lines(lnum, 0, lnum + count, -count);
2638}
2639
2640/*
2641 * Changed lines for the current buffer.
2642 * Must be called AFTER the change and after mark_adjust().
2643 * - mark the buffer changed by calling changed()
2644 * - mark the windows on this buffer to be redisplayed
2645 * - invalidate cached values
2646 * "lnum" is the first line that needs displaying, "lnume" the first line
2647 * below the changed lines (BEFORE the change).
2648 * When only inserting lines, "lnum" and "lnume" are equal.
2649 * Takes care of calling changed() and updating b_mod_*.
2650 */
2651 void
2652changed_lines(lnum, col, lnume, xtra)
2653 linenr_T lnum; /* first line with change */
2654 colnr_T col; /* column in first line with change */
2655 linenr_T lnume; /* line below last changed line */
2656 long xtra; /* number of extra lines (negative when deleting) */
2657{
Bram Moolenaardba8a912005-04-24 22:08:39 +00002658 changed_lines_buf(curbuf, lnum, lnume, xtra);
2659
2660#ifdef FEAT_DIFF
2661 if (xtra == 0 && curwin->w_p_diff)
2662 {
2663 /* When the number of lines doesn't change then mark_adjust() isn't
2664 * called and other diff buffers still need to be marked for
2665 * displaying. */
2666 win_T *wp;
2667 linenr_T wlnum;
2668
2669 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2670 if (wp->w_p_diff && wp != curwin)
2671 {
2672 redraw_win_later(wp, VALID);
2673 wlnum = diff_lnum_win(lnum, wp);
2674 if (wlnum > 0)
2675 changed_lines_buf(wp->w_buffer, wlnum,
2676 lnume - lnum + wlnum, 0L);
2677 }
2678 }
2679#endif
2680
2681 changed_common(lnum, col, lnume, xtra);
2682}
2683
2684 static void
2685changed_lines_buf(buf, lnum, lnume, xtra)
2686 buf_T *buf;
2687 linenr_T lnum; /* first line with change */
2688 linenr_T lnume; /* line below last changed line */
2689 long xtra; /* number of extra lines (negative when deleting) */
2690{
2691 if (buf->b_mod_set)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002692 {
2693 /* find the maximum area that must be redisplayed */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002694 if (lnum < buf->b_mod_top)
2695 buf->b_mod_top = lnum;
2696 if (lnum < buf->b_mod_bot)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002697 {
2698 /* adjust old bot position for xtra lines */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002699 buf->b_mod_bot += xtra;
2700 if (buf->b_mod_bot < lnum)
2701 buf->b_mod_bot = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002702 }
Bram Moolenaardba8a912005-04-24 22:08:39 +00002703 if (lnume + xtra > buf->b_mod_bot)
2704 buf->b_mod_bot = lnume + xtra;
2705 buf->b_mod_xlines += xtra;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002706 }
2707 else
2708 {
2709 /* set the area that must be redisplayed */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002710 buf->b_mod_set = TRUE;
2711 buf->b_mod_top = lnum;
2712 buf->b_mod_bot = lnume + xtra;
2713 buf->b_mod_xlines = xtra;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002714 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002715}
2716
2717 static void
2718changed_common(lnum, col, lnume, xtra)
2719 linenr_T lnum;
2720 colnr_T col;
2721 linenr_T lnume;
2722 long xtra;
2723{
2724 win_T *wp;
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00002725#ifdef FEAT_WINDOWS
2726 tabpage_T *tp;
2727#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002728 int i;
2729#ifdef FEAT_JUMPLIST
2730 int cols;
2731 pos_T *p;
2732 int add;
2733#endif
2734
2735 /* mark the buffer as modified */
2736 changed();
2737
2738 /* set the '. mark */
2739 if (!cmdmod.keepjumps)
2740 {
2741 curbuf->b_last_change.lnum = lnum;
2742 curbuf->b_last_change.col = col;
2743
2744#ifdef FEAT_JUMPLIST
2745 /* Create a new entry if a new undo-able change was started or we
2746 * don't have an entry yet. */
2747 if (curbuf->b_new_change || curbuf->b_changelistlen == 0)
2748 {
2749 if (curbuf->b_changelistlen == 0)
2750 add = TRUE;
2751 else
2752 {
2753 /* Don't create a new entry when the line number is the same
2754 * as the last one and the column is not too far away. Avoids
2755 * creating many entries for typing "xxxxx". */
2756 p = &curbuf->b_changelist[curbuf->b_changelistlen - 1];
2757 if (p->lnum != lnum)
2758 add = TRUE;
2759 else
2760 {
2761 cols = comp_textwidth(FALSE);
2762 if (cols == 0)
2763 cols = 79;
2764 add = (p->col + cols < col || col + cols < p->col);
2765 }
2766 }
2767 if (add)
2768 {
2769 /* This is the first of a new sequence of undo-able changes
2770 * and it's at some distance of the last change. Use a new
2771 * position in the changelist. */
2772 curbuf->b_new_change = FALSE;
2773
2774 if (curbuf->b_changelistlen == JUMPLISTSIZE)
2775 {
2776 /* changelist is full: remove oldest entry */
2777 curbuf->b_changelistlen = JUMPLISTSIZE - 1;
2778 mch_memmove(curbuf->b_changelist, curbuf->b_changelist + 1,
2779 sizeof(pos_T) * (JUMPLISTSIZE - 1));
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00002780 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002781 {
2782 /* Correct position in changelist for other windows on
2783 * this buffer. */
2784 if (wp->w_buffer == curbuf && wp->w_changelistidx > 0)
2785 --wp->w_changelistidx;
2786 }
2787 }
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00002788 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002789 {
2790 /* For other windows, if the position in the changelist is
2791 * at the end it stays at the end. */
2792 if (wp->w_buffer == curbuf
2793 && wp->w_changelistidx == curbuf->b_changelistlen)
2794 ++wp->w_changelistidx;
2795 }
2796 ++curbuf->b_changelistlen;
2797 }
2798 }
2799 curbuf->b_changelist[curbuf->b_changelistlen - 1] =
2800 curbuf->b_last_change;
2801 /* The current window is always after the last change, so that "g,"
2802 * takes you back to it. */
2803 curwin->w_changelistidx = curbuf->b_changelistlen;
2804#endif
2805 }
2806
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00002807 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002808 {
2809 if (wp->w_buffer == curbuf)
2810 {
2811 /* Mark this window to be redrawn later. */
2812 if (wp->w_redr_type < VALID)
2813 wp->w_redr_type = VALID;
2814
2815 /* Check if a change in the buffer has invalidated the cached
2816 * values for the cursor. */
2817#ifdef FEAT_FOLDING
2818 /*
2819 * Update the folds for this window. Can't postpone this, because
2820 * a following operator might work on the whole fold: ">>dd".
2821 */
2822 foldUpdate(wp, lnum, lnume + xtra - 1);
2823
2824 /* The change may cause lines above or below the change to become
2825 * included in a fold. Set lnum/lnume to the first/last line that
2826 * might be displayed differently.
2827 * Set w_cline_folded here as an efficient way to update it when
2828 * inserting lines just above a closed fold. */
2829 i = hasFoldingWin(wp, lnum, &lnum, NULL, FALSE, NULL);
2830 if (wp->w_cursor.lnum == lnum)
2831 wp->w_cline_folded = i;
2832 i = hasFoldingWin(wp, lnume, NULL, &lnume, FALSE, NULL);
2833 if (wp->w_cursor.lnum == lnume)
2834 wp->w_cline_folded = i;
2835
2836 /* If the changed line is in a range of previously folded lines,
2837 * compare with the first line in that range. */
2838 if (wp->w_cursor.lnum <= lnum)
2839 {
2840 i = find_wl_entry(wp, lnum);
2841 if (i >= 0 && wp->w_cursor.lnum > wp->w_lines[i].wl_lnum)
2842 changed_line_abv_curs_win(wp);
2843 }
2844#endif
2845
2846 if (wp->w_cursor.lnum > lnum)
2847 changed_line_abv_curs_win(wp);
2848 else if (wp->w_cursor.lnum == lnum && wp->w_cursor.col >= col)
2849 changed_cline_bef_curs_win(wp);
2850 if (wp->w_botline >= lnum)
2851 {
2852 /* Assume that botline doesn't change (inserted lines make
2853 * other lines scroll down below botline). */
2854 approximate_botline_win(wp);
2855 }
2856
2857 /* Check if any w_lines[] entries have become invalid.
2858 * For entries below the change: Correct the lnums for
2859 * inserted/deleted lines. Makes it possible to stop displaying
2860 * after the change. */
2861 for (i = 0; i < wp->w_lines_valid; ++i)
2862 if (wp->w_lines[i].wl_valid)
2863 {
2864 if (wp->w_lines[i].wl_lnum >= lnum)
2865 {
2866 if (wp->w_lines[i].wl_lnum < lnume)
2867 {
2868 /* line included in change */
2869 wp->w_lines[i].wl_valid = FALSE;
2870 }
2871 else if (xtra != 0)
2872 {
2873 /* line below change */
2874 wp->w_lines[i].wl_lnum += xtra;
2875#ifdef FEAT_FOLDING
2876 wp->w_lines[i].wl_lastlnum += xtra;
2877#endif
2878 }
2879 }
2880#ifdef FEAT_FOLDING
2881 else if (wp->w_lines[i].wl_lastlnum >= lnum)
2882 {
2883 /* change somewhere inside this range of folded lines,
2884 * may need to be redrawn */
2885 wp->w_lines[i].wl_valid = FALSE;
2886 }
2887#endif
2888 }
2889 }
2890 }
2891
2892 /* Call update_screen() later, which checks out what needs to be redrawn,
2893 * since it notices b_mod_set and then uses b_mod_*. */
2894 if (must_redraw < VALID)
2895 must_redraw = VALID;
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002896
2897#ifdef FEAT_AUTOCMD
2898 /* when the cursor line is changed always trigger CursorMoved */
Bram Moolenaare163f1c2006-10-17 09:12:21 +00002899 if (lnum <= curwin->w_cursor.lnum
2900 && lnume + (xtra < 0 ? -xtra : xtra) > curwin->w_cursor.lnum)
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002901 last_cursormoved.lnum = 0;
2902#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002903}
2904
2905/*
2906 * unchanged() is called when the changed flag must be reset for buffer 'buf'
2907 */
2908 void
2909unchanged(buf, ff)
2910 buf_T *buf;
2911 int ff; /* also reset 'fileformat' */
2912{
2913 if (buf->b_changed || (ff && file_ff_differs(buf)))
2914 {
2915 buf->b_changed = 0;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002916 ml_setflags(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002917 if (ff)
2918 save_file_ff(buf);
2919#ifdef FEAT_WINDOWS
2920 check_status(buf);
Bram Moolenaar997fb4b2006-02-17 21:53:23 +00002921 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002922#endif
2923#ifdef FEAT_TITLE
2924 need_maketitle = TRUE; /* set window title later */
2925#endif
2926 }
2927 ++buf->b_changedtick;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002928#ifdef FEAT_NETBEANS_INTG
2929 netbeans_unmodified(buf);
2930#endif
2931}
2932
2933#if defined(FEAT_WINDOWS) || defined(PROTO)
2934/*
2935 * check_status: called when the status bars for the buffer 'buf'
2936 * need to be updated
2937 */
2938 void
2939check_status(buf)
2940 buf_T *buf;
2941{
2942 win_T *wp;
2943
2944 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2945 if (wp->w_buffer == buf && wp->w_status_height)
2946 {
2947 wp->w_redr_status = TRUE;
2948 if (must_redraw < VALID)
2949 must_redraw = VALID;
2950 }
2951}
2952#endif
2953
2954/*
2955 * If the file is readonly, give a warning message with the first change.
2956 * Don't do this for autocommands.
2957 * Don't use emsg(), because it flushes the macro buffer.
Bram Moolenaard5cdbeb2005-10-10 20:59:28 +00002958 * If we have undone all changes b_changed will be FALSE, but "b_did_warn"
Bram Moolenaar071d4272004-06-13 20:20:40 +00002959 * will be TRUE.
2960 */
2961 void
2962change_warning(col)
2963 int col; /* column for message; non-zero when in insert
2964 mode and 'showmode' is on */
2965{
Bram Moolenaar496c5262009-03-18 14:42:00 +00002966 static char *w_readonly = N_("W10: Warning: Changing a readonly file");
2967
Bram Moolenaar071d4272004-06-13 20:20:40 +00002968 if (curbuf->b_did_warn == FALSE
2969 && curbufIsChanged() == 0
2970#ifdef FEAT_AUTOCMD
2971 && !autocmd_busy
2972#endif
2973 && curbuf->b_p_ro)
2974 {
2975#ifdef FEAT_AUTOCMD
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002976 ++curbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002977 apply_autocmds(EVENT_FILECHANGEDRO, NULL, NULL, FALSE, curbuf);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002978 --curbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002979 if (!curbuf->b_p_ro)
2980 return;
2981#endif
2982 /*
2983 * Do what msg() does, but with a column offset if the warning should
2984 * be after the mode message.
2985 */
2986 msg_start();
2987 if (msg_row == Rows - 1)
2988 msg_col = col;
Bram Moolenaar2df6dcc2004-07-12 15:53:54 +00002989 msg_source(hl_attr(HLF_W));
Bram Moolenaar496c5262009-03-18 14:42:00 +00002990 MSG_PUTS_ATTR(_(w_readonly), hl_attr(HLF_W) | MSG_HIST);
2991#ifdef FEAT_EVAL
2992 set_vim_var_string(VV_WARNINGMSG, (char_u *)_(w_readonly), -1);
2993#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002994 msg_clr_eos();
2995 (void)msg_end();
2996 if (msg_silent == 0 && !silent_mode)
2997 {
2998 out_flush();
2999 ui_delay(1000L, TRUE); /* give the user time to think about it */
3000 }
3001 curbuf->b_did_warn = TRUE;
3002 redraw_cmdline = FALSE; /* don't redraw and erase the message */
3003 if (msg_row < Rows - 1)
3004 showmode();
3005 }
3006}
3007
3008/*
3009 * Ask for a reply from the user, a 'y' or a 'n'.
3010 * No other characters are accepted, the message is repeated until a valid
3011 * reply is entered or CTRL-C is hit.
3012 * If direct is TRUE, don't use vgetc() but ui_inchar(), don't get characters
3013 * from any buffers but directly from the user.
3014 *
3015 * return the 'y' or 'n'
3016 */
3017 int
3018ask_yesno(str, direct)
3019 char_u *str;
3020 int direct;
3021{
3022 int r = ' ';
3023 int save_State = State;
3024
3025 if (exiting) /* put terminal in raw mode for this question */
3026 settmode(TMODE_RAW);
3027 ++no_wait_return;
3028#ifdef USE_ON_FLY_SCROLL
3029 dont_scroll = TRUE; /* disallow scrolling here */
3030#endif
3031 State = CONFIRM; /* mouse behaves like with :confirm */
3032#ifdef FEAT_MOUSE
3033 setmouse(); /* disables mouse for xterm */
3034#endif
3035 ++no_mapping;
3036 ++allow_keys; /* no mapping here, but recognize keys */
3037
3038 while (r != 'y' && r != 'n')
3039 {
3040 /* same highlighting as for wait_return */
3041 smsg_attr(hl_attr(HLF_R), (char_u *)"%s (y/n)?", str);
3042 if (direct)
3043 r = get_keystroke();
3044 else
Bram Moolenaar913626c2008-01-03 11:43:42 +00003045 r = plain_vgetc();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003046 if (r == Ctrl_C || r == ESC)
3047 r = 'n';
3048 msg_putchar(r); /* show what you typed */
3049 out_flush();
3050 }
3051 --no_wait_return;
3052 State = save_State;
3053#ifdef FEAT_MOUSE
3054 setmouse();
3055#endif
3056 --no_mapping;
3057 --allow_keys;
3058
3059 return r;
3060}
3061
3062/*
3063 * Get a key stroke directly from the user.
3064 * Ignores mouse clicks and scrollbar events, except a click for the left
3065 * button (used at the more prompt).
3066 * Doesn't use vgetc(), because it syncs undo and eats mapped characters.
3067 * Disadvantage: typeahead is ignored.
3068 * Translates the interrupt character for unix to ESC.
3069 */
3070 int
3071get_keystroke()
3072{
3073#define CBUFLEN 151
3074 char_u buf[CBUFLEN];
3075 int len = 0;
3076 int n;
3077 int save_mapped_ctrl_c = mapped_ctrl_c;
Bram Moolenaar4395a712006-09-05 18:57:57 +00003078 int waited = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003079
3080 mapped_ctrl_c = FALSE; /* mappings are not used here */
3081 for (;;)
3082 {
3083 cursor_on();
3084 out_flush();
3085
3086 /* First time: blocking wait. Second time: wait up to 100ms for a
3087 * terminal code to complete. Leave some room for check_termcode() to
3088 * insert a key code into (max 5 chars plus NUL). And
3089 * fix_input_buffer() can triple the number of bytes. */
3090 n = ui_inchar(buf + len, (CBUFLEN - 6 - len) / 3,
3091 len == 0 ? -1L : 100L, 0);
3092 if (n > 0)
3093 {
3094 /* Replace zero and CSI by a special key code. */
3095 n = fix_input_buffer(buf + len, n, FALSE);
3096 len += n;
Bram Moolenaar4395a712006-09-05 18:57:57 +00003097 waited = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003098 }
Bram Moolenaar4395a712006-09-05 18:57:57 +00003099 else if (len > 0)
3100 ++waited; /* keep track of the waiting time */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003101
Bram Moolenaar4395a712006-09-05 18:57:57 +00003102 /* Incomplete termcode and not timed out yet: get more characters */
3103 if ((n = check_termcode(1, buf, len)) < 0
3104 && (!p_ttimeout || waited * 100L < (p_ttm < 0 ? p_tm : p_ttm)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003105 continue;
Bram Moolenaar4395a712006-09-05 18:57:57 +00003106
Bram Moolenaar071d4272004-06-13 20:20:40 +00003107 /* found a termcode: adjust length */
3108 if (n > 0)
3109 len = n;
3110 if (len == 0) /* nothing typed yet */
3111 continue;
3112
3113 /* Handle modifier and/or special key code. */
3114 n = buf[0];
3115 if (n == K_SPECIAL)
3116 {
3117 n = TO_SPECIAL(buf[1], buf[2]);
3118 if (buf[1] == KS_MODIFIER
3119 || n == K_IGNORE
3120#ifdef FEAT_MOUSE
3121 || n == K_LEFTMOUSE_NM
3122 || n == K_LEFTDRAG
3123 || n == K_LEFTRELEASE
3124 || n == K_LEFTRELEASE_NM
3125 || n == K_MIDDLEMOUSE
3126 || n == K_MIDDLEDRAG
3127 || n == K_MIDDLERELEASE
3128 || n == K_RIGHTMOUSE
3129 || n == K_RIGHTDRAG
3130 || n == K_RIGHTRELEASE
3131 || n == K_MOUSEDOWN
3132 || n == K_MOUSEUP
3133 || n == K_X1MOUSE
3134 || n == K_X1DRAG
3135 || n == K_X1RELEASE
3136 || n == K_X2MOUSE
3137 || n == K_X2DRAG
3138 || n == K_X2RELEASE
3139# ifdef FEAT_GUI
3140 || n == K_VER_SCROLLBAR
3141 || n == K_HOR_SCROLLBAR
3142# endif
3143#endif
3144 )
3145 {
3146 if (buf[1] == KS_MODIFIER)
3147 mod_mask = buf[2];
3148 len -= 3;
3149 if (len > 0)
3150 mch_memmove(buf, buf + 3, (size_t)len);
3151 continue;
3152 }
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00003153 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003154 }
3155#ifdef FEAT_MBYTE
3156 if (has_mbyte)
3157 {
3158 if (MB_BYTE2LEN(n) > len)
3159 continue; /* more bytes to get */
3160 buf[len >= CBUFLEN ? CBUFLEN - 1 : len] = NUL;
3161 n = (*mb_ptr2char)(buf);
3162 }
3163#endif
3164#ifdef UNIX
3165 if (n == intr_char)
3166 n = ESC;
3167#endif
3168 break;
3169 }
3170
3171 mapped_ctrl_c = save_mapped_ctrl_c;
3172 return n;
3173}
3174
3175/*
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003176 * Get a number from the user.
3177 * When "mouse_used" is not NULL allow using the mouse.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003178 */
3179 int
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003180get_number(colon, mouse_used)
3181 int colon; /* allow colon to abort */
3182 int *mouse_used;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003183{
3184 int n = 0;
3185 int c;
Bram Moolenaar3991dab2006-03-27 17:01:56 +00003186 int typed = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003187
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003188 if (mouse_used != NULL)
3189 *mouse_used = FALSE;
3190
Bram Moolenaar071d4272004-06-13 20:20:40 +00003191 /* When not printing messages, the user won't know what to type, return a
3192 * zero (as if CR was hit). */
3193 if (msg_silent != 0)
3194 return 0;
3195
3196#ifdef USE_ON_FLY_SCROLL
3197 dont_scroll = TRUE; /* disallow scrolling here */
3198#endif
3199 ++no_mapping;
3200 ++allow_keys; /* no mapping here, but recognize keys */
3201 for (;;)
3202 {
3203 windgoto(msg_row, msg_col);
3204 c = safe_vgetc();
3205 if (VIM_ISDIGIT(c))
3206 {
3207 n = n * 10 + c - '0';
3208 msg_putchar(c);
Bram Moolenaar3991dab2006-03-27 17:01:56 +00003209 ++typed;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003210 }
3211 else if (c == K_DEL || c == K_KDEL || c == K_BS || c == Ctrl_H)
3212 {
Bram Moolenaar3991dab2006-03-27 17:01:56 +00003213 if (typed > 0)
3214 {
3215 MSG_PUTS("\b \b");
3216 --typed;
3217 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003218 n /= 10;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003219 }
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003220#ifdef FEAT_MOUSE
3221 else if (mouse_used != NULL && c == K_LEFTMOUSE)
3222 {
3223 *mouse_used = TRUE;
3224 n = mouse_row + 1;
3225 break;
3226 }
3227#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003228 else if (n == 0 && c == ':' && colon)
3229 {
3230 stuffcharReadbuff(':');
3231 if (!exmode_active)
3232 cmdline_row = msg_row;
3233 skip_redraw = TRUE; /* skip redraw once */
3234 do_redraw = FALSE;
3235 break;
3236 }
3237 else if (c == CAR || c == NL || c == Ctrl_C || c == ESC)
3238 break;
3239 }
3240 --no_mapping;
3241 --allow_keys;
3242 return n;
3243}
3244
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003245/*
3246 * Ask the user to enter a number.
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003247 * When "mouse_used" is not NULL allow using the mouse and in that case return
3248 * the line number.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003249 */
3250 int
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003251prompt_for_number(mouse_used)
3252 int *mouse_used;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003253{
3254 int i;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003255 int save_cmdline_row;
3256 int save_State;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003257
3258 /* When using ":silent" assume that <CR> was entered. */
Bram Moolenaar42eeac32005-06-29 22:40:58 +00003259 if (mouse_used != NULL)
Bram Moolenaard812df62008-11-09 12:46:09 +00003260 MSG_PUTS(_("Type number and <Enter> or click with mouse (empty cancels): "));
Bram Moolenaar42eeac32005-06-29 22:40:58 +00003261 else
Bram Moolenaard812df62008-11-09 12:46:09 +00003262 MSG_PUTS(_("Type number and <Enter> (empty cancels): "));
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003263
Bram Moolenaar203335e2006-09-03 14:35:42 +00003264 /* Set the state such that text can be selected/copied/pasted and we still
3265 * get mouse events. */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003266 save_cmdline_row = cmdline_row;
Bram Moolenaar203335e2006-09-03 14:35:42 +00003267 cmdline_row = 0;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003268 save_State = State;
Bram Moolenaar203335e2006-09-03 14:35:42 +00003269 State = CMDLINE;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003270
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003271 i = get_number(TRUE, mouse_used);
3272 if (KeyTyped)
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003273 {
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003274 /* don't call wait_return() now */
3275 /* msg_putchar('\n'); */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003276 cmdline_row = msg_row - 1;
3277 need_wait_return = FALSE;
3278 msg_didany = FALSE;
3279 }
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003280 else
3281 cmdline_row = save_cmdline_row;
3282 State = save_State;
3283
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003284 return i;
3285}
3286
Bram Moolenaar071d4272004-06-13 20:20:40 +00003287 void
3288msgmore(n)
3289 long n;
3290{
3291 long pn;
3292
3293 if (global_busy /* no messages now, wait until global is finished */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003294 || !messaging()) /* 'lazyredraw' set, don't do messages now */
3295 return;
3296
Bram Moolenaar7df2d662005-01-25 22:18:08 +00003297 /* We don't want to overwrite another important message, but do overwrite
3298 * a previous "more lines" or "fewer lines" message, so that "5dd" and
3299 * then "put" reports the last action. */
3300 if (keep_msg != NULL && !keep_msg_more)
3301 return;
3302
Bram Moolenaar071d4272004-06-13 20:20:40 +00003303 if (n > 0)
3304 pn = n;
3305 else
3306 pn = -n;
3307
3308 if (pn > p_report)
3309 {
3310 if (pn == 1)
3311 {
3312 if (n > 0)
3313 STRCPY(msg_buf, _("1 more line"));
3314 else
3315 STRCPY(msg_buf, _("1 line less"));
3316 }
3317 else
3318 {
3319 if (n > 0)
3320 sprintf((char *)msg_buf, _("%ld more lines"), pn);
3321 else
3322 sprintf((char *)msg_buf, _("%ld fewer lines"), pn);
3323 }
3324 if (got_int)
3325 STRCAT(msg_buf, _(" (Interrupted)"));
3326 if (msg(msg_buf))
3327 {
Bram Moolenaar238a5642006-02-21 22:12:05 +00003328 set_keep_msg(msg_buf, 0);
Bram Moolenaar7df2d662005-01-25 22:18:08 +00003329 keep_msg_more = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003330 }
3331 }
3332}
3333
3334/*
3335 * flush map and typeahead buffers and give a warning for an error
3336 */
3337 void
3338beep_flush()
3339{
3340 if (emsg_silent == 0)
3341 {
3342 flush_buffers(FALSE);
3343 vim_beep();
3344 }
3345}
3346
3347/*
3348 * give a warning for an error
3349 */
3350 void
3351vim_beep()
3352{
3353 if (emsg_silent == 0)
3354 {
3355 if (p_vb
3356#ifdef FEAT_GUI
3357 /* While the GUI is starting up the termcap is set for the GUI
3358 * but the output still goes to a terminal. */
3359 && !(gui.in_use && gui.starting)
3360#endif
3361 )
3362 {
3363 out_str(T_VB);
3364 }
3365 else
3366 {
3367#ifdef MSDOS
3368 /*
3369 * The number of beeps outputted is reduced to avoid having to wait
3370 * for all the beeps to finish. This is only a problem on systems
3371 * where the beeps don't overlap.
3372 */
3373 if (beep_count == 0 || beep_count == 10)
3374 {
3375 out_char(BELL);
3376 beep_count = 1;
3377 }
3378 else
3379 ++beep_count;
3380#else
3381 out_char(BELL);
3382#endif
3383 }
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003384
3385 /* When 'verbose' is set and we are sourcing a script or executing a
3386 * function give the user a hint where the beep comes from. */
3387 if (vim_strchr(p_debug, 'e') != NULL)
3388 {
3389 msg_source(hl_attr(HLF_W));
3390 msg_attr((char_u *)_("Beep!"), hl_attr(HLF_W));
3391 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003392 }
3393}
3394
3395/*
3396 * To get the "real" home directory:
3397 * - get value of $HOME
3398 * For Unix:
3399 * - go to that directory
3400 * - do mch_dirname() to get the real name of that directory.
3401 * This also works with mounts and links.
3402 * Don't do this for MS-DOS, it will change the "current dir" for a drive.
3403 */
3404static char_u *homedir = NULL;
3405
3406 void
3407init_homedir()
3408{
3409 char_u *var;
3410
Bram Moolenaar05159a02005-02-26 23:04:13 +00003411 /* In case we are called a second time (when 'encoding' changes). */
3412 vim_free(homedir);
3413 homedir = NULL;
3414
Bram Moolenaar071d4272004-06-13 20:20:40 +00003415#ifdef VMS
3416 var = mch_getenv((char_u *)"SYS$LOGIN");
3417#else
3418 var = mch_getenv((char_u *)"HOME");
3419#endif
3420
3421 if (var != NULL && *var == NUL) /* empty is same as not set */
3422 var = NULL;
3423
3424#ifdef WIN3264
3425 /*
3426 * Weird but true: $HOME may contain an indirect reference to another
3427 * variable, esp. "%USERPROFILE%". Happens when $USERPROFILE isn't set
3428 * when $HOME is being set.
3429 */
3430 if (var != NULL && *var == '%')
3431 {
3432 char_u *p;
3433 char_u *exp;
3434
3435 p = vim_strchr(var + 1, '%');
3436 if (p != NULL)
3437 {
Bram Moolenaarce0842a2005-07-18 21:58:11 +00003438 vim_strncpy(NameBuff, var + 1, p - (var + 1));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003439 exp = mch_getenv(NameBuff);
3440 if (exp != NULL && *exp != NUL
3441 && STRLEN(exp) + STRLEN(p) < MAXPATHL)
3442 {
Bram Moolenaar555b2802005-05-19 21:08:39 +00003443 vim_snprintf((char *)NameBuff, MAXPATHL, "%s%s", exp, p + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003444 var = NameBuff;
3445 /* Also set $HOME, it's needed for _viminfo. */
3446 vim_setenv((char_u *)"HOME", NameBuff);
3447 }
3448 }
3449 }
3450
3451 /*
3452 * Typically, $HOME is not defined on Windows, unless the user has
3453 * specifically defined it for Vim's sake. However, on Windows NT
3454 * platforms, $HOMEDRIVE and $HOMEPATH are automatically defined for
3455 * each user. Try constructing $HOME from these.
3456 */
3457 if (var == NULL)
3458 {
3459 char_u *homedrive, *homepath;
3460
3461 homedrive = mch_getenv((char_u *)"HOMEDRIVE");
3462 homepath = mch_getenv((char_u *)"HOMEPATH");
3463 if (homedrive != NULL && homepath != NULL
3464 && STRLEN(homedrive) + STRLEN(homepath) < MAXPATHL)
3465 {
3466 sprintf((char *)NameBuff, "%s%s", homedrive, homepath);
3467 if (NameBuff[0] != NUL)
3468 {
3469 var = NameBuff;
3470 /* Also set $HOME, it's needed for _viminfo. */
3471 vim_setenv((char_u *)"HOME", NameBuff);
3472 }
3473 }
3474 }
Bram Moolenaar05159a02005-02-26 23:04:13 +00003475
3476# if defined(FEAT_MBYTE)
3477 if (enc_utf8 && var != NULL)
3478 {
3479 int len;
3480 char_u *pp;
3481
3482 /* Convert from active codepage to UTF-8. Other conversions are
3483 * not done, because they would fail for non-ASCII characters. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003484 acp_to_enc(var, (int)STRLEN(var), &pp, &len);
Bram Moolenaar05159a02005-02-26 23:04:13 +00003485 if (pp != NULL)
3486 {
3487 homedir = pp;
3488 return;
3489 }
3490 }
3491# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003492#endif
3493
3494#if defined(OS2) || defined(MSDOS) || defined(MSWIN)
3495 /*
3496 * Default home dir is C:/
3497 * Best assumption we can make in such a situation.
3498 */
3499 if (var == NULL)
3500 var = "C:/";
3501#endif
3502 if (var != NULL)
3503 {
3504#ifdef UNIX
3505 /*
3506 * Change to the directory and get the actual path. This resolves
3507 * links. Don't do it when we can't return.
3508 */
3509 if (mch_dirname(NameBuff, MAXPATHL) == OK
3510 && mch_chdir((char *)NameBuff) == 0)
3511 {
3512 if (!mch_chdir((char *)var) && mch_dirname(IObuff, IOSIZE) == OK)
3513 var = IObuff;
3514 if (mch_chdir((char *)NameBuff) != 0)
3515 EMSG(_(e_prev_dir));
3516 }
3517#endif
3518 homedir = vim_strsave(var);
3519 }
3520}
3521
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003522#if defined(EXITFREE) || defined(PROTO)
3523 void
3524free_homedir()
3525{
3526 vim_free(homedir);
3527}
3528#endif
3529
Bram Moolenaar071d4272004-06-13 20:20:40 +00003530/*
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003531 * Call expand_env() and store the result in an allocated string.
3532 * This is not very memory efficient, this expects the result to be freed
3533 * again soon.
3534 */
3535 char_u *
3536expand_env_save(src)
3537 char_u *src;
3538{
3539 return expand_env_save_opt(src, FALSE);
3540}
3541
3542/*
3543 * Idem, but when "one" is TRUE handle the string as one file name, only
3544 * expand "~" at the start.
3545 */
3546 char_u *
3547expand_env_save_opt(src, one)
3548 char_u *src;
3549 int one;
3550{
3551 char_u *p;
3552
3553 p = alloc(MAXPATHL);
3554 if (p != NULL)
3555 expand_env_esc(src, p, MAXPATHL, FALSE, one, NULL);
3556 return p;
3557}
3558
3559/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003560 * Expand environment variable with path name.
3561 * "~/" is also expanded, using $HOME. For Unix "~user/" is expanded.
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003562 * Skips over "\ ", "\~" and "\$" (not for Win32 though).
Bram Moolenaar071d4272004-06-13 20:20:40 +00003563 * If anything fails no expansion is done and dst equals src.
3564 */
3565 void
3566expand_env(src, dst, dstlen)
3567 char_u *src; /* input string e.g. "$HOME/vim.hlp" */
3568 char_u *dst; /* where to put the result */
3569 int dstlen; /* maximum length of the result */
3570{
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003571 expand_env_esc(src, dst, dstlen, FALSE, FALSE, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003572}
3573
3574 void
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003575expand_env_esc(srcp, dst, dstlen, esc, one, startstr)
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003576 char_u *srcp; /* input string e.g. "$HOME/vim.hlp" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003577 char_u *dst; /* where to put the result */
3578 int dstlen; /* maximum length of the result */
3579 int esc; /* escape spaces in expanded variables */
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003580 int one; /* "srcp" is one file name */
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003581 char_u *startstr; /* start again after this (can be NULL) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003582{
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003583 char_u *src;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003584 char_u *tail;
3585 int c;
3586 char_u *var;
3587 int copy_char;
3588 int mustfree; /* var was allocated, need to free it later */
3589 int at_start = TRUE; /* at start of a name */
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003590 int startstr_len = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003591
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003592 if (startstr != NULL)
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003593 startstr_len = (int)STRLEN(startstr);
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003594
3595 src = skipwhite(srcp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003596 --dstlen; /* leave one char space for "\," */
3597 while (*src && dstlen > 0)
3598 {
3599 copy_char = TRUE;
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003600 if ((*src == '$'
3601#ifdef VMS
3602 && at_start
3603#endif
3604 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003605#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3606 || *src == '%'
3607#endif
3608 || (*src == '~' && at_start))
3609 {
3610 mustfree = FALSE;
3611
3612 /*
3613 * The variable name is copied into dst temporarily, because it may
3614 * be a string in read-only memory and a NUL needs to be appended.
3615 */
3616 if (*src != '~') /* environment var */
3617 {
3618 tail = src + 1;
3619 var = dst;
3620 c = dstlen - 1;
3621
3622#ifdef UNIX
3623 /* Unix has ${var-name} type environment vars */
3624 if (*tail == '{' && !vim_isIDc('{'))
3625 {
3626 tail++; /* ignore '{' */
3627 while (c-- > 0 && *tail && *tail != '}')
3628 *var++ = *tail++;
3629 }
3630 else
3631#endif
3632 {
3633 while (c-- > 0 && *tail != NUL && ((vim_isIDc(*tail))
3634#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3635 || (*src == '%' && *tail != '%')
3636#endif
3637 ))
3638 {
3639#ifdef OS2 /* env vars only in uppercase */
3640 *var++ = TOUPPER_LOC(*tail);
3641 tail++; /* toupper() may be a macro! */
3642#else
3643 *var++ = *tail++;
3644#endif
3645 }
3646 }
3647
3648#if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
3649# ifdef UNIX
3650 if (src[1] == '{' && *tail != '}')
3651# else
3652 if (*src == '%' && *tail != '%')
3653# endif
3654 var = NULL;
3655 else
3656 {
3657# ifdef UNIX
3658 if (src[1] == '{')
3659# else
3660 if (*src == '%')
3661#endif
3662 ++tail;
3663#endif
3664 *var = NUL;
3665 var = vim_getenv(dst, &mustfree);
3666#if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
3667 }
3668#endif
3669 }
3670 /* home directory */
3671 else if ( src[1] == NUL
3672 || vim_ispathsep(src[1])
3673 || vim_strchr((char_u *)" ,\t\n", src[1]) != NULL)
3674 {
3675 var = homedir;
3676 tail = src + 1;
3677 }
3678 else /* user directory */
3679 {
3680#if defined(UNIX) || (defined(VMS) && defined(USER_HOME))
3681 /*
3682 * Copy ~user to dst[], so we can put a NUL after it.
3683 */
3684 tail = src;
3685 var = dst;
3686 c = dstlen - 1;
3687 while ( c-- > 0
3688 && *tail
3689 && vim_isfilec(*tail)
3690 && !vim_ispathsep(*tail))
3691 *var++ = *tail++;
3692 *var = NUL;
3693# ifdef UNIX
3694 /*
3695 * If the system supports getpwnam(), use it.
3696 * Otherwise, or if getpwnam() fails, the shell is used to
3697 * expand ~user. This is slower and may fail if the shell
3698 * does not support ~user (old versions of /bin/sh).
3699 */
3700# if defined(HAVE_GETPWNAM) && defined(HAVE_PWD_H)
3701 {
3702 struct passwd *pw;
3703
Bram Moolenaara40ceaf2006-01-13 22:35:40 +00003704 /* Note: memory allocated by getpwnam() is never freed.
3705 * Calling endpwent() apparently doesn't help. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003706 pw = getpwnam((char *)dst + 1);
3707 if (pw != NULL)
3708 var = (char_u *)pw->pw_dir;
3709 else
3710 var = NULL;
3711 }
3712 if (var == NULL)
3713# endif
3714 {
3715 expand_T xpc;
3716
3717 ExpandInit(&xpc);
3718 xpc.xp_context = EXPAND_FILES;
3719 var = ExpandOne(&xpc, dst, NULL,
3720 WILD_ADD_SLASH|WILD_SILENT, WILD_EXPAND_FREE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003721 mustfree = TRUE;
3722 }
3723
3724# else /* !UNIX, thus VMS */
3725 /*
3726 * USER_HOME is a comma-separated list of
3727 * directories to search for the user account in.
3728 */
3729 {
3730 char_u test[MAXPATHL], paths[MAXPATHL];
3731 char_u *path, *next_path, *ptr;
3732 struct stat st;
3733
3734 STRCPY(paths, USER_HOME);
3735 next_path = paths;
3736 while (*next_path)
3737 {
3738 for (path = next_path; *next_path && *next_path != ',';
3739 next_path++);
3740 if (*next_path)
3741 *next_path++ = NUL;
3742 STRCPY(test, path);
3743 STRCAT(test, "/");
3744 STRCAT(test, dst + 1);
3745 if (mch_stat(test, &st) == 0)
3746 {
3747 var = alloc(STRLEN(test) + 1);
3748 STRCPY(var, test);
3749 mustfree = TRUE;
3750 break;
3751 }
3752 }
3753 }
3754# endif /* UNIX */
3755#else
3756 /* cannot expand user's home directory, so don't try */
3757 var = NULL;
3758 tail = (char_u *)""; /* for gcc */
3759#endif /* UNIX || VMS */
3760 }
3761
3762#ifdef BACKSLASH_IN_FILENAME
3763 /* If 'shellslash' is set change backslashes to forward slashes.
3764 * Can't use slash_adjust(), p_ssl may be set temporarily. */
3765 if (p_ssl && var != NULL && vim_strchr(var, '\\') != NULL)
3766 {
3767 char_u *p = vim_strsave(var);
3768
3769 if (p != NULL)
3770 {
3771 if (mustfree)
3772 vim_free(var);
3773 var = p;
3774 mustfree = TRUE;
3775 forward_slash(var);
3776 }
3777 }
3778#endif
3779
3780 /* If "var" contains white space, escape it with a backslash.
3781 * Required for ":e ~/tt" when $HOME includes a space. */
3782 if (esc && var != NULL && vim_strpbrk(var, (char_u *)" \t") != NULL)
3783 {
3784 char_u *p = vim_strsave_escaped(var, (char_u *)" \t");
3785
3786 if (p != NULL)
3787 {
3788 if (mustfree)
3789 vim_free(var);
3790 var = p;
3791 mustfree = TRUE;
3792 }
3793 }
3794
3795 if (var != NULL && *var != NUL
3796 && (STRLEN(var) + STRLEN(tail) + 1 < (unsigned)dstlen))
3797 {
3798 STRCPY(dst, var);
3799 dstlen -= (int)STRLEN(var);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003800 c = (int)STRLEN(var);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003801 /* if var[] ends in a path separator and tail[] starts
3802 * with it, skip a character */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003803 if (*var != NUL && after_pathsep(dst, dst + c)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003804#if defined(BACKSLASH_IN_FILENAME) || defined(AMIGA)
3805 && dst[-1] != ':'
3806#endif
3807 && vim_ispathsep(*tail))
3808 ++tail;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003809 dst += c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003810 src = tail;
3811 copy_char = FALSE;
3812 }
3813 if (mustfree)
3814 vim_free(var);
3815 }
3816
3817 if (copy_char) /* copy at least one char */
3818 {
3819 /*
Bram Moolenaar25394022007-05-10 19:06:20 +00003820 * Recognize the start of a new name, for '~'.
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003821 * Don't do this when "one" is TRUE, to avoid expanding "~" in
3822 * ":edit foo ~ foo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00003823 */
3824 at_start = FALSE;
3825 if (src[0] == '\\' && src[1] != NUL)
3826 {
3827 *dst++ = *src++;
3828 --dstlen;
3829 }
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003830 else if ((src[0] == ' ' || src[0] == ',') && !one)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003831 at_start = TRUE;
3832 *dst++ = *src++;
3833 --dstlen;
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003834
3835 if (startstr != NULL && src - startstr_len >= srcp
3836 && STRNCMP(src - startstr_len, startstr, startstr_len) == 0)
3837 at_start = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003838 }
3839 }
3840 *dst = NUL;
3841}
3842
3843/*
3844 * Vim's version of getenv().
3845 * Special handling of $HOME, $VIM and $VIMRUNTIME.
Bram Moolenaar2f6b0b82005-03-08 22:43:10 +00003846 * Also does ACP to 'enc' conversion for Win32.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003847 */
3848 char_u *
3849vim_getenv(name, mustfree)
3850 char_u *name;
3851 int *mustfree; /* set to TRUE when returned is allocated */
3852{
3853 char_u *p;
3854 char_u *pend;
3855 int vimruntime;
3856
3857#if defined(OS2) || defined(MSDOS) || defined(MSWIN)
3858 /* use "C:/" when $HOME is not set */
3859 if (STRCMP(name, "HOME") == 0)
3860 return homedir;
3861#endif
3862
3863 p = mch_getenv(name);
3864 if (p != NULL && *p == NUL) /* empty is the same as not set */
3865 p = NULL;
3866
3867 if (p != NULL)
Bram Moolenaar05159a02005-02-26 23:04:13 +00003868 {
3869#if defined(FEAT_MBYTE) && defined(WIN3264)
3870 if (enc_utf8)
3871 {
3872 int len;
3873 char_u *pp;
3874
3875 /* Convert from active codepage to UTF-8. Other conversions are
3876 * not done, because they would fail for non-ASCII characters. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003877 acp_to_enc(p, (int)STRLEN(p), &pp, &len);
Bram Moolenaar05159a02005-02-26 23:04:13 +00003878 if (pp != NULL)
3879 {
3880 p = pp;
3881 *mustfree = TRUE;
3882 }
3883 }
3884#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003885 return p;
Bram Moolenaar05159a02005-02-26 23:04:13 +00003886 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003887
3888 vimruntime = (STRCMP(name, "VIMRUNTIME") == 0);
3889 if (!vimruntime && STRCMP(name, "VIM") != 0)
3890 return NULL;
3891
3892 /*
3893 * When expanding $VIMRUNTIME fails, try using $VIM/vim<version> or $VIM.
3894 * Don't do this when default_vimruntime_dir is non-empty.
3895 */
3896 if (vimruntime
3897#ifdef HAVE_PATHDEF
3898 && *default_vimruntime_dir == NUL
3899#endif
3900 )
3901 {
3902 p = mch_getenv((char_u *)"VIM");
3903 if (p != NULL && *p == NUL) /* empty is the same as not set */
3904 p = NULL;
3905 if (p != NULL)
3906 {
3907 p = vim_version_dir(p);
3908 if (p != NULL)
3909 *mustfree = TRUE;
3910 else
3911 p = mch_getenv((char_u *)"VIM");
Bram Moolenaar05159a02005-02-26 23:04:13 +00003912
3913#if defined(FEAT_MBYTE) && defined(WIN3264)
3914 if (enc_utf8)
3915 {
3916 int len;
3917 char_u *pp;
3918
3919 /* Convert from active codepage to UTF-8. Other conversions
3920 * are not done, because they would fail for non-ASCII
3921 * characters. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003922 acp_to_enc(p, (int)STRLEN(p), &pp, &len);
Bram Moolenaar05159a02005-02-26 23:04:13 +00003923 if (pp != NULL)
3924 {
3925 if (mustfree)
3926 vim_free(p);
3927 p = pp;
3928 *mustfree = TRUE;
3929 }
3930 }
3931#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003932 }
3933 }
3934
3935 /*
3936 * When expanding $VIM or $VIMRUNTIME fails, try using:
3937 * - the directory name from 'helpfile' (unless it contains '$')
3938 * - the executable name from argv[0]
3939 */
3940 if (p == NULL)
3941 {
3942 if (p_hf != NULL && vim_strchr(p_hf, '$') == NULL)
3943 p = p_hf;
3944#ifdef USE_EXE_NAME
3945 /*
3946 * Use the name of the executable, obtained from argv[0].
3947 */
3948 else
3949 p = exe_name;
3950#endif
3951 if (p != NULL)
3952 {
3953 /* remove the file name */
3954 pend = gettail(p);
3955
3956 /* remove "doc/" from 'helpfile', if present */
3957 if (p == p_hf)
3958 pend = remove_tail(p, pend, (char_u *)"doc");
3959
3960#ifdef USE_EXE_NAME
3961# ifdef MACOS_X
Bram Moolenaar95e9b492006-03-15 23:04:43 +00003962 /* remove "MacOS" from exe_name and add "Resources/vim" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003963 if (p == exe_name)
3964 {
3965 char_u *pend1;
Bram Moolenaar95e9b492006-03-15 23:04:43 +00003966 char_u *pnew;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003967
Bram Moolenaar95e9b492006-03-15 23:04:43 +00003968 pend1 = remove_tail(p, pend, (char_u *)"MacOS");
3969 if (pend1 != pend)
3970 {
3971 pnew = alloc((unsigned)(pend1 - p) + 15);
3972 if (pnew != NULL)
3973 {
3974 STRNCPY(pnew, p, (pend1 - p));
3975 STRCPY(pnew + (pend1 - p), "Resources/vim");
3976 p = pnew;
3977 pend = p + STRLEN(p);
3978 }
3979 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003980 }
3981# endif
3982 /* remove "src/" from exe_name, if present */
3983 if (p == exe_name)
3984 pend = remove_tail(p, pend, (char_u *)"src");
3985#endif
3986
3987 /* for $VIM, remove "runtime/" or "vim54/", if present */
3988 if (!vimruntime)
3989 {
3990 pend = remove_tail(p, pend, (char_u *)RUNTIME_DIRNAME);
3991 pend = remove_tail(p, pend, (char_u *)VIM_VERSION_NODOT);
3992 }
3993
3994 /* remove trailing path separator */
3995#ifndef MACOS_CLASSIC
3996 /* With MacOS path (with colons) the final colon is required */
Bram Moolenaare21877a2008-02-13 09:58:14 +00003997 /* to avoid confusion between absolute and relative path */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003998 if (pend > p && after_pathsep(p, pend))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003999 --pend;
4000#endif
4001
Bram Moolenaar95e9b492006-03-15 23:04:43 +00004002#ifdef MACOS_X
4003 if (p == exe_name || p == p_hf)
4004#endif
4005 /* check that the result is a directory name */
4006 p = vim_strnsave(p, (int)(pend - p));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004007
4008 if (p != NULL && !mch_isdir(p))
4009 {
4010 vim_free(p);
4011 p = NULL;
4012 }
4013 else
4014 {
4015#ifdef USE_EXE_NAME
4016 /* may add "/vim54" or "/runtime" if it exists */
4017 if (vimruntime && (pend = vim_version_dir(p)) != NULL)
4018 {
4019 vim_free(p);
4020 p = pend;
4021 }
4022#endif
4023 *mustfree = TRUE;
4024 }
4025 }
4026 }
4027
4028#ifdef HAVE_PATHDEF
4029 /* When there is a pathdef.c file we can use default_vim_dir and
4030 * default_vimruntime_dir */
4031 if (p == NULL)
4032 {
4033 /* Only use default_vimruntime_dir when it is not empty */
4034 if (vimruntime && *default_vimruntime_dir != NUL)
4035 {
4036 p = default_vimruntime_dir;
4037 *mustfree = FALSE;
4038 }
4039 else if (*default_vim_dir != NUL)
4040 {
4041 if (vimruntime && (p = vim_version_dir(default_vim_dir)) != NULL)
4042 *mustfree = TRUE;
4043 else
4044 {
4045 p = default_vim_dir;
4046 *mustfree = FALSE;
4047 }
4048 }
4049 }
4050#endif
4051
4052 /*
4053 * Set the environment variable, so that the new value can be found fast
4054 * next time, and others can also use it (e.g. Perl).
4055 */
4056 if (p != NULL)
4057 {
4058 if (vimruntime)
4059 {
4060 vim_setenv((char_u *)"VIMRUNTIME", p);
4061 didset_vimruntime = TRUE;
4062#ifdef FEAT_GETTEXT
4063 {
Bram Moolenaard6754642005-01-17 22:18:45 +00004064 char_u *buf = concat_str(p, (char_u *)"/lang");
Bram Moolenaar071d4272004-06-13 20:20:40 +00004065
4066 if (buf != NULL)
4067 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004068 bindtextdomain(VIMPACKAGE, (char *)buf);
4069 vim_free(buf);
4070 }
4071 }
4072#endif
4073 }
4074 else
4075 {
4076 vim_setenv((char_u *)"VIM", p);
4077 didset_vim = TRUE;
4078 }
4079 }
4080 return p;
4081}
4082
4083/*
4084 * Check if the directory "vimdir/<version>" or "vimdir/runtime" exists.
4085 * Return NULL if not, return its name in allocated memory otherwise.
4086 */
4087 static char_u *
4088vim_version_dir(vimdir)
4089 char_u *vimdir;
4090{
4091 char_u *p;
4092
4093 if (vimdir == NULL || *vimdir == NUL)
4094 return NULL;
4095 p = concat_fnames(vimdir, (char_u *)VIM_VERSION_NODOT, TRUE);
4096 if (p != NULL && mch_isdir(p))
4097 return p;
4098 vim_free(p);
4099 p = concat_fnames(vimdir, (char_u *)RUNTIME_DIRNAME, TRUE);
4100 if (p != NULL && mch_isdir(p))
4101 return p;
4102 vim_free(p);
4103 return NULL;
4104}
4105
4106/*
4107 * If the string between "p" and "pend" ends in "name/", return "pend" minus
4108 * the length of "name/". Otherwise return "pend".
4109 */
4110 static char_u *
4111remove_tail(p, pend, name)
4112 char_u *p;
4113 char_u *pend;
4114 char_u *name;
4115{
4116 int len = (int)STRLEN(name) + 1;
4117 char_u *newend = pend - len;
4118
4119 if (newend >= p
4120 && fnamencmp(newend, name, len - 1) == 0
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004121 && (newend == p || after_pathsep(p, newend)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004122 return newend;
4123 return pend;
4124}
4125
Bram Moolenaar071d4272004-06-13 20:20:40 +00004126/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004127 * Our portable version of setenv.
4128 */
4129 void
4130vim_setenv(name, val)
4131 char_u *name;
4132 char_u *val;
4133{
4134#ifdef HAVE_SETENV
4135 mch_setenv((char *)name, (char *)val, 1);
4136#else
4137 char_u *envbuf;
4138
4139 /*
4140 * Putenv does not copy the string, it has to remain
4141 * valid. The allocated memory will never be freed.
4142 */
4143 envbuf = alloc((unsigned)(STRLEN(name) + STRLEN(val) + 2));
4144 if (envbuf != NULL)
4145 {
4146 sprintf((char *)envbuf, "%s=%s", name, val);
4147 putenv((char *)envbuf);
4148 }
4149#endif
4150}
4151
4152#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
4153/*
4154 * Function given to ExpandGeneric() to obtain an environment variable name.
4155 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004156 char_u *
4157get_env_name(xp, idx)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00004158 expand_T *xp UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004159 int idx;
4160{
4161# if defined(AMIGA) || defined(__MRC__) || defined(__SC__)
4162 /*
4163 * No environ[] on the Amiga and on the Mac (using MPW).
4164 */
4165 return NULL;
4166# else
4167# ifndef __WIN32__
4168 /* Borland C++ 5.2 has this in a header file. */
4169 extern char **environ;
4170# endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00004171# define ENVNAMELEN 100
4172 static char_u name[ENVNAMELEN];
Bram Moolenaar071d4272004-06-13 20:20:40 +00004173 char_u *str;
4174 int n;
4175
4176 str = (char_u *)environ[idx];
4177 if (str == NULL)
4178 return NULL;
4179
Bram Moolenaar21cf8232004-07-16 20:18:37 +00004180 for (n = 0; n < ENVNAMELEN - 1; ++n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004181 {
4182 if (str[n] == '=' || str[n] == NUL)
4183 break;
4184 name[n] = str[n];
4185 }
4186 name[n] = NUL;
4187 return name;
4188# endif
4189}
4190#endif
4191
4192/*
4193 * Replace home directory by "~" in each space or comma separated file name in
4194 * 'src'.
4195 * If anything fails (except when out of space) dst equals src.
4196 */
4197 void
4198home_replace(buf, src, dst, dstlen, one)
4199 buf_T *buf; /* when not NULL, check for help files */
4200 char_u *src; /* input file name */
4201 char_u *dst; /* where to put the result */
4202 int dstlen; /* maximum length of the result */
4203 int one; /* if TRUE, only replace one file name, include
4204 spaces and commas in the file name. */
4205{
4206 size_t dirlen = 0, envlen = 0;
4207 size_t len;
4208 char_u *homedir_env;
4209 char_u *p;
4210
4211 if (src == NULL)
4212 {
4213 *dst = NUL;
4214 return;
4215 }
4216
4217 /*
4218 * If the file is a help file, remove the path completely.
4219 */
4220 if (buf != NULL && buf->b_help)
4221 {
4222 STRCPY(dst, gettail(src));
4223 return;
4224 }
4225
4226 /*
4227 * We check both the value of the $HOME environment variable and the
4228 * "real" home directory.
4229 */
4230 if (homedir != NULL)
4231 dirlen = STRLEN(homedir);
4232
4233#ifdef VMS
4234 homedir_env = mch_getenv((char_u *)"SYS$LOGIN");
4235#else
4236 homedir_env = mch_getenv((char_u *)"HOME");
4237#endif
4238
4239 if (homedir_env != NULL && *homedir_env == NUL)
4240 homedir_env = NULL;
4241 if (homedir_env != NULL)
4242 envlen = STRLEN(homedir_env);
4243
4244 if (!one)
4245 src = skipwhite(src);
4246 while (*src && dstlen > 0)
4247 {
4248 /*
4249 * Here we are at the beginning of a file name.
4250 * First, check to see if the beginning of the file name matches
4251 * $HOME or the "real" home directory. Check that there is a '/'
4252 * after the match (so that if e.g. the file is "/home/pieter/bla",
4253 * and the home directory is "/home/piet", the file does not end up
4254 * as "~er/bla" (which would seem to indicate the file "bla" in user
4255 * er's home directory)).
4256 */
4257 p = homedir;
4258 len = dirlen;
4259 for (;;)
4260 {
4261 if ( len
4262 && fnamencmp(src, p, len) == 0
4263 && (vim_ispathsep(src[len])
4264 || (!one && (src[len] == ',' || src[len] == ' '))
4265 || src[len] == NUL))
4266 {
4267 src += len;
4268 if (--dstlen > 0)
4269 *dst++ = '~';
4270
4271 /*
4272 * If it's just the home directory, add "/".
4273 */
4274 if (!vim_ispathsep(src[0]) && --dstlen > 0)
4275 *dst++ = '/';
4276 break;
4277 }
4278 if (p == homedir_env)
4279 break;
4280 p = homedir_env;
4281 len = envlen;
4282 }
4283
4284 /* if (!one) skip to separator: space or comma */
4285 while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
4286 *dst++ = *src++;
4287 /* skip separator */
4288 while ((*src == ' ' || *src == ',') && --dstlen > 0)
4289 *dst++ = *src++;
4290 }
4291 /* if (dstlen == 0) out of space, what to do??? */
4292
4293 *dst = NUL;
4294}
4295
4296/*
4297 * Like home_replace, store the replaced string in allocated memory.
4298 * When something fails, NULL is returned.
4299 */
4300 char_u *
4301home_replace_save(buf, src)
4302 buf_T *buf; /* when not NULL, check for help files */
4303 char_u *src; /* input file name */
4304{
4305 char_u *dst;
4306 unsigned len;
4307
4308 len = 3; /* space for "~/" and trailing NUL */
4309 if (src != NULL) /* just in case */
4310 len += (unsigned)STRLEN(src);
4311 dst = alloc(len);
4312 if (dst != NULL)
4313 home_replace(buf, src, dst, len, TRUE);
4314 return dst;
4315}
4316
4317/*
4318 * Compare two file names and return:
4319 * FPC_SAME if they both exist and are the same file.
4320 * FPC_SAMEX if they both don't exist and have the same file name.
4321 * FPC_DIFF if they both exist and are different files.
4322 * FPC_NOTX if they both don't exist.
4323 * FPC_DIFFX if one of them doesn't exist.
4324 * For the first name environment variables are expanded
4325 */
4326 int
4327fullpathcmp(s1, s2, checkname)
4328 char_u *s1, *s2;
4329 int checkname; /* when both don't exist, check file names */
4330{
4331#ifdef UNIX
4332 char_u exp1[MAXPATHL];
4333 char_u full1[MAXPATHL];
4334 char_u full2[MAXPATHL];
4335 struct stat st1, st2;
4336 int r1, r2;
4337
4338 expand_env(s1, exp1, MAXPATHL);
4339 r1 = mch_stat((char *)exp1, &st1);
4340 r2 = mch_stat((char *)s2, &st2);
4341 if (r1 != 0 && r2 != 0)
4342 {
4343 /* if mch_stat() doesn't work, may compare the names */
4344 if (checkname)
4345 {
4346 if (fnamecmp(exp1, s2) == 0)
4347 return FPC_SAMEX;
4348 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4349 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4350 if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
4351 return FPC_SAMEX;
4352 }
4353 return FPC_NOTX;
4354 }
4355 if (r1 != 0 || r2 != 0)
4356 return FPC_DIFFX;
4357 if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
4358 return FPC_SAME;
4359 return FPC_DIFF;
4360#else
4361 char_u *exp1; /* expanded s1 */
4362 char_u *full1; /* full path of s1 */
4363 char_u *full2; /* full path of s2 */
4364 int retval = FPC_DIFF;
4365 int r1, r2;
4366
4367 /* allocate one buffer to store three paths (alloc()/free() is slow!) */
4368 if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
4369 {
4370 full1 = exp1 + MAXPATHL;
4371 full2 = full1 + MAXPATHL;
4372
4373 expand_env(s1, exp1, MAXPATHL);
4374 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4375 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4376
4377 /* If vim_FullName() fails, the file probably doesn't exist. */
4378 if (r1 != OK && r2 != OK)
4379 {
4380 if (checkname && fnamecmp(exp1, s2) == 0)
4381 retval = FPC_SAMEX;
4382 else
4383 retval = FPC_NOTX;
4384 }
4385 else if (r1 != OK || r2 != OK)
4386 retval = FPC_DIFFX;
4387 else if (fnamecmp(full1, full2))
4388 retval = FPC_DIFF;
4389 else
4390 retval = FPC_SAME;
4391 vim_free(exp1);
4392 }
4393 return retval;
4394#endif
4395}
4396
4397/*
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004398 * Get the tail of a path: the file name.
4399 * Fail safe: never returns NULL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004400 */
4401 char_u *
4402gettail(fname)
4403 char_u *fname;
4404{
4405 char_u *p1, *p2;
4406
4407 if (fname == NULL)
4408 return (char_u *)"";
4409 for (p1 = p2 = fname; *p2; ) /* find last part of path */
4410 {
4411 if (vim_ispathsep(*p2))
4412 p1 = p2 + 1;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004413 mb_ptr_adv(p2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004414 }
4415 return p1;
4416}
4417
4418/*
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004419 * Get pointer to tail of "fname", including path separators. Putting a NUL
4420 * here leaves the directory name. Takes care of "c:/" and "//".
4421 * Always returns a valid pointer.
4422 */
4423 char_u *
4424gettail_sep(fname)
4425 char_u *fname;
4426{
4427 char_u *p;
4428 char_u *t;
4429
4430 p = get_past_head(fname); /* don't remove the '/' from "c:/file" */
4431 t = gettail(fname);
4432 while (t > p && after_pathsep(fname, t))
4433 --t;
4434#ifdef VMS
4435 /* path separator is part of the path */
4436 ++t;
4437#endif
4438 return t;
4439}
4440
4441/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004442 * get the next path component (just after the next path separator).
4443 */
4444 char_u *
4445getnextcomp(fname)
4446 char_u *fname;
4447{
4448 while (*fname && !vim_ispathsep(*fname))
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004449 mb_ptr_adv(fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004450 if (*fname)
4451 ++fname;
4452 return fname;
4453}
4454
Bram Moolenaar071d4272004-06-13 20:20:40 +00004455/*
4456 * Get a pointer to one character past the head of a path name.
4457 * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
4458 * If there is no head, path is returned.
4459 */
4460 char_u *
4461get_past_head(path)
4462 char_u *path;
4463{
4464 char_u *retval;
4465
4466#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
4467 /* may skip "c:" */
4468 if (isalpha(path[0]) && path[1] == ':')
4469 retval = path + 2;
4470 else
4471 retval = path;
4472#else
4473# if defined(AMIGA)
4474 /* may skip "label:" */
4475 retval = vim_strchr(path, ':');
4476 if (retval == NULL)
4477 retval = path;
4478# else /* Unix */
4479 retval = path;
4480# endif
4481#endif
4482
4483 while (vim_ispathsep(*retval))
4484 ++retval;
4485
4486 return retval;
4487}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004488
4489/*
4490 * return TRUE if 'c' is a path separator.
4491 */
4492 int
4493vim_ispathsep(c)
4494 int c;
4495{
4496#ifdef RISCOS
4497 return (c == '.' || c == ':');
4498#else
4499# ifdef UNIX
4500 return (c == '/'); /* UNIX has ':' inside file names */
4501# else
4502# ifdef BACKSLASH_IN_FILENAME
4503 return (c == ':' || c == '/' || c == '\\');
4504# else
4505# ifdef VMS
4506 /* server"user passwd"::device:[full.path.name]fname.extension;version" */
4507 return (c == ':' || c == '[' || c == ']' || c == '/'
4508 || c == '<' || c == '>' || c == '"' );
Bram Moolenaar1056d982006-03-09 22:37:52 +00004509# else /* Amiga */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004510 return (c == ':' || c == '/');
Bram Moolenaar071d4272004-06-13 20:20:40 +00004511# endif /* VMS */
4512# endif
4513# endif
4514#endif /* RISC OS */
4515}
4516
4517#if defined(FEAT_SEARCHPATH) || defined(PROTO)
4518/*
4519 * return TRUE if 'c' is a path list separator.
4520 */
4521 int
4522vim_ispathlistsep(c)
4523 int c;
4524{
4525#ifdef UNIX
4526 return (c == ':');
4527#else
Bram Moolenaar25394022007-05-10 19:06:20 +00004528 return (c == ';'); /* might not be right for every system... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004529#endif
4530}
4531#endif
4532
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004533#if defined(FEAT_GUI_TABLINE) || defined(FEAT_WINDOWS) \
4534 || defined(FEAT_EVAL) || defined(PROTO)
4535/*
4536 * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
4537 * It's done in-place.
4538 */
4539 void
4540shorten_dir(str)
4541 char_u *str;
4542{
4543 char_u *tail, *s, *d;
4544 int skip = FALSE;
4545
4546 tail = gettail(str);
4547 d = str;
4548 for (s = str; ; ++s)
4549 {
4550 if (s >= tail) /* copy the whole tail */
4551 {
4552 *d++ = *s;
4553 if (*s == NUL)
4554 break;
4555 }
4556 else if (vim_ispathsep(*s)) /* copy '/' and next char */
4557 {
4558 *d++ = *s;
4559 skip = FALSE;
4560 }
4561 else if (!skip)
4562 {
4563 *d++ = *s; /* copy next char */
4564 if (*s != '~' && *s != '.') /* and leading "~" and "." */
4565 skip = TRUE;
4566# ifdef FEAT_MBYTE
4567 if (has_mbyte)
4568 {
4569 int l = mb_ptr2len(s);
4570
4571 while (--l > 0)
Bram Moolenaarb6baca52006-08-15 20:24:14 +00004572 *d++ = *++s;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004573 }
4574# endif
4575 }
4576 }
4577}
4578#endif
4579
Bram Moolenaar900b4d72005-12-12 22:05:50 +00004580/*
4581 * Return TRUE if the directory of "fname" exists, FALSE otherwise.
4582 * Also returns TRUE if there is no directory name.
4583 * "fname" must be writable!.
4584 */
4585 int
4586dir_of_file_exists(fname)
4587 char_u *fname;
4588{
4589 char_u *p;
4590 int c;
4591 int retval;
4592
4593 p = gettail_sep(fname);
4594 if (p == fname)
4595 return TRUE;
4596 c = *p;
4597 *p = NUL;
4598 retval = mch_isdir(fname);
4599 *p = c;
4600 return retval;
4601}
4602
Bram Moolenaar071d4272004-06-13 20:20:40 +00004603#if (defined(CASE_INSENSITIVE_FILENAME) && defined(BACKSLASH_IN_FILENAME)) \
4604 || defined(PROTO)
4605/*
4606 * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally.
4607 */
4608 int
4609vim_fnamecmp(x, y)
4610 char_u *x, *y;
4611{
4612 return vim_fnamencmp(x, y, MAXPATHL);
4613}
4614
4615 int
4616vim_fnamencmp(x, y, len)
4617 char_u *x, *y;
4618 size_t len;
4619{
4620 while (len > 0 && *x && *y)
4621 {
4622 if (TOLOWER_LOC(*x) != TOLOWER_LOC(*y)
4623 && !(*x == '/' && *y == '\\')
4624 && !(*x == '\\' && *y == '/'))
4625 break;
4626 ++x;
4627 ++y;
4628 --len;
4629 }
4630 if (len == 0)
4631 return 0;
4632 return (*x - *y);
4633}
4634#endif
4635
4636/*
4637 * Concatenate file names fname1 and fname2 into allocated memory.
Bram Moolenaar25394022007-05-10 19:06:20 +00004638 * Only add a '/' or '\\' when 'sep' is TRUE and it is necessary.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004639 */
4640 char_u *
4641concat_fnames(fname1, fname2, sep)
4642 char_u *fname1;
4643 char_u *fname2;
4644 int sep;
4645{
4646 char_u *dest;
4647
4648 dest = alloc((unsigned)(STRLEN(fname1) + STRLEN(fname2) + 3));
4649 if (dest != NULL)
4650 {
4651 STRCPY(dest, fname1);
4652 if (sep)
4653 add_pathsep(dest);
4654 STRCAT(dest, fname2);
4655 }
4656 return dest;
4657}
4658
Bram Moolenaard6754642005-01-17 22:18:45 +00004659#if defined(FEAT_EVAL) || defined(FEAT_GETTEXT) || defined(PROTO)
4660/*
4661 * Concatenate two strings and return the result in allocated memory.
4662 * Returns NULL when out of memory.
4663 */
4664 char_u *
4665concat_str(str1, str2)
4666 char_u *str1;
4667 char_u *str2;
4668{
4669 char_u *dest;
4670 size_t l = STRLEN(str1);
4671
4672 dest = alloc((unsigned)(l + STRLEN(str2) + 1L));
4673 if (dest != NULL)
4674 {
4675 STRCPY(dest, str1);
4676 STRCPY(dest + l, str2);
4677 }
4678 return dest;
4679}
4680#endif
4681
Bram Moolenaar071d4272004-06-13 20:20:40 +00004682/*
4683 * Add a path separator to a file name, unless it already ends in a path
4684 * separator.
4685 */
4686 void
4687add_pathsep(p)
4688 char_u *p;
4689{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004690 if (*p != NUL && !after_pathsep(p, p + STRLEN(p)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004691 STRCAT(p, PATHSEPSTR);
4692}
4693
4694/*
4695 * FullName_save - Make an allocated copy of a full file name.
4696 * Returns NULL when out of memory.
4697 */
4698 char_u *
4699FullName_save(fname, force)
4700 char_u *fname;
4701 int force; /* force expansion, even when it already looks
4702 like a full path name */
4703{
4704 char_u *buf;
4705 char_u *new_fname = NULL;
4706
4707 if (fname == NULL)
4708 return NULL;
4709
4710 buf = alloc((unsigned)MAXPATHL);
4711 if (buf != NULL)
4712 {
4713 if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
4714 new_fname = vim_strsave(buf);
4715 else
4716 new_fname = vim_strsave(fname);
4717 vim_free(buf);
4718 }
4719 return new_fname;
4720}
4721
4722#if defined(FEAT_CINDENT) || defined(FEAT_SYN_HL)
4723
4724static char_u *skip_string __ARGS((char_u *p));
4725
4726/*
4727 * Find the start of a comment, not knowing if we are in a comment right now.
4728 * Search starts at w_cursor.lnum and goes backwards.
4729 */
4730 pos_T *
4731find_start_comment(ind_maxcomment) /* XXX */
4732 int ind_maxcomment;
4733{
4734 pos_T *pos;
4735 char_u *line;
4736 char_u *p;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00004737 int cur_maxcomment = ind_maxcomment;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004738
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00004739 for (;;)
4740 {
4741 pos = findmatchlimit(NULL, '*', FM_BACKWARD, cur_maxcomment);
4742 if (pos == NULL)
4743 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004744
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00004745 /*
4746 * Check if the comment start we found is inside a string.
4747 * If it is then restrict the search to below this line and try again.
4748 */
4749 line = ml_get(pos->lnum);
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00004750 for (p = line; *p && (colnr_T)(p - line) < pos->col; ++p)
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00004751 p = skip_string(p);
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00004752 if ((colnr_T)(p - line) <= pos->col)
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00004753 break;
4754 cur_maxcomment = curwin->w_cursor.lnum - pos->lnum - 1;
4755 if (cur_maxcomment <= 0)
4756 {
4757 pos = NULL;
4758 break;
4759 }
4760 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004761 return pos;
4762}
4763
4764/*
4765 * Skip to the end of a "string" and a 'c' character.
4766 * If there is no string or character, return argument unmodified.
4767 */
4768 static char_u *
4769skip_string(p)
4770 char_u *p;
4771{
4772 int i;
4773
4774 /*
4775 * We loop, because strings may be concatenated: "date""time".
4776 */
4777 for ( ; ; ++p)
4778 {
4779 if (p[0] == '\'') /* 'c' or '\n' or '\000' */
4780 {
4781 if (!p[1]) /* ' at end of line */
4782 break;
4783 i = 2;
4784 if (p[1] == '\\') /* '\n' or '\000' */
4785 {
4786 ++i;
4787 while (vim_isdigit(p[i - 1])) /* '\000' */
4788 ++i;
4789 }
4790 if (p[i] == '\'') /* check for trailing ' */
4791 {
4792 p += i;
4793 continue;
4794 }
4795 }
4796 else if (p[0] == '"') /* start of string */
4797 {
4798 for (++p; p[0]; ++p)
4799 {
4800 if (p[0] == '\\' && p[1] != NUL)
4801 ++p;
4802 else if (p[0] == '"') /* end of string */
4803 break;
4804 }
4805 if (p[0] == '"')
4806 continue;
4807 }
4808 break; /* no string found */
4809 }
4810 if (!*p)
4811 --p; /* backup from NUL */
4812 return p;
4813}
4814#endif /* FEAT_CINDENT || FEAT_SYN_HL */
4815
4816#if defined(FEAT_CINDENT) || defined(PROTO)
4817
4818/*
4819 * Do C or expression indenting on the current line.
4820 */
4821 void
4822do_c_expr_indent()
4823{
4824# ifdef FEAT_EVAL
4825 if (*curbuf->b_p_inde != NUL)
4826 fixthisline(get_expr_indent);
4827 else
4828# endif
4829 fixthisline(get_c_indent);
4830}
4831
4832/*
4833 * Functions for C-indenting.
4834 * Most of this originally comes from Eric Fischer.
4835 */
4836/*
4837 * Below "XXX" means that this function may unlock the current line.
4838 */
4839
4840static char_u *cin_skipcomment __ARGS((char_u *));
4841static int cin_nocode __ARGS((char_u *));
4842static pos_T *find_line_comment __ARGS((void));
4843static int cin_islabel_skip __ARGS((char_u **));
4844static int cin_isdefault __ARGS((char_u *));
4845static char_u *after_label __ARGS((char_u *l));
4846static int get_indent_nolabel __ARGS((linenr_T lnum));
4847static int skip_label __ARGS((linenr_T, char_u **pp, int ind_maxcomment));
4848static int cin_first_id_amount __ARGS((void));
4849static int cin_get_equal_amount __ARGS((linenr_T lnum));
4850static int cin_ispreproc __ARGS((char_u *));
4851static int cin_ispreproc_cont __ARGS((char_u **pp, linenr_T *lnump));
4852static int cin_iscomment __ARGS((char_u *));
4853static int cin_islinecomment __ARGS((char_u *));
4854static int cin_isterminated __ARGS((char_u *, int, int));
4855static int cin_isinit __ARGS((void));
4856static int cin_isfuncdecl __ARGS((char_u **, linenr_T));
4857static int cin_isif __ARGS((char_u *));
4858static int cin_iselse __ARGS((char_u *));
4859static int cin_isdo __ARGS((char_u *));
4860static int cin_iswhileofdo __ARGS((char_u *, linenr_T, int));
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00004861static int cin_iswhileofdo_end __ARGS((int terminated, int ind_maxparen, int ind_maxcomment));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004862static int cin_isbreak __ARGS((char_u *));
Bram Moolenaare7c56862007-08-04 10:14:52 +00004863static int cin_is_cpp_baseclass __ARGS((colnr_T *col));
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00004864static int get_baseclass_amount __ARGS((int col, int ind_maxparen, int ind_maxcomment, int ind_cpp_baseclass));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004865static int cin_ends_in __ARGS((char_u *, char_u *, char_u *));
4866static int cin_skip2pos __ARGS((pos_T *trypos));
4867static pos_T *find_start_brace __ARGS((int));
4868static pos_T *find_match_paren __ARGS((int, int));
4869static int corr_ind_maxparen __ARGS((int ind_maxparen, pos_T *startpos));
4870static int find_last_paren __ARGS((char_u *l, int start, int end));
4871static int find_match __ARGS((int lookfor, linenr_T ourscope, int ind_maxparen, int ind_maxcomment));
4872
Bram Moolenaar39353fd2007-03-27 09:02:11 +00004873static int ind_hash_comment = 0; /* # starts a comment */
4874
Bram Moolenaar071d4272004-06-13 20:20:40 +00004875/*
4876 * Skip over white space and C comments within the line.
Bram Moolenaar39353fd2007-03-27 09:02:11 +00004877 * Also skip over Perl/shell comments if desired.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004878 */
4879 static char_u *
4880cin_skipcomment(s)
4881 char_u *s;
4882{
4883 while (*s)
4884 {
Bram Moolenaar39353fd2007-03-27 09:02:11 +00004885 char_u *prev_s = s;
4886
Bram Moolenaar071d4272004-06-13 20:20:40 +00004887 s = skipwhite(s);
Bram Moolenaar39353fd2007-03-27 09:02:11 +00004888
4889 /* Perl/shell # comment comment continues until eol. Require a space
4890 * before # to avoid recognizing $#array. */
4891 if (ind_hash_comment != 0 && s != prev_s && *s == '#')
4892 {
4893 s += STRLEN(s);
4894 break;
4895 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004896 if (*s != '/')
4897 break;
4898 ++s;
4899 if (*s == '/') /* slash-slash comment continues till eol */
4900 {
4901 s += STRLEN(s);
4902 break;
4903 }
4904 if (*s != '*')
4905 break;
4906 for (++s; *s; ++s) /* skip slash-star comment */
4907 if (s[0] == '*' && s[1] == '/')
4908 {
4909 s += 2;
4910 break;
4911 }
4912 }
4913 return s;
4914}
4915
4916/*
4917 * Return TRUE if there there is no code at *s. White space and comments are
4918 * not considered code.
4919 */
4920 static int
4921cin_nocode(s)
4922 char_u *s;
4923{
4924 return *cin_skipcomment(s) == NUL;
4925}
4926
4927/*
4928 * Check previous lines for a "//" line comment, skipping over blank lines.
4929 */
4930 static pos_T *
4931find_line_comment() /* XXX */
4932{
4933 static pos_T pos;
4934 char_u *line;
4935 char_u *p;
4936
4937 pos = curwin->w_cursor;
4938 while (--pos.lnum > 0)
4939 {
4940 line = ml_get(pos.lnum);
4941 p = skipwhite(line);
4942 if (cin_islinecomment(p))
4943 {
4944 pos.col = (int)(p - line);
4945 return &pos;
4946 }
4947 if (*p != NUL)
4948 break;
4949 }
4950 return NULL;
4951}
4952
4953/*
4954 * Check if string matches "label:"; move to character after ':' if true.
4955 */
4956 static int
4957cin_islabel_skip(s)
4958 char_u **s;
4959{
4960 if (!vim_isIDc(**s)) /* need at least one ID character */
4961 return FALSE;
4962
4963 while (vim_isIDc(**s))
4964 (*s)++;
4965
4966 *s = cin_skipcomment(*s);
4967
4968 /* "::" is not a label, it's C++ */
4969 return (**s == ':' && *++*s != ':');
4970}
4971
4972/*
4973 * Recognize a label: "label:".
4974 * Note: curwin->w_cursor must be where we are looking for the label.
4975 */
4976 int
4977cin_islabel(ind_maxcomment) /* XXX */
4978 int ind_maxcomment;
4979{
4980 char_u *s;
4981
4982 s = cin_skipcomment(ml_get_curline());
4983
4984 /*
4985 * Exclude "default" from labels, since it should be indented
4986 * like a switch label. Same for C++ scope declarations.
4987 */
4988 if (cin_isdefault(s))
4989 return FALSE;
4990 if (cin_isscopedecl(s))
4991 return FALSE;
4992
4993 if (cin_islabel_skip(&s))
4994 {
4995 /*
4996 * Only accept a label if the previous line is terminated or is a case
4997 * label.
4998 */
4999 pos_T cursor_save;
5000 pos_T *trypos;
5001 char_u *line;
5002
5003 cursor_save = curwin->w_cursor;
5004 while (curwin->w_cursor.lnum > 1)
5005 {
5006 --curwin->w_cursor.lnum;
5007
5008 /*
5009 * If we're in a comment now, skip to the start of the comment.
5010 */
5011 curwin->w_cursor.col = 0;
5012 if ((trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
5013 curwin->w_cursor = *trypos;
5014
5015 line = ml_get_curline();
5016 if (cin_ispreproc(line)) /* ignore #defines, #if, etc. */
5017 continue;
5018 if (*(line = cin_skipcomment(line)) == NUL)
5019 continue;
5020
5021 curwin->w_cursor = cursor_save;
5022 if (cin_isterminated(line, TRUE, FALSE)
5023 || cin_isscopedecl(line)
5024 || cin_iscase(line)
5025 || (cin_islabel_skip(&line) && cin_nocode(line)))
5026 return TRUE;
5027 return FALSE;
5028 }
5029 curwin->w_cursor = cursor_save;
5030 return TRUE; /* label at start of file??? */
5031 }
5032 return FALSE;
5033}
5034
5035/*
5036 * Recognize structure initialization and enumerations.
5037 * Q&D-Implementation:
5038 * check for "=" at end or "[typedef] enum" at beginning of line.
5039 */
5040 static int
5041cin_isinit(void)
5042{
5043 char_u *s;
5044
5045 s = cin_skipcomment(ml_get_curline());
5046
5047 if (STRNCMP(s, "typedef", 7) == 0 && !vim_isIDc(s[7]))
5048 s = cin_skipcomment(s + 7);
5049
5050 if (STRNCMP(s, "enum", 4) == 0 && !vim_isIDc(s[4]))
5051 return TRUE;
5052
5053 if (cin_ends_in(s, (char_u *)"=", (char_u *)"{"))
5054 return TRUE;
5055
5056 return FALSE;
5057}
5058
5059/*
5060 * Recognize a switch label: "case .*:" or "default:".
5061 */
5062 int
5063cin_iscase(s)
5064 char_u *s;
5065{
5066 s = cin_skipcomment(s);
5067 if (STRNCMP(s, "case", 4) == 0 && !vim_isIDc(s[4]))
5068 {
5069 for (s += 4; *s; ++s)
5070 {
5071 s = cin_skipcomment(s);
5072 if (*s == ':')
5073 {
5074 if (s[1] == ':') /* skip over "::" for C++ */
5075 ++s;
5076 else
5077 return TRUE;
5078 }
5079 if (*s == '\'' && s[1] && s[2] == '\'')
5080 s += 2; /* skip over '.' */
5081 else if (*s == '/' && (s[1] == '*' || s[1] == '/'))
5082 return FALSE; /* stop at comment */
5083 else if (*s == '"')
5084 return FALSE; /* stop at string */
5085 }
5086 return FALSE;
5087 }
5088
5089 if (cin_isdefault(s))
5090 return TRUE;
5091 return FALSE;
5092}
5093
5094/*
5095 * Recognize a "default" switch label.
5096 */
5097 static int
5098cin_isdefault(s)
5099 char_u *s;
5100{
5101 return (STRNCMP(s, "default", 7) == 0
5102 && *(s = cin_skipcomment(s + 7)) == ':'
5103 && s[1] != ':');
5104}
5105
5106/*
5107 * Recognize a "public/private/proctected" scope declaration label.
5108 */
5109 int
5110cin_isscopedecl(s)
5111 char_u *s;
5112{
5113 int i;
5114
5115 s = cin_skipcomment(s);
5116 if (STRNCMP(s, "public", 6) == 0)
5117 i = 6;
5118 else if (STRNCMP(s, "protected", 9) == 0)
5119 i = 9;
5120 else if (STRNCMP(s, "private", 7) == 0)
5121 i = 7;
5122 else
5123 return FALSE;
5124 return (*(s = cin_skipcomment(s + i)) == ':' && s[1] != ':');
5125}
5126
5127/*
5128 * Return a pointer to the first non-empty non-comment character after a ':'.
5129 * Return NULL if not found.
5130 * case 234: a = b;
5131 * ^
5132 */
5133 static char_u *
5134after_label(l)
5135 char_u *l;
5136{
5137 for ( ; *l; ++l)
5138 {
5139 if (*l == ':')
5140 {
5141 if (l[1] == ':') /* skip over "::" for C++ */
5142 ++l;
5143 else if (!cin_iscase(l + 1))
5144 break;
5145 }
5146 else if (*l == '\'' && l[1] && l[2] == '\'')
5147 l += 2; /* skip over 'x' */
5148 }
5149 if (*l == NUL)
5150 return NULL;
5151 l = cin_skipcomment(l + 1);
5152 if (*l == NUL)
5153 return NULL;
5154 return l;
5155}
5156
5157/*
5158 * Get indent of line "lnum", skipping a label.
5159 * Return 0 if there is nothing after the label.
5160 */
5161 static int
5162get_indent_nolabel(lnum) /* XXX */
5163 linenr_T lnum;
5164{
5165 char_u *l;
5166 pos_T fp;
5167 colnr_T col;
5168 char_u *p;
5169
5170 l = ml_get(lnum);
5171 p = after_label(l);
5172 if (p == NULL)
5173 return 0;
5174
5175 fp.col = (colnr_T)(p - l);
5176 fp.lnum = lnum;
5177 getvcol(curwin, &fp, &col, NULL, NULL);
5178 return (int)col;
5179}
5180
5181/*
5182 * Find indent for line "lnum", ignoring any case or jump label.
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005183 * Also return a pointer to the text (after the label) in "pp".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005184 * label: if (asdf && asdfasdf)
5185 * ^
5186 */
5187 static int
5188skip_label(lnum, pp, ind_maxcomment)
5189 linenr_T lnum;
5190 char_u **pp;
5191 int ind_maxcomment;
5192{
5193 char_u *l;
5194 int amount;
5195 pos_T cursor_save;
5196
5197 cursor_save = curwin->w_cursor;
5198 curwin->w_cursor.lnum = lnum;
5199 l = ml_get_curline();
5200 /* XXX */
5201 if (cin_iscase(l) || cin_isscopedecl(l) || cin_islabel(ind_maxcomment))
5202 {
5203 amount = get_indent_nolabel(lnum);
5204 l = after_label(ml_get_curline());
5205 if (l == NULL) /* just in case */
5206 l = ml_get_curline();
5207 }
5208 else
5209 {
5210 amount = get_indent();
5211 l = ml_get_curline();
5212 }
5213 *pp = l;
5214
5215 curwin->w_cursor = cursor_save;
5216 return amount;
5217}
5218
5219/*
5220 * Return the indent of the first variable name after a type in a declaration.
5221 * int a, indent of "a"
5222 * static struct foo b, indent of "b"
5223 * enum bla c, indent of "c"
5224 * Returns zero when it doesn't look like a declaration.
5225 */
5226 static int
5227cin_first_id_amount()
5228{
5229 char_u *line, *p, *s;
5230 int len;
5231 pos_T fp;
5232 colnr_T col;
5233
5234 line = ml_get_curline();
5235 p = skipwhite(line);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005236 len = (int)(skiptowhite(p) - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005237 if (len == 6 && STRNCMP(p, "static", 6) == 0)
5238 {
5239 p = skipwhite(p + 6);
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00005240 len = (int)(skiptowhite(p) - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005241 }
5242 if (len == 6 && STRNCMP(p, "struct", 6) == 0)
5243 p = skipwhite(p + 6);
5244 else if (len == 4 && STRNCMP(p, "enum", 4) == 0)
5245 p = skipwhite(p + 4);
5246 else if ((len == 8 && STRNCMP(p, "unsigned", 8) == 0)
5247 || (len == 6 && STRNCMP(p, "signed", 6) == 0))
5248 {
5249 s = skipwhite(p + len);
5250 if ((STRNCMP(s, "int", 3) == 0 && vim_iswhite(s[3]))
5251 || (STRNCMP(s, "long", 4) == 0 && vim_iswhite(s[4]))
5252 || (STRNCMP(s, "short", 5) == 0 && vim_iswhite(s[5]))
5253 || (STRNCMP(s, "char", 4) == 0 && vim_iswhite(s[4])))
5254 p = s;
5255 }
5256 for (len = 0; vim_isIDc(p[len]); ++len)
5257 ;
5258 if (len == 0 || !vim_iswhite(p[len]) || cin_nocode(p))
5259 return 0;
5260
5261 p = skipwhite(p + len);
5262 fp.lnum = curwin->w_cursor.lnum;
5263 fp.col = (colnr_T)(p - line);
5264 getvcol(curwin, &fp, &col, NULL, NULL);
5265 return (int)col;
5266}
5267
5268/*
5269 * Return the indent of the first non-blank after an equal sign.
5270 * char *foo = "here";
5271 * Return zero if no (useful) equal sign found.
5272 * Return -1 if the line above "lnum" ends in a backslash.
5273 * foo = "asdf\
5274 * asdf\
5275 * here";
5276 */
5277 static int
5278cin_get_equal_amount(lnum)
5279 linenr_T lnum;
5280{
5281 char_u *line;
5282 char_u *s;
5283 colnr_T col;
5284 pos_T fp;
5285
5286 if (lnum > 1)
5287 {
5288 line = ml_get(lnum - 1);
5289 if (*line != NUL && line[STRLEN(line) - 1] == '\\')
5290 return -1;
5291 }
5292
5293 line = s = ml_get(lnum);
5294 while (*s != NUL && vim_strchr((char_u *)"=;{}\"'", *s) == NULL)
5295 {
5296 if (cin_iscomment(s)) /* ignore comments */
5297 s = cin_skipcomment(s);
5298 else
5299 ++s;
5300 }
5301 if (*s != '=')
5302 return 0;
5303
5304 s = skipwhite(s + 1);
5305 if (cin_nocode(s))
5306 return 0;
5307
5308 if (*s == '"') /* nice alignment for continued strings */
5309 ++s;
5310
5311 fp.lnum = lnum;
5312 fp.col = (colnr_T)(s - line);
5313 getvcol(curwin, &fp, &col, NULL, NULL);
5314 return (int)col;
5315}
5316
5317/*
5318 * Recognize a preprocessor statement: Any line that starts with '#'.
5319 */
5320 static int
5321cin_ispreproc(s)
5322 char_u *s;
5323{
5324 s = skipwhite(s);
5325 if (*s == '#')
5326 return TRUE;
5327 return FALSE;
5328}
5329
5330/*
5331 * Return TRUE if line "*pp" at "*lnump" is a preprocessor statement or a
5332 * continuation line of a preprocessor statement. Decrease "*lnump" to the
5333 * start and return the line in "*pp".
5334 */
5335 static int
5336cin_ispreproc_cont(pp, lnump)
5337 char_u **pp;
5338 linenr_T *lnump;
5339{
5340 char_u *line = *pp;
5341 linenr_T lnum = *lnump;
5342 int retval = FALSE;
5343
Bram Moolenaard8e9bb22005-07-09 21:14:46 +00005344 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005345 {
5346 if (cin_ispreproc(line))
5347 {
5348 retval = TRUE;
5349 *lnump = lnum;
5350 break;
5351 }
5352 if (lnum == 1)
5353 break;
5354 line = ml_get(--lnum);
5355 if (*line == NUL || line[STRLEN(line) - 1] != '\\')
5356 break;
5357 }
5358
5359 if (lnum != *lnump)
5360 *pp = ml_get(*lnump);
5361 return retval;
5362}
5363
5364/*
5365 * Recognize the start of a C or C++ comment.
5366 */
5367 static int
5368cin_iscomment(p)
5369 char_u *p;
5370{
5371 return (p[0] == '/' && (p[1] == '*' || p[1] == '/'));
5372}
5373
5374/*
5375 * Recognize the start of a "//" comment.
5376 */
5377 static int
5378cin_islinecomment(p)
5379 char_u *p;
5380{
5381 return (p[0] == '/' && p[1] == '/');
5382}
5383
5384/*
5385 * Recognize a line that starts with '{' or '}', or ends with ';', '{' or '}'.
5386 * Don't consider "} else" a terminated line.
5387 * Return the character terminating the line (ending char's have precedence if
5388 * both apply in order to determine initializations).
5389 */
5390 static int
5391cin_isterminated(s, incl_open, incl_comma)
5392 char_u *s;
5393 int incl_open; /* include '{' at the end as terminator */
5394 int incl_comma; /* recognize a trailing comma */
5395{
5396 char_u found_start = 0;
5397
5398 s = cin_skipcomment(s);
5399
5400 if (*s == '{' || (*s == '}' && !cin_iselse(s)))
5401 found_start = *s;
5402
5403 while (*s)
5404 {
5405 /* skip over comments, "" strings and 'c'haracters */
5406 s = skip_string(cin_skipcomment(s));
5407 if ((*s == ';' || (incl_open && *s == '{') || *s == '}'
5408 || (incl_comma && *s == ','))
5409 && cin_nocode(s + 1))
5410 return *s;
5411
5412 if (*s)
5413 s++;
5414 }
5415 return found_start;
5416}
5417
5418/*
5419 * Recognize the basic picture of a function declaration -- it needs to
5420 * have an open paren somewhere and a close paren at the end of the line and
5421 * no semicolons anywhere.
5422 * When a line ends in a comma we continue looking in the next line.
5423 * "sp" points to a string with the line. When looking at other lines it must
5424 * be restored to the line. When it's NULL fetch lines here.
5425 * "lnum" is where we start looking.
5426 */
5427 static int
5428cin_isfuncdecl(sp, first_lnum)
5429 char_u **sp;
5430 linenr_T first_lnum;
5431{
5432 char_u *s;
5433 linenr_T lnum = first_lnum;
5434 int retval = FALSE;
5435
5436 if (sp == NULL)
5437 s = ml_get(lnum);
5438 else
5439 s = *sp;
5440
5441 while (*s && *s != '(' && *s != ';' && *s != '\'' && *s != '"')
5442 {
5443 if (cin_iscomment(s)) /* ignore comments */
5444 s = cin_skipcomment(s);
5445 else
5446 ++s;
5447 }
5448 if (*s != '(')
5449 return FALSE; /* ';', ' or " before any () or no '(' */
5450
5451 while (*s && *s != ';' && *s != '\'' && *s != '"')
5452 {
5453 if (*s == ')' && cin_nocode(s + 1))
5454 {
5455 /* ')' at the end: may have found a match
5456 * Check for he previous line not to end in a backslash:
5457 * #if defined(x) && \
5458 * defined(y)
5459 */
5460 lnum = first_lnum - 1;
5461 s = ml_get(lnum);
5462 if (*s == NUL || s[STRLEN(s) - 1] != '\\')
5463 retval = TRUE;
5464 goto done;
5465 }
5466 if (*s == ',' && cin_nocode(s + 1))
5467 {
5468 /* ',' at the end: continue looking in the next line */
5469 if (lnum >= curbuf->b_ml.ml_line_count)
5470 break;
5471
5472 s = ml_get(++lnum);
5473 }
5474 else if (cin_iscomment(s)) /* ignore comments */
5475 s = cin_skipcomment(s);
5476 else
5477 ++s;
5478 }
5479
5480done:
5481 if (lnum != first_lnum && sp != NULL)
5482 *sp = ml_get(first_lnum);
5483
5484 return retval;
5485}
5486
5487 static int
5488cin_isif(p)
5489 char_u *p;
5490{
5491 return (STRNCMP(p, "if", 2) == 0 && !vim_isIDc(p[2]));
5492}
5493
5494 static int
5495cin_iselse(p)
5496 char_u *p;
5497{
5498 if (*p == '}') /* accept "} else" */
5499 p = cin_skipcomment(p + 1);
5500 return (STRNCMP(p, "else", 4) == 0 && !vim_isIDc(p[4]));
5501}
5502
5503 static int
5504cin_isdo(p)
5505 char_u *p;
5506{
5507 return (STRNCMP(p, "do", 2) == 0 && !vim_isIDc(p[2]));
5508}
5509
5510/*
5511 * Check if this is a "while" that should have a matching "do".
5512 * We only accept a "while (condition) ;", with only white space between the
5513 * ')' and ';'. The condition may be spread over several lines.
5514 */
5515 static int
5516cin_iswhileofdo(p, lnum, ind_maxparen) /* XXX */
5517 char_u *p;
5518 linenr_T lnum;
5519 int ind_maxparen;
5520{
5521 pos_T cursor_save;
5522 pos_T *trypos;
5523 int retval = FALSE;
5524
5525 p = cin_skipcomment(p);
5526 if (*p == '}') /* accept "} while (cond);" */
5527 p = cin_skipcomment(p + 1);
5528 if (STRNCMP(p, "while", 5) == 0 && !vim_isIDc(p[5]))
5529 {
5530 cursor_save = curwin->w_cursor;
5531 curwin->w_cursor.lnum = lnum;
5532 curwin->w_cursor.col = 0;
5533 p = ml_get_curline();
5534 while (*p && *p != 'w') /* skip any '}', until the 'w' of the "while" */
5535 {
5536 ++p;
5537 ++curwin->w_cursor.col;
5538 }
5539 if ((trypos = findmatchlimit(NULL, 0, 0, ind_maxparen)) != NULL
5540 && *cin_skipcomment(ml_get_pos(trypos) + 1) == ';')
5541 retval = TRUE;
5542 curwin->w_cursor = cursor_save;
5543 }
5544 return retval;
5545}
5546
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005547/*
5548 * Return TRUE if we are at the end of a do-while.
5549 * do
5550 * nothing;
5551 * while (foo
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00005552 * && bar); <-- here
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005553 * Adjust the cursor to the line with "while".
5554 */
5555 static int
5556cin_iswhileofdo_end(terminated, ind_maxparen, ind_maxcomment)
5557 int terminated;
5558 int ind_maxparen;
5559 int ind_maxcomment;
5560{
5561 char_u *line;
5562 char_u *p;
5563 char_u *s;
5564 pos_T *trypos;
5565 int i;
5566
5567 if (terminated != ';') /* there must be a ';' at the end */
5568 return FALSE;
5569
5570 p = line = ml_get_curline();
5571 while (*p != NUL)
5572 {
5573 p = cin_skipcomment(p);
5574 if (*p == ')')
5575 {
5576 s = skipwhite(p + 1);
5577 if (*s == ';' && cin_nocode(s + 1))
5578 {
5579 /* Found ");" at end of the line, now check there is "while"
5580 * before the matching '('. XXX */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005581 i = (int)(p - line);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005582 curwin->w_cursor.col = i;
5583 trypos = find_match_paren(ind_maxparen, ind_maxcomment);
5584 if (trypos != NULL)
5585 {
5586 s = cin_skipcomment(ml_get(trypos->lnum));
5587 if (*s == '}') /* accept "} while (cond);" */
5588 s = cin_skipcomment(s + 1);
5589 if (STRNCMP(s, "while", 5) == 0 && !vim_isIDc(s[5]))
5590 {
5591 curwin->w_cursor.lnum = trypos->lnum;
5592 return TRUE;
5593 }
5594 }
5595
5596 /* Searching may have made "line" invalid, get it again. */
5597 line = ml_get_curline();
5598 p = line + i;
5599 }
5600 }
5601 if (*p != NUL)
5602 ++p;
5603 }
5604 return FALSE;
5605}
5606
Bram Moolenaar071d4272004-06-13 20:20:40 +00005607 static int
5608cin_isbreak(p)
5609 char_u *p;
5610{
5611 return (STRNCMP(p, "break", 5) == 0 && !vim_isIDc(p[5]));
5612}
5613
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005614/*
5615 * Find the position of a C++ base-class declaration or
Bram Moolenaar071d4272004-06-13 20:20:40 +00005616 * constructor-initialization. eg:
5617 *
5618 * class MyClass :
5619 * baseClass <-- here
5620 * class MyClass : public baseClass,
5621 * anotherBaseClass <-- here (should probably lineup ??)
5622 * MyClass::MyClass(...) :
5623 * baseClass(...) <-- here (constructor-initialization)
Bram Moolenaar18144c82006-04-12 21:52:12 +00005624 *
5625 * This is a lot of guessing. Watch out for "cond ? func() : foo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005626 */
5627 static int
Bram Moolenaare7c56862007-08-04 10:14:52 +00005628cin_is_cpp_baseclass(col)
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005629 colnr_T *col; /* return: column to align with */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005630{
5631 char_u *s;
5632 int class_or_struct, lookfor_ctor_init, cpp_base_class;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005633 linenr_T lnum = curwin->w_cursor.lnum;
Bram Moolenaare7c56862007-08-04 10:14:52 +00005634 char_u *line = ml_get_curline();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005635
5636 *col = 0;
5637
Bram Moolenaar21cf8232004-07-16 20:18:37 +00005638 s = skipwhite(line);
5639 if (*s == '#') /* skip #define FOO x ? (x) : x */
5640 return FALSE;
5641 s = cin_skipcomment(s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005642 if (*s == NUL)
5643 return FALSE;
5644
5645 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
5646
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005647 /* Search for a line starting with '#', empty, ending in ';' or containing
5648 * '{' or '}' and start below it. This handles the following situations:
5649 * a = cond ?
5650 * func() :
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00005651 * asdf;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005652 * func::foo()
5653 * : something
5654 * {}
5655 * Foo::Foo (int one, int two)
5656 * : something(4),
5657 * somethingelse(3)
5658 * {}
5659 */
5660 while (lnum > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005661 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00005662 line = ml_get(lnum - 1);
5663 s = skipwhite(line);
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005664 if (*s == '#' || *s == NUL)
5665 break;
5666 while (*s != NUL)
5667 {
5668 s = cin_skipcomment(s);
5669 if (*s == '{' || *s == '}'
5670 || (*s == ';' && cin_nocode(s + 1)))
5671 break;
5672 if (*s != NUL)
5673 ++s;
5674 }
5675 if (*s != NUL)
5676 break;
5677 --lnum;
5678 }
5679
Bram Moolenaare7c56862007-08-04 10:14:52 +00005680 line = ml_get(lnum);
5681 s = cin_skipcomment(line);
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005682 for (;;)
5683 {
5684 if (*s == NUL)
5685 {
5686 if (lnum == curwin->w_cursor.lnum)
5687 break;
5688 /* Continue in the cursor line. */
Bram Moolenaare7c56862007-08-04 10:14:52 +00005689 line = ml_get(++lnum);
5690 s = cin_skipcomment(line);
5691 if (*s == NUL)
5692 continue;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005693 }
5694
Bram Moolenaar071d4272004-06-13 20:20:40 +00005695 if (s[0] == ':')
5696 {
5697 if (s[1] == ':')
5698 {
5699 /* skip double colon. It can't be a constructor
5700 * initialization any more */
5701 lookfor_ctor_init = FALSE;
5702 s = cin_skipcomment(s + 2);
5703 }
5704 else if (lookfor_ctor_init || class_or_struct)
5705 {
5706 /* we have something found, that looks like the start of
Bram Moolenaare21877a2008-02-13 09:58:14 +00005707 * cpp-base-class-declaration or constructor-initialization */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005708 cpp_base_class = TRUE;
5709 lookfor_ctor_init = class_or_struct = FALSE;
5710 *col = 0;
5711 s = cin_skipcomment(s + 1);
5712 }
5713 else
5714 s = cin_skipcomment(s + 1);
5715 }
5716 else if ((STRNCMP(s, "class", 5) == 0 && !vim_isIDc(s[5]))
5717 || (STRNCMP(s, "struct", 6) == 0 && !vim_isIDc(s[6])))
5718 {
5719 class_or_struct = TRUE;
5720 lookfor_ctor_init = FALSE;
5721
5722 if (*s == 'c')
5723 s = cin_skipcomment(s + 5);
5724 else
5725 s = cin_skipcomment(s + 6);
5726 }
5727 else
5728 {
5729 if (s[0] == '{' || s[0] == '}' || s[0] == ';')
5730 {
5731 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
5732 }
5733 else if (s[0] == ')')
5734 {
5735 /* Constructor-initialization is assumed if we come across
5736 * something like "):" */
5737 class_or_struct = FALSE;
5738 lookfor_ctor_init = TRUE;
5739 }
Bram Moolenaar18144c82006-04-12 21:52:12 +00005740 else if (s[0] == '?')
5741 {
5742 /* Avoid seeing '() :' after '?' as constructor init. */
5743 return FALSE;
5744 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005745 else if (!vim_isIDc(s[0]))
5746 {
5747 /* if it is not an identifier, we are wrong */
5748 class_or_struct = FALSE;
5749 lookfor_ctor_init = FALSE;
5750 }
5751 else if (*col == 0)
5752 {
5753 /* it can't be a constructor-initialization any more */
5754 lookfor_ctor_init = FALSE;
5755
5756 /* the first statement starts here: lineup with this one... */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005757 if (cpp_base_class)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005758 *col = (colnr_T)(s - line);
5759 }
5760
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005761 /* When the line ends in a comma don't align with it. */
5762 if (lnum == curwin->w_cursor.lnum && *s == ',' && cin_nocode(s + 1))
5763 *col = 0;
5764
Bram Moolenaar071d4272004-06-13 20:20:40 +00005765 s = cin_skipcomment(s + 1);
5766 }
5767 }
5768
5769 return cpp_base_class;
5770}
5771
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005772 static int
5773get_baseclass_amount(col, ind_maxparen, ind_maxcomment, ind_cpp_baseclass)
5774 int col;
5775 int ind_maxparen;
5776 int ind_maxcomment;
5777 int ind_cpp_baseclass;
5778{
5779 int amount;
5780 colnr_T vcol;
5781 pos_T *trypos;
5782
5783 if (col == 0)
5784 {
5785 amount = get_indent();
5786 if (find_last_paren(ml_get_curline(), '(', ')')
5787 && (trypos = find_match_paren(ind_maxparen,
5788 ind_maxcomment)) != NULL)
5789 amount = get_indent_lnum(trypos->lnum); /* XXX */
5790 if (!cin_ends_in(ml_get_curline(), (char_u *)",", NULL))
5791 amount += ind_cpp_baseclass;
5792 }
5793 else
5794 {
5795 curwin->w_cursor.col = col;
5796 getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
5797 amount = (int)vcol;
5798 }
5799 if (amount < ind_cpp_baseclass)
5800 amount = ind_cpp_baseclass;
5801 return amount;
5802}
5803
Bram Moolenaar071d4272004-06-13 20:20:40 +00005804/*
5805 * Return TRUE if string "s" ends with the string "find", possibly followed by
5806 * white space and comments. Skip strings and comments.
5807 * Ignore "ignore" after "find" if it's not NULL.
5808 */
5809 static int
5810cin_ends_in(s, find, ignore)
5811 char_u *s;
5812 char_u *find;
5813 char_u *ignore;
5814{
5815 char_u *p = s;
5816 char_u *r;
5817 int len = (int)STRLEN(find);
5818
5819 while (*p != NUL)
5820 {
5821 p = cin_skipcomment(p);
5822 if (STRNCMP(p, find, len) == 0)
5823 {
5824 r = skipwhite(p + len);
5825 if (ignore != NULL && STRNCMP(r, ignore, STRLEN(ignore)) == 0)
5826 r = skipwhite(r + STRLEN(ignore));
5827 if (cin_nocode(r))
5828 return TRUE;
5829 }
5830 if (*p != NUL)
5831 ++p;
5832 }
5833 return FALSE;
5834}
5835
5836/*
5837 * Skip strings, chars and comments until at or past "trypos".
5838 * Return the column found.
5839 */
5840 static int
5841cin_skip2pos(trypos)
5842 pos_T *trypos;
5843{
5844 char_u *line;
5845 char_u *p;
5846
5847 p = line = ml_get(trypos->lnum);
5848 while (*p && (colnr_T)(p - line) < trypos->col)
5849 {
5850 if (cin_iscomment(p))
5851 p = cin_skipcomment(p);
5852 else
5853 {
5854 p = skip_string(p);
5855 ++p;
5856 }
5857 }
5858 return (int)(p - line);
5859}
5860
5861/*
5862 * Find the '{' at the start of the block we are in.
5863 * Return NULL if no match found.
5864 * Ignore a '{' that is in a comment, makes indenting the next three lines
5865 * work. */
5866/* foo() */
5867/* { */
5868/* } */
5869
5870 static pos_T *
5871find_start_brace(ind_maxcomment) /* XXX */
5872 int ind_maxcomment;
5873{
5874 pos_T cursor_save;
5875 pos_T *trypos;
5876 pos_T *pos;
5877 static pos_T pos_copy;
5878
5879 cursor_save = curwin->w_cursor;
5880 while ((trypos = findmatchlimit(NULL, '{', FM_BLOCKSTOP, 0)) != NULL)
5881 {
5882 pos_copy = *trypos; /* copy pos_T, next findmatch will change it */
5883 trypos = &pos_copy;
5884 curwin->w_cursor = *trypos;
5885 pos = NULL;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005886 /* ignore the { if it's in a // or / * * / comment */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005887 if ((colnr_T)cin_skip2pos(trypos) == trypos->col
5888 && (pos = find_start_comment(ind_maxcomment)) == NULL) /* XXX */
5889 break;
5890 if (pos != NULL)
5891 curwin->w_cursor.lnum = pos->lnum;
5892 }
5893 curwin->w_cursor = cursor_save;
5894 return trypos;
5895}
5896
5897/*
5898 * Find the matching '(', failing if it is in a comment.
5899 * Return NULL of no match found.
5900 */
5901 static pos_T *
5902find_match_paren(ind_maxparen, ind_maxcomment) /* XXX */
5903 int ind_maxparen;
5904 int ind_maxcomment;
5905{
5906 pos_T cursor_save;
5907 pos_T *trypos;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005908 static pos_T pos_copy;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005909
5910 cursor_save = curwin->w_cursor;
5911 if ((trypos = findmatchlimit(NULL, '(', 0, ind_maxparen)) != NULL)
5912 {
5913 /* check if the ( is in a // comment */
5914 if ((colnr_T)cin_skip2pos(trypos) > trypos->col)
5915 trypos = NULL;
5916 else
5917 {
5918 pos_copy = *trypos; /* copy trypos, findmatch will change it */
5919 trypos = &pos_copy;
5920 curwin->w_cursor = *trypos;
5921 if (find_start_comment(ind_maxcomment) != NULL) /* XXX */
5922 trypos = NULL;
5923 }
5924 }
5925 curwin->w_cursor = cursor_save;
5926 return trypos;
5927}
5928
5929/*
5930 * Return ind_maxparen corrected for the difference in line number between the
5931 * cursor position and "startpos". This makes sure that searching for a
5932 * matching paren above the cursor line doesn't find a match because of
5933 * looking a few lines further.
5934 */
5935 static int
5936corr_ind_maxparen(ind_maxparen, startpos)
5937 int ind_maxparen;
5938 pos_T *startpos;
5939{
5940 long n = (long)startpos->lnum - (long)curwin->w_cursor.lnum;
5941
5942 if (n > 0 && n < ind_maxparen / 2)
5943 return ind_maxparen - (int)n;
5944 return ind_maxparen;
5945}
5946
5947/*
5948 * Set w_cursor.col to the column number of the last unmatched ')' or '{' in
5949 * line "l".
5950 */
5951 static int
5952find_last_paren(l, start, end)
5953 char_u *l;
5954 int start, end;
5955{
5956 int i;
5957 int retval = FALSE;
5958 int open_count = 0;
5959
5960 curwin->w_cursor.col = 0; /* default is start of line */
5961
5962 for (i = 0; l[i]; i++)
5963 {
5964 i = (int)(cin_skipcomment(l + i) - l); /* ignore parens in comments */
5965 i = (int)(skip_string(l + i) - l); /* ignore parens in quotes */
5966 if (l[i] == start)
5967 ++open_count;
5968 else if (l[i] == end)
5969 {
5970 if (open_count > 0)
5971 --open_count;
5972 else
5973 {
5974 curwin->w_cursor.col = i;
5975 retval = TRUE;
5976 }
5977 }
5978 }
5979 return retval;
5980}
5981
5982 int
5983get_c_indent()
5984{
5985 /*
5986 * spaces from a block's opening brace the prevailing indent for that
5987 * block should be
5988 */
5989 int ind_level = curbuf->b_p_sw;
5990
5991 /*
5992 * spaces from the edge of the line an open brace that's at the end of a
5993 * line is imagined to be.
5994 */
5995 int ind_open_imag = 0;
5996
5997 /*
5998 * spaces from the prevailing indent for a line that is not precededof by
5999 * an opening brace.
6000 */
6001 int ind_no_brace = 0;
6002
6003 /*
6004 * column where the first { of a function should be located }
6005 */
6006 int ind_first_open = 0;
6007
6008 /*
6009 * spaces from the prevailing indent a leftmost open brace should be
6010 * located
6011 */
6012 int ind_open_extra = 0;
6013
6014 /*
6015 * spaces from the matching open brace (real location for one at the left
6016 * edge; imaginary location from one that ends a line) the matching close
6017 * brace should be located
6018 */
6019 int ind_close_extra = 0;
6020
6021 /*
6022 * spaces from the edge of the line an open brace sitting in the leftmost
6023 * column is imagined to be
6024 */
6025 int ind_open_left_imag = 0;
6026
6027 /*
6028 * spaces from the switch() indent a "case xx" label should be located
6029 */
6030 int ind_case = curbuf->b_p_sw;
6031
6032 /*
6033 * spaces from the "case xx:" code after a switch() should be located
6034 */
6035 int ind_case_code = curbuf->b_p_sw;
6036
6037 /*
6038 * lineup break at end of case in switch() with case label
6039 */
6040 int ind_case_break = 0;
6041
6042 /*
6043 * spaces from the class declaration indent a scope declaration label
6044 * should be located
6045 */
6046 int ind_scopedecl = curbuf->b_p_sw;
6047
6048 /*
6049 * spaces from the scope declaration label code should be located
6050 */
6051 int ind_scopedecl_code = curbuf->b_p_sw;
6052
6053 /*
6054 * amount K&R-style parameters should be indented
6055 */
6056 int ind_param = curbuf->b_p_sw;
6057
6058 /*
6059 * amount a function type spec should be indented
6060 */
6061 int ind_func_type = curbuf->b_p_sw;
6062
6063 /*
6064 * amount a cpp base class declaration or constructor initialization
6065 * should be indented
6066 */
6067 int ind_cpp_baseclass = curbuf->b_p_sw;
6068
6069 /*
6070 * additional spaces beyond the prevailing indent a continuation line
6071 * should be located
6072 */
6073 int ind_continuation = curbuf->b_p_sw;
6074
6075 /*
6076 * spaces from the indent of the line with an unclosed parentheses
6077 */
6078 int ind_unclosed = curbuf->b_p_sw * 2;
6079
6080 /*
6081 * spaces from the indent of the line with an unclosed parentheses, which
6082 * itself is also unclosed
6083 */
6084 int ind_unclosed2 = curbuf->b_p_sw;
6085
6086 /*
6087 * suppress ignoring spaces from the indent of a line starting with an
6088 * unclosed parentheses.
6089 */
6090 int ind_unclosed_noignore = 0;
6091
6092 /*
6093 * If the opening paren is the last nonwhite character on the line, and
6094 * ind_unclosed_wrapped is nonzero, use this indent relative to the outer
6095 * context (for very long lines).
6096 */
6097 int ind_unclosed_wrapped = 0;
6098
6099 /*
6100 * suppress ignoring white space when lining up with the character after
6101 * an unclosed parentheses.
6102 */
6103 int ind_unclosed_whiteok = 0;
6104
6105 /*
6106 * indent a closing parentheses under the line start of the matching
6107 * opening parentheses.
6108 */
6109 int ind_matching_paren = 0;
6110
6111 /*
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006112 * indent a closing parentheses under the previous line.
6113 */
6114 int ind_paren_prev = 0;
6115
6116 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006117 * Extra indent for comments.
6118 */
6119 int ind_comment = 0;
6120
6121 /*
6122 * spaces from the comment opener when there is nothing after it.
6123 */
6124 int ind_in_comment = 3;
6125
6126 /*
6127 * boolean: if non-zero, use ind_in_comment even if there is something
6128 * after the comment opener.
6129 */
6130 int ind_in_comment2 = 0;
6131
6132 /*
6133 * max lines to search for an open paren
6134 */
6135 int ind_maxparen = 20;
6136
6137 /*
6138 * max lines to search for an open comment
6139 */
6140 int ind_maxcomment = 70;
6141
6142 /*
6143 * handle braces for java code
6144 */
6145 int ind_java = 0;
6146
6147 /*
6148 * handle blocked cases correctly
6149 */
6150 int ind_keep_case_label = 0;
6151
6152 pos_T cur_curpos;
6153 int amount;
6154 int scope_amount;
Bram Moolenaarb21e5842006-04-16 18:30:08 +00006155 int cur_amount = MAXCOL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006156 colnr_T col;
6157 char_u *theline;
6158 char_u *linecopy;
6159 pos_T *trypos;
6160 pos_T *tryposBrace = NULL;
6161 pos_T our_paren_pos;
6162 char_u *start;
6163 int start_brace;
Bram Moolenaare21877a2008-02-13 09:58:14 +00006164#define BRACE_IN_COL0 1 /* '{' is in column 0 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006165#define BRACE_AT_START 2 /* '{' is at start of line */
6166#define BRACE_AT_END 3 /* '{' is at end of line */
6167 linenr_T ourscope;
6168 char_u *l;
6169 char_u *look;
6170 char_u terminated;
6171 int lookfor;
6172#define LOOKFOR_INITIAL 0
6173#define LOOKFOR_IF 1
6174#define LOOKFOR_DO 2
6175#define LOOKFOR_CASE 3
6176#define LOOKFOR_ANY 4
6177#define LOOKFOR_TERM 5
6178#define LOOKFOR_UNTERM 6
6179#define LOOKFOR_SCOPEDECL 7
6180#define LOOKFOR_NOBREAK 8
6181#define LOOKFOR_CPP_BASECLASS 9
6182#define LOOKFOR_ENUM_OR_INIT 10
6183
6184 int whilelevel;
6185 linenr_T lnum;
6186 char_u *options;
6187 int fraction = 0; /* init for GCC */
6188 int divider;
6189 int n;
6190 int iscase;
6191 int lookfor_break;
6192 int cont_amount = 0; /* amount for continuation line */
6193
6194 for (options = curbuf->b_p_cino; *options; )
6195 {
6196 l = options++;
6197 if (*options == '-')
6198 ++options;
6199 n = getdigits(&options);
6200 divider = 0;
6201 if (*options == '.') /* ".5s" means a fraction */
6202 {
6203 fraction = atol((char *)++options);
6204 while (VIM_ISDIGIT(*options))
6205 {
6206 ++options;
6207 if (divider)
6208 divider *= 10;
6209 else
6210 divider = 10;
6211 }
6212 }
6213 if (*options == 's') /* "2s" means two times 'shiftwidth' */
6214 {
6215 if (n == 0 && fraction == 0)
6216 n = curbuf->b_p_sw; /* just "s" is one 'shiftwidth' */
6217 else
6218 {
6219 n *= curbuf->b_p_sw;
6220 if (divider)
6221 n += (curbuf->b_p_sw * fraction + divider / 2) / divider;
6222 }
6223 ++options;
6224 }
6225 if (l[1] == '-')
6226 n = -n;
6227 /* When adding an entry here, also update the default 'cinoptions' in
Bram Moolenaar39353fd2007-03-27 09:02:11 +00006228 * doc/indent.txt, and add explanation for it! */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006229 switch (*l)
6230 {
6231 case '>': ind_level = n; break;
6232 case 'e': ind_open_imag = n; break;
6233 case 'n': ind_no_brace = n; break;
6234 case 'f': ind_first_open = n; break;
6235 case '{': ind_open_extra = n; break;
6236 case '}': ind_close_extra = n; break;
6237 case '^': ind_open_left_imag = n; break;
6238 case ':': ind_case = n; break;
6239 case '=': ind_case_code = n; break;
6240 case 'b': ind_case_break = n; break;
6241 case 'p': ind_param = n; break;
6242 case 't': ind_func_type = n; break;
6243 case '/': ind_comment = n; break;
6244 case 'c': ind_in_comment = n; break;
6245 case 'C': ind_in_comment2 = n; break;
6246 case 'i': ind_cpp_baseclass = n; break;
6247 case '+': ind_continuation = n; break;
6248 case '(': ind_unclosed = n; break;
6249 case 'u': ind_unclosed2 = n; break;
6250 case 'U': ind_unclosed_noignore = n; break;
6251 case 'W': ind_unclosed_wrapped = n; break;
6252 case 'w': ind_unclosed_whiteok = n; break;
6253 case 'm': ind_matching_paren = n; break;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006254 case 'M': ind_paren_prev = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006255 case ')': ind_maxparen = n; break;
6256 case '*': ind_maxcomment = n; break;
6257 case 'g': ind_scopedecl = n; break;
6258 case 'h': ind_scopedecl_code = n; break;
6259 case 'j': ind_java = n; break;
6260 case 'l': ind_keep_case_label = n; break;
Bram Moolenaar39353fd2007-03-27 09:02:11 +00006261 case '#': ind_hash_comment = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006262 }
6263 }
6264
6265 /* remember where the cursor was when we started */
6266 cur_curpos = curwin->w_cursor;
6267
6268 /* Get a copy of the current contents of the line.
6269 * This is required, because only the most recent line obtained with
6270 * ml_get is valid! */
6271 linecopy = vim_strsave(ml_get(cur_curpos.lnum));
6272 if (linecopy == NULL)
6273 return 0;
6274
6275 /*
6276 * In insert mode and the cursor is on a ')' truncate the line at the
6277 * cursor position. We don't want to line up with the matching '(' when
6278 * inserting new stuff.
6279 * For unknown reasons the cursor might be past the end of the line, thus
6280 * check for that.
6281 */
6282 if ((State & INSERT)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006283 && curwin->w_cursor.col < (colnr_T)STRLEN(linecopy)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006284 && linecopy[curwin->w_cursor.col] == ')')
6285 linecopy[curwin->w_cursor.col] = NUL;
6286
6287 theline = skipwhite(linecopy);
6288
6289 /* move the cursor to the start of the line */
6290
6291 curwin->w_cursor.col = 0;
6292
6293 /*
6294 * #defines and so on always go at the left when included in 'cinkeys'.
6295 */
6296 if (*theline == '#' && (*linecopy == '#' || in_cinkeys('#', ' ', TRUE)))
6297 {
6298 amount = 0;
6299 }
6300
6301 /*
6302 * Is it a non-case label? Then that goes at the left margin too.
6303 */
6304 else if (cin_islabel(ind_maxcomment)) /* XXX */
6305 {
6306 amount = 0;
6307 }
6308
6309 /*
6310 * If we're inside a "//" comment and there is a "//" comment in a
6311 * previous line, lineup with that one.
6312 */
6313 else if (cin_islinecomment(theline)
6314 && (trypos = find_line_comment()) != NULL) /* XXX */
6315 {
6316 /* find how indented the line beginning the comment is */
6317 getvcol(curwin, trypos, &col, NULL, NULL);
6318 amount = col;
6319 }
6320
6321 /*
6322 * If we're inside a comment and not looking at the start of the
6323 * comment, try using the 'comments' option.
6324 */
6325 else if (!cin_iscomment(theline)
6326 && (trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
6327 {
6328 int lead_start_len = 2;
6329 int lead_middle_len = 1;
6330 char_u lead_start[COM_MAX_LEN]; /* start-comment string */
6331 char_u lead_middle[COM_MAX_LEN]; /* middle-comment string */
6332 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
6333 char_u *p;
6334 int start_align = 0;
6335 int start_off = 0;
6336 int done = FALSE;
6337
6338 /* find how indented the line beginning the comment is */
6339 getvcol(curwin, trypos, &col, NULL, NULL);
6340 amount = col;
6341
6342 p = curbuf->b_p_com;
6343 while (*p != NUL)
6344 {
6345 int align = 0;
6346 int off = 0;
6347 int what = 0;
6348
6349 while (*p != NUL && *p != ':')
6350 {
6351 if (*p == COM_START || *p == COM_END || *p == COM_MIDDLE)
6352 what = *p++;
6353 else if (*p == COM_LEFT || *p == COM_RIGHT)
6354 align = *p++;
6355 else if (VIM_ISDIGIT(*p) || *p == '-')
6356 off = getdigits(&p);
6357 else
6358 ++p;
6359 }
6360
6361 if (*p == ':')
6362 ++p;
6363 (void)copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
6364 if (what == COM_START)
6365 {
6366 STRCPY(lead_start, lead_end);
6367 lead_start_len = (int)STRLEN(lead_start);
6368 start_off = off;
6369 start_align = align;
6370 }
6371 else if (what == COM_MIDDLE)
6372 {
6373 STRCPY(lead_middle, lead_end);
6374 lead_middle_len = (int)STRLEN(lead_middle);
6375 }
6376 else if (what == COM_END)
6377 {
6378 /* If our line starts with the middle comment string, line it
6379 * up with the comment opener per the 'comments' option. */
6380 if (STRNCMP(theline, lead_middle, lead_middle_len) == 0
6381 && STRNCMP(theline, lead_end, STRLEN(lead_end)) != 0)
6382 {
6383 done = TRUE;
6384 if (curwin->w_cursor.lnum > 1)
6385 {
6386 /* If the start comment string matches in the previous
Bram Moolenaare21877a2008-02-13 09:58:14 +00006387 * line, use the indent of that line plus offset. If
Bram Moolenaar071d4272004-06-13 20:20:40 +00006388 * the middle comment string matches in the previous
6389 * line, use the indent of that line. XXX */
6390 look = skipwhite(ml_get(curwin->w_cursor.lnum - 1));
6391 if (STRNCMP(look, lead_start, lead_start_len) == 0)
6392 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6393 else if (STRNCMP(look, lead_middle,
6394 lead_middle_len) == 0)
6395 {
6396 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6397 break;
6398 }
6399 /* If the start comment string doesn't match with the
6400 * start of the comment, skip this entry. XXX */
6401 else if (STRNCMP(ml_get(trypos->lnum) + trypos->col,
6402 lead_start, lead_start_len) != 0)
6403 continue;
6404 }
6405 if (start_off != 0)
6406 amount += start_off;
6407 else if (start_align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006408 amount += vim_strsize(lead_start)
6409 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006410 break;
6411 }
6412
6413 /* If our line starts with the end comment string, line it up
6414 * with the middle comment */
6415 if (STRNCMP(theline, lead_middle, lead_middle_len) != 0
6416 && STRNCMP(theline, lead_end, STRLEN(lead_end)) == 0)
6417 {
6418 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6419 /* XXX */
6420 if (off != 0)
6421 amount += off;
6422 else if (align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006423 amount += vim_strsize(lead_start)
6424 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006425 done = TRUE;
6426 break;
6427 }
6428 }
6429 }
6430
6431 /* If our line starts with an asterisk, line up with the
6432 * asterisk in the comment opener; otherwise, line up
6433 * with the first character of the comment text.
6434 */
6435 if (done)
6436 ;
6437 else if (theline[0] == '*')
6438 amount += 1;
6439 else
6440 {
6441 /*
6442 * If we are more than one line away from the comment opener, take
6443 * the indent of the previous non-empty line. If 'cino' has "CO"
6444 * and we are just below the comment opener and there are any
6445 * white characters after it line up with the text after it;
6446 * otherwise, add the amount specified by "c" in 'cino'
6447 */
6448 amount = -1;
6449 for (lnum = cur_curpos.lnum - 1; lnum > trypos->lnum; --lnum)
6450 {
6451 if (linewhite(lnum)) /* skip blank lines */
6452 continue;
6453 amount = get_indent_lnum(lnum); /* XXX */
6454 break;
6455 }
6456 if (amount == -1) /* use the comment opener */
6457 {
6458 if (!ind_in_comment2)
6459 {
6460 start = ml_get(trypos->lnum);
6461 look = start + trypos->col + 2; /* skip / and * */
6462 if (*look != NUL) /* if something after it */
6463 trypos->col = (colnr_T)(skipwhite(look) - start);
6464 }
6465 getvcol(curwin, trypos, &col, NULL, NULL);
6466 amount = col;
6467 if (ind_in_comment2 || *look == NUL)
6468 amount += ind_in_comment;
6469 }
6470 }
6471 }
6472
6473 /*
6474 * Are we inside parentheses or braces?
6475 */ /* XXX */
6476 else if (((trypos = find_match_paren(ind_maxparen, ind_maxcomment)) != NULL
6477 && ind_java == 0)
6478 || (tryposBrace = find_start_brace(ind_maxcomment)) != NULL
6479 || trypos != NULL)
6480 {
6481 if (trypos != NULL && tryposBrace != NULL)
6482 {
6483 /* Both an unmatched '(' and '{' is found. Use the one which is
6484 * closer to the current cursor position, set the other to NULL. */
6485 if (trypos->lnum != tryposBrace->lnum
6486 ? trypos->lnum < tryposBrace->lnum
6487 : trypos->col < tryposBrace->col)
6488 trypos = NULL;
6489 else
6490 tryposBrace = NULL;
6491 }
6492
6493 if (trypos != NULL)
6494 {
6495 /*
6496 * If the matching paren is more than one line away, use the indent of
6497 * a previous non-empty line that matches the same paren.
6498 */
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006499 if (theline[0] == ')' && ind_paren_prev)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006500 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006501 /* Line up with the start of the matching paren line. */
6502 amount = get_indent_lnum(curwin->w_cursor.lnum - 1); /* XXX */
6503 }
6504 else
6505 {
6506 amount = -1;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006507 our_paren_pos = *trypos;
6508 for (lnum = cur_curpos.lnum - 1; lnum > our_paren_pos.lnum; --lnum)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006509 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006510 l = skipwhite(ml_get(lnum));
6511 if (cin_nocode(l)) /* skip comment lines */
6512 continue;
6513 if (cin_ispreproc_cont(&l, &lnum))
6514 continue; /* ignore #define, #if, etc. */
6515 curwin->w_cursor.lnum = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006516
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006517 /* Skip a comment. XXX */
6518 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
6519 {
6520 lnum = trypos->lnum + 1;
6521 continue;
6522 }
6523
6524 /* XXX */
6525 if ((trypos = find_match_paren(
6526 corr_ind_maxparen(ind_maxparen, &cur_curpos),
Bram Moolenaar071d4272004-06-13 20:20:40 +00006527 ind_maxcomment)) != NULL
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006528 && trypos->lnum == our_paren_pos.lnum
6529 && trypos->col == our_paren_pos.col)
6530 {
6531 amount = get_indent_lnum(lnum); /* XXX */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006532
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006533 if (theline[0] == ')')
6534 {
6535 if (our_paren_pos.lnum != lnum
6536 && cur_amount > amount)
6537 cur_amount = amount;
6538 amount = -1;
6539 }
6540 break;
6541 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006542 }
6543 }
6544
6545 /*
6546 * Line up with line where the matching paren is. XXX
6547 * If the line starts with a '(' or the indent for unclosed
6548 * parentheses is zero, line up with the unclosed parentheses.
6549 */
6550 if (amount == -1)
6551 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006552 int ignore_paren_col = 0;
6553
Bram Moolenaar071d4272004-06-13 20:20:40 +00006554 amount = skip_label(our_paren_pos.lnum, &look, ind_maxcomment);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006555 look = skipwhite(look);
6556 if (*look == '(')
6557 {
6558 linenr_T save_lnum = curwin->w_cursor.lnum;
6559 char_u *line;
6560 int look_col;
6561
6562 /* Ignore a '(' in front of the line that has a match before
6563 * our matching '('. */
6564 curwin->w_cursor.lnum = our_paren_pos.lnum;
6565 line = ml_get_curline();
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006566 look_col = (int)(look - line);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006567 curwin->w_cursor.col = look_col + 1;
6568 if ((trypos = findmatchlimit(NULL, ')', 0, ind_maxparen))
6569 != NULL
6570 && trypos->lnum == our_paren_pos.lnum
6571 && trypos->col < our_paren_pos.col)
6572 ignore_paren_col = trypos->col + 1;
6573
6574 curwin->w_cursor.lnum = save_lnum;
6575 look = ml_get(our_paren_pos.lnum) + look_col;
6576 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006577 if (theline[0] == ')' || ind_unclosed == 0
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006578 || (!ind_unclosed_noignore && *look == '('
6579 && ignore_paren_col == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006580 {
6581 /*
6582 * If we're looking at a close paren, line up right there;
6583 * otherwise, line up with the next (non-white) character.
6584 * When ind_unclosed_wrapped is set and the matching paren is
6585 * the last nonwhite character of the line, use either the
6586 * indent of the current line or the indentation of the next
6587 * outer paren and add ind_unclosed_wrapped (for very long
6588 * lines).
6589 */
6590 if (theline[0] != ')')
6591 {
6592 cur_amount = MAXCOL;
6593 l = ml_get(our_paren_pos.lnum);
6594 if (ind_unclosed_wrapped
6595 && cin_ends_in(l, (char_u *)"(", NULL))
6596 {
6597 /* look for opening unmatched paren, indent one level
6598 * for each additional level */
6599 n = 1;
6600 for (col = 0; col < our_paren_pos.col; ++col)
6601 {
6602 switch (l[col])
6603 {
6604 case '(':
6605 case '{': ++n;
6606 break;
6607
6608 case ')':
6609 case '}': if (n > 1)
6610 --n;
6611 break;
6612 }
6613 }
6614
6615 our_paren_pos.col = 0;
6616 amount += n * ind_unclosed_wrapped;
6617 }
6618 else if (ind_unclosed_whiteok)
6619 our_paren_pos.col++;
6620 else
6621 {
6622 col = our_paren_pos.col + 1;
6623 while (vim_iswhite(l[col]))
6624 col++;
6625 if (l[col] != NUL) /* In case of trailing space */
6626 our_paren_pos.col = col;
6627 else
6628 our_paren_pos.col++;
6629 }
6630 }
6631
6632 /*
6633 * Find how indented the paren is, or the character after it
6634 * if we did the above "if".
6635 */
6636 if (our_paren_pos.col > 0)
6637 {
6638 getvcol(curwin, &our_paren_pos, &col, NULL, NULL);
6639 if (cur_amount > (int)col)
6640 cur_amount = col;
6641 }
6642 }
6643
6644 if (theline[0] == ')' && ind_matching_paren)
6645 {
6646 /* Line up with the start of the matching paren line. */
6647 }
6648 else if (ind_unclosed == 0 || (!ind_unclosed_noignore
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006649 && *look == '(' && ignore_paren_col == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006650 {
6651 if (cur_amount != MAXCOL)
6652 amount = cur_amount;
6653 }
6654 else
6655 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006656 /* Add ind_unclosed2 for each '(' before our matching one, but
6657 * ignore (void) before the line (ignore_paren_col). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006658 col = our_paren_pos.col;
Bram Moolenaarb21e5842006-04-16 18:30:08 +00006659 while ((int)our_paren_pos.col > ignore_paren_col)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006660 {
6661 --our_paren_pos.col;
6662 switch (*ml_get_pos(&our_paren_pos))
6663 {
6664 case '(': amount += ind_unclosed2;
6665 col = our_paren_pos.col;
6666 break;
6667 case ')': amount -= ind_unclosed2;
6668 col = MAXCOL;
6669 break;
6670 }
6671 }
6672
6673 /* Use ind_unclosed once, when the first '(' is not inside
6674 * braces */
6675 if (col == MAXCOL)
6676 amount += ind_unclosed;
6677 else
6678 {
6679 curwin->w_cursor.lnum = our_paren_pos.lnum;
6680 curwin->w_cursor.col = col;
6681 if ((trypos = find_match_paren(ind_maxparen,
6682 ind_maxcomment)) != NULL)
6683 amount += ind_unclosed2;
6684 else
6685 amount += ind_unclosed;
6686 }
6687 /*
6688 * For a line starting with ')' use the minimum of the two
6689 * positions, to avoid giving it more indent than the previous
6690 * lines:
6691 * func_long_name( if (x
6692 * arg && yy
6693 * ) ^ not here ) ^ not here
6694 */
6695 if (cur_amount < amount)
6696 amount = cur_amount;
6697 }
6698 }
6699
6700 /* add extra indent for a comment */
6701 if (cin_iscomment(theline))
6702 amount += ind_comment;
6703 }
6704
6705 /*
6706 * Are we at least inside braces, then?
6707 */
6708 else
6709 {
6710 trypos = tryposBrace;
6711
6712 ourscope = trypos->lnum;
6713 start = ml_get(ourscope);
6714
6715 /*
6716 * Now figure out how indented the line is in general.
6717 * If the brace was at the start of the line, we use that;
6718 * otherwise, check out the indentation of the line as
6719 * a whole and then add the "imaginary indent" to that.
6720 */
6721 look = skipwhite(start);
6722 if (*look == '{')
6723 {
6724 getvcol(curwin, trypos, &col, NULL, NULL);
6725 amount = col;
6726 if (*start == '{')
6727 start_brace = BRACE_IN_COL0;
6728 else
6729 start_brace = BRACE_AT_START;
6730 }
6731 else
6732 {
6733 /*
6734 * that opening brace might have been on a continuation
6735 * line. if so, find the start of the line.
6736 */
6737 curwin->w_cursor.lnum = ourscope;
6738
6739 /*
6740 * position the cursor over the rightmost paren, so that
6741 * matching it will take us back to the start of the line.
6742 */
6743 lnum = ourscope;
6744 if (find_last_paren(start, '(', ')')
6745 && (trypos = find_match_paren(ind_maxparen,
6746 ind_maxcomment)) != NULL)
6747 lnum = trypos->lnum;
6748
6749 /*
6750 * It could have been something like
6751 * case 1: if (asdf &&
6752 * ldfd) {
6753 * }
6754 */
6755 if (ind_keep_case_label && cin_iscase(skipwhite(ml_get_curline())))
6756 amount = get_indent();
6757 else
6758 amount = skip_label(lnum, &l, ind_maxcomment);
6759
6760 start_brace = BRACE_AT_END;
6761 }
6762
6763 /*
6764 * if we're looking at a closing brace, that's where
6765 * we want to be. otherwise, add the amount of room
6766 * that an indent is supposed to be.
6767 */
6768 if (theline[0] == '}')
6769 {
6770 /*
6771 * they may want closing braces to line up with something
6772 * other than the open brace. indulge them, if so.
6773 */
6774 amount += ind_close_extra;
6775 }
6776 else
6777 {
6778 /*
6779 * If we're looking at an "else", try to find an "if"
6780 * to match it with.
6781 * If we're looking at a "while", try to find a "do"
6782 * to match it with.
6783 */
6784 lookfor = LOOKFOR_INITIAL;
6785 if (cin_iselse(theline))
6786 lookfor = LOOKFOR_IF;
6787 else if (cin_iswhileofdo(theline, cur_curpos.lnum, ind_maxparen))
6788 /* XXX */
6789 lookfor = LOOKFOR_DO;
6790 if (lookfor != LOOKFOR_INITIAL)
6791 {
6792 curwin->w_cursor.lnum = cur_curpos.lnum;
6793 if (find_match(lookfor, ourscope, ind_maxparen,
6794 ind_maxcomment) == OK)
6795 {
6796 amount = get_indent(); /* XXX */
6797 goto theend;
6798 }
6799 }
6800
6801 /*
6802 * We get here if we are not on an "while-of-do" or "else" (or
6803 * failed to find a matching "if").
6804 * Search backwards for something to line up with.
6805 * First set amount for when we don't find anything.
6806 */
6807
6808 /*
6809 * if the '{' is _really_ at the left margin, use the imaginary
6810 * location of a left-margin brace. Otherwise, correct the
6811 * location for ind_open_extra.
6812 */
6813
6814 if (start_brace == BRACE_IN_COL0) /* '{' is in column 0 */
6815 {
6816 amount = ind_open_left_imag;
6817 }
6818 else
6819 {
6820 if (start_brace == BRACE_AT_END) /* '{' is at end of line */
6821 amount += ind_open_imag;
6822 else
6823 {
6824 /* Compensate for adding ind_open_extra later. */
6825 amount -= ind_open_extra;
6826 if (amount < 0)
6827 amount = 0;
6828 }
6829 }
6830
6831 lookfor_break = FALSE;
6832
6833 if (cin_iscase(theline)) /* it's a switch() label */
6834 {
6835 lookfor = LOOKFOR_CASE; /* find a previous switch() label */
6836 amount += ind_case;
6837 }
6838 else if (cin_isscopedecl(theline)) /* private:, ... */
6839 {
6840 lookfor = LOOKFOR_SCOPEDECL; /* class decl is this block */
6841 amount += ind_scopedecl;
6842 }
6843 else
6844 {
6845 if (ind_case_break && cin_isbreak(theline)) /* break; ... */
6846 lookfor_break = TRUE;
6847
6848 lookfor = LOOKFOR_INITIAL;
6849 amount += ind_level; /* ind_level from start of block */
6850 }
6851 scope_amount = amount;
6852 whilelevel = 0;
6853
6854 /*
6855 * Search backwards. If we find something we recognize, line up
6856 * with that.
6857 *
6858 * if we're looking at an open brace, indent
6859 * the usual amount relative to the conditional
6860 * that opens the block.
6861 */
6862 curwin->w_cursor = cur_curpos;
6863 for (;;)
6864 {
6865 curwin->w_cursor.lnum--;
6866 curwin->w_cursor.col = 0;
6867
6868 /*
6869 * If we went all the way back to the start of our scope, line
6870 * up with it.
6871 */
6872 if (curwin->w_cursor.lnum <= ourscope)
6873 {
6874 /* we reached end of scope:
6875 * if looking for a enum or structure initialization
6876 * go further back:
6877 * if it is an initializer (enum xxx or xxx =), then
6878 * don't add ind_continuation, otherwise it is a variable
6879 * declaration:
6880 * int x,
6881 * here; <-- add ind_continuation
6882 */
6883 if (lookfor == LOOKFOR_ENUM_OR_INIT)
6884 {
6885 if (curwin->w_cursor.lnum == 0
6886 || curwin->w_cursor.lnum
6887 < ourscope - ind_maxparen)
6888 {
6889 /* nothing found (abuse ind_maxparen as limit)
6890 * assume terminated line (i.e. a variable
6891 * initialization) */
6892 if (cont_amount > 0)
6893 amount = cont_amount;
6894 else
6895 amount += ind_continuation;
6896 break;
6897 }
6898
6899 l = ml_get_curline();
6900
6901 /*
6902 * If we're in a comment now, skip to the start of the
6903 * comment.
6904 */
6905 trypos = find_start_comment(ind_maxcomment);
6906 if (trypos != NULL)
6907 {
6908 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00006909 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006910 continue;
6911 }
6912
6913 /*
6914 * Skip preprocessor directives and blank lines.
6915 */
6916 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
6917 continue;
6918
6919 if (cin_nocode(l))
6920 continue;
6921
6922 terminated = cin_isterminated(l, FALSE, TRUE);
6923
6924 /*
6925 * If we are at top level and the line looks like a
6926 * function declaration, we are done
6927 * (it's a variable declaration).
6928 */
6929 if (start_brace != BRACE_IN_COL0
6930 || !cin_isfuncdecl(&l, curwin->w_cursor.lnum))
6931 {
6932 /* if the line is terminated with another ','
6933 * it is a continued variable initialization.
6934 * don't add extra indent.
6935 * TODO: does not work, if a function
6936 * declaration is split over multiple lines:
6937 * cin_isfuncdecl returns FALSE then.
6938 */
6939 if (terminated == ',')
6940 break;
6941
6942 /* if it es a enum declaration or an assignment,
6943 * we are done.
6944 */
6945 if (terminated != ';' && cin_isinit())
6946 break;
6947
6948 /* nothing useful found */
6949 if (terminated == 0 || terminated == '{')
6950 continue;
6951 }
6952
6953 if (terminated != ';')
6954 {
6955 /* Skip parens and braces. Position the cursor
6956 * over the rightmost paren, so that matching it
6957 * will take us back to the start of the line.
6958 */ /* XXX */
6959 trypos = NULL;
6960 if (find_last_paren(l, '(', ')'))
6961 trypos = find_match_paren(ind_maxparen,
6962 ind_maxcomment);
6963
6964 if (trypos == NULL && find_last_paren(l, '{', '}'))
6965 trypos = find_start_brace(ind_maxcomment);
6966
6967 if (trypos != NULL)
6968 {
6969 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00006970 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006971 continue;
6972 }
6973 }
6974
6975 /* it's a variable declaration, add indentation
6976 * like in
6977 * int a,
6978 * b;
6979 */
6980 if (cont_amount > 0)
6981 amount = cont_amount;
6982 else
6983 amount += ind_continuation;
6984 }
6985 else if (lookfor == LOOKFOR_UNTERM)
6986 {
6987 if (cont_amount > 0)
6988 amount = cont_amount;
6989 else
6990 amount += ind_continuation;
6991 }
6992 else if (lookfor != LOOKFOR_TERM
6993 && lookfor != LOOKFOR_CPP_BASECLASS)
6994 {
6995 amount = scope_amount;
6996 if (theline[0] == '{')
6997 amount += ind_open_extra;
6998 }
6999 break;
7000 }
7001
7002 /*
7003 * If we're in a comment now, skip to the start of the comment.
7004 */ /* XXX */
7005 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
7006 {
7007 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007008 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007009 continue;
7010 }
7011
7012 l = ml_get_curline();
7013
7014 /*
7015 * If this is a switch() label, may line up relative to that.
Bram Moolenaar18144c82006-04-12 21:52:12 +00007016 * If this is a C++ scope declaration, do the same.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007017 */
7018 iscase = cin_iscase(l);
7019 if (iscase || cin_isscopedecl(l))
7020 {
7021 /* we are only looking for cpp base class
7022 * declaration/initialization any longer */
7023 if (lookfor == LOOKFOR_CPP_BASECLASS)
7024 break;
7025
7026 /* When looking for a "do" we are not interested in
7027 * labels. */
7028 if (whilelevel > 0)
7029 continue;
7030
7031 /*
7032 * case xx:
7033 * c = 99 + <- this indent plus continuation
7034 *-> here;
7035 */
7036 if (lookfor == LOOKFOR_UNTERM
7037 || lookfor == LOOKFOR_ENUM_OR_INIT)
7038 {
7039 if (cont_amount > 0)
7040 amount = cont_amount;
7041 else
7042 amount += ind_continuation;
7043 break;
7044 }
7045
7046 /*
7047 * case xx: <- line up with this case
7048 * x = 333;
7049 * case yy:
7050 */
7051 if ( (iscase && lookfor == LOOKFOR_CASE)
7052 || (iscase && lookfor_break)
7053 || (!iscase && lookfor == LOOKFOR_SCOPEDECL))
7054 {
7055 /*
7056 * Check that this case label is not for another
7057 * switch()
7058 */ /* XXX */
7059 if ((trypos = find_start_brace(ind_maxcomment)) ==
7060 NULL || trypos->lnum == ourscope)
7061 {
7062 amount = get_indent(); /* XXX */
7063 break;
7064 }
7065 continue;
7066 }
7067
7068 n = get_indent_nolabel(curwin->w_cursor.lnum); /* XXX */
7069
7070 /*
7071 * case xx: if (cond) <- line up with this if
7072 * y = y + 1;
7073 * -> s = 99;
7074 *
7075 * case xx:
7076 * if (cond) <- line up with this line
7077 * y = y + 1;
7078 * -> s = 99;
7079 */
7080 if (lookfor == LOOKFOR_TERM)
7081 {
7082 if (n)
7083 amount = n;
7084
7085 if (!lookfor_break)
7086 break;
7087 }
7088
7089 /*
7090 * case xx: x = x + 1; <- line up with this x
7091 * -> y = y + 1;
7092 *
7093 * case xx: if (cond) <- line up with this if
7094 * -> y = y + 1;
7095 */
7096 if (n)
7097 {
7098 amount = n;
7099 l = after_label(ml_get_curline());
7100 if (l != NULL && cin_is_cinword(l))
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007101 {
7102 if (theline[0] == '{')
7103 amount += ind_open_extra;
7104 else
7105 amount += ind_level + ind_no_brace;
7106 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007107 break;
7108 }
7109
7110 /*
7111 * Try to get the indent of a statement before the switch
7112 * label. If nothing is found, line up relative to the
7113 * switch label.
7114 * break; <- may line up with this line
7115 * case xx:
7116 * -> y = 1;
7117 */
7118 scope_amount = get_indent() + (iscase /* XXX */
7119 ? ind_case_code : ind_scopedecl_code);
7120 lookfor = ind_case_break ? LOOKFOR_NOBREAK : LOOKFOR_ANY;
7121 continue;
7122 }
7123
7124 /*
7125 * Looking for a switch() label or C++ scope declaration,
7126 * ignore other lines, skip {}-blocks.
7127 */
7128 if (lookfor == LOOKFOR_CASE || lookfor == LOOKFOR_SCOPEDECL)
7129 {
7130 if (find_last_paren(l, '{', '}') && (trypos =
7131 find_start_brace(ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007132 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007133 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007134 curwin->w_cursor.col = 0;
7135 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007136 continue;
7137 }
7138
7139 /*
7140 * Ignore jump labels with nothing after them.
7141 */
7142 if (cin_islabel(ind_maxcomment))
7143 {
7144 l = after_label(ml_get_curline());
7145 if (l == NULL || cin_nocode(l))
7146 continue;
7147 }
7148
7149 /*
7150 * Ignore #defines, #if, etc.
7151 * Ignore comment and empty lines.
7152 * (need to get the line again, cin_islabel() may have
7153 * unlocked it)
7154 */
7155 l = ml_get_curline();
7156 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum)
7157 || cin_nocode(l))
7158 continue;
7159
7160 /*
7161 * Are we at the start of a cpp base class declaration or
7162 * constructor initialization?
7163 */ /* XXX */
Bram Moolenaar18144c82006-04-12 21:52:12 +00007164 n = FALSE;
7165 if (lookfor != LOOKFOR_TERM && ind_cpp_baseclass > 0)
7166 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00007167 n = cin_is_cpp_baseclass(&col);
Bram Moolenaar18144c82006-04-12 21:52:12 +00007168 l = ml_get_curline();
7169 }
7170 if (n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007171 {
7172 if (lookfor == LOOKFOR_UNTERM)
7173 {
7174 if (cont_amount > 0)
7175 amount = cont_amount;
7176 else
7177 amount += ind_continuation;
7178 }
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007179 else if (theline[0] == '{')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007180 {
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007181 /* Need to find start of the declaration. */
7182 lookfor = LOOKFOR_UNTERM;
7183 ind_continuation = 0;
7184 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007185 }
7186 else
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007187 /* XXX */
7188 amount = get_baseclass_amount(col, ind_maxparen,
7189 ind_maxcomment, ind_cpp_baseclass);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007190 break;
7191 }
7192 else if (lookfor == LOOKFOR_CPP_BASECLASS)
7193 {
7194 /* only look, whether there is a cpp base class
Bram Moolenaar18144c82006-04-12 21:52:12 +00007195 * declaration or initialization before the opening brace.
7196 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007197 if (cin_isterminated(l, TRUE, FALSE))
7198 break;
7199 else
7200 continue;
7201 }
7202
7203 /*
7204 * What happens next depends on the line being terminated.
7205 * If terminated with a ',' only consider it terminating if
Bram Moolenaar25394022007-05-10 19:06:20 +00007206 * there is another unterminated statement behind, eg:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007207 * 123,
7208 * sizeof
7209 * here
7210 * Otherwise check whether it is a enumeration or structure
7211 * initialisation (not indented) or a variable declaration
7212 * (indented).
7213 */
7214 terminated = cin_isterminated(l, FALSE, TRUE);
7215
7216 if (terminated == 0 || (lookfor != LOOKFOR_UNTERM
7217 && terminated == ','))
7218 {
7219 /*
7220 * if we're in the middle of a paren thing,
7221 * go back to the line that starts it so
7222 * we can get the right prevailing indent
7223 * if ( foo &&
7224 * bar )
7225 */
7226 /*
7227 * position the cursor over the rightmost paren, so that
7228 * matching it will take us back to the start of the line.
7229 */
7230 (void)find_last_paren(l, '(', ')');
7231 trypos = find_match_paren(
7232 corr_ind_maxparen(ind_maxparen, &cur_curpos),
7233 ind_maxcomment);
7234
7235 /*
7236 * If we are looking for ',', we also look for matching
7237 * braces.
7238 */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007239 if (trypos == NULL && terminated == ','
7240 && find_last_paren(l, '{', '}'))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007241 trypos = find_start_brace(ind_maxcomment);
7242
7243 if (trypos != NULL)
7244 {
7245 /*
7246 * Check if we are on a case label now. This is
7247 * handled above.
7248 * case xx: if ( asdf &&
7249 * asdf)
7250 */
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007251 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007252 l = ml_get_curline();
7253 if (cin_iscase(l) || cin_isscopedecl(l))
7254 {
7255 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007256 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007257 continue;
7258 }
7259 }
7260
7261 /*
7262 * Skip over continuation lines to find the one to get the
7263 * indent from
7264 * char *usethis = "bla\
7265 * bla",
7266 * here;
7267 */
7268 if (terminated == ',')
7269 {
7270 while (curwin->w_cursor.lnum > 1)
7271 {
7272 l = ml_get(curwin->w_cursor.lnum - 1);
7273 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
7274 break;
7275 --curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007276 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007277 }
7278 }
7279
7280 /*
7281 * Get indent and pointer to text for current line,
7282 * ignoring any jump label. XXX
7283 */
7284 cur_amount = skip_label(curwin->w_cursor.lnum,
7285 &l, ind_maxcomment);
7286
7287 /*
7288 * If this is just above the line we are indenting, and it
7289 * starts with a '{', line it up with this line.
7290 * while (not)
7291 * -> {
7292 * }
7293 */
7294 if (terminated != ',' && lookfor != LOOKFOR_TERM
7295 && theline[0] == '{')
7296 {
7297 amount = cur_amount;
7298 /*
7299 * Only add ind_open_extra when the current line
7300 * doesn't start with a '{', which must have a match
7301 * in the same line (scope is the same). Probably:
7302 * { 1, 2 },
7303 * -> { 3, 4 }
7304 */
7305 if (*skipwhite(l) != '{')
7306 amount += ind_open_extra;
7307
7308 if (ind_cpp_baseclass)
7309 {
7310 /* have to look back, whether it is a cpp base
7311 * class declaration or initialization */
7312 lookfor = LOOKFOR_CPP_BASECLASS;
7313 continue;
7314 }
7315 break;
7316 }
7317
7318 /*
7319 * Check if we are after an "if", "while", etc.
7320 * Also allow " } else".
7321 */
7322 if (cin_is_cinword(l) || cin_iselse(skipwhite(l)))
7323 {
7324 /*
7325 * Found an unterminated line after an if (), line up
7326 * with the last one.
7327 * if (cond)
7328 * 100 +
7329 * -> here;
7330 */
7331 if (lookfor == LOOKFOR_UNTERM
7332 || lookfor == LOOKFOR_ENUM_OR_INIT)
7333 {
7334 if (cont_amount > 0)
7335 amount = cont_amount;
7336 else
7337 amount += ind_continuation;
7338 break;
7339 }
7340
7341 /*
7342 * If this is just above the line we are indenting, we
7343 * are finished.
7344 * while (not)
7345 * -> here;
7346 * Otherwise this indent can be used when the line
7347 * before this is terminated.
7348 * yyy;
7349 * if (stat)
7350 * while (not)
7351 * xxx;
7352 * -> here;
7353 */
7354 amount = cur_amount;
7355 if (theline[0] == '{')
7356 amount += ind_open_extra;
7357 if (lookfor != LOOKFOR_TERM)
7358 {
7359 amount += ind_level + ind_no_brace;
7360 break;
7361 }
7362
7363 /*
7364 * Special trick: when expecting the while () after a
7365 * do, line up with the while()
7366 * do
7367 * x = 1;
7368 * -> here
7369 */
7370 l = skipwhite(ml_get_curline());
7371 if (cin_isdo(l))
7372 {
7373 if (whilelevel == 0)
7374 break;
7375 --whilelevel;
7376 }
7377
7378 /*
7379 * When searching for a terminated line, don't use the
7380 * one between the "if" and the "else".
7381 * Need to use the scope of this "else". XXX
7382 * If whilelevel != 0 continue looking for a "do {".
7383 */
7384 if (cin_iselse(l)
7385 && whilelevel == 0
7386 && ((trypos = find_start_brace(ind_maxcomment))
7387 == NULL
7388 || find_match(LOOKFOR_IF, trypos->lnum,
7389 ind_maxparen, ind_maxcomment) == FAIL))
7390 break;
7391 }
7392
7393 /*
7394 * If we're below an unterminated line that is not an
7395 * "if" or something, we may line up with this line or
Bram Moolenaar25394022007-05-10 19:06:20 +00007396 * add something for a continuation line, depending on
Bram Moolenaar071d4272004-06-13 20:20:40 +00007397 * the line before this one.
7398 */
7399 else
7400 {
7401 /*
7402 * Found two unterminated lines on a row, line up with
7403 * the last one.
7404 * c = 99 +
7405 * 100 +
7406 * -> here;
7407 */
7408 if (lookfor == LOOKFOR_UNTERM)
7409 {
7410 /* When line ends in a comma add extra indent */
7411 if (terminated == ',')
7412 amount += ind_continuation;
7413 break;
7414 }
7415
7416 if (lookfor == LOOKFOR_ENUM_OR_INIT)
7417 {
7418 /* Found two lines ending in ',', lineup with the
7419 * lowest one, but check for cpp base class
7420 * declaration/initialization, if it is an
7421 * opening brace or we are looking just for
7422 * enumerations/initializations. */
7423 if (terminated == ',')
7424 {
7425 if (ind_cpp_baseclass == 0)
7426 break;
7427
7428 lookfor = LOOKFOR_CPP_BASECLASS;
7429 continue;
7430 }
7431
7432 /* Ignore unterminated lines in between, but
7433 * reduce indent. */
7434 if (amount > cur_amount)
7435 amount = cur_amount;
7436 }
7437 else
7438 {
7439 /*
7440 * Found first unterminated line on a row, may
7441 * line up with this line, remember its indent
7442 * 100 +
7443 * -> here;
7444 */
7445 amount = cur_amount;
7446
7447 /*
7448 * If previous line ends in ',', check whether we
7449 * are in an initialization or enum
7450 * struct xxx =
7451 * {
7452 * sizeof a,
7453 * 124 };
7454 * or a normal possible continuation line.
7455 * but only, of no other statement has been found
7456 * yet.
7457 */
7458 if (lookfor == LOOKFOR_INITIAL && terminated == ',')
7459 {
7460 lookfor = LOOKFOR_ENUM_OR_INIT;
7461 cont_amount = cin_first_id_amount();
7462 }
7463 else
7464 {
7465 if (lookfor == LOOKFOR_INITIAL
7466 && *l != NUL
7467 && l[STRLEN(l) - 1] == '\\')
7468 /* XXX */
7469 cont_amount = cin_get_equal_amount(
7470 curwin->w_cursor.lnum);
7471 if (lookfor != LOOKFOR_TERM)
7472 lookfor = LOOKFOR_UNTERM;
7473 }
7474 }
7475 }
7476 }
7477
7478 /*
7479 * Check if we are after a while (cond);
7480 * If so: Ignore until the matching "do".
7481 */
7482 /* XXX */
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007483 else if (cin_iswhileofdo_end(terminated, ind_maxparen,
7484 ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007485 {
7486 /*
7487 * Found an unterminated line after a while ();, line up
7488 * with the last one.
7489 * while (cond);
7490 * 100 + <- line up with this one
7491 * -> here;
7492 */
7493 if (lookfor == LOOKFOR_UNTERM
7494 || lookfor == LOOKFOR_ENUM_OR_INIT)
7495 {
7496 if (cont_amount > 0)
7497 amount = cont_amount;
7498 else
7499 amount += ind_continuation;
7500 break;
7501 }
7502
7503 if (whilelevel == 0)
7504 {
7505 lookfor = LOOKFOR_TERM;
7506 amount = get_indent(); /* XXX */
7507 if (theline[0] == '{')
7508 amount += ind_open_extra;
7509 }
7510 ++whilelevel;
7511 }
7512
7513 /*
7514 * We are after a "normal" statement.
7515 * If we had another statement we can stop now and use the
7516 * indent of that other statement.
7517 * Otherwise the indent of the current statement may be used,
7518 * search backwards for the next "normal" statement.
7519 */
7520 else
7521 {
7522 /*
7523 * Skip single break line, if before a switch label. It
7524 * may be lined up with the case label.
7525 */
7526 if (lookfor == LOOKFOR_NOBREAK
7527 && cin_isbreak(skipwhite(ml_get_curline())))
7528 {
7529 lookfor = LOOKFOR_ANY;
7530 continue;
7531 }
7532
7533 /*
7534 * Handle "do {" line.
7535 */
7536 if (whilelevel > 0)
7537 {
7538 l = cin_skipcomment(ml_get_curline());
7539 if (cin_isdo(l))
7540 {
7541 amount = get_indent(); /* XXX */
7542 --whilelevel;
7543 continue;
7544 }
7545 }
7546
7547 /*
7548 * Found a terminated line above an unterminated line. Add
7549 * the amount for a continuation line.
7550 * x = 1;
7551 * y = foo +
7552 * -> here;
7553 * or
7554 * int x = 1;
7555 * int foo,
7556 * -> here;
7557 */
7558 if (lookfor == LOOKFOR_UNTERM
7559 || lookfor == LOOKFOR_ENUM_OR_INIT)
7560 {
7561 if (cont_amount > 0)
7562 amount = cont_amount;
7563 else
7564 amount += ind_continuation;
7565 break;
7566 }
7567
7568 /*
7569 * Found a terminated line above a terminated line or "if"
7570 * etc. line. Use the amount of the line below us.
7571 * x = 1; x = 1;
7572 * if (asdf) y = 2;
7573 * while (asdf) ->here;
7574 * here;
7575 * ->foo;
7576 */
7577 if (lookfor == LOOKFOR_TERM)
7578 {
7579 if (!lookfor_break && whilelevel == 0)
7580 break;
7581 }
7582
7583 /*
7584 * First line above the one we're indenting is terminated.
7585 * To know what needs to be done look further backward for
7586 * a terminated line.
7587 */
7588 else
7589 {
7590 /*
7591 * position the cursor over the rightmost paren, so
7592 * that matching it will take us back to the start of
7593 * the line. Helps for:
7594 * func(asdr,
7595 * asdfasdf);
7596 * here;
7597 */
7598term_again:
7599 l = ml_get_curline();
7600 if (find_last_paren(l, '(', ')')
7601 && (trypos = find_match_paren(ind_maxparen,
7602 ind_maxcomment)) != NULL)
7603 {
7604 /*
7605 * Check if we are on a case label now. This is
7606 * handled above.
7607 * case xx: if ( asdf &&
7608 * asdf)
7609 */
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007610 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007611 l = ml_get_curline();
7612 if (cin_iscase(l) || cin_isscopedecl(l))
7613 {
7614 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007615 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007616 continue;
7617 }
7618 }
7619
7620 /* When aligning with the case statement, don't align
7621 * with a statement after it.
7622 * case 1: { <-- don't use this { position
7623 * stat;
7624 * }
7625 * case 2:
7626 * stat;
7627 * }
7628 */
7629 iscase = (ind_keep_case_label && cin_iscase(l));
7630
7631 /*
7632 * Get indent and pointer to text for current line,
7633 * ignoring any jump label.
7634 */
7635 amount = skip_label(curwin->w_cursor.lnum,
7636 &l, ind_maxcomment);
7637
7638 if (theline[0] == '{')
7639 amount += ind_open_extra;
7640 /* See remark above: "Only add ind_open_extra.." */
Bram Moolenaar18144c82006-04-12 21:52:12 +00007641 l = skipwhite(l);
7642 if (*l == '{')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007643 amount -= ind_open_extra;
7644 lookfor = iscase ? LOOKFOR_ANY : LOOKFOR_TERM;
7645
7646 /*
Bram Moolenaar18144c82006-04-12 21:52:12 +00007647 * When a terminated line starts with "else" skip to
7648 * the matching "if":
7649 * else 3;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00007650 * indent this;
Bram Moolenaar18144c82006-04-12 21:52:12 +00007651 * Need to use the scope of this "else". XXX
7652 * If whilelevel != 0 continue looking for a "do {".
7653 */
7654 if (lookfor == LOOKFOR_TERM
7655 && *l != '}'
7656 && cin_iselse(l)
7657 && whilelevel == 0)
7658 {
7659 if ((trypos = find_start_brace(ind_maxcomment))
7660 == NULL
7661 || find_match(LOOKFOR_IF, trypos->lnum,
7662 ind_maxparen, ind_maxcomment) == FAIL)
7663 break;
7664 continue;
7665 }
7666
7667 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007668 * If we're at the end of a block, skip to the start of
7669 * that block.
7670 */
7671 curwin->w_cursor.col = 0;
7672 if (*cin_skipcomment(l) == '}'
7673 && (trypos = find_start_brace(ind_maxcomment))
7674 != NULL) /* XXX */
7675 {
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007676 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007677 /* if not "else {" check for terminated again */
7678 /* but skip block for "} else {" */
7679 l = cin_skipcomment(ml_get_curline());
7680 if (*l == '}' || !cin_iselse(l))
7681 goto term_again;
7682 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007683 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007684 }
7685 }
7686 }
7687 }
7688 }
7689 }
7690
7691 /* add extra indent for a comment */
7692 if (cin_iscomment(theline))
7693 amount += ind_comment;
7694 }
7695
7696 /*
7697 * ok -- we're not inside any sort of structure at all!
7698 *
7699 * this means we're at the top level, and everything should
7700 * basically just match where the previous line is, except
7701 * for the lines immediately following a function declaration,
7702 * which are K&R-style parameters and need to be indented.
7703 */
7704 else
7705 {
7706 /*
7707 * if our line starts with an open brace, forget about any
7708 * prevailing indent and make sure it looks like the start
7709 * of a function
7710 */
7711
7712 if (theline[0] == '{')
7713 {
7714 amount = ind_first_open;
7715 }
7716
7717 /*
7718 * If the NEXT line is a function declaration, the current
7719 * line needs to be indented as a function type spec.
7720 * Don't do this if the current line looks like a comment
7721 * or if the current line is terminated, ie. ends in ';'.
7722 */
7723 else if (cur_curpos.lnum < curbuf->b_ml.ml_line_count
7724 && !cin_nocode(theline)
7725 && !cin_ends_in(theline, (char_u *)":", NULL)
7726 && !cin_ends_in(theline, (char_u *)",", NULL)
7727 && cin_isfuncdecl(NULL, cur_curpos.lnum + 1)
7728 && !cin_isterminated(theline, FALSE, TRUE))
7729 {
7730 amount = ind_func_type;
7731 }
7732 else
7733 {
7734 amount = 0;
7735 curwin->w_cursor = cur_curpos;
7736
7737 /* search backwards until we find something we recognize */
7738
7739 while (curwin->w_cursor.lnum > 1)
7740 {
7741 curwin->w_cursor.lnum--;
7742 curwin->w_cursor.col = 0;
7743
7744 l = ml_get_curline();
7745
7746 /*
7747 * If we're in a comment now, skip to the start of the comment.
7748 */ /* XXX */
7749 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
7750 {
7751 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007752 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007753 continue;
7754 }
7755
7756 /*
Bram Moolenaar18144c82006-04-12 21:52:12 +00007757 * Are we at the start of a cpp base class declaration or
7758 * constructor initialization?
Bram Moolenaar071d4272004-06-13 20:20:40 +00007759 */ /* XXX */
Bram Moolenaar18144c82006-04-12 21:52:12 +00007760 n = FALSE;
7761 if (ind_cpp_baseclass != 0 && theline[0] != '{')
7762 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00007763 n = cin_is_cpp_baseclass(&col);
Bram Moolenaar18144c82006-04-12 21:52:12 +00007764 l = ml_get_curline();
7765 }
7766 if (n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007767 {
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007768 /* XXX */
7769 amount = get_baseclass_amount(col, ind_maxparen,
7770 ind_maxcomment, ind_cpp_baseclass);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007771 break;
7772 }
7773
7774 /*
7775 * Skip preprocessor directives and blank lines.
7776 */
7777 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7778 continue;
7779
7780 if (cin_nocode(l))
7781 continue;
7782
7783 /*
7784 * If the previous line ends in ',', use one level of
7785 * indentation:
7786 * int foo,
7787 * bar;
7788 * do this before checking for '}' in case of eg.
7789 * enum foobar
7790 * {
7791 * ...
7792 * } foo,
7793 * bar;
7794 */
7795 n = 0;
7796 if (cin_ends_in(l, (char_u *)",", NULL)
7797 || (*l != NUL && (n = l[STRLEN(l) - 1]) == '\\'))
7798 {
7799 /* take us back to opening paren */
7800 if (find_last_paren(l, '(', ')')
7801 && (trypos = find_match_paren(ind_maxparen,
7802 ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007803 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007804
7805 /* For a line ending in ',' that is a continuation line go
7806 * back to the first line with a backslash:
7807 * char *foo = "bla\
7808 * bla",
7809 * here;
7810 */
7811 while (n == 0 && curwin->w_cursor.lnum > 1)
7812 {
7813 l = ml_get(curwin->w_cursor.lnum - 1);
7814 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
7815 break;
7816 --curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007817 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007818 }
7819
7820 amount = get_indent(); /* XXX */
7821
7822 if (amount == 0)
7823 amount = cin_first_id_amount();
7824 if (amount == 0)
7825 amount = ind_continuation;
7826 break;
7827 }
7828
7829 /*
7830 * If the line looks like a function declaration, and we're
7831 * not in a comment, put it the left margin.
7832 */
7833 if (cin_isfuncdecl(NULL, cur_curpos.lnum)) /* XXX */
7834 break;
7835 l = ml_get_curline();
7836
7837 /*
7838 * Finding the closing '}' of a previous function. Put
7839 * current line at the left margin. For when 'cino' has "fs".
7840 */
7841 if (*skipwhite(l) == '}')
7842 break;
7843
7844 /* (matching {)
7845 * If the previous line ends on '};' (maybe followed by
7846 * comments) align at column 0. For example:
7847 * char *string_array[] = { "foo",
7848 * / * x * / "b};ar" }; / * foobar * /
7849 */
7850 if (cin_ends_in(l, (char_u *)"};", NULL))
7851 break;
7852
7853 /*
7854 * If the PREVIOUS line is a function declaration, the current
7855 * line (and the ones that follow) needs to be indented as
7856 * parameters.
7857 */
7858 if (cin_isfuncdecl(&l, curwin->w_cursor.lnum))
7859 {
7860 amount = ind_param;
7861 break;
7862 }
7863
7864 /*
7865 * If the previous line ends in ';' and the line before the
7866 * previous line ends in ',' or '\', ident to column zero:
7867 * int foo,
7868 * bar;
7869 * indent_to_0 here;
7870 */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007871 if (cin_ends_in(l, (char_u *)";", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007872 {
7873 l = ml_get(curwin->w_cursor.lnum - 1);
7874 if (cin_ends_in(l, (char_u *)",", NULL)
7875 || (*l != NUL && l[STRLEN(l) - 1] == '\\'))
7876 break;
7877 l = ml_get_curline();
7878 }
7879
7880 /*
7881 * Doesn't look like anything interesting -- so just
7882 * use the indent of this line.
7883 *
7884 * Position the cursor over the rightmost paren, so that
7885 * matching it will take us back to the start of the line.
7886 */
7887 find_last_paren(l, '(', ')');
7888
7889 if ((trypos = find_match_paren(ind_maxparen,
7890 ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007891 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007892 amount = get_indent(); /* XXX */
7893 break;
7894 }
7895
7896 /* add extra indent for a comment */
7897 if (cin_iscomment(theline))
7898 amount += ind_comment;
7899
7900 /* add extra indent if the previous line ended in a backslash:
7901 * "asdfasdf\
7902 * here";
7903 * char *foo = "asdf\
7904 * here";
7905 */
7906 if (cur_curpos.lnum > 1)
7907 {
7908 l = ml_get(cur_curpos.lnum - 1);
7909 if (*l != NUL && l[STRLEN(l) - 1] == '\\')
7910 {
7911 cur_amount = cin_get_equal_amount(cur_curpos.lnum - 1);
7912 if (cur_amount > 0)
7913 amount = cur_amount;
7914 else if (cur_amount == 0)
7915 amount += ind_continuation;
7916 }
7917 }
7918 }
7919 }
7920
7921theend:
7922 /* put the cursor back where it belongs */
7923 curwin->w_cursor = cur_curpos;
7924
7925 vim_free(linecopy);
7926
7927 if (amount < 0)
7928 return 0;
7929 return amount;
7930}
7931
7932 static int
7933find_match(lookfor, ourscope, ind_maxparen, ind_maxcomment)
7934 int lookfor;
7935 linenr_T ourscope;
7936 int ind_maxparen;
7937 int ind_maxcomment;
7938{
7939 char_u *look;
7940 pos_T *theirscope;
7941 char_u *mightbeif;
7942 int elselevel;
7943 int whilelevel;
7944
7945 if (lookfor == LOOKFOR_IF)
7946 {
7947 elselevel = 1;
7948 whilelevel = 0;
7949 }
7950 else
7951 {
7952 elselevel = 0;
7953 whilelevel = 1;
7954 }
7955
7956 curwin->w_cursor.col = 0;
7957
7958 while (curwin->w_cursor.lnum > ourscope + 1)
7959 {
7960 curwin->w_cursor.lnum--;
7961 curwin->w_cursor.col = 0;
7962
7963 look = cin_skipcomment(ml_get_curline());
7964 if (cin_iselse(look)
7965 || cin_isif(look)
7966 || cin_isdo(look) /* XXX */
7967 || cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
7968 {
7969 /*
7970 * if we've gone outside the braces entirely,
7971 * we must be out of scope...
7972 */
7973 theirscope = find_start_brace(ind_maxcomment); /* XXX */
7974 if (theirscope == NULL)
7975 break;
7976
7977 /*
7978 * and if the brace enclosing this is further
7979 * back than the one enclosing the else, we're
7980 * out of luck too.
7981 */
7982 if (theirscope->lnum < ourscope)
7983 break;
7984
7985 /*
7986 * and if they're enclosed in a *deeper* brace,
7987 * then we can ignore it because it's in a
7988 * different scope...
7989 */
7990 if (theirscope->lnum > ourscope)
7991 continue;
7992
7993 /*
7994 * if it was an "else" (that's not an "else if")
7995 * then we need to go back to another if, so
7996 * increment elselevel
7997 */
7998 look = cin_skipcomment(ml_get_curline());
7999 if (cin_iselse(look))
8000 {
8001 mightbeif = cin_skipcomment(look + 4);
8002 if (!cin_isif(mightbeif))
8003 ++elselevel;
8004 continue;
8005 }
8006
8007 /*
8008 * if it was a "while" then we need to go back to
8009 * another "do", so increment whilelevel. XXX
8010 */
8011 if (cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
8012 {
8013 ++whilelevel;
8014 continue;
8015 }
8016
8017 /* If it's an "if" decrement elselevel */
8018 look = cin_skipcomment(ml_get_curline());
8019 if (cin_isif(look))
8020 {
8021 elselevel--;
8022 /*
8023 * When looking for an "if" ignore "while"s that
8024 * get in the way.
8025 */
8026 if (elselevel == 0 && lookfor == LOOKFOR_IF)
8027 whilelevel = 0;
8028 }
8029
8030 /* If it's a "do" decrement whilelevel */
8031 if (cin_isdo(look))
8032 whilelevel--;
8033
8034 /*
8035 * if we've used up all the elses, then
8036 * this must be the if that we want!
8037 * match the indent level of that if.
8038 */
8039 if (elselevel <= 0 && whilelevel <= 0)
8040 {
8041 return OK;
8042 }
8043 }
8044 }
8045 return FAIL;
8046}
8047
8048# if defined(FEAT_EVAL) || defined(PROTO)
8049/*
8050 * Get indent level from 'indentexpr'.
8051 */
8052 int
8053get_expr_indent()
8054{
8055 int indent;
8056 pos_T pos;
8057 int save_State;
Bram Moolenaard1f56e62006-02-22 21:25:37 +00008058 int use_sandbox = was_set_insecurely((char_u *)"indentexpr",
8059 OPT_LOCAL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008060
8061 pos = curwin->w_cursor;
8062 set_vim_var_nr(VV_LNUM, curwin->w_cursor.lnum);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00008063 if (use_sandbox)
8064 ++sandbox;
8065 ++textlock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008066 indent = eval_to_number(curbuf->b_p_inde);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00008067 if (use_sandbox)
8068 --sandbox;
8069 --textlock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008070
8071 /* Restore the cursor position so that 'indentexpr' doesn't need to.
8072 * Pretend to be in Insert mode, allow cursor past end of line for "o"
8073 * command. */
8074 save_State = State;
8075 State = INSERT;
8076 curwin->w_cursor = pos;
8077 check_cursor();
8078 State = save_State;
8079
8080 /* If there is an error, just keep the current indent. */
8081 if (indent < 0)
8082 indent = get_indent();
8083
8084 return indent;
8085}
8086# endif
8087
8088#endif /* FEAT_CINDENT */
8089
8090#if defined(FEAT_LISP) || defined(PROTO)
8091
8092static int lisp_match __ARGS((char_u *p));
8093
8094 static int
8095lisp_match(p)
8096 char_u *p;
8097{
8098 char_u buf[LSIZE];
8099 int len;
8100 char_u *word = p_lispwords;
8101
8102 while (*word != NUL)
8103 {
8104 (void)copy_option_part(&word, buf, LSIZE, ",");
8105 len = (int)STRLEN(buf);
8106 if (STRNCMP(buf, p, len) == 0 && p[len] == ' ')
8107 return TRUE;
8108 }
8109 return FALSE;
8110}
8111
8112/*
8113 * When 'p' is present in 'cpoptions, a Vi compatible method is used.
8114 * The incompatible newer method is quite a bit better at indenting
8115 * code in lisp-like languages than the traditional one; it's still
8116 * mostly heuristics however -- Dirk van Deun, dirk@rave.org
8117 *
8118 * TODO:
8119 * Findmatch() should be adapted for lisp, also to make showmatch
8120 * work correctly: now (v5.3) it seems all C/C++ oriented:
8121 * - it does not recognize the #\( and #\) notations as character literals
8122 * - it doesn't know about comments starting with a semicolon
8123 * - it incorrectly interprets '(' as a character literal
8124 * All this messes up get_lisp_indent in some rare cases.
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008125 * Update from Sergey Khorev:
8126 * I tried to fix the first two issues.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008127 */
8128 int
8129get_lisp_indent()
8130{
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008131 pos_T *pos, realpos, paren;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008132 int amount;
8133 char_u *that;
8134 colnr_T col;
8135 colnr_T firsttry;
8136 int parencount, quotecount;
8137 int vi_lisp;
8138
8139 /* Set vi_lisp to use the vi-compatible method */
8140 vi_lisp = (vim_strchr(p_cpo, CPO_LISP) != NULL);
8141
8142 realpos = curwin->w_cursor;
8143 curwin->w_cursor.col = 0;
8144
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008145 if ((pos = findmatch(NULL, '(')) == NULL)
8146 pos = findmatch(NULL, '[');
8147 else
8148 {
8149 paren = *pos;
8150 pos = findmatch(NULL, '[');
8151 if (pos == NULL || ltp(pos, &paren))
8152 pos = &paren;
8153 }
8154 if (pos != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008155 {
8156 /* Extra trick: Take the indent of the first previous non-white
8157 * line that is at the same () level. */
8158 amount = -1;
8159 parencount = 0;
8160
8161 while (--curwin->w_cursor.lnum >= pos->lnum)
8162 {
8163 if (linewhite(curwin->w_cursor.lnum))
8164 continue;
8165 for (that = ml_get_curline(); *that != NUL; ++that)
8166 {
8167 if (*that == ';')
8168 {
8169 while (*(that + 1) != NUL)
8170 ++that;
8171 continue;
8172 }
8173 if (*that == '\\')
8174 {
8175 if (*(that + 1) != NUL)
8176 ++that;
8177 continue;
8178 }
8179 if (*that == '"' && *(that + 1) != NUL)
8180 {
Bram Moolenaar15ff6c12006-09-15 18:18:09 +00008181 while (*++that && *that != '"')
8182 {
8183 /* skipping escaped characters in the string */
8184 if (*that == '\\')
8185 {
8186 if (*++that == NUL)
8187 break;
8188 if (that[1] == NUL)
8189 {
8190 ++that;
8191 break;
8192 }
8193 }
8194 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008195 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008196 if (*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008197 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008198 else if (*that == ')' || *that == ']')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008199 --parencount;
8200 }
8201 if (parencount == 0)
8202 {
8203 amount = get_indent();
8204 break;
8205 }
8206 }
8207
8208 if (amount == -1)
8209 {
8210 curwin->w_cursor.lnum = pos->lnum;
8211 curwin->w_cursor.col = pos->col;
8212 col = pos->col;
8213
8214 that = ml_get_curline();
8215
8216 if (vi_lisp && get_indent() == 0)
8217 amount = 2;
8218 else
8219 {
8220 amount = 0;
8221 while (*that && col)
8222 {
8223 amount += lbr_chartabsize_adv(&that, (colnr_T)amount);
8224 col--;
8225 }
8226
8227 /*
8228 * Some keywords require "body" indenting rules (the
8229 * non-standard-lisp ones are Scheme special forms):
8230 *
8231 * (let ((a 1)) instead (let ((a 1))
8232 * (...)) of (...))
8233 */
8234
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008235 if (!vi_lisp && (*that == '(' || *that == '[')
8236 && lisp_match(that + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008237 amount += 2;
8238 else
8239 {
8240 that++;
8241 amount++;
8242 firsttry = amount;
8243
8244 while (vim_iswhite(*that))
8245 {
8246 amount += lbr_chartabsize(that, (colnr_T)amount);
8247 ++that;
8248 }
8249
8250 if (*that && *that != ';') /* not a comment line */
8251 {
Bram Moolenaare21877a2008-02-13 09:58:14 +00008252 /* test *that != '(' to accommodate first let/do
Bram Moolenaar071d4272004-06-13 20:20:40 +00008253 * argument if it is more than one line */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008254 if (!vi_lisp && *that != '(' && *that != '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008255 firsttry++;
8256
8257 parencount = 0;
8258 quotecount = 0;
8259
8260 if (vi_lisp
8261 || (*that != '"'
8262 && *that != '\''
8263 && *that != '#'
8264 && (*that < '0' || *that > '9')))
8265 {
8266 while (*that
8267 && (!vim_iswhite(*that)
8268 || quotecount
8269 || parencount)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008270 && (!((*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008271 && !quotecount
8272 && !parencount
8273 && vi_lisp)))
8274 {
8275 if (*that == '"')
8276 quotecount = !quotecount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008277 if ((*that == '(' || *that == '[')
8278 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008279 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008280 if ((*that == ')' || *that == ']')
8281 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008282 --parencount;
8283 if (*that == '\\' && *(that+1) != NUL)
8284 amount += lbr_chartabsize_adv(&that,
8285 (colnr_T)amount);
8286 amount += lbr_chartabsize_adv(&that,
8287 (colnr_T)amount);
8288 }
8289 }
8290 while (vim_iswhite(*that))
8291 {
8292 amount += lbr_chartabsize(that, (colnr_T)amount);
8293 that++;
8294 }
8295 if (!*that || *that == ';')
8296 amount = firsttry;
8297 }
8298 }
8299 }
8300 }
8301 }
8302 else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008303 amount = 0; /* no matching '(' or '[' found, use zero indent */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008304
8305 curwin->w_cursor = realpos;
8306
8307 return amount;
8308}
8309#endif /* FEAT_LISP */
8310
8311 void
8312prepare_to_exit()
8313{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00008314#if defined(SIGHUP) && defined(SIG_IGN)
8315 /* Ignore SIGHUP, because a dropped connection causes a read error, which
8316 * makes Vim exit and then handling SIGHUP causes various reentrance
8317 * problems. */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00008318 signal(SIGHUP, SIG_IGN);
8319#endif
8320
Bram Moolenaar071d4272004-06-13 20:20:40 +00008321#ifdef FEAT_GUI
8322 if (gui.in_use)
8323 {
8324 gui.dying = TRUE;
8325 out_trash(); /* trash any pending output */
8326 }
8327 else
8328#endif
8329 {
8330 windgoto((int)Rows - 1, 0);
8331
8332 /*
8333 * Switch terminal mode back now, so messages end up on the "normal"
8334 * screen (if there are two screens).
8335 */
8336 settmode(TMODE_COOK);
8337#ifdef WIN3264
8338 if (can_end_termcap_mode(FALSE) == TRUE)
8339#endif
8340 stoptermcap();
8341 out_flush();
8342 }
8343}
8344
8345/*
8346 * Preserve files and exit.
8347 * When called IObuff must contain a message.
8348 */
8349 void
8350preserve_exit()
8351{
8352 buf_T *buf;
8353
8354 prepare_to_exit();
8355
Bram Moolenaar4770d092006-01-12 23:22:24 +00008356 /* Setting this will prevent free() calls. That avoids calling free()
8357 * recursively when free() was invoked with a bad pointer. */
8358 really_exiting = TRUE;
8359
Bram Moolenaar071d4272004-06-13 20:20:40 +00008360 out_str(IObuff);
8361 screen_start(); /* don't know where cursor is now */
8362 out_flush();
8363
8364 ml_close_notmod(); /* close all not-modified buffers */
8365
8366 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8367 {
8368 if (buf->b_ml.ml_mfp != NULL && buf->b_ml.ml_mfp->mf_fname != NULL)
8369 {
8370 OUT_STR(_("Vim: preserving files...\n"));
8371 screen_start(); /* don't know where cursor is now */
8372 out_flush();
8373 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
8374 break;
8375 }
8376 }
8377
8378 ml_close_all(FALSE); /* close all memfiles, without deleting */
8379
8380 OUT_STR(_("Vim: Finished.\n"));
8381
8382 getout(1);
8383}
8384
8385/*
8386 * return TRUE if "fname" exists.
8387 */
8388 int
8389vim_fexists(fname)
8390 char_u *fname;
8391{
8392 struct stat st;
8393
8394 if (mch_stat((char *)fname, &st))
8395 return FALSE;
8396 return TRUE;
8397}
8398
8399/*
8400 * Check for CTRL-C pressed, but only once in a while.
8401 * Should be used instead of ui_breakcheck() for functions that check for
8402 * each line in the file. Calling ui_breakcheck() each time takes too much
8403 * time, because it can be a system call.
8404 */
8405
8406#ifndef BREAKCHECK_SKIP
8407# ifdef FEAT_GUI /* assume the GUI only runs on fast computers */
8408# define BREAKCHECK_SKIP 200
8409# else
8410# define BREAKCHECK_SKIP 32
8411# endif
8412#endif
8413
8414static int breakcheck_count = 0;
8415
8416 void
8417line_breakcheck()
8418{
8419 if (++breakcheck_count >= BREAKCHECK_SKIP)
8420 {
8421 breakcheck_count = 0;
8422 ui_breakcheck();
8423 }
8424}
8425
8426/*
8427 * Like line_breakcheck() but check 10 times less often.
8428 */
8429 void
8430fast_breakcheck()
8431{
8432 if (++breakcheck_count >= BREAKCHECK_SKIP * 10)
8433 {
8434 breakcheck_count = 0;
8435 ui_breakcheck();
8436 }
8437}
8438
8439/*
8440 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching
8441 * 'wildignore'.
Bram Moolenaar362e1a32006-03-06 23:29:24 +00008442 * Returns OK or FAIL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008443 */
8444 int
8445expand_wildcards(num_pat, pat, num_file, file, flags)
8446 int num_pat; /* number of input patterns */
8447 char_u **pat; /* array of input patterns */
8448 int *num_file; /* resulting number of files */
8449 char_u ***file; /* array of resulting files */
8450 int flags; /* EW_DIR, etc. */
8451{
8452 int retval;
8453 int i, j;
8454 char_u *p;
8455 int non_suf_match; /* number without matching suffix */
8456
8457 retval = gen_expand_wildcards(num_pat, pat, num_file, file, flags);
8458
8459 /* When keeping all matches, return here */
8460 if (flags & EW_KEEPALL)
8461 return retval;
8462
8463#ifdef FEAT_WILDIGN
8464 /*
8465 * Remove names that match 'wildignore'.
8466 */
8467 if (*p_wig)
8468 {
8469 char_u *ffname;
8470
8471 /* check all files in (*file)[] */
8472 for (i = 0; i < *num_file; ++i)
8473 {
8474 ffname = FullName_save((*file)[i], FALSE);
8475 if (ffname == NULL) /* out of memory */
8476 break;
8477# ifdef VMS
8478 vms_remove_version(ffname);
8479# endif
8480 if (match_file_list(p_wig, (*file)[i], ffname))
8481 {
8482 /* remove this matching file from the list */
8483 vim_free((*file)[i]);
8484 for (j = i; j + 1 < *num_file; ++j)
8485 (*file)[j] = (*file)[j + 1];
8486 --*num_file;
8487 --i;
8488 }
8489 vim_free(ffname);
8490 }
8491 }
8492#endif
8493
8494 /*
8495 * Move the names where 'suffixes' match to the end.
8496 */
8497 if (*num_file > 1)
8498 {
8499 non_suf_match = 0;
8500 for (i = 0; i < *num_file; ++i)
8501 {
8502 if (!match_suffix((*file)[i]))
8503 {
8504 /*
8505 * Move the name without matching suffix to the front
8506 * of the list.
8507 */
8508 p = (*file)[i];
8509 for (j = i; j > non_suf_match; --j)
8510 (*file)[j] = (*file)[j - 1];
8511 (*file)[non_suf_match++] = p;
8512 }
8513 }
8514 }
8515
8516 return retval;
8517}
8518
8519/*
8520 * Return TRUE if "fname" matches with an entry in 'suffixes'.
8521 */
8522 int
8523match_suffix(fname)
8524 char_u *fname;
8525{
8526 int fnamelen, setsuflen;
8527 char_u *setsuf;
8528#define MAXSUFLEN 30 /* maximum length of a file suffix */
8529 char_u suf_buf[MAXSUFLEN];
8530
8531 fnamelen = (int)STRLEN(fname);
8532 setsuflen = 0;
8533 for (setsuf = p_su; *setsuf; )
8534 {
8535 setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
Bram Moolenaar055a2ba2009-07-14 19:40:21 +00008536 if (setsuflen == 0)
8537 {
8538 char_u *tail = gettail(fname);
8539
8540 /* empty entry: match name without a '.' */
8541 if (vim_strchr(tail, '.') == NULL)
8542 {
8543 setsuflen = 1;
8544 break;
8545 }
8546 }
8547 else
8548 {
8549 if (fnamelen >= setsuflen
8550 && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
8551 (size_t)setsuflen) == 0)
8552 break;
8553 setsuflen = 0;
8554 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008555 }
8556 return (setsuflen != 0);
8557}
8558
8559#if !defined(NO_EXPANDPATH) || defined(PROTO)
8560
8561# ifdef VIM_BACKTICK
8562static int vim_backtick __ARGS((char_u *p));
8563static int expand_backtick __ARGS((garray_T *gap, char_u *pat, int flags));
8564# endif
8565
8566# if defined(MSDOS) || defined(FEAT_GUI_W16) || defined(WIN3264)
8567/*
8568 * File name expansion code for MS-DOS, Win16 and Win32. It's here because
8569 * it's shared between these systems.
8570 */
8571# if defined(DJGPP) || defined(PROTO)
8572# define _cdecl /* DJGPP doesn't have this */
8573# else
8574# ifdef __BORLANDC__
8575# define _cdecl _RTLENTRYF
8576# endif
8577# endif
8578
8579/*
8580 * comparison function for qsort in dos_expandpath()
8581 */
8582 static int _cdecl
8583pstrcmp(const void *a, const void *b)
8584{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00008585 return (pathcmp(*(char **)a, *(char **)b, -1));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008586}
8587
8588# ifndef WIN3264
8589 static void
8590namelowcpy(
8591 char_u *d,
8592 char_u *s)
8593{
8594# ifdef DJGPP
8595 if (USE_LONG_FNAME) /* don't lower case on Windows 95/NT systems */
8596 while (*s)
8597 *d++ = *s++;
8598 else
8599# endif
8600 while (*s)
8601 *d++ = TOLOWER_LOC(*s++);
8602 *d = NUL;
8603}
8604# endif
8605
8606/*
Bram Moolenaar231334e2005-07-25 20:46:57 +00008607 * Recursively expand one path component into all matching files and/or
8608 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008609 * Return the number of matches found.
8610 * "path" has backslashes before chars that are not to be expanded, starting
8611 * at "path[wildoff]".
Bram Moolenaar231334e2005-07-25 20:46:57 +00008612 * Return the number of matches found.
8613 * NOTE: much of this is identical to unix_expandpath(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00008614 */
8615 static int
8616dos_expandpath(
8617 garray_T *gap,
8618 char_u *path,
8619 int wildoff,
Bram Moolenaar231334e2005-07-25 20:46:57 +00008620 int flags, /* EW_* flags */
Bram Moolenaar25394022007-05-10 19:06:20 +00008621 int didstar) /* expanded "**" once already */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008622{
Bram Moolenaar231334e2005-07-25 20:46:57 +00008623 char_u *buf;
8624 char_u *path_end;
8625 char_u *p, *s, *e;
8626 int start_len = gap->ga_len;
8627 char_u *pat;
8628 regmatch_T regmatch;
8629 int starts_with_dot;
8630 int matches;
8631 int len;
8632 int starstar = FALSE;
8633 static int stardepth = 0; /* depth for "**" expansion */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008634#ifdef WIN3264
8635 WIN32_FIND_DATA fb;
8636 HANDLE hFind = (HANDLE)0;
8637# ifdef FEAT_MBYTE
8638 WIN32_FIND_DATAW wfb;
8639 WCHAR *wn = NULL; /* UCS-2 name, NULL when not used. */
8640# endif
8641#else
8642 struct ffblk fb;
8643#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008644 char_u *matchname;
Bram Moolenaar231334e2005-07-25 20:46:57 +00008645 int ok;
8646
8647 /* Expanding "**" may take a long time, check for CTRL-C. */
8648 if (stardepth > 0)
8649 {
8650 ui_breakcheck();
8651 if (got_int)
8652 return 0;
8653 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008654
8655 /* make room for file name */
Bram Moolenaar231334e2005-07-25 20:46:57 +00008656 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008657 if (buf == NULL)
8658 return 0;
8659
8660 /*
8661 * Find the first part in the path name that contains a wildcard or a ~1.
8662 * Copy it into buf, including the preceding characters.
8663 */
8664 p = buf;
8665 s = buf;
8666 e = NULL;
8667 path_end = path;
8668 while (*path_end != NUL)
8669 {
8670 /* May ignore a wildcard that has a backslash before it; it will
8671 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
8672 if (path_end >= path + wildoff && rem_backslash(path_end))
8673 *p++ = *path_end++;
8674 else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
8675 {
8676 if (e != NULL)
8677 break;
8678 s = p + 1;
8679 }
8680 else if (path_end >= path + wildoff
8681 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
8682 e = p;
8683#ifdef FEAT_MBYTE
8684 if (has_mbyte)
8685 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00008686 len = (*mb_ptr2len)(path_end);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008687 STRNCPY(p, path_end, len);
8688 p += len;
8689 path_end += len;
8690 }
8691 else
8692#endif
8693 *p++ = *path_end++;
8694 }
8695 e = p;
8696 *e = NUL;
8697
8698 /* now we have one wildcard component between s and e */
8699 /* Remove backslashes between "wildoff" and the start of the wildcard
8700 * component. */
8701 for (p = buf + wildoff; p < s; ++p)
8702 if (rem_backslash(p))
8703 {
Bram Moolenaar8c8de832008-06-24 22:58:06 +00008704 STRMOVE(p, p + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008705 --e;
8706 --s;
8707 }
8708
Bram Moolenaar231334e2005-07-25 20:46:57 +00008709 /* Check for "**" between "s" and "e". */
8710 for (p = s; p < e; ++p)
8711 if (p[0] == '*' && p[1] == '*')
8712 starstar = TRUE;
8713
Bram Moolenaar071d4272004-06-13 20:20:40 +00008714 starts_with_dot = (*s == '.');
8715 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
8716 if (pat == NULL)
8717 {
8718 vim_free(buf);
8719 return 0;
8720 }
8721
8722 /* compile the regexp into a program */
8723 regmatch.rm_ic = TRUE; /* Always ignore case */
8724 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
8725 vim_free(pat);
8726
8727 if (regmatch.regprog == NULL)
8728 {
8729 vim_free(buf);
8730 return 0;
8731 }
8732
8733 /* remember the pattern or file name being looked for */
8734 matchname = vim_strsave(s);
8735
Bram Moolenaar231334e2005-07-25 20:46:57 +00008736 /* If "**" is by itself, this is the first time we encounter it and more
8737 * is following then find matches without any directory. */
8738 if (!didstar && stardepth < 100 && starstar && e - s == 2
8739 && *path_end == '/')
8740 {
8741 STRCPY(s, path_end + 1);
8742 ++stardepth;
8743 (void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
8744 --stardepth;
8745 }
8746
Bram Moolenaar071d4272004-06-13 20:20:40 +00008747 /* Scan all files in the directory with "dir/ *.*" */
8748 STRCPY(s, "*.*");
8749#ifdef WIN3264
8750# ifdef FEAT_MBYTE
8751 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
8752 {
8753 /* The active codepage differs from 'encoding'. Attempt using the
8754 * wide function. If it fails because it is not implemented fall back
8755 * to the non-wide version (for Windows 98) */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00008756 wn = enc_to_utf16(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008757 if (wn != NULL)
8758 {
8759 hFind = FindFirstFileW(wn, &wfb);
8760 if (hFind == INVALID_HANDLE_VALUE
8761 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
8762 {
8763 vim_free(wn);
8764 wn = NULL;
8765 }
8766 }
8767 }
8768
8769 if (wn == NULL)
8770# endif
8771 hFind = FindFirstFile(buf, &fb);
8772 ok = (hFind != INVALID_HANDLE_VALUE);
8773#else
8774 /* If we are expanding wildcards we try both files and directories */
8775 ok = (findfirst((char *)buf, &fb,
8776 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
8777#endif
8778
8779 while (ok)
8780 {
8781#ifdef WIN3264
8782# ifdef FEAT_MBYTE
8783 if (wn != NULL)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00008784 p = utf16_to_enc(wfb.cFileName, NULL); /* p is allocated here */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008785 else
8786# endif
8787 p = (char_u *)fb.cFileName;
8788#else
8789 p = (char_u *)fb.ff_name;
8790#endif
8791 /* Ignore entries starting with a dot, unless when asked for. Accept
8792 * all entries found with "matchname". */
8793 if ((p[0] != '.' || starts_with_dot)
8794 && (matchname == NULL
8795 || vim_regexec(&regmatch, p, (colnr_T)0)))
8796 {
8797#ifdef WIN3264
8798 STRCPY(s, p);
8799#else
8800 namelowcpy(s, p);
8801#endif
8802 len = (int)STRLEN(buf);
Bram Moolenaar231334e2005-07-25 20:46:57 +00008803
8804 if (starstar && stardepth < 100)
8805 {
8806 /* For "**" in the pattern first go deeper in the tree to
8807 * find matches. */
8808 STRCPY(buf + len, "/**");
8809 STRCPY(buf + len + 3, path_end);
8810 ++stardepth;
8811 (void)dos_expandpath(gap, buf, len + 1, flags, TRUE);
8812 --stardepth;
8813 }
8814
Bram Moolenaar071d4272004-06-13 20:20:40 +00008815 STRCPY(buf + len, path_end);
8816 if (mch_has_exp_wildcard(path_end))
8817 {
8818 /* need to expand another component of the path */
8819 /* remove backslashes for the remaining components only */
Bram Moolenaar231334e2005-07-25 20:46:57 +00008820 (void)dos_expandpath(gap, buf, len + 1, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008821 }
8822 else
8823 {
8824 /* no more wildcards, check if there is a match */
8825 /* remove backslashes for the remaining components only */
8826 if (*path_end != 0)
8827 backslash_halve(buf + len + 1);
8828 if (mch_getperm(buf) >= 0) /* add existing file */
8829 addfile(gap, buf, flags);
8830 }
8831 }
8832
8833#ifdef WIN3264
8834# ifdef FEAT_MBYTE
8835 if (wn != NULL)
8836 {
8837 vim_free(p);
8838 ok = FindNextFileW(hFind, &wfb);
8839 }
8840 else
8841# endif
8842 ok = FindNextFile(hFind, &fb);
8843#else
8844 ok = (findnext(&fb) == 0);
8845#endif
8846
8847 /* If no more matches and no match was used, try expanding the name
8848 * itself. Finds the long name of a short filename. */
8849 if (!ok && matchname != NULL && gap->ga_len == start_len)
8850 {
8851 STRCPY(s, matchname);
8852#ifdef WIN3264
8853 FindClose(hFind);
8854# ifdef FEAT_MBYTE
8855 if (wn != NULL)
8856 {
8857 vim_free(wn);
Bram Moolenaar36f692d2008-11-20 16:10:17 +00008858 wn = enc_to_utf16(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008859 if (wn != NULL)
8860 hFind = FindFirstFileW(wn, &wfb);
8861 }
8862 if (wn == NULL)
8863# endif
8864 hFind = FindFirstFile(buf, &fb);
8865 ok = (hFind != INVALID_HANDLE_VALUE);
8866#else
8867 ok = (findfirst((char *)buf, &fb,
8868 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
8869#endif
8870 vim_free(matchname);
8871 matchname = NULL;
8872 }
8873 }
8874
8875#ifdef WIN3264
8876 FindClose(hFind);
8877# ifdef FEAT_MBYTE
8878 vim_free(wn);
8879# endif
8880#endif
8881 vim_free(buf);
8882 vim_free(regmatch.regprog);
8883 vim_free(matchname);
8884
8885 matches = gap->ga_len - start_len;
8886 if (matches > 0)
8887 qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
8888 sizeof(char_u *), pstrcmp);
8889 return matches;
8890}
8891
8892 int
8893mch_expandpath(
8894 garray_T *gap,
8895 char_u *path,
8896 int flags) /* EW_* flags */
8897{
Bram Moolenaar231334e2005-07-25 20:46:57 +00008898 return dos_expandpath(gap, path, 0, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008899}
8900# endif /* MSDOS || FEAT_GUI_W16 || WIN3264 */
8901
Bram Moolenaar231334e2005-07-25 20:46:57 +00008902#if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
8903 || defined(PROTO)
8904/*
8905 * Unix style wildcard expansion code.
8906 * It's here because it's used both for Unix and Mac.
8907 */
8908static int pstrcmp __ARGS((const void *, const void *));
8909
8910 static int
8911pstrcmp(a, b)
8912 const void *a, *b;
8913{
8914 return (pathcmp(*(char **)a, *(char **)b, -1));
8915}
8916
8917/*
8918 * Recursively expand one path component into all matching files and/or
8919 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
8920 * "path" has backslashes before chars that are not to be expanded, starting
8921 * at "path + wildoff".
8922 * Return the number of matches found.
8923 * NOTE: much of this is identical to dos_expandpath(), keep in sync!
8924 */
8925 int
8926unix_expandpath(gap, path, wildoff, flags, didstar)
8927 garray_T *gap;
8928 char_u *path;
8929 int wildoff;
8930 int flags; /* EW_* flags */
8931 int didstar; /* expanded "**" once already */
8932{
8933 char_u *buf;
8934 char_u *path_end;
8935 char_u *p, *s, *e;
8936 int start_len = gap->ga_len;
8937 char_u *pat;
8938 regmatch_T regmatch;
8939 int starts_with_dot;
8940 int matches;
8941 int len;
8942 int starstar = FALSE;
8943 static int stardepth = 0; /* depth for "**" expansion */
8944
8945 DIR *dirp;
8946 struct dirent *dp;
8947
8948 /* Expanding "**" may take a long time, check for CTRL-C. */
8949 if (stardepth > 0)
8950 {
8951 ui_breakcheck();
8952 if (got_int)
8953 return 0;
8954 }
8955
8956 /* make room for file name */
8957 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
8958 if (buf == NULL)
8959 return 0;
8960
8961 /*
8962 * Find the first part in the path name that contains a wildcard.
8963 * Copy it into "buf", including the preceding characters.
8964 */
8965 p = buf;
8966 s = buf;
8967 e = NULL;
8968 path_end = path;
8969 while (*path_end != NUL)
8970 {
8971 /* May ignore a wildcard that has a backslash before it; it will
8972 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
8973 if (path_end >= path + wildoff && rem_backslash(path_end))
8974 *p++ = *path_end++;
8975 else if (*path_end == '/')
8976 {
8977 if (e != NULL)
8978 break;
8979 s = p + 1;
8980 }
8981 else if (path_end >= path + wildoff
8982 && vim_strchr((char_u *)"*?[{~$", *path_end) != NULL)
8983 e = p;
8984#ifdef FEAT_MBYTE
8985 if (has_mbyte)
8986 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00008987 len = (*mb_ptr2len)(path_end);
Bram Moolenaar231334e2005-07-25 20:46:57 +00008988 STRNCPY(p, path_end, len);
8989 p += len;
8990 path_end += len;
8991 }
8992 else
8993#endif
8994 *p++ = *path_end++;
8995 }
8996 e = p;
8997 *e = NUL;
8998
8999 /* now we have one wildcard component between "s" and "e" */
9000 /* Remove backslashes between "wildoff" and the start of the wildcard
9001 * component. */
9002 for (p = buf + wildoff; p < s; ++p)
9003 if (rem_backslash(p))
9004 {
Bram Moolenaar8c8de832008-06-24 22:58:06 +00009005 STRMOVE(p, p + 1);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009006 --e;
9007 --s;
9008 }
9009
9010 /* Check for "**" between "s" and "e". */
9011 for (p = s; p < e; ++p)
9012 if (p[0] == '*' && p[1] == '*')
9013 starstar = TRUE;
9014
9015 /* convert the file pattern to a regexp pattern */
9016 starts_with_dot = (*s == '.');
9017 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
9018 if (pat == NULL)
9019 {
9020 vim_free(buf);
9021 return 0;
9022 }
9023
9024 /* compile the regexp into a program */
Bram Moolenaarcc016f52005-12-10 20:23:46 +00009025#ifdef CASE_INSENSITIVE_FILENAME
Bram Moolenaar231334e2005-07-25 20:46:57 +00009026 regmatch.rm_ic = TRUE; /* Behave like Terminal.app */
9027#else
9028 regmatch.rm_ic = FALSE; /* Don't ever ignore case */
9029#endif
9030 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
9031 vim_free(pat);
9032
9033 if (regmatch.regprog == NULL)
9034 {
9035 vim_free(buf);
9036 return 0;
9037 }
9038
9039 /* If "**" is by itself, this is the first time we encounter it and more
9040 * is following then find matches without any directory. */
9041 if (!didstar && stardepth < 100 && starstar && e - s == 2
9042 && *path_end == '/')
9043 {
9044 STRCPY(s, path_end + 1);
9045 ++stardepth;
9046 (void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
9047 --stardepth;
9048 }
9049
9050 /* open the directory for scanning */
9051 *s = NUL;
9052 dirp = opendir(*buf == NUL ? "." : (char *)buf);
9053
9054 /* Find all matching entries */
9055 if (dirp != NULL)
9056 {
9057 for (;;)
9058 {
9059 dp = readdir(dirp);
9060 if (dp == NULL)
9061 break;
9062 if ((dp->d_name[0] != '.' || starts_with_dot)
9063 && vim_regexec(&regmatch, (char_u *)dp->d_name, (colnr_T)0))
9064 {
9065 STRCPY(s, dp->d_name);
9066 len = STRLEN(buf);
9067
9068 if (starstar && stardepth < 100)
9069 {
9070 /* For "**" in the pattern first go deeper in the tree to
9071 * find matches. */
9072 STRCPY(buf + len, "/**");
9073 STRCPY(buf + len + 3, path_end);
9074 ++stardepth;
9075 (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
9076 --stardepth;
9077 }
9078
9079 STRCPY(buf + len, path_end);
9080 if (mch_has_exp_wildcard(path_end)) /* handle more wildcards */
9081 {
9082 /* need to expand another component of the path */
9083 /* remove backslashes for the remaining components only */
9084 (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
9085 }
9086 else
9087 {
9088 /* no more wildcards, check if there is a match */
9089 /* remove backslashes for the remaining components only */
9090 if (*path_end != NUL)
9091 backslash_halve(buf + len + 1);
9092 if (mch_getperm(buf) >= 0) /* add existing file */
9093 {
Bram Moolenaar95e9b492006-03-15 23:04:43 +00009094#ifdef MACOS_CONVERT
Bram Moolenaar231334e2005-07-25 20:46:57 +00009095 size_t precomp_len = STRLEN(buf)+1;
9096 char_u *precomp_buf =
9097 mac_precompose_path(buf, precomp_len, &precomp_len);
Bram Moolenaar95e9b492006-03-15 23:04:43 +00009098
Bram Moolenaar231334e2005-07-25 20:46:57 +00009099 if (precomp_buf)
9100 {
9101 mch_memmove(buf, precomp_buf, precomp_len);
9102 vim_free(precomp_buf);
9103 }
9104#endif
9105 addfile(gap, buf, flags);
9106 }
9107 }
9108 }
9109 }
9110
9111 closedir(dirp);
9112 }
9113
9114 vim_free(buf);
9115 vim_free(regmatch.regprog);
9116
9117 matches = gap->ga_len - start_len;
9118 if (matches > 0)
9119 qsort(((char_u **)gap->ga_data) + start_len, matches,
9120 sizeof(char_u *), pstrcmp);
9121 return matches;
9122}
9123#endif
9124
Bram Moolenaar071d4272004-06-13 20:20:40 +00009125/*
9126 * Generic wildcard expansion code.
9127 *
9128 * Characters in "pat" that should not be expanded must be preceded with a
9129 * backslash. E.g., "/path\ with\ spaces/my\*star*"
9130 *
9131 * Return FAIL when no single file was found. In this case "num_file" is not
9132 * set, and "file" may contain an error message.
9133 * Return OK when some files found. "num_file" is set to the number of
9134 * matches, "file" to the array of matches. Call FreeWild() later.
9135 */
9136 int
9137gen_expand_wildcards(num_pat, pat, num_file, file, flags)
9138 int num_pat; /* number of input patterns */
9139 char_u **pat; /* array of input patterns */
9140 int *num_file; /* resulting number of files */
9141 char_u ***file; /* array of resulting files */
9142 int flags; /* EW_* flags */
9143{
9144 int i;
9145 garray_T ga;
9146 char_u *p;
9147 static int recursive = FALSE;
9148 int add_pat;
9149
9150 /*
9151 * expand_env() is called to expand things like "~user". If this fails,
9152 * it calls ExpandOne(), which brings us back here. In this case, always
9153 * call the machine specific expansion function, if possible. Otherwise,
9154 * return FAIL.
9155 */
9156 if (recursive)
9157#ifdef SPECIAL_WILDCHAR
9158 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
9159#else
9160 return FAIL;
9161#endif
9162
9163#ifdef SPECIAL_WILDCHAR
9164 /*
9165 * If there are any special wildcard characters which we cannot handle
9166 * here, call machine specific function for all the expansion. This
9167 * avoids starting the shell for each argument separately.
9168 * For `=expr` do use the internal function.
9169 */
9170 for (i = 0; i < num_pat; i++)
9171 {
9172 if (vim_strpbrk(pat[i], (char_u *)SPECIAL_WILDCHAR) != NULL
9173# ifdef VIM_BACKTICK
9174 && !(vim_backtick(pat[i]) && pat[i][1] == '=')
9175# endif
9176 )
9177 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
9178 }
9179#endif
9180
9181 recursive = TRUE;
9182
9183 /*
9184 * The matching file names are stored in a growarray. Init it empty.
9185 */
9186 ga_init2(&ga, (int)sizeof(char_u *), 30);
9187
9188 for (i = 0; i < num_pat; ++i)
9189 {
9190 add_pat = -1;
9191 p = pat[i];
9192
9193#ifdef VIM_BACKTICK
9194 if (vim_backtick(p))
9195 add_pat = expand_backtick(&ga, p, flags);
9196 else
9197#endif
9198 {
9199 /*
9200 * First expand environment variables, "~/" and "~user/".
9201 */
9202 if (vim_strpbrk(p, (char_u *)"$~") != NULL)
9203 {
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00009204 p = expand_env_save_opt(p, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009205 if (p == NULL)
9206 p = pat[i];
9207#ifdef UNIX
9208 /*
9209 * On Unix, if expand_env() can't expand an environment
9210 * variable, use the shell to do that. Discard previously
9211 * found file names and start all over again.
9212 */
9213 else if (vim_strpbrk(p, (char_u *)"$~") != NULL)
9214 {
9215 vim_free(p);
Bram Moolenaar782027e2009-06-24 14:25:49 +00009216 ga_clear_strings(&ga);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009217 i = mch_expand_wildcards(num_pat, pat, num_file, file,
9218 flags);
9219 recursive = FALSE;
9220 return i;
9221 }
9222#endif
9223 }
9224
9225 /*
9226 * If there are wildcards: Expand file names and add each match to
9227 * the list. If there is no match, and EW_NOTFOUND is given, add
9228 * the pattern.
9229 * If there are no wildcards: Add the file name if it exists or
9230 * when EW_NOTFOUND is given.
9231 */
9232 if (mch_has_exp_wildcard(p))
9233 add_pat = mch_expandpath(&ga, p, flags);
9234 }
9235
9236 if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
9237 {
9238 char_u *t = backslash_halve_save(p);
9239
9240#if defined(MACOS_CLASSIC)
9241 slash_to_colon(t);
9242#endif
9243 /* When EW_NOTFOUND is used, always add files and dirs. Makes
9244 * "vim c:/" work. */
9245 if (flags & EW_NOTFOUND)
9246 addfile(&ga, t, flags | EW_DIR | EW_FILE);
9247 else if (mch_getperm(t) >= 0)
9248 addfile(&ga, t, flags);
9249 vim_free(t);
9250 }
9251
9252 if (p != pat[i])
9253 vim_free(p);
9254 }
9255
9256 *num_file = ga.ga_len;
9257 *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data : (char_u **)"";
9258
9259 recursive = FALSE;
9260
9261 return (ga.ga_data != NULL) ? OK : FAIL;
9262}
9263
9264# ifdef VIM_BACKTICK
9265
9266/*
9267 * Return TRUE if we can expand this backtick thing here.
9268 */
9269 static int
9270vim_backtick(p)
9271 char_u *p;
9272{
9273 return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
9274}
9275
9276/*
9277 * Expand an item in `backticks` by executing it as a command.
9278 * Currently only works when pat[] starts and ends with a `.
9279 * Returns number of file names found.
9280 */
9281 static int
9282expand_backtick(gap, pat, flags)
9283 garray_T *gap;
9284 char_u *pat;
9285 int flags; /* EW_* flags */
9286{
9287 char_u *p;
9288 char_u *cmd;
9289 char_u *buffer;
9290 int cnt = 0;
9291 int i;
9292
9293 /* Create the command: lop off the backticks. */
9294 cmd = vim_strnsave(pat + 1, (int)STRLEN(pat) - 2);
9295 if (cmd == NULL)
9296 return 0;
9297
9298#ifdef FEAT_EVAL
9299 if (*cmd == '=') /* `={expr}`: Expand expression */
Bram Moolenaar362e1a32006-03-06 23:29:24 +00009300 buffer = eval_to_string(cmd + 1, &p, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009301 else
9302#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00009303 buffer = get_cmd_output(cmd, NULL,
9304 (flags & EW_SILENT) ? SHELL_SILENT : 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009305 vim_free(cmd);
9306 if (buffer == NULL)
9307 return 0;
9308
9309 cmd = buffer;
9310 while (*cmd != NUL)
9311 {
9312 cmd = skipwhite(cmd); /* skip over white space */
9313 p = cmd;
9314 while (*p != NUL && *p != '\r' && *p != '\n') /* skip over entry */
9315 ++p;
9316 /* add an entry if it is not empty */
9317 if (p > cmd)
9318 {
9319 i = *p;
9320 *p = NUL;
9321 addfile(gap, cmd, flags);
9322 *p = i;
9323 ++cnt;
9324 }
9325 cmd = p;
9326 while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
9327 ++cmd;
9328 }
9329
9330 vim_free(buffer);
9331 return cnt;
9332}
9333# endif /* VIM_BACKTICK */
9334
9335/*
9336 * Add a file to a file list. Accepted flags:
9337 * EW_DIR add directories
9338 * EW_FILE add files
Bram Moolenaar1f35bf92006-03-07 22:38:47 +00009339 * EW_EXEC add executable files
Bram Moolenaar071d4272004-06-13 20:20:40 +00009340 * EW_NOTFOUND add even when it doesn't exist
9341 * EW_ADDSLASH add slash after directory name
9342 */
9343 void
9344addfile(gap, f, flags)
9345 garray_T *gap;
9346 char_u *f; /* filename */
9347 int flags;
9348{
9349 char_u *p;
9350 int isdir;
9351
9352 /* if the file/dir doesn't exist, may not add it */
9353 if (!(flags & EW_NOTFOUND) && mch_getperm(f) < 0)
9354 return;
9355
9356#ifdef FNAME_ILLEGAL
9357 /* if the file/dir contains illegal characters, don't add it */
9358 if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
9359 return;
9360#endif
9361
9362 isdir = mch_isdir(f);
9363 if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
9364 return;
9365
Bram Moolenaar1f35bf92006-03-07 22:38:47 +00009366 /* If the file isn't executable, may not add it. Do accept directories. */
9367 if (!isdir && (flags & EW_EXEC) && !mch_can_exe(f))
9368 return;
9369
Bram Moolenaar071d4272004-06-13 20:20:40 +00009370 /* Make room for another item in the file list. */
9371 if (ga_grow(gap, 1) == FAIL)
9372 return;
9373
9374 p = alloc((unsigned)(STRLEN(f) + 1 + isdir));
9375 if (p == NULL)
9376 return;
9377
9378 STRCPY(p, f);
9379#ifdef BACKSLASH_IN_FILENAME
9380 slash_adjust(p);
9381#endif
9382 /*
9383 * Append a slash or backslash after directory names if none is present.
9384 */
9385#ifndef DONT_ADD_PATHSEP_TO_DIR
9386 if (isdir && (flags & EW_ADDSLASH))
9387 add_pathsep(p);
9388#endif
9389 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009390}
9391#endif /* !NO_EXPANDPATH */
9392
9393#if defined(VIM_BACKTICK) || defined(FEAT_EVAL) || defined(PROTO)
9394
9395#ifndef SEEK_SET
9396# define SEEK_SET 0
9397#endif
9398#ifndef SEEK_END
9399# define SEEK_END 2
9400#endif
9401
9402/*
9403 * Get the stdout of an external command.
9404 * Returns an allocated string, or NULL for error.
9405 */
9406 char_u *
Bram Moolenaarc0197e22004-09-13 20:26:32 +00009407get_cmd_output(cmd, infile, flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009408 char_u *cmd;
Bram Moolenaarc0197e22004-09-13 20:26:32 +00009409 char_u *infile; /* optional input file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009410 int flags; /* can be SHELL_SILENT */
9411{
9412 char_u *tempname;
9413 char_u *command;
9414 char_u *buffer = NULL;
9415 int len;
9416 int i = 0;
9417 FILE *fd;
9418
9419 if (check_restricted() || check_secure())
9420 return NULL;
9421
9422 /* get a name for the temp file */
9423 if ((tempname = vim_tempname('o')) == NULL)
9424 {
9425 EMSG(_(e_notmp));
9426 return NULL;
9427 }
9428
9429 /* Add the redirection stuff */
Bram Moolenaarc0197e22004-09-13 20:26:32 +00009430 command = make_filter_cmd(cmd, infile, tempname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009431 if (command == NULL)
9432 goto done;
9433
9434 /*
9435 * Call the shell to execute the command (errors are ignored).
9436 * Don't check timestamps here.
9437 */
9438 ++no_check_timestamps;
9439 call_shell(command, SHELL_DOOUT | SHELL_EXPAND | flags);
9440 --no_check_timestamps;
9441
9442 vim_free(command);
9443
9444 /*
9445 * read the names from the file into memory
9446 */
9447# ifdef VMS
Bram Moolenaar25394022007-05-10 19:06:20 +00009448 /* created temporary file is not always readable as binary */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009449 fd = mch_fopen((char *)tempname, "r");
9450# else
9451 fd = mch_fopen((char *)tempname, READBIN);
9452# endif
9453
9454 if (fd == NULL)
9455 {
9456 EMSG2(_(e_notopen), tempname);
9457 goto done;
9458 }
9459
9460 fseek(fd, 0L, SEEK_END);
9461 len = ftell(fd); /* get size of temp file */
9462 fseek(fd, 0L, SEEK_SET);
9463
9464 buffer = alloc(len + 1);
9465 if (buffer != NULL)
9466 i = (int)fread((char *)buffer, (size_t)1, (size_t)len, fd);
9467 fclose(fd);
9468 mch_remove(tempname);
9469 if (buffer == NULL)
9470 goto done;
9471#ifdef VMS
9472 len = i; /* VMS doesn't give us what we asked for... */
9473#endif
9474 if (i != len)
9475 {
9476 EMSG2(_(e_notread), tempname);
9477 vim_free(buffer);
9478 buffer = NULL;
9479 }
9480 else
9481 buffer[len] = '\0'; /* make sure the buffer is terminated */
9482
9483done:
9484 vim_free(tempname);
9485 return buffer;
9486}
9487#endif
9488
9489/*
9490 * Free the list of files returned by expand_wildcards() or other expansion
9491 * functions.
9492 */
9493 void
9494FreeWild(count, files)
9495 int count;
9496 char_u **files;
9497{
Bram Moolenaarfc1421e2006-04-20 22:17:20 +00009498 if (count <= 0 || files == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009499 return;
9500#if defined(__EMX__) && defined(__ALWAYS_HAS_TRAILING_NULL_POINTER) /* XXX */
9501 /*
9502 * Is this still OK for when other functions than expand_wildcards() have
9503 * been used???
9504 */
9505 _fnexplodefree((char **)files);
9506#else
9507 while (count--)
9508 vim_free(files[count]);
9509 vim_free(files);
9510#endif
9511}
9512
9513/*
9514 * return TRUE when need to go to Insert mode because of 'insertmode'.
9515 * Don't do this when still processing a command or a mapping.
9516 * Don't do this when inside a ":normal" command.
9517 */
9518 int
9519goto_im()
9520{
9521 return (p_im && stuff_empty() && typebuf_typed());
9522}