blob: 80e7fa693db0390dc88ae431b263265c124bc0fe [file] [log] [blame]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001/* vi:set ts=8 sts=4 sw=4:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * misc1.c: functions that didn't seem to fit elsewhere
12 */
13
14#include "vim.h"
15#include "version.h"
16
Bram Moolenaar071d4272004-06-13 20:20:40 +000017static char_u *vim_version_dir __ARGS((char_u *vimdir));
18static char_u *remove_tail __ARGS((char_u *p, char_u *pend, char_u *name));
Bram Moolenaar071d4272004-06-13 20:20:40 +000019static int copy_indent __ARGS((int size, char_u *src));
20
21/*
22 * Count the size (in window cells) of the indent in the current line.
23 */
24 int
25get_indent()
26{
27 return get_indent_str(ml_get_curline(), (int)curbuf->b_p_ts);
28}
29
30/*
31 * Count the size (in window cells) of the indent in line "lnum".
32 */
33 int
34get_indent_lnum(lnum)
35 linenr_T lnum;
36{
37 return get_indent_str(ml_get(lnum), (int)curbuf->b_p_ts);
38}
39
40#if defined(FEAT_FOLDING) || defined(PROTO)
41/*
42 * Count the size (in window cells) of the indent in line "lnum" of buffer
43 * "buf".
44 */
45 int
46get_indent_buf(buf, lnum)
47 buf_T *buf;
48 linenr_T lnum;
49{
50 return get_indent_str(ml_get_buf(buf, lnum, FALSE), (int)buf->b_p_ts);
51}
52#endif
53
54/*
55 * count the size (in window cells) of the indent in line "ptr", with
56 * 'tabstop' at "ts"
57 */
Bram Moolenaar4399ef42005-02-12 14:29:27 +000058 int
Bram Moolenaar071d4272004-06-13 20:20:40 +000059get_indent_str(ptr, ts)
60 char_u *ptr;
61 int ts;
62{
63 int count = 0;
64
65 for ( ; *ptr; ++ptr)
66 {
67 if (*ptr == TAB) /* count a tab for what it is worth */
68 count += ts - (count % ts);
69 else if (*ptr == ' ')
70 ++count; /* count a space for one */
71 else
72 break;
73 }
Bram Moolenaar4399ef42005-02-12 14:29:27 +000074 return count;
Bram Moolenaar071d4272004-06-13 20:20:40 +000075}
76
77/*
78 * Set the indent of the current line.
79 * Leaves the cursor on the first non-blank in the line.
80 * Caller must take care of undo.
81 * "flags":
82 * SIN_CHANGED: call changed_bytes() if the line was changed.
83 * SIN_INSERT: insert the indent in front of the line.
84 * SIN_UNDO: save line for undo before changing it.
85 * Returns TRUE if the line was changed.
86 */
87 int
88set_indent(size, flags)
Bram Moolenaar5002c292007-07-24 13:26:15 +000089 int size; /* measured in spaces */
Bram Moolenaar071d4272004-06-13 20:20:40 +000090 int flags;
91{
92 char_u *p;
93 char_u *newline;
94 char_u *oldline;
95 char_u *s;
96 int todo;
Bram Moolenaar5002c292007-07-24 13:26:15 +000097 int ind_len; /* measured in characters */
Bram Moolenaar071d4272004-06-13 20:20:40 +000098 int line_len;
99 int doit = FALSE;
Bram Moolenaar5002c292007-07-24 13:26:15 +0000100 int ind_done = 0; /* measured in spaces */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000101 int tab_pad;
Bram Moolenaar5409c052005-03-18 20:27:04 +0000102 int retval = FALSE;
Bram Moolenaar4d64b782007-08-14 20:16:42 +0000103 int orig_char_len = -1; /* number of initial whitespace chars when
Bram Moolenaar5002c292007-07-24 13:26:15 +0000104 'et' and 'pi' are both set */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000105
106 /*
107 * First check if there is anything to do and compute the number of
108 * characters needed for the indent.
109 */
110 todo = size;
111 ind_len = 0;
112 p = oldline = ml_get_curline();
113
114 /* Calculate the buffer size for the new indent, and check to see if it
115 * isn't already set */
116
Bram Moolenaar5002c292007-07-24 13:26:15 +0000117 /* if 'expandtab' isn't set: use TABs; if both 'expandtab' and
118 * 'preserveindent' are set count the number of characters at the
119 * beginning of the line to be copied */
120 if (!curbuf->b_p_et || (!(flags & SIN_INSERT) && curbuf->b_p_pi))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000121 {
122 /* If 'preserveindent' is set then reuse as much as possible of
123 * the existing indent structure for the new indent */
124 if (!(flags & SIN_INSERT) && curbuf->b_p_pi)
125 {
126 ind_done = 0;
127
128 /* count as many characters as we can use */
129 while (todo > 0 && vim_iswhite(*p))
130 {
131 if (*p == TAB)
132 {
133 tab_pad = (int)curbuf->b_p_ts
134 - (ind_done % (int)curbuf->b_p_ts);
135 /* stop if this tab will overshoot the target */
136 if (todo < tab_pad)
137 break;
138 todo -= tab_pad;
139 ++ind_len;
140 ind_done += tab_pad;
141 }
142 else
143 {
144 --todo;
145 ++ind_len;
146 ++ind_done;
147 }
148 ++p;
149 }
150
Bram Moolenaar5002c292007-07-24 13:26:15 +0000151 /* Set initial number of whitespace chars to copy if we are
152 * preserving indent but expandtab is set */
153 if (curbuf->b_p_et)
154 orig_char_len = ind_len;
155
Bram Moolenaar071d4272004-06-13 20:20:40 +0000156 /* Fill to next tabstop with a tab, if possible */
157 tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
Bram Moolenaar4d64b782007-08-14 20:16:42 +0000158 if (todo >= tab_pad && orig_char_len == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000159 {
160 doit = TRUE;
161 todo -= tab_pad;
162 ++ind_len;
163 /* ind_done += tab_pad; */
164 }
165 }
166
167 /* count tabs required for indent */
168 while (todo >= (int)curbuf->b_p_ts)
169 {
170 if (*p != TAB)
171 doit = TRUE;
172 else
173 ++p;
174 todo -= (int)curbuf->b_p_ts;
175 ++ind_len;
176 /* ind_done += (int)curbuf->b_p_ts; */
177 }
178 }
179 /* count spaces required for indent */
180 while (todo > 0)
181 {
182 if (*p != ' ')
183 doit = TRUE;
184 else
185 ++p;
186 --todo;
187 ++ind_len;
188 /* ++ind_done; */
189 }
190
191 /* Return if the indent is OK already. */
192 if (!doit && !vim_iswhite(*p) && !(flags & SIN_INSERT))
193 return FALSE;
194
195 /* Allocate memory for the new line. */
196 if (flags & SIN_INSERT)
197 p = oldline;
198 else
199 p = skipwhite(p);
200 line_len = (int)STRLEN(p) + 1;
Bram Moolenaar5002c292007-07-24 13:26:15 +0000201
202 /* If 'preserveindent' and 'expandtab' are both set keep the original
203 * characters and allocate accordingly. We will fill the rest with spaces
204 * after the if (!curbuf->b_p_et) below. */
Bram Moolenaar4d64b782007-08-14 20:16:42 +0000205 if (orig_char_len != -1)
Bram Moolenaar5002c292007-07-24 13:26:15 +0000206 {
207 newline = alloc(orig_char_len + size - ind_done + line_len);
208 if (newline == NULL)
209 return FALSE;
Bram Moolenaar4d64b782007-08-14 20:16:42 +0000210 todo = size - ind_done;
211 ind_len = orig_char_len + todo; /* Set total length of indent in
212 * characters, which may have been
213 * undercounted until now */
Bram Moolenaar5002c292007-07-24 13:26:15 +0000214 p = oldline;
215 s = newline;
216 while (orig_char_len > 0)
217 {
218 *s++ = *p++;
219 orig_char_len--;
220 }
Bram Moolenaar913626c2008-01-03 11:43:42 +0000221
Bram Moolenaar5002c292007-07-24 13:26:15 +0000222 /* Skip over any additional white space (useful when newindent is less
223 * than old) */
224 while (vim_iswhite(*p))
Bram Moolenaar913626c2008-01-03 11:43:42 +0000225 ++p;
Bram Moolenaarcc00b952007-08-11 12:32:57 +0000226
Bram Moolenaar5002c292007-07-24 13:26:15 +0000227 }
228 else
229 {
230 todo = size;
231 newline = alloc(ind_len + line_len);
232 if (newline == NULL)
233 return FALSE;
234 s = newline;
235 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000236
237 /* Put the characters in the new line. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000238 /* if 'expandtab' isn't set: use TABs */
239 if (!curbuf->b_p_et)
240 {
241 /* If 'preserveindent' is set then reuse as much as possible of
242 * the existing indent structure for the new indent */
243 if (!(flags & SIN_INSERT) && curbuf->b_p_pi)
244 {
245 p = oldline;
246 ind_done = 0;
247
248 while (todo > 0 && vim_iswhite(*p))
249 {
250 if (*p == TAB)
251 {
252 tab_pad = (int)curbuf->b_p_ts
253 - (ind_done % (int)curbuf->b_p_ts);
254 /* stop if this tab will overshoot the target */
255 if (todo < tab_pad)
256 break;
257 todo -= tab_pad;
258 ind_done += tab_pad;
259 }
260 else
261 {
262 --todo;
263 ++ind_done;
264 }
265 *s++ = *p++;
266 }
267
268 /* Fill to next tabstop with a tab, if possible */
269 tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
270 if (todo >= tab_pad)
271 {
272 *s++ = TAB;
273 todo -= tab_pad;
274 }
275
276 p = skipwhite(p);
277 }
278
279 while (todo >= (int)curbuf->b_p_ts)
280 {
281 *s++ = TAB;
282 todo -= (int)curbuf->b_p_ts;
283 }
284 }
285 while (todo > 0)
286 {
287 *s++ = ' ';
288 --todo;
289 }
290 mch_memmove(s, p, (size_t)line_len);
291
292 /* Replace the line (unless undo fails). */
293 if (!(flags & SIN_UNDO) || u_savesub(curwin->w_cursor.lnum) == OK)
294 {
295 ml_replace(curwin->w_cursor.lnum, newline, FALSE);
296 if (flags & SIN_CHANGED)
297 changed_bytes(curwin->w_cursor.lnum, 0);
298 /* Correct saved cursor position if it's after the indent. */
299 if (saved_cursor.lnum == curwin->w_cursor.lnum
300 && saved_cursor.col >= (colnr_T)(p - oldline))
Bram Moolenaara93fa7e2006-04-17 22:14:47 +0000301 saved_cursor.col += ind_len - (colnr_T)(p - oldline);
Bram Moolenaar5409c052005-03-18 20:27:04 +0000302 retval = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000303 }
304 else
305 vim_free(newline);
306
307 curwin->w_cursor.col = ind_len;
Bram Moolenaar5409c052005-03-18 20:27:04 +0000308 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000309}
310
311/*
312 * Copy the indent from ptr to the current line (and fill to size)
313 * Leaves the cursor on the first non-blank in the line.
314 * Returns TRUE if the line was changed.
315 */
316 static int
317copy_indent(size, src)
318 int size;
319 char_u *src;
320{
321 char_u *p = NULL;
322 char_u *line = NULL;
323 char_u *s;
324 int todo;
325 int ind_len;
326 int line_len = 0;
327 int tab_pad;
328 int ind_done;
329 int round;
330
331 /* Round 1: compute the number of characters needed for the indent
332 * Round 2: copy the characters. */
333 for (round = 1; round <= 2; ++round)
334 {
335 todo = size;
336 ind_len = 0;
337 ind_done = 0;
338 s = src;
339
340 /* Count/copy the usable portion of the source line */
341 while (todo > 0 && vim_iswhite(*s))
342 {
343 if (*s == TAB)
344 {
345 tab_pad = (int)curbuf->b_p_ts
346 - (ind_done % (int)curbuf->b_p_ts);
347 /* Stop if this tab will overshoot the target */
348 if (todo < tab_pad)
349 break;
350 todo -= tab_pad;
351 ind_done += tab_pad;
352 }
353 else
354 {
355 --todo;
356 ++ind_done;
357 }
358 ++ind_len;
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000359 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000360 *p++ = *s;
361 ++s;
362 }
363
364 /* Fill to next tabstop with a tab, if possible */
365 tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
Bram Moolenaarc42e7ed2011-09-07 19:58:09 +0200366 if (todo >= tab_pad && !curbuf->b_p_et)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000367 {
368 todo -= tab_pad;
369 ++ind_len;
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000370 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000371 *p++ = TAB;
372 }
373
374 /* Add tabs required for indent */
Bram Moolenaarc42e7ed2011-09-07 19:58:09 +0200375 while (todo >= (int)curbuf->b_p_ts && !curbuf->b_p_et)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000376 {
377 todo -= (int)curbuf->b_p_ts;
378 ++ind_len;
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000379 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000380 *p++ = TAB;
381 }
382
383 /* Count/add spaces required for indent */
384 while (todo > 0)
385 {
386 --todo;
387 ++ind_len;
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000388 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000389 *p++ = ' ';
390 }
391
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000392 if (p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000393 {
394 /* Allocate memory for the result: the copied indent, new indent
395 * and the rest of the line. */
396 line_len = (int)STRLEN(ml_get_curline()) + 1;
397 line = alloc(ind_len + line_len);
398 if (line == NULL)
399 return FALSE;
400 p = line;
401 }
402 }
403
404 /* Append the original line */
405 mch_memmove(p, ml_get_curline(), (size_t)line_len);
406
407 /* Replace the line */
408 ml_replace(curwin->w_cursor.lnum, line, FALSE);
409
410 /* Put the cursor after the indent. */
411 curwin->w_cursor.col = ind_len;
412 return TRUE;
413}
414
415/*
416 * Return the indent of the current line after a number. Return -1 if no
417 * number was found. Used for 'n' in 'formatoptions': numbered list.
Bram Moolenaar86b68352004-12-27 21:59:20 +0000418 * Since a pattern is used it can actually handle more than numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000419 */
420 int
421get_number_indent(lnum)
422 linenr_T lnum;
423{
Bram Moolenaar071d4272004-06-13 20:20:40 +0000424 colnr_T col;
425 pos_T pos;
426
427 if (lnum > curbuf->b_ml.ml_line_count)
428 return -1;
Bram Moolenaar86b68352004-12-27 21:59:20 +0000429 pos.lnum = 0;
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200430
431#ifdef FEAT_COMMENTS
432 if (has_format_option(FO_Q_COMS) && has_format_option(FO_Q_NUMBER))
Bram Moolenaar86b68352004-12-27 21:59:20 +0000433 {
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200434 regmatch_T regmatch;
435 int lead_len; /* length of comment leader */
436
437 lead_len = get_leader_len(ml_get(lnum), NULL, FALSE, TRUE);
438 regmatch.regprog = vim_regcomp(curbuf->b_p_flp, RE_MAGIC);
439 if (regmatch.regprog != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +0000440 {
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200441 regmatch.rm_ic = FALSE;
442
443 /* vim_regexec() expects a pointer to a line. This lets us
444 * start matching for the flp beyond any comment leader... */
445 if (vim_regexec(&regmatch, ml_get(lnum) + lead_len, (colnr_T)0))
446 {
447 pos.lnum = lnum;
Bram Moolenaar36105782012-06-14 20:59:25 +0200448 pos.col = (colnr_T)(*regmatch.endp - ml_get(lnum));
Bram Moolenaar86b68352004-12-27 21:59:20 +0000449#ifdef FEAT_VIRTUALEDIT
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200450 pos.coladd = 0;
Bram Moolenaar86b68352004-12-27 21:59:20 +0000451#endif
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200452 }
Bram Moolenaar86b68352004-12-27 21:59:20 +0000453 }
454 vim_free(regmatch.regprog);
455 }
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200456 else
457 {
458 /*
459 * What follows is the orig code that is not "comment aware"...
460 *
461 * I'm not sure if regmmatch_T (multi-match) is needed in this case.
462 * It may be true that this section would work properly using the
Bram Moolenaardc7e85e2012-06-20 12:40:08 +0200463 * regmatch_T code above, in which case, these two separate sections
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200464 * should be consolidated w/ FEAT_COMMENTS making lead_len > 0...
465 */
466#endif
467 regmmatch_T regmatch;
468
469 regmatch.regprog = vim_regcomp(curbuf->b_p_flp, RE_MAGIC);
470
471 if (regmatch.regprog != NULL)
472 {
473 regmatch.rmm_ic = FALSE;
474 regmatch.rmm_maxcol = 0;
475 if (vim_regexec_multi(&regmatch, curwin, curbuf,
476 lnum, (colnr_T)0, NULL))
477 {
478 pos.lnum = regmatch.endpos[0].lnum + lnum;
479 pos.col = regmatch.endpos[0].col;
480#ifdef FEAT_VIRTUALEDIT
481 pos.coladd = 0;
482#endif
483 }
484 vim_free(regmatch.regprog);
485 }
486#ifdef FEAT_COMMENTS
487 }
488#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +0000489
490 if (pos.lnum == 0 || *ml_get_pos(&pos) == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000491 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000492 getvcol(curwin, &pos, &col, NULL, NULL);
493 return (int)col;
494}
495
496#if defined(FEAT_CINDENT) || defined(FEAT_SMARTINDENT)
497
498static int cin_is_cinword __ARGS((char_u *line));
499
500/*
501 * Return TRUE if the string "line" starts with a word from 'cinwords'.
502 */
503 static int
504cin_is_cinword(line)
505 char_u *line;
506{
507 char_u *cinw;
508 char_u *cinw_buf;
509 int cinw_len;
510 int retval = FALSE;
511 int len;
512
513 cinw_len = (int)STRLEN(curbuf->b_p_cinw) + 1;
514 cinw_buf = alloc((unsigned)cinw_len);
515 if (cinw_buf != NULL)
516 {
517 line = skipwhite(line);
518 for (cinw = curbuf->b_p_cinw; *cinw; )
519 {
520 len = copy_option_part(&cinw, cinw_buf, cinw_len, ",");
521 if (STRNCMP(line, cinw_buf, len) == 0
522 && (!vim_iswordc(line[len]) || !vim_iswordc(line[len - 1])))
523 {
524 retval = TRUE;
525 break;
526 }
527 }
528 vim_free(cinw_buf);
529 }
530 return retval;
531}
532#endif
533
534/*
535 * open_line: Add a new line below or above the current line.
536 *
537 * For VREPLACE mode, we only add a new line when we get to the end of the
538 * file, otherwise we just start replacing the next line.
539 *
540 * Caller must take care of undo. Since VREPLACE may affect any number of
541 * lines however, it may call u_save_cursor() again when starting to change a
542 * new line.
543 * "flags": OPENLINE_DELSPACES delete spaces after cursor
544 * OPENLINE_DO_COM format comments
545 * OPENLINE_KEEPTRAIL keep trailing spaces
546 * OPENLINE_MARKFIX adjust mark positions after the line break
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200547 * OPENLINE_COM_LIST format comments with list or 2nd line indent
548 *
549 * "second_line_indent": indent for after ^^D in Insert mode or if flag
550 * OPENLINE_COM_LIST
Bram Moolenaar071d4272004-06-13 20:20:40 +0000551 *
552 * Return TRUE for success, FALSE for failure
553 */
554 int
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200555open_line(dir, flags, second_line_indent)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000556 int dir; /* FORWARD or BACKWARD */
557 int flags;
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200558 int second_line_indent;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000559{
560 char_u *saved_line; /* copy of the original line */
561 char_u *next_line = NULL; /* copy of the next line */
562 char_u *p_extra = NULL; /* what goes to next line */
563 int less_cols = 0; /* less columns for mark in new line */
564 int less_cols_off = 0; /* columns to skip for mark adjust */
565 pos_T old_cursor; /* old cursor position */
566 int newcol = 0; /* new cursor column */
567 int newindent = 0; /* auto-indent of the new line */
568 int n;
569 int trunc_line = FALSE; /* truncate current line afterwards */
570 int retval = FALSE; /* return value, default is FAIL */
571#ifdef FEAT_COMMENTS
572 int extra_len = 0; /* length of p_extra string */
573 int lead_len; /* length of comment leader */
574 char_u *lead_flags; /* position in 'comments' for comment leader */
575 char_u *leader = NULL; /* copy of comment leader */
576#endif
577 char_u *allocated = NULL; /* allocated memory */
578#if defined(FEAT_SMARTINDENT) || defined(FEAT_VREPLACE) || defined(FEAT_LISP) \
579 || defined(FEAT_CINDENT) || defined(FEAT_COMMENTS)
580 char_u *p;
581#endif
582 int saved_char = NUL; /* init for GCC */
583#if defined(FEAT_SMARTINDENT) || defined(FEAT_COMMENTS)
584 pos_T *pos;
585#endif
586#ifdef FEAT_SMARTINDENT
587 int do_si = (!p_paste && curbuf->b_p_si
588# ifdef FEAT_CINDENT
589 && !curbuf->b_p_cin
590# endif
591 );
592 int no_si = FALSE; /* reset did_si afterwards */
593 int first_char = NUL; /* init for GCC */
594#endif
595#if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
596 int vreplace_mode;
597#endif
598 int did_append; /* appended a new line */
599 int saved_pi = curbuf->b_p_pi; /* copy of preserveindent setting */
600
601 /*
602 * make a copy of the current line so we can mess with it
603 */
604 saved_line = vim_strsave(ml_get_curline());
605 if (saved_line == NULL) /* out of memory! */
606 return FALSE;
607
608#ifdef FEAT_VREPLACE
609 if (State & VREPLACE_FLAG)
610 {
611 /*
612 * With VREPLACE we make a copy of the next line, which we will be
613 * starting to replace. First make the new line empty and let vim play
614 * with the indenting and comment leader to its heart's content. Then
615 * we grab what it ended up putting on the new line, put back the
616 * original line, and call ins_char() to put each new character onto
617 * the line, replacing what was there before and pushing the right
618 * stuff onto the replace stack. -- webb.
619 */
620 if (curwin->w_cursor.lnum < orig_line_count)
621 next_line = vim_strsave(ml_get(curwin->w_cursor.lnum + 1));
622 else
623 next_line = vim_strsave((char_u *)"");
624 if (next_line == NULL) /* out of memory! */
625 goto theend;
626
627 /*
628 * In VREPLACE mode, a NL replaces the rest of the line, and starts
629 * replacing the next line, so push all of the characters left on the
630 * line onto the replace stack. We'll push any other characters that
631 * might be replaced at the start of the next line (due to autoindent
632 * etc) a bit later.
633 */
634 replace_push(NUL); /* Call twice because BS over NL expects it */
635 replace_push(NUL);
636 p = saved_line + curwin->w_cursor.col;
637 while (*p != NUL)
Bram Moolenaar2c994e82008-01-02 16:49:36 +0000638 {
639#ifdef FEAT_MBYTE
640 if (has_mbyte)
641 p += replace_push_mb(p);
642 else
643#endif
644 replace_push(*p++);
645 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000646 saved_line[curwin->w_cursor.col] = NUL;
647 }
648#endif
649
650 if ((State & INSERT)
651#ifdef FEAT_VREPLACE
652 && !(State & VREPLACE_FLAG)
653#endif
654 )
655 {
656 p_extra = saved_line + curwin->w_cursor.col;
657#ifdef FEAT_SMARTINDENT
658 if (do_si) /* need first char after new line break */
659 {
660 p = skipwhite(p_extra);
661 first_char = *p;
662 }
663#endif
664#ifdef FEAT_COMMENTS
665 extra_len = (int)STRLEN(p_extra);
666#endif
667 saved_char = *p_extra;
668 *p_extra = NUL;
669 }
670
671 u_clearline(); /* cannot do "U" command when adding lines */
672#ifdef FEAT_SMARTINDENT
673 did_si = FALSE;
674#endif
675 ai_col = 0;
676
677 /*
678 * If we just did an auto-indent, then we didn't type anything on
679 * the prior line, and it should be truncated. Do this even if 'ai' is not
680 * set because automatically inserting a comment leader also sets did_ai.
681 */
682 if (dir == FORWARD && did_ai)
683 trunc_line = TRUE;
684
685 /*
686 * If 'autoindent' and/or 'smartindent' is set, try to figure out what
687 * indent to use for the new line.
688 */
689 if (curbuf->b_p_ai
690#ifdef FEAT_SMARTINDENT
691 || do_si
692#endif
693 )
694 {
695 /*
696 * count white space on current line
697 */
698 newindent = get_indent_str(saved_line, (int)curbuf->b_p_ts);
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200699 if (newindent == 0 && !(flags & OPENLINE_COM_LIST))
700 newindent = second_line_indent; /* for ^^D command in insert mode */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000701
702#ifdef FEAT_SMARTINDENT
703 /*
704 * Do smart indenting.
705 * In insert/replace mode (only when dir == FORWARD)
706 * we may move some text to the next line. If it starts with '{'
707 * don't add an indent. Fixes inserting a NL before '{' in line
708 * "if (condition) {"
709 */
710 if (!trunc_line && do_si && *saved_line != NUL
711 && (p_extra == NULL || first_char != '{'))
712 {
713 char_u *ptr;
714 char_u last_char;
715
716 old_cursor = curwin->w_cursor;
717 ptr = saved_line;
718# ifdef FEAT_COMMENTS
719 if (flags & OPENLINE_DO_COM)
Bram Moolenaar81340392012-06-06 16:12:59 +0200720 lead_len = get_leader_len(ptr, NULL, FALSE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000721 else
722 lead_len = 0;
723# endif
724 if (dir == FORWARD)
725 {
726 /*
727 * Skip preprocessor directives, unless they are
728 * recognised as comments.
729 */
730 if (
731# ifdef FEAT_COMMENTS
732 lead_len == 0 &&
733# endif
734 ptr[0] == '#')
735 {
736 while (ptr[0] == '#' && curwin->w_cursor.lnum > 1)
737 ptr = ml_get(--curwin->w_cursor.lnum);
738 newindent = get_indent();
739 }
740# ifdef FEAT_COMMENTS
741 if (flags & OPENLINE_DO_COM)
Bram Moolenaar81340392012-06-06 16:12:59 +0200742 lead_len = get_leader_len(ptr, NULL, FALSE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000743 else
744 lead_len = 0;
745 if (lead_len > 0)
746 {
747 /*
748 * This case gets the following right:
749 * \*
750 * * A comment (read '\' as '/').
751 * *\
752 * #define IN_THE_WAY
753 * This should line up here;
754 */
755 p = skipwhite(ptr);
756 if (p[0] == '/' && p[1] == '*')
757 p++;
758 if (p[0] == '*')
759 {
760 for (p++; *p; p++)
761 {
762 if (p[0] == '/' && p[-1] == '*')
763 {
764 /*
765 * End of C comment, indent should line up
766 * with the line containing the start of
767 * the comment
768 */
769 curwin->w_cursor.col = (colnr_T)(p - ptr);
770 if ((pos = findmatch(NULL, NUL)) != NULL)
771 {
772 curwin->w_cursor.lnum = pos->lnum;
773 newindent = get_indent();
774 }
775 }
776 }
777 }
778 }
779 else /* Not a comment line */
780# endif
781 {
782 /* Find last non-blank in line */
783 p = ptr + STRLEN(ptr) - 1;
784 while (p > ptr && vim_iswhite(*p))
785 --p;
786 last_char = *p;
787
788 /*
789 * find the character just before the '{' or ';'
790 */
791 if (last_char == '{' || last_char == ';')
792 {
793 if (p > ptr)
794 --p;
795 while (p > ptr && vim_iswhite(*p))
796 --p;
797 }
798 /*
799 * Try to catch lines that are split over multiple
800 * lines. eg:
801 * if (condition &&
802 * condition) {
803 * Should line up here!
804 * }
805 */
806 if (*p == ')')
807 {
808 curwin->w_cursor.col = (colnr_T)(p - ptr);
809 if ((pos = findmatch(NULL, '(')) != NULL)
810 {
811 curwin->w_cursor.lnum = pos->lnum;
812 newindent = get_indent();
813 ptr = ml_get_curline();
814 }
815 }
816 /*
817 * If last character is '{' do indent, without
818 * checking for "if" and the like.
819 */
820 if (last_char == '{')
821 {
822 did_si = TRUE; /* do indent */
823 no_si = TRUE; /* don't delete it when '{' typed */
824 }
825 /*
826 * Look for "if" and the like, use 'cinwords'.
827 * Don't do this if the previous line ended in ';' or
828 * '}'.
829 */
830 else if (last_char != ';' && last_char != '}'
831 && cin_is_cinword(ptr))
832 did_si = TRUE;
833 }
834 }
835 else /* dir == BACKWARD */
836 {
837 /*
838 * Skip preprocessor directives, unless they are
839 * recognised as comments.
840 */
841 if (
842# ifdef FEAT_COMMENTS
843 lead_len == 0 &&
844# endif
845 ptr[0] == '#')
846 {
847 int was_backslashed = FALSE;
848
849 while ((ptr[0] == '#' || was_backslashed) &&
850 curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
851 {
852 if (*ptr && ptr[STRLEN(ptr) - 1] == '\\')
853 was_backslashed = TRUE;
854 else
855 was_backslashed = FALSE;
856 ptr = ml_get(++curwin->w_cursor.lnum);
857 }
858 if (was_backslashed)
859 newindent = 0; /* Got to end of file */
860 else
861 newindent = get_indent();
862 }
863 p = skipwhite(ptr);
864 if (*p == '}') /* if line starts with '}': do indent */
865 did_si = TRUE;
866 else /* can delete indent when '{' typed */
867 can_si_back = TRUE;
868 }
869 curwin->w_cursor = old_cursor;
870 }
871 if (do_si)
872 can_si = TRUE;
873#endif /* FEAT_SMARTINDENT */
874
875 did_ai = TRUE;
876 }
877
878#ifdef FEAT_COMMENTS
879 /*
880 * Find out if the current line starts with a comment leader.
881 * This may then be inserted in front of the new line.
882 */
883 end_comment_pending = NUL;
884 if (flags & OPENLINE_DO_COM)
Bram Moolenaar81340392012-06-06 16:12:59 +0200885 lead_len = get_leader_len(saved_line, &lead_flags, dir == BACKWARD, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000886 else
887 lead_len = 0;
888 if (lead_len > 0)
889 {
890 char_u *lead_repl = NULL; /* replaces comment leader */
891 int lead_repl_len = 0; /* length of *lead_repl */
892 char_u lead_middle[COM_MAX_LEN]; /* middle-comment string */
893 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
894 char_u *comment_end = NULL; /* where lead_end has been found */
895 int extra_space = FALSE; /* append extra space */
896 int current_flag;
897 int require_blank = FALSE; /* requires blank after middle */
898 char_u *p2;
899
900 /*
901 * If the comment leader has the start, middle or end flag, it may not
902 * be used or may be replaced with the middle leader.
903 */
904 for (p = lead_flags; *p && *p != ':'; ++p)
905 {
906 if (*p == COM_BLANK)
907 {
908 require_blank = TRUE;
909 continue;
910 }
911 if (*p == COM_START || *p == COM_MIDDLE)
912 {
913 current_flag = *p;
914 if (*p == COM_START)
915 {
916 /*
917 * Doing "O" on a start of comment does not insert leader.
918 */
919 if (dir == BACKWARD)
920 {
921 lead_len = 0;
922 break;
923 }
924
925 /* find start of middle part */
926 (void)copy_option_part(&p, lead_middle, COM_MAX_LEN, ",");
927 require_blank = FALSE;
928 }
929
930 /*
931 * Isolate the strings of the middle and end leader.
932 */
933 while (*p && p[-1] != ':') /* find end of middle flags */
934 {
935 if (*p == COM_BLANK)
936 require_blank = TRUE;
937 ++p;
938 }
939 (void)copy_option_part(&p, lead_middle, COM_MAX_LEN, ",");
940
941 while (*p && p[-1] != ':') /* find end of end flags */
942 {
943 /* Check whether we allow automatic ending of comments */
944 if (*p == COM_AUTO_END)
945 end_comment_pending = -1; /* means we want to set it */
946 ++p;
947 }
948 n = copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
949
950 if (end_comment_pending == -1) /* we can set it now */
951 end_comment_pending = lead_end[n - 1];
952
953 /*
954 * If the end of the comment is in the same line, don't use
955 * the comment leader.
956 */
957 if (dir == FORWARD)
958 {
959 for (p = saved_line + lead_len; *p; ++p)
960 if (STRNCMP(p, lead_end, n) == 0)
961 {
962 comment_end = p;
963 lead_len = 0;
964 break;
965 }
966 }
967
968 /*
969 * Doing "o" on a start of comment inserts the middle leader.
970 */
971 if (lead_len > 0)
972 {
973 if (current_flag == COM_START)
974 {
975 lead_repl = lead_middle;
976 lead_repl_len = (int)STRLEN(lead_middle);
977 }
978
979 /*
980 * If we have hit RETURN immediately after the start
981 * comment leader, then put a space after the middle
982 * comment leader on the next line.
983 */
984 if (!vim_iswhite(saved_line[lead_len - 1])
985 && ((p_extra != NULL
986 && (int)curwin->w_cursor.col == lead_len)
987 || (p_extra == NULL
988 && saved_line[lead_len] == NUL)
989 || require_blank))
990 extra_space = TRUE;
991 }
992 break;
993 }
994 if (*p == COM_END)
995 {
996 /*
997 * Doing "o" on the end of a comment does not insert leader.
998 * Remember where the end is, might want to use it to find the
999 * start (for C-comments).
1000 */
1001 if (dir == FORWARD)
1002 {
1003 comment_end = skipwhite(saved_line);
1004 lead_len = 0;
1005 break;
1006 }
1007
1008 /*
1009 * Doing "O" on the end of a comment inserts the middle leader.
1010 * Find the string for the middle leader, searching backwards.
1011 */
1012 while (p > curbuf->b_p_com && *p != ',')
1013 --p;
1014 for (lead_repl = p; lead_repl > curbuf->b_p_com
1015 && lead_repl[-1] != ':'; --lead_repl)
1016 ;
1017 lead_repl_len = (int)(p - lead_repl);
1018
1019 /* We can probably always add an extra space when doing "O" on
1020 * the comment-end */
1021 extra_space = TRUE;
1022
1023 /* Check whether we allow automatic ending of comments */
1024 for (p2 = p; *p2 && *p2 != ':'; p2++)
1025 {
1026 if (*p2 == COM_AUTO_END)
1027 end_comment_pending = -1; /* means we want to set it */
1028 }
1029 if (end_comment_pending == -1)
1030 {
1031 /* Find last character in end-comment string */
1032 while (*p2 && *p2 != ',')
1033 p2++;
1034 end_comment_pending = p2[-1];
1035 }
1036 break;
1037 }
1038 if (*p == COM_FIRST)
1039 {
1040 /*
1041 * Comment leader for first line only: Don't repeat leader
1042 * when using "O", blank out leader when using "o".
1043 */
1044 if (dir == BACKWARD)
1045 lead_len = 0;
1046 else
1047 {
1048 lead_repl = (char_u *)"";
1049 lead_repl_len = 0;
1050 }
1051 break;
1052 }
1053 }
1054 if (lead_len)
1055 {
Bram Moolenaardc7e85e2012-06-20 12:40:08 +02001056 /* allocate buffer (may concatenate p_extra later) */
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +02001057 leader = alloc(lead_len + lead_repl_len + extra_space + extra_len
Bram Moolenaardc7e85e2012-06-20 12:40:08 +02001058 + (second_line_indent > 0 ? second_line_indent : 0) + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001059 allocated = leader; /* remember to free it later */
1060
1061 if (leader == NULL)
1062 lead_len = 0;
1063 else
1064 {
Bram Moolenaarce0842a2005-07-18 21:58:11 +00001065 vim_strncpy(leader, saved_line, lead_len);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001066
1067 /*
1068 * Replace leader with lead_repl, right or left adjusted
1069 */
1070 if (lead_repl != NULL)
1071 {
1072 int c = 0;
1073 int off = 0;
1074
Bram Moolenaard7d5b472009-11-11 16:30:08 +00001075 for (p = lead_flags; *p != NUL && *p != ':'; )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001076 {
1077 if (*p == COM_RIGHT || *p == COM_LEFT)
Bram Moolenaard7d5b472009-11-11 16:30:08 +00001078 c = *p++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001079 else if (VIM_ISDIGIT(*p) || *p == '-')
1080 off = getdigits(&p);
Bram Moolenaard7d5b472009-11-11 16:30:08 +00001081 else
1082 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001083 }
1084 if (c == COM_RIGHT) /* right adjusted leader */
1085 {
1086 /* find last non-white in the leader to line up with */
1087 for (p = leader + lead_len - 1; p > leader
1088 && vim_iswhite(*p); --p)
1089 ;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001090 ++p;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001091
1092#ifdef FEAT_MBYTE
1093 /* Compute the length of the replaced characters in
1094 * screen characters, not bytes. */
1095 {
1096 int repl_size = vim_strnsize(lead_repl,
1097 lead_repl_len);
1098 int old_size = 0;
1099 char_u *endp = p;
1100 int l;
1101
1102 while (old_size < repl_size && p > leader)
1103 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001104 mb_ptr_back(leader, p);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001105 old_size += ptr2cells(p);
1106 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001107 l = lead_repl_len - (int)(endp - p);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001108 if (l != 0)
1109 mch_memmove(endp + l, endp,
1110 (size_t)((leader + lead_len) - endp));
1111 lead_len += l;
1112 }
1113#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001114 if (p < leader + lead_repl_len)
1115 p = leader;
1116 else
1117 p -= lead_repl_len;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001118#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001119 mch_memmove(p, lead_repl, (size_t)lead_repl_len);
1120 if (p + lead_repl_len > leader + lead_len)
1121 p[lead_repl_len] = NUL;
1122
1123 /* blank-out any other chars from the old leader. */
1124 while (--p >= leader)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001125 {
1126#ifdef FEAT_MBYTE
1127 int l = mb_head_off(leader, p);
1128
1129 if (l > 1)
1130 {
1131 p -= l;
1132 if (ptr2cells(p) > 1)
1133 {
1134 p[1] = ' ';
1135 --l;
1136 }
1137 mch_memmove(p + 1, p + l + 1,
1138 (size_t)((leader + lead_len) - (p + l + 1)));
1139 lead_len -= l;
1140 *p = ' ';
1141 }
1142 else
1143#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001144 if (!vim_iswhite(*p))
1145 *p = ' ';
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001146 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001147 }
1148 else /* left adjusted leader */
1149 {
1150 p = skipwhite(leader);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001151#ifdef FEAT_MBYTE
1152 /* Compute the length of the replaced characters in
1153 * screen characters, not bytes. Move the part that is
1154 * not to be overwritten. */
1155 {
1156 int repl_size = vim_strnsize(lead_repl,
1157 lead_repl_len);
1158 int i;
1159 int l;
1160
1161 for (i = 0; p[i] != NUL && i < lead_len; i += l)
1162 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00001163 l = (*mb_ptr2len)(p + i);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001164 if (vim_strnsize(p, i + l) > repl_size)
1165 break;
1166 }
1167 if (i != lead_repl_len)
1168 {
1169 mch_memmove(p + lead_repl_len, p + i,
Bram Moolenaar2d7ff052009-11-17 15:08:26 +00001170 (size_t)(lead_len - i - (p - leader)));
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001171 lead_len += lead_repl_len - i;
1172 }
1173 }
1174#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001175 mch_memmove(p, lead_repl, (size_t)lead_repl_len);
1176
1177 /* Replace any remaining non-white chars in the old
1178 * leader by spaces. Keep Tabs, the indent must
1179 * remain the same. */
1180 for (p += lead_repl_len; p < leader + lead_len; ++p)
1181 if (!vim_iswhite(*p))
1182 {
1183 /* Don't put a space before a TAB. */
1184 if (p + 1 < leader + lead_len && p[1] == TAB)
1185 {
1186 --lead_len;
1187 mch_memmove(p, p + 1,
1188 (leader + lead_len) - p);
1189 }
1190 else
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001191 {
1192#ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00001193 int l = (*mb_ptr2len)(p);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001194
1195 if (l > 1)
1196 {
1197 if (ptr2cells(p) > 1)
1198 {
1199 /* Replace a double-wide char with
1200 * two spaces */
1201 --l;
1202 *p++ = ' ';
1203 }
1204 mch_memmove(p + 1, p + l,
1205 (leader + lead_len) - p);
1206 lead_len -= l - 1;
1207 }
1208#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001209 *p = ' ';
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001210 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001211 }
1212 *p = NUL;
1213 }
1214
1215 /* Recompute the indent, it may have changed. */
1216 if (curbuf->b_p_ai
1217#ifdef FEAT_SMARTINDENT
1218 || do_si
1219#endif
1220 )
1221 newindent = get_indent_str(leader, (int)curbuf->b_p_ts);
1222
1223 /* Add the indent offset */
1224 if (newindent + off < 0)
1225 {
1226 off = -newindent;
1227 newindent = 0;
1228 }
1229 else
1230 newindent += off;
1231
1232 /* Correct trailing spaces for the shift, so that
1233 * alignment remains equal. */
1234 while (off > 0 && lead_len > 0
1235 && leader[lead_len - 1] == ' ')
1236 {
1237 /* Don't do it when there is a tab before the space */
1238 if (vim_strchr(skipwhite(leader), '\t') != NULL)
1239 break;
1240 --lead_len;
1241 --off;
1242 }
1243
1244 /* If the leader ends in white space, don't add an
1245 * extra space */
1246 if (lead_len > 0 && vim_iswhite(leader[lead_len - 1]))
1247 extra_space = FALSE;
1248 leader[lead_len] = NUL;
1249 }
1250
1251 if (extra_space)
1252 {
1253 leader[lead_len++] = ' ';
1254 leader[lead_len] = NUL;
1255 }
1256
1257 newcol = lead_len;
1258
1259 /*
1260 * if a new indent will be set below, remove the indent that
1261 * is in the comment leader
1262 */
1263 if (newindent
1264#ifdef FEAT_SMARTINDENT
1265 || did_si
1266#endif
1267 )
1268 {
1269 while (lead_len && vim_iswhite(*leader))
1270 {
1271 --lead_len;
1272 --newcol;
1273 ++leader;
1274 }
1275 }
1276
1277 }
1278#ifdef FEAT_SMARTINDENT
1279 did_si = can_si = FALSE;
1280#endif
1281 }
1282 else if (comment_end != NULL)
1283 {
1284 /*
1285 * We have finished a comment, so we don't use the leader.
1286 * If this was a C-comment and 'ai' or 'si' is set do a normal
1287 * indent to align with the line containing the start of the
1288 * comment.
1289 */
1290 if (comment_end[0] == '*' && comment_end[1] == '/' &&
1291 (curbuf->b_p_ai
1292#ifdef FEAT_SMARTINDENT
1293 || do_si
1294#endif
1295 ))
1296 {
1297 old_cursor = curwin->w_cursor;
1298 curwin->w_cursor.col = (colnr_T)(comment_end - saved_line);
1299 if ((pos = findmatch(NULL, NUL)) != NULL)
1300 {
1301 curwin->w_cursor.lnum = pos->lnum;
1302 newindent = get_indent();
1303 }
1304 curwin->w_cursor = old_cursor;
1305 }
1306 }
1307 }
1308#endif
1309
1310 /* (State == INSERT || State == REPLACE), only when dir == FORWARD */
1311 if (p_extra != NULL)
1312 {
1313 *p_extra = saved_char; /* restore char that NUL replaced */
1314
1315 /*
1316 * When 'ai' set or "flags" has OPENLINE_DELSPACES, skip to the first
1317 * non-blank.
1318 *
1319 * When in REPLACE mode, put the deleted blanks on the replace stack,
1320 * preceded by a NUL, so they can be put back when a BS is entered.
1321 */
1322 if (REPLACE_NORMAL(State))
1323 replace_push(NUL); /* end of extra blanks */
1324 if (curbuf->b_p_ai || (flags & OPENLINE_DELSPACES))
1325 {
1326 while ((*p_extra == ' ' || *p_extra == '\t')
1327#ifdef FEAT_MBYTE
1328 && (!enc_utf8
1329 || !utf_iscomposing(utf_ptr2char(p_extra + 1)))
1330#endif
1331 )
1332 {
1333 if (REPLACE_NORMAL(State))
1334 replace_push(*p_extra);
1335 ++p_extra;
1336 ++less_cols_off;
1337 }
1338 }
1339 if (*p_extra != NUL)
1340 did_ai = FALSE; /* append some text, don't truncate now */
1341
1342 /* columns for marks adjusted for removed columns */
1343 less_cols = (int)(p_extra - saved_line);
1344 }
1345
1346 if (p_extra == NULL)
1347 p_extra = (char_u *)""; /* append empty line */
1348
1349#ifdef FEAT_COMMENTS
1350 /* concatenate leader and p_extra, if there is a leader */
1351 if (lead_len)
1352 {
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +02001353 if (flags & OPENLINE_COM_LIST && second_line_indent > 0)
1354 {
1355 int i;
Bram Moolenaar36105782012-06-14 20:59:25 +02001356 int padding = second_line_indent
1357 - (newindent + (int)STRLEN(leader));
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +02001358
1359 /* Here whitespace is inserted after the comment char.
1360 * Below, set_indent(newindent, SIN_INSERT) will insert the
1361 * whitespace needed before the comment char. */
1362 for (i = 0; i < padding; i++)
1363 {
1364 STRCAT(leader, " ");
1365 newcol++;
1366 }
1367 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001368 STRCAT(leader, p_extra);
1369 p_extra = leader;
1370 did_ai = TRUE; /* So truncating blanks works with comments */
1371 less_cols -= lead_len;
1372 }
1373 else
1374 end_comment_pending = NUL; /* turns out there was no leader */
1375#endif
1376
1377 old_cursor = curwin->w_cursor;
1378 if (dir == BACKWARD)
1379 --curwin->w_cursor.lnum;
1380#ifdef FEAT_VREPLACE
1381 if (!(State & VREPLACE_FLAG) || old_cursor.lnum >= orig_line_count)
1382#endif
1383 {
1384 if (ml_append(curwin->w_cursor.lnum, p_extra, (colnr_T)0, FALSE)
1385 == FAIL)
1386 goto theend;
1387 /* Postpone calling changed_lines(), because it would mess up folding
1388 * with markers. */
1389 mark_adjust(curwin->w_cursor.lnum + 1, (linenr_T)MAXLNUM, 1L, 0L);
1390 did_append = TRUE;
1391 }
1392#ifdef FEAT_VREPLACE
1393 else
1394 {
1395 /*
1396 * In VREPLACE mode we are starting to replace the next line.
1397 */
1398 curwin->w_cursor.lnum++;
1399 if (curwin->w_cursor.lnum >= Insstart.lnum + vr_lines_changed)
1400 {
1401 /* In case we NL to a new line, BS to the previous one, and NL
1402 * again, we don't want to save the new line for undo twice.
1403 */
1404 (void)u_save_cursor(); /* errors are ignored! */
1405 vr_lines_changed++;
1406 }
1407 ml_replace(curwin->w_cursor.lnum, p_extra, TRUE);
1408 changed_bytes(curwin->w_cursor.lnum, 0);
1409 curwin->w_cursor.lnum--;
1410 did_append = FALSE;
1411 }
1412#endif
1413
1414 if (newindent
1415#ifdef FEAT_SMARTINDENT
1416 || did_si
1417#endif
1418 )
1419 {
1420 ++curwin->w_cursor.lnum;
1421#ifdef FEAT_SMARTINDENT
1422 if (did_si)
1423 {
1424 if (p_sr)
1425 newindent -= newindent % (int)curbuf->b_p_sw;
1426 newindent += (int)curbuf->b_p_sw;
1427 }
1428#endif
Bram Moolenaar5002c292007-07-24 13:26:15 +00001429 /* Copy the indent */
1430 if (curbuf->b_p_ci)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001431 {
1432 (void)copy_indent(newindent, saved_line);
1433
1434 /*
1435 * Set the 'preserveindent' option so that any further screwing
1436 * with the line doesn't entirely destroy our efforts to preserve
1437 * it. It gets restored at the function end.
1438 */
1439 curbuf->b_p_pi = TRUE;
1440 }
1441 else
1442 (void)set_indent(newindent, SIN_INSERT);
1443 less_cols -= curwin->w_cursor.col;
1444
1445 ai_col = curwin->w_cursor.col;
1446
1447 /*
1448 * In REPLACE mode, for each character in the new indent, there must
1449 * be a NUL on the replace stack, for when it is deleted with BS
1450 */
1451 if (REPLACE_NORMAL(State))
1452 for (n = 0; n < (int)curwin->w_cursor.col; ++n)
1453 replace_push(NUL);
1454 newcol += curwin->w_cursor.col;
1455#ifdef FEAT_SMARTINDENT
1456 if (no_si)
1457 did_si = FALSE;
1458#endif
1459 }
1460
1461#ifdef FEAT_COMMENTS
1462 /*
1463 * In REPLACE mode, for each character in the extra leader, there must be
1464 * a NUL on the replace stack, for when it is deleted with BS.
1465 */
1466 if (REPLACE_NORMAL(State))
1467 while (lead_len-- > 0)
1468 replace_push(NUL);
1469#endif
1470
1471 curwin->w_cursor = old_cursor;
1472
1473 if (dir == FORWARD)
1474 {
1475 if (trunc_line || (State & INSERT))
1476 {
1477 /* truncate current line at cursor */
1478 saved_line[curwin->w_cursor.col] = NUL;
1479 /* Remove trailing white space, unless OPENLINE_KEEPTRAIL used. */
1480 if (trunc_line && !(flags & OPENLINE_KEEPTRAIL))
1481 truncate_spaces(saved_line);
1482 ml_replace(curwin->w_cursor.lnum, saved_line, FALSE);
1483 saved_line = NULL;
1484 if (did_append)
1485 {
1486 changed_lines(curwin->w_cursor.lnum, curwin->w_cursor.col,
1487 curwin->w_cursor.lnum + 1, 1L);
1488 did_append = FALSE;
1489
1490 /* Move marks after the line break to the new line. */
1491 if (flags & OPENLINE_MARKFIX)
1492 mark_col_adjust(curwin->w_cursor.lnum,
1493 curwin->w_cursor.col + less_cols_off,
1494 1L, (long)-less_cols);
1495 }
1496 else
1497 changed_bytes(curwin->w_cursor.lnum, curwin->w_cursor.col);
1498 }
1499
1500 /*
1501 * Put the cursor on the new line. Careful: the scrollup() above may
1502 * have moved w_cursor, we must use old_cursor.
1503 */
1504 curwin->w_cursor.lnum = old_cursor.lnum + 1;
1505 }
1506 if (did_append)
1507 changed_lines(curwin->w_cursor.lnum, 0, curwin->w_cursor.lnum, 1L);
1508
1509 curwin->w_cursor.col = newcol;
1510#ifdef FEAT_VIRTUALEDIT
1511 curwin->w_cursor.coladd = 0;
1512#endif
1513
1514#if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
1515 /*
1516 * In VREPLACE mode, we are handling the replace stack ourselves, so stop
1517 * fixthisline() from doing it (via change_indent()) by telling it we're in
1518 * normal INSERT mode.
1519 */
1520 if (State & VREPLACE_FLAG)
1521 {
1522 vreplace_mode = State; /* So we know to put things right later */
1523 State = INSERT;
1524 }
1525 else
1526 vreplace_mode = 0;
1527#endif
1528#ifdef FEAT_LISP
1529 /*
1530 * May do lisp indenting.
1531 */
1532 if (!p_paste
1533# ifdef FEAT_COMMENTS
1534 && leader == NULL
1535# endif
1536 && curbuf->b_p_lisp
1537 && curbuf->b_p_ai)
1538 {
1539 fixthisline(get_lisp_indent);
1540 p = ml_get_curline();
1541 ai_col = (colnr_T)(skipwhite(p) - p);
1542 }
1543#endif
1544#ifdef FEAT_CINDENT
1545 /*
1546 * May do indenting after opening a new line.
1547 */
1548 if (!p_paste
1549 && (curbuf->b_p_cin
1550# ifdef FEAT_EVAL
1551 || *curbuf->b_p_inde != NUL
1552# endif
1553 )
1554 && in_cinkeys(dir == FORWARD
1555 ? KEY_OPEN_FORW
1556 : KEY_OPEN_BACK, ' ', linewhite(curwin->w_cursor.lnum)))
1557 {
1558 do_c_expr_indent();
1559 p = ml_get_curline();
1560 ai_col = (colnr_T)(skipwhite(p) - p);
1561 }
1562#endif
1563#if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
1564 if (vreplace_mode != 0)
1565 State = vreplace_mode;
1566#endif
1567
1568#ifdef FEAT_VREPLACE
1569 /*
1570 * Finally, VREPLACE gets the stuff on the new line, then puts back the
1571 * original line, and inserts the new stuff char by char, pushing old stuff
1572 * onto the replace stack (via ins_char()).
1573 */
1574 if (State & VREPLACE_FLAG)
1575 {
1576 /* Put new line in p_extra */
1577 p_extra = vim_strsave(ml_get_curline());
1578 if (p_extra == NULL)
1579 goto theend;
1580
1581 /* Put back original line */
1582 ml_replace(curwin->w_cursor.lnum, next_line, FALSE);
1583
1584 /* Insert new stuff into line again */
1585 curwin->w_cursor.col = 0;
1586#ifdef FEAT_VIRTUALEDIT
1587 curwin->w_cursor.coladd = 0;
1588#endif
1589 ins_bytes(p_extra); /* will call changed_bytes() */
1590 vim_free(p_extra);
1591 next_line = NULL;
1592 }
1593#endif
1594
1595 retval = TRUE; /* success! */
1596theend:
1597 curbuf->b_p_pi = saved_pi;
1598 vim_free(saved_line);
1599 vim_free(next_line);
1600 vim_free(allocated);
1601 return retval;
1602}
1603
1604#if defined(FEAT_COMMENTS) || defined(PROTO)
1605/*
1606 * get_leader_len() returns the length of the prefix of the given string
1607 * which introduces a comment. If this string is not a comment then 0 is
1608 * returned.
1609 * When "flags" is not NULL, it is set to point to the flags of the recognized
1610 * comment leader.
1611 * "backward" must be true for the "O" command.
Bram Moolenaar81340392012-06-06 16:12:59 +02001612 * If "include_space" is set, include trailing whitespace while calculating the
1613 * length.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001614 */
1615 int
Bram Moolenaar81340392012-06-06 16:12:59 +02001616get_leader_len(line, flags, backward, include_space)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001617 char_u *line;
1618 char_u **flags;
1619 int backward;
Bram Moolenaar81340392012-06-06 16:12:59 +02001620 int include_space;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001621{
1622 int i, j;
Bram Moolenaar81340392012-06-06 16:12:59 +02001623 int result;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001624 int got_com = FALSE;
1625 int found_one;
1626 char_u part_buf[COM_MAX_LEN]; /* buffer for one option part */
1627 char_u *string; /* pointer to comment string */
1628 char_u *list;
Bram Moolenaara4271d52011-05-10 13:38:27 +02001629 int middle_match_len = 0;
1630 char_u *prev_list;
Bram Moolenaar05da4282011-05-10 14:44:11 +02001631 char_u *saved_flags = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001632
Bram Moolenaar81340392012-06-06 16:12:59 +02001633 result = i = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001634 while (vim_iswhite(line[i])) /* leading white space is ignored */
1635 ++i;
1636
1637 /*
1638 * Repeat to match several nested comment strings.
1639 */
Bram Moolenaara4271d52011-05-10 13:38:27 +02001640 while (line[i] != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001641 {
1642 /*
1643 * scan through the 'comments' option for a match
1644 */
1645 found_one = FALSE;
1646 for (list = curbuf->b_p_com; *list; )
1647 {
Bram Moolenaara4271d52011-05-10 13:38:27 +02001648 /* Get one option part into part_buf[]. Advance "list" to next
1649 * one. Put "string" at start of string. */
1650 if (!got_com && flags != NULL)
1651 *flags = list; /* remember where flags started */
1652 prev_list = list;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001653 (void)copy_option_part(&list, part_buf, COM_MAX_LEN, ",");
1654 string = vim_strchr(part_buf, ':');
1655 if (string == NULL) /* missing ':', ignore this part */
1656 continue;
1657 *string++ = NUL; /* isolate flags from string */
1658
Bram Moolenaara4271d52011-05-10 13:38:27 +02001659 /* If we found a middle match previously, use that match when this
1660 * is not a middle or end. */
1661 if (middle_match_len != 0
1662 && vim_strchr(part_buf, COM_MIDDLE) == NULL
1663 && vim_strchr(part_buf, COM_END) == NULL)
1664 break;
1665
1666 /* When we already found a nested comment, only accept further
1667 * nested comments. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001668 if (got_com && vim_strchr(part_buf, COM_NEST) == NULL)
1669 continue;
1670
Bram Moolenaara4271d52011-05-10 13:38:27 +02001671 /* When 'O' flag present and using "O" command skip this one. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001672 if (backward && vim_strchr(part_buf, COM_NOBACK) != NULL)
1673 continue;
1674
Bram Moolenaara4271d52011-05-10 13:38:27 +02001675 /* Line contents and string must match.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001676 * When string starts with white space, must have some white space
1677 * (but the amount does not need to match, there might be a mix of
Bram Moolenaara4271d52011-05-10 13:38:27 +02001678 * TABs and spaces). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001679 if (vim_iswhite(string[0]))
1680 {
1681 if (i == 0 || !vim_iswhite(line[i - 1]))
Bram Moolenaara4271d52011-05-10 13:38:27 +02001682 continue; /* missing shite space */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001683 while (vim_iswhite(string[0]))
1684 ++string;
1685 }
1686 for (j = 0; string[j] != NUL && string[j] == line[i + j]; ++j)
1687 ;
1688 if (string[j] != NUL)
Bram Moolenaara4271d52011-05-10 13:38:27 +02001689 continue; /* string doesn't match */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001690
Bram Moolenaara4271d52011-05-10 13:38:27 +02001691 /* When 'b' flag used, there must be white space or an
1692 * end-of-line after the string in the line. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001693 if (vim_strchr(part_buf, COM_BLANK) != NULL
1694 && !vim_iswhite(line[i + j]) && line[i + j] != NUL)
1695 continue;
1696
Bram Moolenaara4271d52011-05-10 13:38:27 +02001697 /* We have found a match, stop searching unless this is a middle
1698 * comment. The middle comment can be a substring of the end
1699 * comment in which case it's better to return the length of the
1700 * end comment and its flags. Thus we keep searching with middle
1701 * and end matches and use an end match if it matches better. */
1702 if (vim_strchr(part_buf, COM_MIDDLE) != NULL)
1703 {
1704 if (middle_match_len == 0)
1705 {
1706 middle_match_len = j;
1707 saved_flags = prev_list;
1708 }
1709 continue;
1710 }
1711 if (middle_match_len != 0 && j > middle_match_len)
1712 /* Use this match instead of the middle match, since it's a
1713 * longer thus better match. */
1714 middle_match_len = 0;
1715
1716 if (middle_match_len == 0)
1717 i += j;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001718 found_one = TRUE;
1719 break;
1720 }
1721
Bram Moolenaara4271d52011-05-10 13:38:27 +02001722 if (middle_match_len != 0)
1723 {
1724 /* Use the previously found middle match after failing to find a
1725 * match with an end. */
1726 if (!got_com && flags != NULL)
1727 *flags = saved_flags;
1728 i += middle_match_len;
1729 found_one = TRUE;
1730 }
1731
1732 /* No match found, stop scanning. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001733 if (!found_one)
1734 break;
1735
Bram Moolenaar81340392012-06-06 16:12:59 +02001736 result = i;
1737
Bram Moolenaara4271d52011-05-10 13:38:27 +02001738 /* Include any trailing white space. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001739 while (vim_iswhite(line[i]))
1740 ++i;
1741
Bram Moolenaar81340392012-06-06 16:12:59 +02001742 if (include_space)
1743 result = i;
1744
Bram Moolenaara4271d52011-05-10 13:38:27 +02001745 /* If this comment doesn't nest, stop here. */
1746 got_com = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001747 if (vim_strchr(part_buf, COM_NEST) == NULL)
1748 break;
1749 }
Bram Moolenaar81340392012-06-06 16:12:59 +02001750 return result;
1751}
Bram Moolenaara4271d52011-05-10 13:38:27 +02001752
Bram Moolenaar81340392012-06-06 16:12:59 +02001753/*
1754 * Return the offset at which the last comment in line starts. If there is no
1755 * comment in the whole line, -1 is returned.
1756 *
1757 * When "flags" is not null, it is set to point to the flags describing the
1758 * recognized comment leader.
1759 */
1760 int
1761get_last_leader_offset(line, flags)
1762 char_u *line;
1763 char_u **flags;
1764{
1765 int result = -1;
1766 int i, j;
1767 int lower_check_bound = 0;
1768 char_u *string;
1769 char_u *com_leader;
1770 char_u *com_flags;
1771 char_u *list;
1772 int found_one;
1773 char_u part_buf[COM_MAX_LEN]; /* buffer for one option part */
1774
1775 /*
1776 * Repeat to match several nested comment strings.
1777 */
1778 i = (int)STRLEN(line);
1779 while (--i >= lower_check_bound)
1780 {
1781 /*
1782 * scan through the 'comments' option for a match
1783 */
1784 found_one = FALSE;
1785 for (list = curbuf->b_p_com; *list; )
1786 {
1787 char_u *flags_save = list;
1788
1789 /*
1790 * Get one option part into part_buf[]. Advance list to next one.
1791 * put string at start of string.
1792 */
1793 (void)copy_option_part(&list, part_buf, COM_MAX_LEN, ",");
1794 string = vim_strchr(part_buf, ':');
1795 if (string == NULL) /* If everything is fine, this cannot actually
1796 * happen. */
1797 {
1798 continue;
1799 }
1800 *string++ = NUL; /* Isolate flags from string. */
1801 com_leader = string;
1802
1803 /*
1804 * Line contents and string must match.
1805 * When string starts with white space, must have some white space
1806 * (but the amount does not need to match, there might be a mix of
1807 * TABs and spaces).
1808 */
1809 if (vim_iswhite(string[0]))
1810 {
1811 if (i == 0 || !vim_iswhite(line[i - 1]))
1812 continue;
1813 while (vim_iswhite(string[0]))
1814 ++string;
1815 }
1816 for (j = 0; string[j] != NUL && string[j] == line[i + j]; ++j)
1817 /* do nothing */;
1818 if (string[j] != NUL)
1819 continue;
1820
1821 /*
1822 * When 'b' flag used, there must be white space or an
1823 * end-of-line after the string in the line.
1824 */
1825 if (vim_strchr(part_buf, COM_BLANK) != NULL
1826 && !vim_iswhite(line[i + j]) && line[i + j] != NUL)
1827 {
1828 continue;
1829 }
1830
1831 /*
1832 * We have found a match, stop searching.
1833 */
1834 found_one = TRUE;
1835
1836 if (flags)
1837 *flags = flags_save;
1838 com_flags = flags_save;
1839
1840 break;
1841 }
1842
1843 if (found_one)
1844 {
1845 char_u part_buf2[COM_MAX_LEN]; /* buffer for one option part */
1846 int len1, len2, off;
1847
1848 result = i;
1849 /*
1850 * If this comment nests, continue searching.
1851 */
1852 if (vim_strchr(part_buf, COM_NEST) != NULL)
1853 continue;
1854
1855 lower_check_bound = i;
1856
1857 /* Let's verify whether the comment leader found is a substring
1858 * of other comment leaders. If it is, let's adjust the
1859 * lower_check_bound so that we make sure that we have determined
1860 * the comment leader correctly.
1861 */
1862
1863 while (vim_iswhite(*com_leader))
1864 ++com_leader;
1865 len1 = (int)STRLEN(com_leader);
1866
1867 for (list = curbuf->b_p_com; *list; )
1868 {
1869 char_u *flags_save = list;
1870
1871 (void)copy_option_part(&list, part_buf2, COM_MAX_LEN, ",");
1872 if (flags_save == com_flags)
1873 continue;
1874 string = vim_strchr(part_buf2, ':');
1875 ++string;
1876 while (vim_iswhite(*string))
1877 ++string;
1878 len2 = (int)STRLEN(string);
1879 if (len2 == 0)
1880 continue;
1881
1882 /* Now we have to verify whether string ends with a substring
1883 * beginning the com_leader. */
1884 for (off = (len2 > i ? i : len2); off > 0 && off + len1 > len2;)
1885 {
1886 --off;
1887 if (!STRNCMP(string + off, com_leader, len2 - off))
1888 {
1889 if (i - off < lower_check_bound)
1890 lower_check_bound = i - off;
1891 }
1892 }
1893 }
1894 }
1895 }
1896 return result;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001897}
1898#endif
1899
1900/*
1901 * Return the number of window lines occupied by buffer line "lnum".
1902 */
1903 int
1904plines(lnum)
1905 linenr_T lnum;
1906{
1907 return plines_win(curwin, lnum, TRUE);
1908}
1909
1910 int
1911plines_win(wp, lnum, winheight)
1912 win_T *wp;
1913 linenr_T lnum;
1914 int winheight; /* when TRUE limit to window height */
1915{
1916#if defined(FEAT_DIFF) || defined(PROTO)
1917 /* Check for filler lines above this buffer line. When folded the result
1918 * is one line anyway. */
1919 return plines_win_nofill(wp, lnum, winheight) + diff_check_fill(wp, lnum);
1920}
1921
1922 int
1923plines_nofill(lnum)
1924 linenr_T lnum;
1925{
1926 return plines_win_nofill(curwin, lnum, TRUE);
1927}
1928
1929 int
1930plines_win_nofill(wp, lnum, winheight)
1931 win_T *wp;
1932 linenr_T lnum;
1933 int winheight; /* when TRUE limit to window height */
1934{
1935#endif
1936 int lines;
1937
1938 if (!wp->w_p_wrap)
1939 return 1;
1940
1941#ifdef FEAT_VERTSPLIT
1942 if (wp->w_width == 0)
1943 return 1;
1944#endif
1945
1946#ifdef FEAT_FOLDING
1947 /* A folded lines is handled just like an empty line. */
1948 /* NOTE: Caller must handle lines that are MAYBE folded. */
1949 if (lineFolded(wp, lnum) == TRUE)
1950 return 1;
1951#endif
1952
1953 lines = plines_win_nofold(wp, lnum);
1954 if (winheight > 0 && lines > wp->w_height)
1955 return (int)wp->w_height;
1956 return lines;
1957}
1958
1959/*
1960 * Return number of window lines physical line "lnum" will occupy in window
1961 * "wp". Does not care about folding, 'wrap' or 'diff'.
1962 */
1963 int
1964plines_win_nofold(wp, lnum)
1965 win_T *wp;
1966 linenr_T lnum;
1967{
1968 char_u *s;
1969 long col;
1970 int width;
1971
1972 s = ml_get_buf(wp->w_buffer, lnum, FALSE);
1973 if (*s == NUL) /* empty line */
1974 return 1;
1975 col = win_linetabsize(wp, s, (colnr_T)MAXCOL);
1976
1977 /*
1978 * If list mode is on, then the '$' at the end of the line may take up one
1979 * extra column.
1980 */
1981 if (wp->w_p_list && lcs_eol != NUL)
1982 col += 1;
1983
1984 /*
Bram Moolenaar64486672010-05-16 15:46:46 +02001985 * Add column offset for 'number', 'relativenumber' and 'foldcolumn'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001986 */
1987 width = W_WIDTH(wp) - win_col_off(wp);
1988 if (width <= 0)
1989 return 32000;
1990 if (col <= width)
1991 return 1;
1992 col -= width;
1993 width += win_col_off2(wp);
1994 return (col + (width - 1)) / width + 1;
1995}
1996
1997/*
1998 * Like plines_win(), but only reports the number of physical screen lines
1999 * used from the start of the line to the given column number.
2000 */
2001 int
2002plines_win_col(wp, lnum, column)
2003 win_T *wp;
2004 linenr_T lnum;
2005 long column;
2006{
2007 long col;
2008 char_u *s;
2009 int lines = 0;
2010 int width;
2011
2012#ifdef FEAT_DIFF
2013 /* Check for filler lines above this buffer line. When folded the result
2014 * is one line anyway. */
2015 lines = diff_check_fill(wp, lnum);
2016#endif
2017
2018 if (!wp->w_p_wrap)
2019 return lines + 1;
2020
2021#ifdef FEAT_VERTSPLIT
2022 if (wp->w_width == 0)
2023 return lines + 1;
2024#endif
2025
2026 s = ml_get_buf(wp->w_buffer, lnum, FALSE);
2027
2028 col = 0;
2029 while (*s != NUL && --column >= 0)
2030 {
2031 col += win_lbr_chartabsize(wp, s, (colnr_T)col, NULL);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002032 mb_ptr_adv(s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002033 }
2034
2035 /*
2036 * If *s is a TAB, and the TAB is not displayed as ^I, and we're not in
2037 * INSERT mode, then col must be adjusted so that it represents the last
2038 * screen position of the TAB. This only fixes an error when the TAB wraps
2039 * from one screen line to the next (when 'columns' is not a multiple of
2040 * 'ts') -- webb.
2041 */
2042 if (*s == TAB && (State & NORMAL) && (!wp->w_p_list || lcs_tab1))
2043 col += win_lbr_chartabsize(wp, s, (colnr_T)col, NULL) - 1;
2044
2045 /*
Bram Moolenaar64486672010-05-16 15:46:46 +02002046 * Add column offset for 'number', 'relativenumber', 'foldcolumn', etc.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002047 */
2048 width = W_WIDTH(wp) - win_col_off(wp);
Bram Moolenaar26470632006-10-24 19:12:40 +00002049 if (width <= 0)
2050 return 9999;
2051
2052 lines += 1;
2053 if (col > width)
2054 lines += (col - width) / (width + win_col_off2(wp)) + 1;
2055 return lines;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002056}
2057
2058 int
2059plines_m_win(wp, first, last)
2060 win_T *wp;
2061 linenr_T first, last;
2062{
2063 int count = 0;
2064
2065 while (first <= last)
2066 {
2067#ifdef FEAT_FOLDING
2068 int x;
2069
2070 /* Check if there are any really folded lines, but also included lines
2071 * that are maybe folded. */
2072 x = foldedCount(wp, first, NULL);
2073 if (x > 0)
2074 {
2075 ++count; /* count 1 for "+-- folded" line */
2076 first += x;
2077 }
2078 else
2079#endif
2080 {
2081#ifdef FEAT_DIFF
2082 if (first == wp->w_topline)
2083 count += plines_win_nofill(wp, first, TRUE) + wp->w_topfill;
2084 else
2085#endif
2086 count += plines_win(wp, first, TRUE);
2087 ++first;
2088 }
2089 }
2090 return (count);
2091}
2092
2093#if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) || defined(PROTO)
2094/*
2095 * Insert string "p" at the cursor position. Stops at a NUL byte.
2096 * Handles Replace mode and multi-byte characters.
2097 */
2098 void
2099ins_bytes(p)
2100 char_u *p;
2101{
2102 ins_bytes_len(p, (int)STRLEN(p));
2103}
2104#endif
2105
2106#if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) \
2107 || defined(FEAT_COMMENTS) || defined(FEAT_MBYTE) || defined(PROTO)
2108/*
2109 * Insert string "p" with length "len" at the cursor position.
2110 * Handles Replace mode and multi-byte characters.
2111 */
2112 void
2113ins_bytes_len(p, len)
2114 char_u *p;
2115 int len;
2116{
2117 int i;
2118# ifdef FEAT_MBYTE
2119 int n;
2120
Bram Moolenaar176dd1e2008-06-21 14:30:28 +00002121 if (has_mbyte)
2122 for (i = 0; i < len; i += n)
2123 {
2124 if (enc_utf8)
2125 /* avoid reading past p[len] */
2126 n = utfc_ptr2len_len(p + i, len - i);
2127 else
2128 n = (*mb_ptr2len)(p + i);
2129 ins_char_bytes(p + i, n);
2130 }
2131 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002132# endif
Bram Moolenaar176dd1e2008-06-21 14:30:28 +00002133 for (i = 0; i < len; ++i)
2134 ins_char(p[i]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002135}
2136#endif
2137
2138/*
2139 * Insert or replace a single character at the cursor position.
2140 * When in REPLACE or VREPLACE mode, replace any existing character.
2141 * Caller must have prepared for undo.
2142 * For multi-byte characters we get the whole character, the caller must
2143 * convert bytes to a character.
2144 */
2145 void
2146ins_char(c)
2147 int c;
2148{
2149#if defined(FEAT_MBYTE) || defined(PROTO)
Bram Moolenaar9a920d82012-06-01 15:21:02 +02002150 char_u buf[MB_MAXBYTES + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002151 int n;
2152
2153 n = (*mb_char2bytes)(c, buf);
2154
2155 /* When "c" is 0x100, 0x200, etc. we don't want to insert a NUL byte.
2156 * Happens for CTRL-Vu9900. */
2157 if (buf[0] == 0)
2158 buf[0] = '\n';
2159
2160 ins_char_bytes(buf, n);
2161}
2162
2163 void
2164ins_char_bytes(buf, charlen)
2165 char_u *buf;
2166 int charlen;
2167{
2168 int c = buf[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002169#endif
2170 int newlen; /* nr of bytes inserted */
2171 int oldlen; /* nr of bytes deleted (0 when not replacing) */
2172 char_u *p;
2173 char_u *newp;
2174 char_u *oldp;
2175 int linelen; /* length of old line including NUL */
2176 colnr_T col;
2177 linenr_T lnum = curwin->w_cursor.lnum;
2178 int i;
2179
2180#ifdef FEAT_VIRTUALEDIT
2181 /* Break tabs if needed. */
2182 if (virtual_active() && curwin->w_cursor.coladd > 0)
2183 coladvance_force(getviscol());
2184#endif
2185
2186 col = curwin->w_cursor.col;
2187 oldp = ml_get(lnum);
2188 linelen = (int)STRLEN(oldp) + 1;
2189
2190 /* The lengths default to the values for when not replacing. */
2191 oldlen = 0;
2192#ifdef FEAT_MBYTE
2193 newlen = charlen;
2194#else
2195 newlen = 1;
2196#endif
2197
2198 if (State & REPLACE_FLAG)
2199 {
2200#ifdef FEAT_VREPLACE
2201 if (State & VREPLACE_FLAG)
2202 {
2203 colnr_T new_vcol = 0; /* init for GCC */
2204 colnr_T vcol;
2205 int old_list;
2206#ifndef FEAT_MBYTE
2207 char_u buf[2];
2208#endif
2209
2210 /*
2211 * Disable 'list' temporarily, unless 'cpo' contains the 'L' flag.
2212 * Returns the old value of list, so when finished,
2213 * curwin->w_p_list should be set back to this.
2214 */
2215 old_list = curwin->w_p_list;
2216 if (old_list && vim_strchr(p_cpo, CPO_LISTWM) == NULL)
2217 curwin->w_p_list = FALSE;
2218
2219 /*
2220 * In virtual replace mode each character may replace one or more
2221 * characters (zero if it's a TAB). Count the number of bytes to
2222 * be deleted to make room for the new character, counting screen
2223 * cells. May result in adding spaces to fill a gap.
2224 */
2225 getvcol(curwin, &curwin->w_cursor, NULL, &vcol, NULL);
2226#ifndef FEAT_MBYTE
2227 buf[0] = c;
2228 buf[1] = NUL;
2229#endif
2230 new_vcol = vcol + chartabsize(buf, vcol);
2231 while (oldp[col + oldlen] != NUL && vcol < new_vcol)
2232 {
2233 vcol += chartabsize(oldp + col + oldlen, vcol);
2234 /* Don't need to remove a TAB that takes us to the right
2235 * position. */
2236 if (vcol > new_vcol && oldp[col + oldlen] == TAB)
2237 break;
2238#ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002239 oldlen += (*mb_ptr2len)(oldp + col + oldlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002240#else
2241 ++oldlen;
2242#endif
2243 /* Deleted a bit too much, insert spaces. */
2244 if (vcol > new_vcol)
2245 newlen += vcol - new_vcol;
2246 }
2247 curwin->w_p_list = old_list;
2248 }
2249 else
2250#endif
2251 if (oldp[col] != NUL)
2252 {
2253 /* normal replace */
2254#ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002255 oldlen = (*mb_ptr2len)(oldp + col);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002256#else
2257 oldlen = 1;
2258#endif
2259 }
2260
2261
2262 /* Push the replaced bytes onto the replace stack, so that they can be
2263 * put back when BS is used. The bytes of a multi-byte character are
2264 * done the other way around, so that the first byte is popped off
2265 * first (it tells the byte length of the character). */
2266 replace_push(NUL);
2267 for (i = 0; i < oldlen; ++i)
2268 {
2269#ifdef FEAT_MBYTE
Bram Moolenaar2c994e82008-01-02 16:49:36 +00002270 if (has_mbyte)
2271 i += replace_push_mb(oldp + col + i) - 1;
2272 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002273#endif
Bram Moolenaar2c994e82008-01-02 16:49:36 +00002274 replace_push(oldp[col + i]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002275 }
2276 }
2277
2278 newp = alloc_check((unsigned)(linelen + newlen - oldlen));
2279 if (newp == NULL)
2280 return;
2281
2282 /* Copy bytes before the cursor. */
2283 if (col > 0)
2284 mch_memmove(newp, oldp, (size_t)col);
2285
2286 /* Copy bytes after the changed character(s). */
2287 p = newp + col;
2288 mch_memmove(p + newlen, oldp + col + oldlen,
2289 (size_t)(linelen - col - oldlen));
2290
2291 /* Insert or overwrite the new character. */
2292#ifdef FEAT_MBYTE
2293 mch_memmove(p, buf, charlen);
2294 i = charlen;
2295#else
2296 *p = c;
2297 i = 1;
2298#endif
2299
2300 /* Fill with spaces when necessary. */
2301 while (i < newlen)
2302 p[i++] = ' ';
2303
2304 /* Replace the line in the buffer. */
2305 ml_replace(lnum, newp, FALSE);
2306
2307 /* mark the buffer as changed and prepare for displaying */
2308 changed_bytes(lnum, col);
2309
2310 /*
2311 * If we're in Insert or Replace mode and 'showmatch' is set, then briefly
2312 * show the match for right parens and braces.
2313 */
2314 if (p_sm && (State & INSERT)
2315 && msg_silent == 0
2316#ifdef FEAT_MBYTE
2317 && charlen == 1
2318#endif
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00002319#ifdef FEAT_INS_EXPAND
2320 && !ins_compl_active()
2321#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002322 )
2323 showmatch(c);
2324
2325#ifdef FEAT_RIGHTLEFT
2326 if (!p_ri || (State & REPLACE_FLAG))
2327#endif
2328 {
2329 /* Normal insert: move cursor right */
2330#ifdef FEAT_MBYTE
2331 curwin->w_cursor.col += charlen;
2332#else
2333 ++curwin->w_cursor.col;
2334#endif
2335 }
2336 /*
2337 * TODO: should try to update w_row here, to avoid recomputing it later.
2338 */
2339}
2340
2341/*
2342 * Insert a string at the cursor position.
2343 * Note: Does NOT handle Replace mode.
2344 * Caller must have prepared for undo.
2345 */
2346 void
2347ins_str(s)
2348 char_u *s;
2349{
2350 char_u *oldp, *newp;
2351 int newlen = (int)STRLEN(s);
2352 int oldlen;
2353 colnr_T col;
2354 linenr_T lnum = curwin->w_cursor.lnum;
2355
2356#ifdef FEAT_VIRTUALEDIT
2357 if (virtual_active() && curwin->w_cursor.coladd > 0)
2358 coladvance_force(getviscol());
2359#endif
2360
2361 col = curwin->w_cursor.col;
2362 oldp = ml_get(lnum);
2363 oldlen = (int)STRLEN(oldp);
2364
2365 newp = alloc_check((unsigned)(oldlen + newlen + 1));
2366 if (newp == NULL)
2367 return;
2368 if (col > 0)
2369 mch_memmove(newp, oldp, (size_t)col);
2370 mch_memmove(newp + col, s, (size_t)newlen);
2371 mch_memmove(newp + col + newlen, oldp + col, (size_t)(oldlen - col + 1));
2372 ml_replace(lnum, newp, FALSE);
2373 changed_bytes(lnum, col);
2374 curwin->w_cursor.col += newlen;
2375}
2376
2377/*
2378 * Delete one character under the cursor.
2379 * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
2380 * Caller must have prepared for undo.
2381 *
2382 * return FAIL for failure, OK otherwise
2383 */
2384 int
2385del_char(fixpos)
2386 int fixpos;
2387{
2388#ifdef FEAT_MBYTE
2389 if (has_mbyte)
2390 {
2391 /* Make sure the cursor is at the start of a character. */
2392 mb_adjust_cursor();
2393 if (*ml_get_cursor() == NUL)
2394 return FAIL;
2395 return del_chars(1L, fixpos);
2396 }
2397#endif
Bram Moolenaare3226be2005-12-18 22:10:00 +00002398 return del_bytes(1L, fixpos, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002399}
2400
2401#if defined(FEAT_MBYTE) || defined(PROTO)
2402/*
2403 * Like del_bytes(), but delete characters instead of bytes.
2404 */
2405 int
2406del_chars(count, fixpos)
2407 long count;
2408 int fixpos;
2409{
2410 long bytes = 0;
2411 long i;
2412 char_u *p;
2413 int l;
2414
2415 p = ml_get_cursor();
2416 for (i = 0; i < count && *p != NUL; ++i)
2417 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002418 l = (*mb_ptr2len)(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002419 bytes += l;
2420 p += l;
2421 }
Bram Moolenaare3226be2005-12-18 22:10:00 +00002422 return del_bytes(bytes, fixpos, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002423}
2424#endif
2425
2426/*
2427 * Delete "count" bytes under the cursor.
2428 * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
2429 * Caller must have prepared for undo.
2430 *
2431 * return FAIL for failure, OK otherwise
2432 */
2433 int
Bram Moolenaarca003e12006-03-17 23:19:38 +00002434del_bytes(count, fixpos_arg, use_delcombine)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002435 long count;
Bram Moolenaarca003e12006-03-17 23:19:38 +00002436 int fixpos_arg;
Bram Moolenaar78a15312009-05-15 19:33:18 +00002437 int use_delcombine UNUSED; /* 'delcombine' option applies */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002438{
2439 char_u *oldp, *newp;
2440 colnr_T oldlen;
2441 linenr_T lnum = curwin->w_cursor.lnum;
2442 colnr_T col = curwin->w_cursor.col;
2443 int was_alloced;
2444 long movelen;
Bram Moolenaarca003e12006-03-17 23:19:38 +00002445 int fixpos = fixpos_arg;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002446
2447 oldp = ml_get(lnum);
2448 oldlen = (int)STRLEN(oldp);
2449
2450 /*
2451 * Can't do anything when the cursor is on the NUL after the line.
2452 */
2453 if (col >= oldlen)
2454 return FAIL;
2455
2456#ifdef FEAT_MBYTE
2457 /* If 'delcombine' is set and deleting (less than) one character, only
2458 * delete the last combining character. */
Bram Moolenaare3226be2005-12-18 22:10:00 +00002459 if (p_deco && use_delcombine && enc_utf8
2460 && utfc_ptr2len(oldp + col) >= count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002461 {
Bram Moolenaar362e1a32006-03-06 23:29:24 +00002462 int cc[MAX_MCO];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002463 int n;
2464
Bram Moolenaar362e1a32006-03-06 23:29:24 +00002465 (void)utfc_ptr2char(oldp + col, cc);
2466 if (cc[0] != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002467 {
2468 /* Find the last composing char, there can be several. */
2469 n = col;
2470 do
2471 {
2472 col = n;
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002473 count = utf_ptr2len(oldp + n);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002474 n += count;
2475 } while (UTF_COMPOSINGLIKE(oldp + col, oldp + n));
2476 fixpos = 0;
2477 }
2478 }
2479#endif
2480
2481 /*
2482 * When count is too big, reduce it.
2483 */
2484 movelen = (long)oldlen - (long)col - count + 1; /* includes trailing NUL */
2485 if (movelen <= 1)
2486 {
2487 /*
2488 * If we just took off the last character of a non-blank line, and
Bram Moolenaarca003e12006-03-17 23:19:38 +00002489 * fixpos is TRUE, we don't want to end up positioned at the NUL,
2490 * unless "restart_edit" is set or 'virtualedit' contains "onemore".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002491 */
Bram Moolenaarca003e12006-03-17 23:19:38 +00002492 if (col > 0 && fixpos && restart_edit == 0
2493#ifdef FEAT_VIRTUALEDIT
2494 && (ve_flags & VE_ONEMORE) == 0
2495#endif
2496 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00002497 {
2498 --curwin->w_cursor.col;
2499#ifdef FEAT_VIRTUALEDIT
2500 curwin->w_cursor.coladd = 0;
2501#endif
2502#ifdef FEAT_MBYTE
2503 if (has_mbyte)
2504 curwin->w_cursor.col -=
2505 (*mb_head_off)(oldp, oldp + curwin->w_cursor.col);
2506#endif
2507 }
2508 count = oldlen - col;
2509 movelen = 1;
2510 }
2511
2512 /*
2513 * If the old line has been allocated the deletion can be done in the
2514 * existing line. Otherwise a new line has to be allocated
Bram Moolenaare21877a2008-02-13 09:58:14 +00002515 * Can't do this when using Netbeans, because we would need to invoke
2516 * netbeans_removed(), which deallocates the line. Let ml_replace() take
Bram Moolenaar1a509df2010-08-01 17:59:57 +02002517 * care of notifying Netbeans.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002518 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002519#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02002520 if (netbeans_active())
Bram Moolenaare21877a2008-02-13 09:58:14 +00002521 was_alloced = FALSE;
2522 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002523#endif
Bram Moolenaare21877a2008-02-13 09:58:14 +00002524 was_alloced = ml_line_alloced(); /* check if oldp was allocated */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002525 if (was_alloced)
2526 newp = oldp; /* use same allocated memory */
2527 else
2528 { /* need to allocate a new line */
2529 newp = alloc((unsigned)(oldlen + 1 - count));
2530 if (newp == NULL)
2531 return FAIL;
2532 mch_memmove(newp, oldp, (size_t)col);
2533 }
2534 mch_memmove(newp + col, oldp + col + count, (size_t)movelen);
2535 if (!was_alloced)
2536 ml_replace(lnum, newp, FALSE);
2537
2538 /* mark the buffer as changed and prepare for displaying */
2539 changed_bytes(lnum, curwin->w_cursor.col);
2540
2541 return OK;
2542}
2543
2544/*
2545 * Delete from cursor to end of line.
2546 * Caller must have prepared for undo.
2547 *
2548 * return FAIL for failure, OK otherwise
2549 */
2550 int
2551truncate_line(fixpos)
2552 int fixpos; /* if TRUE fix the cursor position when done */
2553{
2554 char_u *newp;
2555 linenr_T lnum = curwin->w_cursor.lnum;
2556 colnr_T col = curwin->w_cursor.col;
2557
2558 if (col == 0)
2559 newp = vim_strsave((char_u *)"");
2560 else
2561 newp = vim_strnsave(ml_get(lnum), col);
2562
2563 if (newp == NULL)
2564 return FAIL;
2565
2566 ml_replace(lnum, newp, FALSE);
2567
2568 /* mark the buffer as changed and prepare for displaying */
2569 changed_bytes(lnum, curwin->w_cursor.col);
2570
2571 /*
2572 * If "fixpos" is TRUE we don't want to end up positioned at the NUL.
2573 */
2574 if (fixpos && curwin->w_cursor.col > 0)
2575 --curwin->w_cursor.col;
2576
2577 return OK;
2578}
2579
2580/*
2581 * Delete "nlines" lines at the cursor.
2582 * Saves the lines for undo first if "undo" is TRUE.
2583 */
2584 void
2585del_lines(nlines, undo)
2586 long nlines; /* number of lines to delete */
2587 int undo; /* if TRUE, prepare for undo */
2588{
2589 long n;
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002590 linenr_T first = curwin->w_cursor.lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002591
2592 if (nlines <= 0)
2593 return;
2594
2595 /* save the deleted lines for undo */
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002596 if (undo && u_savedel(first, nlines) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002597 return;
2598
2599 for (n = 0; n < nlines; )
2600 {
2601 if (curbuf->b_ml.ml_flags & ML_EMPTY) /* nothing to delete */
2602 break;
2603
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002604 ml_delete(first, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002605 ++n;
2606
2607 /* If we delete the last line in the file, stop */
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002608 if (first > curbuf->b_ml.ml_line_count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002609 break;
2610 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002611
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002612 /* Correct the cursor position before calling deleted_lines_mark(), it may
2613 * trigger a callback to display the cursor. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002614 curwin->w_cursor.col = 0;
2615 check_cursor_lnum();
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002616
2617 /* adjust marks, mark the buffer as changed and prepare for displaying */
2618 deleted_lines_mark(first, n);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002619}
2620
2621 int
2622gchar_pos(pos)
2623 pos_T *pos;
2624{
2625 char_u *ptr = ml_get_pos(pos);
2626
2627#ifdef FEAT_MBYTE
2628 if (has_mbyte)
2629 return (*mb_ptr2char)(ptr);
2630#endif
2631 return (int)*ptr;
2632}
2633
2634 int
2635gchar_cursor()
2636{
2637#ifdef FEAT_MBYTE
2638 if (has_mbyte)
2639 return (*mb_ptr2char)(ml_get_cursor());
2640#endif
2641 return (int)*ml_get_cursor();
2642}
2643
2644/*
2645 * Write a character at the current cursor position.
2646 * It is directly written into the block.
2647 */
2648 void
2649pchar_cursor(c)
2650 int c;
2651{
2652 *(ml_get_buf(curbuf, curwin->w_cursor.lnum, TRUE)
2653 + curwin->w_cursor.col) = c;
2654}
2655
Bram Moolenaar071d4272004-06-13 20:20:40 +00002656/*
2657 * When extra == 0: Return TRUE if the cursor is before or on the first
2658 * non-blank in the line.
2659 * When extra == 1: Return TRUE if the cursor is before the first non-blank in
2660 * the line.
2661 */
2662 int
2663inindent(extra)
2664 int extra;
2665{
2666 char_u *ptr;
2667 colnr_T col;
2668
2669 for (col = 0, ptr = ml_get_curline(); vim_iswhite(*ptr); ++col)
2670 ++ptr;
2671 if (col >= curwin->w_cursor.col + extra)
2672 return TRUE;
2673 else
2674 return FALSE;
2675}
2676
2677/*
2678 * Skip to next part of an option argument: Skip space and comma.
2679 */
2680 char_u *
2681skip_to_option_part(p)
2682 char_u *p;
2683{
2684 if (*p == ',')
2685 ++p;
2686 while (*p == ' ')
2687 ++p;
2688 return p;
2689}
2690
2691/*
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002692 * Call this function when something in the current buffer is changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002693 *
2694 * Most often called through changed_bytes() and changed_lines(), which also
2695 * mark the area of the display to be redrawn.
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002696 *
2697 * Careful: may trigger autocommands that reload the buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002698 */
2699 void
2700changed()
2701{
2702#if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
2703 /* The text of the preediting area is inserted, but this doesn't
2704 * mean a change of the buffer yet. That is delayed until the
2705 * text is committed. (this means preedit becomes empty) */
2706 if (im_is_preediting() && !xim_changed_while_preediting)
2707 return;
2708 xim_changed_while_preediting = FALSE;
2709#endif
2710
2711 if (!curbuf->b_changed)
2712 {
2713 int save_msg_scroll = msg_scroll;
2714
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002715 /* Give a warning about changing a read-only file. This may also
2716 * check-out the file, thus change "curbuf"! */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002717 change_warning(0);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002718
Bram Moolenaar071d4272004-06-13 20:20:40 +00002719 /* Create a swap file if that is wanted.
2720 * Don't do this for "nofile" and "nowrite" buffer types. */
2721 if (curbuf->b_may_swap
2722#ifdef FEAT_QUICKFIX
2723 && !bt_dontwrite(curbuf)
2724#endif
2725 )
2726 {
2727 ml_open_file(curbuf);
2728
2729 /* The ml_open_file() can cause an ATTENTION message.
2730 * Wait two seconds, to make sure the user reads this unexpected
2731 * message. Since we could be anywhere, call wait_return() now,
2732 * and don't let the emsg() set msg_scroll. */
2733 if (need_wait_return && emsg_silent == 0)
2734 {
2735 out_flush();
2736 ui_delay(2000L, TRUE);
2737 wait_return(TRUE);
2738 msg_scroll = save_msg_scroll;
2739 }
2740 }
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02002741 changed_int();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002742 }
2743 ++curbuf->b_changedtick;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002744}
2745
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02002746/*
2747 * Internal part of changed(), no user interaction.
2748 */
2749 void
2750changed_int()
2751{
2752 curbuf->b_changed = TRUE;
2753 ml_setflags(curbuf);
2754#ifdef FEAT_WINDOWS
2755 check_status(curbuf);
2756 redraw_tabline = TRUE;
2757#endif
2758#ifdef FEAT_TITLE
2759 need_maketitle = TRUE; /* set window title later */
2760#endif
2761}
2762
Bram Moolenaardba8a912005-04-24 22:08:39 +00002763static void changedOneline __ARGS((buf_T *buf, linenr_T lnum));
2764static void changed_lines_buf __ARGS((buf_T *buf, linenr_T lnum, linenr_T lnume, long xtra));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002765static void changed_common __ARGS((linenr_T lnum, colnr_T col, linenr_T lnume, long xtra));
2766
2767/*
2768 * Changed bytes within a single line for the current buffer.
2769 * - marks the windows on this buffer to be redisplayed
2770 * - marks the buffer changed by calling changed()
2771 * - invalidates cached values
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002772 * Careful: may trigger autocommands that reload the buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002773 */
2774 void
2775changed_bytes(lnum, col)
2776 linenr_T lnum;
2777 colnr_T col;
2778{
Bram Moolenaardba8a912005-04-24 22:08:39 +00002779 changedOneline(curbuf, lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002780 changed_common(lnum, col, lnum + 1, 0L);
Bram Moolenaardba8a912005-04-24 22:08:39 +00002781
2782#ifdef FEAT_DIFF
2783 /* Diff highlighting in other diff windows may need to be updated too. */
2784 if (curwin->w_p_diff)
2785 {
2786 win_T *wp;
2787 linenr_T wlnum;
2788
2789 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2790 if (wp->w_p_diff && wp != curwin)
2791 {
2792 redraw_win_later(wp, VALID);
2793 wlnum = diff_lnum_win(lnum, wp);
2794 if (wlnum > 0)
2795 changedOneline(wp->w_buffer, wlnum);
2796 }
2797 }
2798#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002799}
2800
2801 static void
Bram Moolenaardba8a912005-04-24 22:08:39 +00002802changedOneline(buf, lnum)
2803 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002804 linenr_T lnum;
2805{
Bram Moolenaardba8a912005-04-24 22:08:39 +00002806 if (buf->b_mod_set)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002807 {
2808 /* find the maximum area that must be redisplayed */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002809 if (lnum < buf->b_mod_top)
2810 buf->b_mod_top = lnum;
2811 else if (lnum >= buf->b_mod_bot)
2812 buf->b_mod_bot = lnum + 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002813 }
2814 else
2815 {
2816 /* set the area that must be redisplayed to one line */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002817 buf->b_mod_set = TRUE;
2818 buf->b_mod_top = lnum;
2819 buf->b_mod_bot = lnum + 1;
2820 buf->b_mod_xlines = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002821 }
2822}
2823
2824/*
2825 * Appended "count" lines below line "lnum" in the current buffer.
2826 * Must be called AFTER the change and after mark_adjust().
2827 * Takes care of marking the buffer to be redrawn and sets the changed flag.
2828 */
2829 void
2830appended_lines(lnum, count)
2831 linenr_T lnum;
2832 long count;
2833{
2834 changed_lines(lnum + 1, 0, lnum + 1, count);
2835}
2836
2837/*
2838 * Like appended_lines(), but adjust marks first.
2839 */
2840 void
2841appended_lines_mark(lnum, count)
2842 linenr_T lnum;
2843 long count;
2844{
2845 mark_adjust(lnum + 1, (linenr_T)MAXLNUM, count, 0L);
2846 changed_lines(lnum + 1, 0, lnum + 1, count);
2847}
2848
2849/*
2850 * Deleted "count" lines at line "lnum" in the current buffer.
2851 * Must be called AFTER the change and after mark_adjust().
2852 * Takes care of marking the buffer to be redrawn and sets the changed flag.
2853 */
2854 void
2855deleted_lines(lnum, count)
2856 linenr_T lnum;
2857 long count;
2858{
2859 changed_lines(lnum, 0, lnum + count, -count);
2860}
2861
2862/*
2863 * Like deleted_lines(), but adjust marks first.
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002864 * Make sure the cursor is on a valid line before calling, a GUI callback may
2865 * be triggered to display the cursor.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002866 */
2867 void
2868deleted_lines_mark(lnum, count)
2869 linenr_T lnum;
2870 long count;
2871{
2872 mark_adjust(lnum, (linenr_T)(lnum + count - 1), (long)MAXLNUM, -count);
2873 changed_lines(lnum, 0, lnum + count, -count);
2874}
2875
2876/*
2877 * Changed lines for the current buffer.
2878 * Must be called AFTER the change and after mark_adjust().
2879 * - mark the buffer changed by calling changed()
2880 * - mark the windows on this buffer to be redisplayed
2881 * - invalidate cached values
2882 * "lnum" is the first line that needs displaying, "lnume" the first line
2883 * below the changed lines (BEFORE the change).
2884 * When only inserting lines, "lnum" and "lnume" are equal.
2885 * Takes care of calling changed() and updating b_mod_*.
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002886 * Careful: may trigger autocommands that reload the buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002887 */
2888 void
2889changed_lines(lnum, col, lnume, xtra)
2890 linenr_T lnum; /* first line with change */
2891 colnr_T col; /* column in first line with change */
2892 linenr_T lnume; /* line below last changed line */
2893 long xtra; /* number of extra lines (negative when deleting) */
2894{
Bram Moolenaardba8a912005-04-24 22:08:39 +00002895 changed_lines_buf(curbuf, lnum, lnume, xtra);
2896
2897#ifdef FEAT_DIFF
2898 if (xtra == 0 && curwin->w_p_diff)
2899 {
2900 /* When the number of lines doesn't change then mark_adjust() isn't
2901 * called and other diff buffers still need to be marked for
2902 * displaying. */
2903 win_T *wp;
2904 linenr_T wlnum;
2905
2906 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2907 if (wp->w_p_diff && wp != curwin)
2908 {
2909 redraw_win_later(wp, VALID);
2910 wlnum = diff_lnum_win(lnum, wp);
2911 if (wlnum > 0)
2912 changed_lines_buf(wp->w_buffer, wlnum,
2913 lnume - lnum + wlnum, 0L);
2914 }
2915 }
2916#endif
2917
2918 changed_common(lnum, col, lnume, xtra);
2919}
2920
2921 static void
2922changed_lines_buf(buf, lnum, lnume, xtra)
2923 buf_T *buf;
2924 linenr_T lnum; /* first line with change */
2925 linenr_T lnume; /* line below last changed line */
2926 long xtra; /* number of extra lines (negative when deleting) */
2927{
2928 if (buf->b_mod_set)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002929 {
2930 /* find the maximum area that must be redisplayed */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002931 if (lnum < buf->b_mod_top)
2932 buf->b_mod_top = lnum;
2933 if (lnum < buf->b_mod_bot)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002934 {
2935 /* adjust old bot position for xtra lines */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002936 buf->b_mod_bot += xtra;
2937 if (buf->b_mod_bot < lnum)
2938 buf->b_mod_bot = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002939 }
Bram Moolenaardba8a912005-04-24 22:08:39 +00002940 if (lnume + xtra > buf->b_mod_bot)
2941 buf->b_mod_bot = lnume + xtra;
2942 buf->b_mod_xlines += xtra;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002943 }
2944 else
2945 {
2946 /* set the area that must be redisplayed */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002947 buf->b_mod_set = TRUE;
2948 buf->b_mod_top = lnum;
2949 buf->b_mod_bot = lnume + xtra;
2950 buf->b_mod_xlines = xtra;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002951 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002952}
2953
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002954/*
2955 * Common code for when a change is was made.
2956 * See changed_lines() for the arguments.
2957 * Careful: may trigger autocommands that reload the buffer.
2958 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002959 static void
2960changed_common(lnum, col, lnume, xtra)
2961 linenr_T lnum;
2962 colnr_T col;
2963 linenr_T lnume;
2964 long xtra;
2965{
2966 win_T *wp;
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00002967#ifdef FEAT_WINDOWS
2968 tabpage_T *tp;
2969#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002970 int i;
2971#ifdef FEAT_JUMPLIST
2972 int cols;
2973 pos_T *p;
2974 int add;
2975#endif
2976
2977 /* mark the buffer as modified */
2978 changed();
2979
2980 /* set the '. mark */
2981 if (!cmdmod.keepjumps)
2982 {
2983 curbuf->b_last_change.lnum = lnum;
2984 curbuf->b_last_change.col = col;
2985
2986#ifdef FEAT_JUMPLIST
2987 /* Create a new entry if a new undo-able change was started or we
2988 * don't have an entry yet. */
2989 if (curbuf->b_new_change || curbuf->b_changelistlen == 0)
2990 {
2991 if (curbuf->b_changelistlen == 0)
2992 add = TRUE;
2993 else
2994 {
2995 /* Don't create a new entry when the line number is the same
2996 * as the last one and the column is not too far away. Avoids
2997 * creating many entries for typing "xxxxx". */
2998 p = &curbuf->b_changelist[curbuf->b_changelistlen - 1];
2999 if (p->lnum != lnum)
3000 add = TRUE;
3001 else
3002 {
3003 cols = comp_textwidth(FALSE);
3004 if (cols == 0)
3005 cols = 79;
3006 add = (p->col + cols < col || col + cols < p->col);
3007 }
3008 }
3009 if (add)
3010 {
3011 /* This is the first of a new sequence of undo-able changes
3012 * and it's at some distance of the last change. Use a new
3013 * position in the changelist. */
3014 curbuf->b_new_change = FALSE;
3015
3016 if (curbuf->b_changelistlen == JUMPLISTSIZE)
3017 {
3018 /* changelist is full: remove oldest entry */
3019 curbuf->b_changelistlen = JUMPLISTSIZE - 1;
3020 mch_memmove(curbuf->b_changelist, curbuf->b_changelist + 1,
3021 sizeof(pos_T) * (JUMPLISTSIZE - 1));
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00003022 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003023 {
3024 /* Correct position in changelist for other windows on
3025 * this buffer. */
3026 if (wp->w_buffer == curbuf && wp->w_changelistidx > 0)
3027 --wp->w_changelistidx;
3028 }
3029 }
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00003030 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003031 {
3032 /* For other windows, if the position in the changelist is
3033 * at the end it stays at the end. */
3034 if (wp->w_buffer == curbuf
3035 && wp->w_changelistidx == curbuf->b_changelistlen)
3036 ++wp->w_changelistidx;
3037 }
3038 ++curbuf->b_changelistlen;
3039 }
3040 }
3041 curbuf->b_changelist[curbuf->b_changelistlen - 1] =
3042 curbuf->b_last_change;
3043 /* The current window is always after the last change, so that "g,"
3044 * takes you back to it. */
3045 curwin->w_changelistidx = curbuf->b_changelistlen;
3046#endif
3047 }
3048
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00003049 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003050 {
3051 if (wp->w_buffer == curbuf)
3052 {
3053 /* Mark this window to be redrawn later. */
3054 if (wp->w_redr_type < VALID)
3055 wp->w_redr_type = VALID;
3056
3057 /* Check if a change in the buffer has invalidated the cached
3058 * values for the cursor. */
3059#ifdef FEAT_FOLDING
3060 /*
3061 * Update the folds for this window. Can't postpone this, because
3062 * a following operator might work on the whole fold: ">>dd".
3063 */
3064 foldUpdate(wp, lnum, lnume + xtra - 1);
3065
3066 /* The change may cause lines above or below the change to become
3067 * included in a fold. Set lnum/lnume to the first/last line that
3068 * might be displayed differently.
3069 * Set w_cline_folded here as an efficient way to update it when
3070 * inserting lines just above a closed fold. */
3071 i = hasFoldingWin(wp, lnum, &lnum, NULL, FALSE, NULL);
3072 if (wp->w_cursor.lnum == lnum)
3073 wp->w_cline_folded = i;
3074 i = hasFoldingWin(wp, lnume, NULL, &lnume, FALSE, NULL);
3075 if (wp->w_cursor.lnum == lnume)
3076 wp->w_cline_folded = i;
3077
3078 /* If the changed line is in a range of previously folded lines,
3079 * compare with the first line in that range. */
3080 if (wp->w_cursor.lnum <= lnum)
3081 {
3082 i = find_wl_entry(wp, lnum);
3083 if (i >= 0 && wp->w_cursor.lnum > wp->w_lines[i].wl_lnum)
3084 changed_line_abv_curs_win(wp);
3085 }
3086#endif
3087
3088 if (wp->w_cursor.lnum > lnum)
3089 changed_line_abv_curs_win(wp);
3090 else if (wp->w_cursor.lnum == lnum && wp->w_cursor.col >= col)
3091 changed_cline_bef_curs_win(wp);
3092 if (wp->w_botline >= lnum)
3093 {
3094 /* Assume that botline doesn't change (inserted lines make
3095 * other lines scroll down below botline). */
3096 approximate_botline_win(wp);
3097 }
3098
3099 /* Check if any w_lines[] entries have become invalid.
3100 * For entries below the change: Correct the lnums for
3101 * inserted/deleted lines. Makes it possible to stop displaying
3102 * after the change. */
3103 for (i = 0; i < wp->w_lines_valid; ++i)
3104 if (wp->w_lines[i].wl_valid)
3105 {
3106 if (wp->w_lines[i].wl_lnum >= lnum)
3107 {
3108 if (wp->w_lines[i].wl_lnum < lnume)
3109 {
3110 /* line included in change */
3111 wp->w_lines[i].wl_valid = FALSE;
3112 }
3113 else if (xtra != 0)
3114 {
3115 /* line below change */
3116 wp->w_lines[i].wl_lnum += xtra;
3117#ifdef FEAT_FOLDING
3118 wp->w_lines[i].wl_lastlnum += xtra;
3119#endif
3120 }
3121 }
3122#ifdef FEAT_FOLDING
3123 else if (wp->w_lines[i].wl_lastlnum >= lnum)
3124 {
3125 /* change somewhere inside this range of folded lines,
3126 * may need to be redrawn */
3127 wp->w_lines[i].wl_valid = FALSE;
3128 }
3129#endif
3130 }
Bram Moolenaar3234cc62009-11-03 17:47:12 +00003131
3132#ifdef FEAT_FOLDING
3133 /* Take care of side effects for setting w_topline when folds have
3134 * changed. Esp. when the buffer was changed in another window. */
3135 if (hasAnyFolding(wp))
3136 set_topline(wp, wp->w_topline);
3137#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003138 }
3139 }
3140
3141 /* Call update_screen() later, which checks out what needs to be redrawn,
3142 * since it notices b_mod_set and then uses b_mod_*. */
3143 if (must_redraw < VALID)
3144 must_redraw = VALID;
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00003145
3146#ifdef FEAT_AUTOCMD
3147 /* when the cursor line is changed always trigger CursorMoved */
Bram Moolenaare163f1c2006-10-17 09:12:21 +00003148 if (lnum <= curwin->w_cursor.lnum
3149 && lnume + (xtra < 0 ? -xtra : xtra) > curwin->w_cursor.lnum)
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00003150 last_cursormoved.lnum = 0;
3151#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003152}
3153
3154/*
3155 * unchanged() is called when the changed flag must be reset for buffer 'buf'
3156 */
3157 void
3158unchanged(buf, ff)
3159 buf_T *buf;
3160 int ff; /* also reset 'fileformat' */
3161{
Bram Moolenaar164c60f2011-01-22 00:11:50 +01003162 if (buf->b_changed || (ff && file_ff_differs(buf, FALSE)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003163 {
3164 buf->b_changed = 0;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003165 ml_setflags(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003166 if (ff)
3167 save_file_ff(buf);
3168#ifdef FEAT_WINDOWS
3169 check_status(buf);
Bram Moolenaar997fb4b2006-02-17 21:53:23 +00003170 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003171#endif
3172#ifdef FEAT_TITLE
3173 need_maketitle = TRUE; /* set window title later */
3174#endif
3175 }
3176 ++buf->b_changedtick;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003177#ifdef FEAT_NETBEANS_INTG
3178 netbeans_unmodified(buf);
3179#endif
3180}
3181
3182#if defined(FEAT_WINDOWS) || defined(PROTO)
3183/*
3184 * check_status: called when the status bars for the buffer 'buf'
3185 * need to be updated
3186 */
3187 void
3188check_status(buf)
3189 buf_T *buf;
3190{
3191 win_T *wp;
3192
3193 for (wp = firstwin; wp != NULL; wp = wp->w_next)
3194 if (wp->w_buffer == buf && wp->w_status_height)
3195 {
3196 wp->w_redr_status = TRUE;
3197 if (must_redraw < VALID)
3198 must_redraw = VALID;
3199 }
3200}
3201#endif
3202
3203/*
3204 * If the file is readonly, give a warning message with the first change.
3205 * Don't do this for autocommands.
3206 * Don't use emsg(), because it flushes the macro buffer.
Bram Moolenaard5cdbeb2005-10-10 20:59:28 +00003207 * If we have undone all changes b_changed will be FALSE, but "b_did_warn"
Bram Moolenaar071d4272004-06-13 20:20:40 +00003208 * will be TRUE.
Bram Moolenaarb0b50882010-07-07 18:26:28 +02003209 * Careful: may trigger autocommands that reload the buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003210 */
3211 void
3212change_warning(col)
3213 int col; /* column for message; non-zero when in insert
3214 mode and 'showmode' is on */
3215{
Bram Moolenaar496c5262009-03-18 14:42:00 +00003216 static char *w_readonly = N_("W10: Warning: Changing a readonly file");
3217
Bram Moolenaar071d4272004-06-13 20:20:40 +00003218 if (curbuf->b_did_warn == FALSE
3219 && curbufIsChanged() == 0
3220#ifdef FEAT_AUTOCMD
3221 && !autocmd_busy
3222#endif
3223 && curbuf->b_p_ro)
3224 {
3225#ifdef FEAT_AUTOCMD
Bram Moolenaar910f66f2006-04-05 20:41:53 +00003226 ++curbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003227 apply_autocmds(EVENT_FILECHANGEDRO, NULL, NULL, FALSE, curbuf);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00003228 --curbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003229 if (!curbuf->b_p_ro)
3230 return;
3231#endif
3232 /*
3233 * Do what msg() does, but with a column offset if the warning should
3234 * be after the mode message.
3235 */
3236 msg_start();
3237 if (msg_row == Rows - 1)
3238 msg_col = col;
Bram Moolenaar2df6dcc2004-07-12 15:53:54 +00003239 msg_source(hl_attr(HLF_W));
Bram Moolenaar496c5262009-03-18 14:42:00 +00003240 MSG_PUTS_ATTR(_(w_readonly), hl_attr(HLF_W) | MSG_HIST);
3241#ifdef FEAT_EVAL
3242 set_vim_var_string(VV_WARNINGMSG, (char_u *)_(w_readonly), -1);
3243#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003244 msg_clr_eos();
3245 (void)msg_end();
3246 if (msg_silent == 0 && !silent_mode)
3247 {
3248 out_flush();
3249 ui_delay(1000L, TRUE); /* give the user time to think about it */
3250 }
3251 curbuf->b_did_warn = TRUE;
3252 redraw_cmdline = FALSE; /* don't redraw and erase the message */
3253 if (msg_row < Rows - 1)
3254 showmode();
3255 }
3256}
3257
3258/*
3259 * Ask for a reply from the user, a 'y' or a 'n'.
3260 * No other characters are accepted, the message is repeated until a valid
3261 * reply is entered or CTRL-C is hit.
3262 * If direct is TRUE, don't use vgetc() but ui_inchar(), don't get characters
3263 * from any buffers but directly from the user.
3264 *
3265 * return the 'y' or 'n'
3266 */
3267 int
3268ask_yesno(str, direct)
3269 char_u *str;
3270 int direct;
3271{
3272 int r = ' ';
3273 int save_State = State;
3274
3275 if (exiting) /* put terminal in raw mode for this question */
3276 settmode(TMODE_RAW);
3277 ++no_wait_return;
3278#ifdef USE_ON_FLY_SCROLL
3279 dont_scroll = TRUE; /* disallow scrolling here */
3280#endif
3281 State = CONFIRM; /* mouse behaves like with :confirm */
3282#ifdef FEAT_MOUSE
3283 setmouse(); /* disables mouse for xterm */
3284#endif
3285 ++no_mapping;
3286 ++allow_keys; /* no mapping here, but recognize keys */
3287
3288 while (r != 'y' && r != 'n')
3289 {
3290 /* same highlighting as for wait_return */
3291 smsg_attr(hl_attr(HLF_R), (char_u *)"%s (y/n)?", str);
3292 if (direct)
3293 r = get_keystroke();
3294 else
Bram Moolenaar913626c2008-01-03 11:43:42 +00003295 r = plain_vgetc();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003296 if (r == Ctrl_C || r == ESC)
3297 r = 'n';
3298 msg_putchar(r); /* show what you typed */
3299 out_flush();
3300 }
3301 --no_wait_return;
3302 State = save_State;
3303#ifdef FEAT_MOUSE
3304 setmouse();
3305#endif
3306 --no_mapping;
3307 --allow_keys;
3308
3309 return r;
3310}
3311
3312/*
3313 * Get a key stroke directly from the user.
3314 * Ignores mouse clicks and scrollbar events, except a click for the left
3315 * button (used at the more prompt).
3316 * Doesn't use vgetc(), because it syncs undo and eats mapped characters.
3317 * Disadvantage: typeahead is ignored.
3318 * Translates the interrupt character for unix to ESC.
3319 */
3320 int
3321get_keystroke()
3322{
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003323 char_u *buf = NULL;
3324 int buflen = 150;
3325 int maxlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003326 int len = 0;
3327 int n;
3328 int save_mapped_ctrl_c = mapped_ctrl_c;
Bram Moolenaar4395a712006-09-05 18:57:57 +00003329 int waited = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003330
3331 mapped_ctrl_c = FALSE; /* mappings are not used here */
3332 for (;;)
3333 {
3334 cursor_on();
3335 out_flush();
3336
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003337 /* Leave some room for check_termcode() to insert a key code into (max
3338 * 5 chars plus NUL). And fix_input_buffer() can triple the number of
3339 * bytes. */
3340 maxlen = (buflen - 6 - len) / 3;
3341 if (buf == NULL)
3342 buf = alloc(buflen);
3343 else if (maxlen < 10)
3344 {
Bram Moolenaardc7e85e2012-06-20 12:40:08 +02003345 /* Need some more space. This might happen when receiving a long
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003346 * escape sequence. */
3347 buflen += 100;
3348 buf = vim_realloc(buf, buflen);
3349 maxlen = (buflen - 6 - len) / 3;
3350 }
3351 if (buf == NULL)
3352 {
3353 do_outofmem_msg((long_u)buflen);
3354 return ESC; /* panic! */
3355 }
3356
Bram Moolenaar071d4272004-06-13 20:20:40 +00003357 /* First time: blocking wait. Second time: wait up to 100ms for a
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003358 * terminal code to complete. */
3359 n = ui_inchar(buf + len, maxlen, len == 0 ? -1L : 100L, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003360 if (n > 0)
3361 {
3362 /* Replace zero and CSI by a special key code. */
3363 n = fix_input_buffer(buf + len, n, FALSE);
3364 len += n;
Bram Moolenaar4395a712006-09-05 18:57:57 +00003365 waited = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003366 }
Bram Moolenaar4395a712006-09-05 18:57:57 +00003367 else if (len > 0)
3368 ++waited; /* keep track of the waiting time */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003369
Bram Moolenaar4395a712006-09-05 18:57:57 +00003370 /* Incomplete termcode and not timed out yet: get more characters */
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003371 if ((n = check_termcode(1, buf, buflen, &len)) < 0
Bram Moolenaar4395a712006-09-05 18:57:57 +00003372 && (!p_ttimeout || waited * 100L < (p_ttm < 0 ? p_tm : p_ttm)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003373 continue;
Bram Moolenaar4395a712006-09-05 18:57:57 +00003374
Bram Moolenaar946ffd42010-12-30 12:30:31 +01003375 if (n == KEYLEN_REMOVED) /* key code removed */
Bram Moolenaar6eb634e2011-03-03 15:04:08 +01003376 {
Bram Moolenaarfd30cd42011-03-22 13:07:26 +01003377 if (must_redraw != 0 && !need_wait_return && (State & CMDLINE) == 0)
Bram Moolenaar6eb634e2011-03-03 15:04:08 +01003378 {
3379 /* Redrawing was postponed, do it now. */
3380 update_screen(0);
3381 setcursor(); /* put cursor back where it belongs */
3382 }
Bram Moolenaar946ffd42010-12-30 12:30:31 +01003383 continue;
Bram Moolenaar6eb634e2011-03-03 15:04:08 +01003384 }
Bram Moolenaar946ffd42010-12-30 12:30:31 +01003385 if (n > 0) /* found a termcode: adjust length */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003386 len = n;
Bram Moolenaar946ffd42010-12-30 12:30:31 +01003387 if (len == 0) /* nothing typed yet */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003388 continue;
3389
3390 /* Handle modifier and/or special key code. */
3391 n = buf[0];
3392 if (n == K_SPECIAL)
3393 {
3394 n = TO_SPECIAL(buf[1], buf[2]);
3395 if (buf[1] == KS_MODIFIER
3396 || n == K_IGNORE
3397#ifdef FEAT_MOUSE
3398 || n == K_LEFTMOUSE_NM
3399 || n == K_LEFTDRAG
3400 || n == K_LEFTRELEASE
3401 || n == K_LEFTRELEASE_NM
3402 || n == K_MIDDLEMOUSE
3403 || n == K_MIDDLEDRAG
3404 || n == K_MIDDLERELEASE
3405 || n == K_RIGHTMOUSE
3406 || n == K_RIGHTDRAG
3407 || n == K_RIGHTRELEASE
3408 || n == K_MOUSEDOWN
3409 || n == K_MOUSEUP
Bram Moolenaar8d9b40e2010-07-25 15:49:07 +02003410 || n == K_MOUSELEFT
3411 || n == K_MOUSERIGHT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003412 || n == K_X1MOUSE
3413 || n == K_X1DRAG
3414 || n == K_X1RELEASE
3415 || n == K_X2MOUSE
3416 || n == K_X2DRAG
3417 || n == K_X2RELEASE
3418# ifdef FEAT_GUI
3419 || n == K_VER_SCROLLBAR
3420 || n == K_HOR_SCROLLBAR
3421# endif
3422#endif
3423 )
3424 {
3425 if (buf[1] == KS_MODIFIER)
3426 mod_mask = buf[2];
3427 len -= 3;
3428 if (len > 0)
3429 mch_memmove(buf, buf + 3, (size_t)len);
3430 continue;
3431 }
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00003432 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003433 }
3434#ifdef FEAT_MBYTE
3435 if (has_mbyte)
3436 {
3437 if (MB_BYTE2LEN(n) > len)
3438 continue; /* more bytes to get */
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003439 buf[len >= buflen ? buflen - 1 : len] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003440 n = (*mb_ptr2char)(buf);
3441 }
3442#endif
3443#ifdef UNIX
3444 if (n == intr_char)
3445 n = ESC;
3446#endif
3447 break;
3448 }
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003449 vim_free(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003450
3451 mapped_ctrl_c = save_mapped_ctrl_c;
3452 return n;
3453}
3454
3455/*
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003456 * Get a number from the user.
3457 * When "mouse_used" is not NULL allow using the mouse.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003458 */
3459 int
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003460get_number(colon, mouse_used)
3461 int colon; /* allow colon to abort */
3462 int *mouse_used;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003463{
3464 int n = 0;
3465 int c;
Bram Moolenaar3991dab2006-03-27 17:01:56 +00003466 int typed = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003467
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003468 if (mouse_used != NULL)
3469 *mouse_used = FALSE;
3470
Bram Moolenaar071d4272004-06-13 20:20:40 +00003471 /* When not printing messages, the user won't know what to type, return a
3472 * zero (as if CR was hit). */
3473 if (msg_silent != 0)
3474 return 0;
3475
3476#ifdef USE_ON_FLY_SCROLL
3477 dont_scroll = TRUE; /* disallow scrolling here */
3478#endif
3479 ++no_mapping;
3480 ++allow_keys; /* no mapping here, but recognize keys */
3481 for (;;)
3482 {
3483 windgoto(msg_row, msg_col);
3484 c = safe_vgetc();
3485 if (VIM_ISDIGIT(c))
3486 {
3487 n = n * 10 + c - '0';
3488 msg_putchar(c);
Bram Moolenaar3991dab2006-03-27 17:01:56 +00003489 ++typed;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003490 }
3491 else if (c == K_DEL || c == K_KDEL || c == K_BS || c == Ctrl_H)
3492 {
Bram Moolenaar3991dab2006-03-27 17:01:56 +00003493 if (typed > 0)
3494 {
3495 MSG_PUTS("\b \b");
3496 --typed;
3497 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003498 n /= 10;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003499 }
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003500#ifdef FEAT_MOUSE
3501 else if (mouse_used != NULL && c == K_LEFTMOUSE)
3502 {
3503 *mouse_used = TRUE;
3504 n = mouse_row + 1;
3505 break;
3506 }
3507#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003508 else if (n == 0 && c == ':' && colon)
3509 {
3510 stuffcharReadbuff(':');
3511 if (!exmode_active)
3512 cmdline_row = msg_row;
3513 skip_redraw = TRUE; /* skip redraw once */
3514 do_redraw = FALSE;
3515 break;
3516 }
3517 else if (c == CAR || c == NL || c == Ctrl_C || c == ESC)
3518 break;
3519 }
3520 --no_mapping;
3521 --allow_keys;
3522 return n;
3523}
3524
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003525/*
3526 * Ask the user to enter a number.
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003527 * When "mouse_used" is not NULL allow using the mouse and in that case return
3528 * the line number.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003529 */
3530 int
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003531prompt_for_number(mouse_used)
3532 int *mouse_used;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003533{
3534 int i;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003535 int save_cmdline_row;
3536 int save_State;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003537
3538 /* When using ":silent" assume that <CR> was entered. */
Bram Moolenaar42eeac32005-06-29 22:40:58 +00003539 if (mouse_used != NULL)
Bram Moolenaard812df62008-11-09 12:46:09 +00003540 MSG_PUTS(_("Type number and <Enter> or click with mouse (empty cancels): "));
Bram Moolenaar42eeac32005-06-29 22:40:58 +00003541 else
Bram Moolenaard812df62008-11-09 12:46:09 +00003542 MSG_PUTS(_("Type number and <Enter> (empty cancels): "));
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003543
Bram Moolenaar203335e2006-09-03 14:35:42 +00003544 /* Set the state such that text can be selected/copied/pasted and we still
3545 * get mouse events. */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003546 save_cmdline_row = cmdline_row;
Bram Moolenaar203335e2006-09-03 14:35:42 +00003547 cmdline_row = 0;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003548 save_State = State;
Bram Moolenaar203335e2006-09-03 14:35:42 +00003549 State = CMDLINE;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003550
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003551 i = get_number(TRUE, mouse_used);
3552 if (KeyTyped)
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003553 {
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003554 /* don't call wait_return() now */
3555 /* msg_putchar('\n'); */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003556 cmdline_row = msg_row - 1;
3557 need_wait_return = FALSE;
3558 msg_didany = FALSE;
Bram Moolenaarb2450162009-07-22 09:04:20 +00003559 msg_didout = FALSE;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003560 }
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003561 else
3562 cmdline_row = save_cmdline_row;
3563 State = save_State;
3564
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003565 return i;
3566}
3567
Bram Moolenaar071d4272004-06-13 20:20:40 +00003568 void
3569msgmore(n)
3570 long n;
3571{
3572 long pn;
3573
3574 if (global_busy /* no messages now, wait until global is finished */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003575 || !messaging()) /* 'lazyredraw' set, don't do messages now */
3576 return;
3577
Bram Moolenaar7df2d662005-01-25 22:18:08 +00003578 /* We don't want to overwrite another important message, but do overwrite
3579 * a previous "more lines" or "fewer lines" message, so that "5dd" and
3580 * then "put" reports the last action. */
3581 if (keep_msg != NULL && !keep_msg_more)
3582 return;
3583
Bram Moolenaar071d4272004-06-13 20:20:40 +00003584 if (n > 0)
3585 pn = n;
3586 else
3587 pn = -n;
3588
3589 if (pn > p_report)
3590 {
3591 if (pn == 1)
3592 {
3593 if (n > 0)
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003594 vim_strncpy(msg_buf, (char_u *)_("1 more line"),
3595 MSG_BUF_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003596 else
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003597 vim_strncpy(msg_buf, (char_u *)_("1 line less"),
3598 MSG_BUF_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003599 }
3600 else
3601 {
3602 if (n > 0)
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003603 vim_snprintf((char *)msg_buf, MSG_BUF_LEN,
3604 _("%ld more lines"), pn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003605 else
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003606 vim_snprintf((char *)msg_buf, MSG_BUF_LEN,
3607 _("%ld fewer lines"), pn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003608 }
3609 if (got_int)
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003610 vim_strcat(msg_buf, (char_u *)_(" (Interrupted)"), MSG_BUF_LEN);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003611 if (msg(msg_buf))
3612 {
Bram Moolenaar238a5642006-02-21 22:12:05 +00003613 set_keep_msg(msg_buf, 0);
Bram Moolenaar7df2d662005-01-25 22:18:08 +00003614 keep_msg_more = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003615 }
3616 }
3617}
3618
3619/*
3620 * flush map and typeahead buffers and give a warning for an error
3621 */
3622 void
3623beep_flush()
3624{
3625 if (emsg_silent == 0)
3626 {
3627 flush_buffers(FALSE);
3628 vim_beep();
3629 }
3630}
3631
3632/*
3633 * give a warning for an error
3634 */
3635 void
3636vim_beep()
3637{
3638 if (emsg_silent == 0)
3639 {
3640 if (p_vb
3641#ifdef FEAT_GUI
3642 /* While the GUI is starting up the termcap is set for the GUI
3643 * but the output still goes to a terminal. */
3644 && !(gui.in_use && gui.starting)
3645#endif
3646 )
3647 {
3648 out_str(T_VB);
3649 }
3650 else
3651 {
3652#ifdef MSDOS
3653 /*
3654 * The number of beeps outputted is reduced to avoid having to wait
3655 * for all the beeps to finish. This is only a problem on systems
3656 * where the beeps don't overlap.
3657 */
3658 if (beep_count == 0 || beep_count == 10)
3659 {
3660 out_char(BELL);
3661 beep_count = 1;
3662 }
3663 else
3664 ++beep_count;
3665#else
3666 out_char(BELL);
3667#endif
3668 }
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003669
3670 /* When 'verbose' is set and we are sourcing a script or executing a
3671 * function give the user a hint where the beep comes from. */
3672 if (vim_strchr(p_debug, 'e') != NULL)
3673 {
3674 msg_source(hl_attr(HLF_W));
3675 msg_attr((char_u *)_("Beep!"), hl_attr(HLF_W));
3676 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003677 }
3678}
3679
3680/*
3681 * To get the "real" home directory:
3682 * - get value of $HOME
3683 * For Unix:
3684 * - go to that directory
3685 * - do mch_dirname() to get the real name of that directory.
3686 * This also works with mounts and links.
3687 * Don't do this for MS-DOS, it will change the "current dir" for a drive.
3688 */
3689static char_u *homedir = NULL;
3690
3691 void
3692init_homedir()
3693{
3694 char_u *var;
3695
Bram Moolenaar05159a02005-02-26 23:04:13 +00003696 /* In case we are called a second time (when 'encoding' changes). */
3697 vim_free(homedir);
3698 homedir = NULL;
3699
Bram Moolenaar071d4272004-06-13 20:20:40 +00003700#ifdef VMS
3701 var = mch_getenv((char_u *)"SYS$LOGIN");
3702#else
3703 var = mch_getenv((char_u *)"HOME");
3704#endif
3705
3706 if (var != NULL && *var == NUL) /* empty is same as not set */
3707 var = NULL;
3708
3709#ifdef WIN3264
3710 /*
3711 * Weird but true: $HOME may contain an indirect reference to another
3712 * variable, esp. "%USERPROFILE%". Happens when $USERPROFILE isn't set
3713 * when $HOME is being set.
3714 */
3715 if (var != NULL && *var == '%')
3716 {
3717 char_u *p;
3718 char_u *exp;
3719
3720 p = vim_strchr(var + 1, '%');
3721 if (p != NULL)
3722 {
Bram Moolenaarce0842a2005-07-18 21:58:11 +00003723 vim_strncpy(NameBuff, var + 1, p - (var + 1));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003724 exp = mch_getenv(NameBuff);
3725 if (exp != NULL && *exp != NUL
3726 && STRLEN(exp) + STRLEN(p) < MAXPATHL)
3727 {
Bram Moolenaar555b2802005-05-19 21:08:39 +00003728 vim_snprintf((char *)NameBuff, MAXPATHL, "%s%s", exp, p + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003729 var = NameBuff;
3730 /* Also set $HOME, it's needed for _viminfo. */
3731 vim_setenv((char_u *)"HOME", NameBuff);
3732 }
3733 }
3734 }
3735
3736 /*
3737 * Typically, $HOME is not defined on Windows, unless the user has
3738 * specifically defined it for Vim's sake. However, on Windows NT
3739 * platforms, $HOMEDRIVE and $HOMEPATH are automatically defined for
3740 * each user. Try constructing $HOME from these.
3741 */
3742 if (var == NULL)
3743 {
3744 char_u *homedrive, *homepath;
3745
3746 homedrive = mch_getenv((char_u *)"HOMEDRIVE");
3747 homepath = mch_getenv((char_u *)"HOMEPATH");
Bram Moolenaar6f977012010-01-06 17:53:38 +01003748 if (homepath == NULL || *homepath == NUL)
3749 homepath = "\\";
3750 if (homedrive != NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00003751 && STRLEN(homedrive) + STRLEN(homepath) < MAXPATHL)
3752 {
3753 sprintf((char *)NameBuff, "%s%s", homedrive, homepath);
3754 if (NameBuff[0] != NUL)
3755 {
3756 var = NameBuff;
3757 /* Also set $HOME, it's needed for _viminfo. */
3758 vim_setenv((char_u *)"HOME", NameBuff);
3759 }
3760 }
3761 }
Bram Moolenaar05159a02005-02-26 23:04:13 +00003762
3763# if defined(FEAT_MBYTE)
3764 if (enc_utf8 && var != NULL)
3765 {
3766 int len;
Bram Moolenaarb453a532011-04-28 17:48:44 +02003767 char_u *pp = NULL;
Bram Moolenaar05159a02005-02-26 23:04:13 +00003768
3769 /* Convert from active codepage to UTF-8. Other conversions are
3770 * not done, because they would fail for non-ASCII characters. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003771 acp_to_enc(var, (int)STRLEN(var), &pp, &len);
Bram Moolenaar05159a02005-02-26 23:04:13 +00003772 if (pp != NULL)
3773 {
3774 homedir = pp;
3775 return;
3776 }
3777 }
3778# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003779#endif
3780
3781#if defined(OS2) || defined(MSDOS) || defined(MSWIN)
3782 /*
3783 * Default home dir is C:/
3784 * Best assumption we can make in such a situation.
3785 */
3786 if (var == NULL)
3787 var = "C:/";
3788#endif
3789 if (var != NULL)
3790 {
3791#ifdef UNIX
3792 /*
3793 * Change to the directory and get the actual path. This resolves
3794 * links. Don't do it when we can't return.
3795 */
3796 if (mch_dirname(NameBuff, MAXPATHL) == OK
3797 && mch_chdir((char *)NameBuff) == 0)
3798 {
3799 if (!mch_chdir((char *)var) && mch_dirname(IObuff, IOSIZE) == OK)
3800 var = IObuff;
3801 if (mch_chdir((char *)NameBuff) != 0)
3802 EMSG(_(e_prev_dir));
3803 }
3804#endif
3805 homedir = vim_strsave(var);
3806 }
3807}
3808
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003809#if defined(EXITFREE) || defined(PROTO)
3810 void
3811free_homedir()
3812{
3813 vim_free(homedir);
3814}
3815#endif
3816
Bram Moolenaar071d4272004-06-13 20:20:40 +00003817/*
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003818 * Call expand_env() and store the result in an allocated string.
3819 * This is not very memory efficient, this expects the result to be freed
3820 * again soon.
3821 */
3822 char_u *
3823expand_env_save(src)
3824 char_u *src;
3825{
3826 return expand_env_save_opt(src, FALSE);
3827}
3828
3829/*
3830 * Idem, but when "one" is TRUE handle the string as one file name, only
3831 * expand "~" at the start.
3832 */
3833 char_u *
3834expand_env_save_opt(src, one)
3835 char_u *src;
3836 int one;
3837{
3838 char_u *p;
3839
3840 p = alloc(MAXPATHL);
3841 if (p != NULL)
3842 expand_env_esc(src, p, MAXPATHL, FALSE, one, NULL);
3843 return p;
3844}
3845
3846/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003847 * Expand environment variable with path name.
3848 * "~/" is also expanded, using $HOME. For Unix "~user/" is expanded.
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003849 * Skips over "\ ", "\~" and "\$" (not for Win32 though).
Bram Moolenaar071d4272004-06-13 20:20:40 +00003850 * If anything fails no expansion is done and dst equals src.
3851 */
3852 void
3853expand_env(src, dst, dstlen)
3854 char_u *src; /* input string e.g. "$HOME/vim.hlp" */
3855 char_u *dst; /* where to put the result */
3856 int dstlen; /* maximum length of the result */
3857{
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003858 expand_env_esc(src, dst, dstlen, FALSE, FALSE, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003859}
3860
3861 void
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003862expand_env_esc(srcp, dst, dstlen, esc, one, startstr)
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003863 char_u *srcp; /* input string e.g. "$HOME/vim.hlp" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003864 char_u *dst; /* where to put the result */
3865 int dstlen; /* maximum length of the result */
3866 int esc; /* escape spaces in expanded variables */
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003867 int one; /* "srcp" is one file name */
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003868 char_u *startstr; /* start again after this (can be NULL) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003869{
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003870 char_u *src;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003871 char_u *tail;
3872 int c;
3873 char_u *var;
3874 int copy_char;
3875 int mustfree; /* var was allocated, need to free it later */
3876 int at_start = TRUE; /* at start of a name */
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003877 int startstr_len = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003878
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003879 if (startstr != NULL)
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003880 startstr_len = (int)STRLEN(startstr);
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003881
3882 src = skipwhite(srcp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003883 --dstlen; /* leave one char space for "\," */
3884 while (*src && dstlen > 0)
3885 {
3886 copy_char = TRUE;
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003887 if ((*src == '$'
3888#ifdef VMS
3889 && at_start
3890#endif
3891 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003892#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3893 || *src == '%'
3894#endif
3895 || (*src == '~' && at_start))
3896 {
3897 mustfree = FALSE;
3898
3899 /*
3900 * The variable name is copied into dst temporarily, because it may
3901 * be a string in read-only memory and a NUL needs to be appended.
3902 */
3903 if (*src != '~') /* environment var */
3904 {
3905 tail = src + 1;
3906 var = dst;
3907 c = dstlen - 1;
3908
3909#ifdef UNIX
3910 /* Unix has ${var-name} type environment vars */
3911 if (*tail == '{' && !vim_isIDc('{'))
3912 {
3913 tail++; /* ignore '{' */
3914 while (c-- > 0 && *tail && *tail != '}')
3915 *var++ = *tail++;
3916 }
3917 else
3918#endif
3919 {
3920 while (c-- > 0 && *tail != NUL && ((vim_isIDc(*tail))
3921#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3922 || (*src == '%' && *tail != '%')
3923#endif
3924 ))
3925 {
3926#ifdef OS2 /* env vars only in uppercase */
3927 *var++ = TOUPPER_LOC(*tail);
3928 tail++; /* toupper() may be a macro! */
3929#else
3930 *var++ = *tail++;
3931#endif
3932 }
3933 }
3934
3935#if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
3936# ifdef UNIX
3937 if (src[1] == '{' && *tail != '}')
3938# else
3939 if (*src == '%' && *tail != '%')
3940# endif
3941 var = NULL;
3942 else
3943 {
3944# ifdef UNIX
3945 if (src[1] == '{')
3946# else
3947 if (*src == '%')
3948#endif
3949 ++tail;
3950#endif
3951 *var = NUL;
3952 var = vim_getenv(dst, &mustfree);
3953#if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
3954 }
3955#endif
3956 }
3957 /* home directory */
3958 else if ( src[1] == NUL
3959 || vim_ispathsep(src[1])
3960 || vim_strchr((char_u *)" ,\t\n", src[1]) != NULL)
3961 {
3962 var = homedir;
3963 tail = src + 1;
3964 }
3965 else /* user directory */
3966 {
3967#if defined(UNIX) || (defined(VMS) && defined(USER_HOME))
3968 /*
3969 * Copy ~user to dst[], so we can put a NUL after it.
3970 */
3971 tail = src;
3972 var = dst;
3973 c = dstlen - 1;
3974 while ( c-- > 0
3975 && *tail
3976 && vim_isfilec(*tail)
3977 && !vim_ispathsep(*tail))
3978 *var++ = *tail++;
3979 *var = NUL;
3980# ifdef UNIX
3981 /*
3982 * If the system supports getpwnam(), use it.
3983 * Otherwise, or if getpwnam() fails, the shell is used to
3984 * expand ~user. This is slower and may fail if the shell
3985 * does not support ~user (old versions of /bin/sh).
3986 */
3987# if defined(HAVE_GETPWNAM) && defined(HAVE_PWD_H)
3988 {
3989 struct passwd *pw;
3990
Bram Moolenaara40ceaf2006-01-13 22:35:40 +00003991 /* Note: memory allocated by getpwnam() is never freed.
3992 * Calling endpwent() apparently doesn't help. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003993 pw = getpwnam((char *)dst + 1);
3994 if (pw != NULL)
3995 var = (char_u *)pw->pw_dir;
3996 else
3997 var = NULL;
3998 }
3999 if (var == NULL)
4000# endif
4001 {
4002 expand_T xpc;
4003
4004 ExpandInit(&xpc);
4005 xpc.xp_context = EXPAND_FILES;
4006 var = ExpandOne(&xpc, dst, NULL,
4007 WILD_ADD_SLASH|WILD_SILENT, WILD_EXPAND_FREE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004008 mustfree = TRUE;
4009 }
4010
4011# else /* !UNIX, thus VMS */
4012 /*
4013 * USER_HOME is a comma-separated list of
4014 * directories to search for the user account in.
4015 */
4016 {
4017 char_u test[MAXPATHL], paths[MAXPATHL];
4018 char_u *path, *next_path, *ptr;
4019 struct stat st;
4020
4021 STRCPY(paths, USER_HOME);
4022 next_path = paths;
4023 while (*next_path)
4024 {
4025 for (path = next_path; *next_path && *next_path != ',';
4026 next_path++);
4027 if (*next_path)
4028 *next_path++ = NUL;
4029 STRCPY(test, path);
4030 STRCAT(test, "/");
4031 STRCAT(test, dst + 1);
4032 if (mch_stat(test, &st) == 0)
4033 {
4034 var = alloc(STRLEN(test) + 1);
4035 STRCPY(var, test);
4036 mustfree = TRUE;
4037 break;
4038 }
4039 }
4040 }
4041# endif /* UNIX */
4042#else
4043 /* cannot expand user's home directory, so don't try */
4044 var = NULL;
4045 tail = (char_u *)""; /* for gcc */
4046#endif /* UNIX || VMS */
4047 }
4048
4049#ifdef BACKSLASH_IN_FILENAME
4050 /* If 'shellslash' is set change backslashes to forward slashes.
4051 * Can't use slash_adjust(), p_ssl may be set temporarily. */
4052 if (p_ssl && var != NULL && vim_strchr(var, '\\') != NULL)
4053 {
4054 char_u *p = vim_strsave(var);
4055
4056 if (p != NULL)
4057 {
4058 if (mustfree)
4059 vim_free(var);
4060 var = p;
4061 mustfree = TRUE;
4062 forward_slash(var);
4063 }
4064 }
4065#endif
4066
4067 /* If "var" contains white space, escape it with a backslash.
4068 * Required for ":e ~/tt" when $HOME includes a space. */
4069 if (esc && var != NULL && vim_strpbrk(var, (char_u *)" \t") != NULL)
4070 {
4071 char_u *p = vim_strsave_escaped(var, (char_u *)" \t");
4072
4073 if (p != NULL)
4074 {
4075 if (mustfree)
4076 vim_free(var);
4077 var = p;
4078 mustfree = TRUE;
4079 }
4080 }
4081
4082 if (var != NULL && *var != NUL
4083 && (STRLEN(var) + STRLEN(tail) + 1 < (unsigned)dstlen))
4084 {
4085 STRCPY(dst, var);
4086 dstlen -= (int)STRLEN(var);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004087 c = (int)STRLEN(var);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004088 /* if var[] ends in a path separator and tail[] starts
4089 * with it, skip a character */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004090 if (*var != NUL && after_pathsep(dst, dst + c)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004091#if defined(BACKSLASH_IN_FILENAME) || defined(AMIGA)
4092 && dst[-1] != ':'
4093#endif
4094 && vim_ispathsep(*tail))
4095 ++tail;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004096 dst += c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004097 src = tail;
4098 copy_char = FALSE;
4099 }
4100 if (mustfree)
4101 vim_free(var);
4102 }
4103
4104 if (copy_char) /* copy at least one char */
4105 {
4106 /*
Bram Moolenaar25394022007-05-10 19:06:20 +00004107 * Recognize the start of a new name, for '~'.
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00004108 * Don't do this when "one" is TRUE, to avoid expanding "~" in
4109 * ":edit foo ~ foo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00004110 */
4111 at_start = FALSE;
4112 if (src[0] == '\\' && src[1] != NUL)
4113 {
4114 *dst++ = *src++;
4115 --dstlen;
4116 }
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00004117 else if ((src[0] == ' ' || src[0] == ',') && !one)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004118 at_start = TRUE;
4119 *dst++ = *src++;
4120 --dstlen;
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00004121
4122 if (startstr != NULL && src - startstr_len >= srcp
4123 && STRNCMP(src - startstr_len, startstr, startstr_len) == 0)
4124 at_start = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004125 }
4126 }
4127 *dst = NUL;
4128}
4129
4130/*
4131 * Vim's version of getenv().
4132 * Special handling of $HOME, $VIM and $VIMRUNTIME.
Bram Moolenaar2f6b0b82005-03-08 22:43:10 +00004133 * Also does ACP to 'enc' conversion for Win32.
Bram Moolenaarb453a532011-04-28 17:48:44 +02004134 * "mustfree" is set to TRUE when returned is allocated, it must be
4135 * initialized to FALSE by the caller.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004136 */
4137 char_u *
4138vim_getenv(name, mustfree)
4139 char_u *name;
Bram Moolenaarb453a532011-04-28 17:48:44 +02004140 int *mustfree;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004141{
4142 char_u *p;
4143 char_u *pend;
4144 int vimruntime;
4145
4146#if defined(OS2) || defined(MSDOS) || defined(MSWIN)
4147 /* use "C:/" when $HOME is not set */
4148 if (STRCMP(name, "HOME") == 0)
4149 return homedir;
4150#endif
4151
4152 p = mch_getenv(name);
4153 if (p != NULL && *p == NUL) /* empty is the same as not set */
4154 p = NULL;
4155
4156 if (p != NULL)
Bram Moolenaar05159a02005-02-26 23:04:13 +00004157 {
4158#if defined(FEAT_MBYTE) && defined(WIN3264)
4159 if (enc_utf8)
4160 {
4161 int len;
Bram Moolenaarb453a532011-04-28 17:48:44 +02004162 char_u *pp = NULL;
Bram Moolenaar05159a02005-02-26 23:04:13 +00004163
4164 /* Convert from active codepage to UTF-8. Other conversions are
4165 * not done, because they would fail for non-ASCII characters. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004166 acp_to_enc(p, (int)STRLEN(p), &pp, &len);
Bram Moolenaar05159a02005-02-26 23:04:13 +00004167 if (pp != NULL)
4168 {
4169 p = pp;
4170 *mustfree = TRUE;
4171 }
4172 }
4173#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004174 return p;
Bram Moolenaar05159a02005-02-26 23:04:13 +00004175 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004176
4177 vimruntime = (STRCMP(name, "VIMRUNTIME") == 0);
4178 if (!vimruntime && STRCMP(name, "VIM") != 0)
4179 return NULL;
4180
4181 /*
4182 * When expanding $VIMRUNTIME fails, try using $VIM/vim<version> or $VIM.
4183 * Don't do this when default_vimruntime_dir is non-empty.
4184 */
4185 if (vimruntime
4186#ifdef HAVE_PATHDEF
4187 && *default_vimruntime_dir == NUL
4188#endif
4189 )
4190 {
4191 p = mch_getenv((char_u *)"VIM");
4192 if (p != NULL && *p == NUL) /* empty is the same as not set */
4193 p = NULL;
4194 if (p != NULL)
4195 {
4196 p = vim_version_dir(p);
4197 if (p != NULL)
4198 *mustfree = TRUE;
4199 else
4200 p = mch_getenv((char_u *)"VIM");
Bram Moolenaar05159a02005-02-26 23:04:13 +00004201
4202#if defined(FEAT_MBYTE) && defined(WIN3264)
4203 if (enc_utf8)
4204 {
4205 int len;
Bram Moolenaarb453a532011-04-28 17:48:44 +02004206 char_u *pp = NULL;
Bram Moolenaar05159a02005-02-26 23:04:13 +00004207
4208 /* Convert from active codepage to UTF-8. Other conversions
4209 * are not done, because they would fail for non-ASCII
4210 * characters. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004211 acp_to_enc(p, (int)STRLEN(p), &pp, &len);
Bram Moolenaar05159a02005-02-26 23:04:13 +00004212 if (pp != NULL)
4213 {
Bram Moolenaarb453a532011-04-28 17:48:44 +02004214 if (*mustfree)
Bram Moolenaar05159a02005-02-26 23:04:13 +00004215 vim_free(p);
4216 p = pp;
4217 *mustfree = TRUE;
4218 }
4219 }
4220#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004221 }
4222 }
4223
4224 /*
4225 * When expanding $VIM or $VIMRUNTIME fails, try using:
4226 * - the directory name from 'helpfile' (unless it contains '$')
4227 * - the executable name from argv[0]
4228 */
4229 if (p == NULL)
4230 {
4231 if (p_hf != NULL && vim_strchr(p_hf, '$') == NULL)
4232 p = p_hf;
4233#ifdef USE_EXE_NAME
4234 /*
4235 * Use the name of the executable, obtained from argv[0].
4236 */
4237 else
4238 p = exe_name;
4239#endif
4240 if (p != NULL)
4241 {
4242 /* remove the file name */
4243 pend = gettail(p);
4244
4245 /* remove "doc/" from 'helpfile', if present */
4246 if (p == p_hf)
4247 pend = remove_tail(p, pend, (char_u *)"doc");
4248
4249#ifdef USE_EXE_NAME
4250# ifdef MACOS_X
Bram Moolenaar95e9b492006-03-15 23:04:43 +00004251 /* remove "MacOS" from exe_name and add "Resources/vim" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004252 if (p == exe_name)
4253 {
4254 char_u *pend1;
Bram Moolenaar95e9b492006-03-15 23:04:43 +00004255 char_u *pnew;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004256
Bram Moolenaar95e9b492006-03-15 23:04:43 +00004257 pend1 = remove_tail(p, pend, (char_u *)"MacOS");
4258 if (pend1 != pend)
4259 {
4260 pnew = alloc((unsigned)(pend1 - p) + 15);
4261 if (pnew != NULL)
4262 {
4263 STRNCPY(pnew, p, (pend1 - p));
4264 STRCPY(pnew + (pend1 - p), "Resources/vim");
4265 p = pnew;
4266 pend = p + STRLEN(p);
4267 }
4268 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004269 }
4270# endif
4271 /* remove "src/" from exe_name, if present */
4272 if (p == exe_name)
4273 pend = remove_tail(p, pend, (char_u *)"src");
4274#endif
4275
4276 /* for $VIM, remove "runtime/" or "vim54/", if present */
4277 if (!vimruntime)
4278 {
4279 pend = remove_tail(p, pend, (char_u *)RUNTIME_DIRNAME);
4280 pend = remove_tail(p, pend, (char_u *)VIM_VERSION_NODOT);
4281 }
4282
4283 /* remove trailing path separator */
4284#ifndef MACOS_CLASSIC
4285 /* With MacOS path (with colons) the final colon is required */
Bram Moolenaare21877a2008-02-13 09:58:14 +00004286 /* to avoid confusion between absolute and relative path */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004287 if (pend > p && after_pathsep(p, pend))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004288 --pend;
4289#endif
4290
Bram Moolenaar95e9b492006-03-15 23:04:43 +00004291#ifdef MACOS_X
4292 if (p == exe_name || p == p_hf)
4293#endif
4294 /* check that the result is a directory name */
4295 p = vim_strnsave(p, (int)(pend - p));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004296
4297 if (p != NULL && !mch_isdir(p))
4298 {
4299 vim_free(p);
4300 p = NULL;
4301 }
4302 else
4303 {
4304#ifdef USE_EXE_NAME
4305 /* may add "/vim54" or "/runtime" if it exists */
4306 if (vimruntime && (pend = vim_version_dir(p)) != NULL)
4307 {
4308 vim_free(p);
4309 p = pend;
4310 }
4311#endif
4312 *mustfree = TRUE;
4313 }
4314 }
4315 }
4316
4317#ifdef HAVE_PATHDEF
4318 /* When there is a pathdef.c file we can use default_vim_dir and
4319 * default_vimruntime_dir */
4320 if (p == NULL)
4321 {
4322 /* Only use default_vimruntime_dir when it is not empty */
4323 if (vimruntime && *default_vimruntime_dir != NUL)
4324 {
4325 p = default_vimruntime_dir;
4326 *mustfree = FALSE;
4327 }
4328 else if (*default_vim_dir != NUL)
4329 {
4330 if (vimruntime && (p = vim_version_dir(default_vim_dir)) != NULL)
4331 *mustfree = TRUE;
4332 else
4333 {
4334 p = default_vim_dir;
4335 *mustfree = FALSE;
4336 }
4337 }
4338 }
4339#endif
4340
4341 /*
4342 * Set the environment variable, so that the new value can be found fast
4343 * next time, and others can also use it (e.g. Perl).
4344 */
4345 if (p != NULL)
4346 {
4347 if (vimruntime)
4348 {
4349 vim_setenv((char_u *)"VIMRUNTIME", p);
4350 didset_vimruntime = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004351 }
4352 else
4353 {
4354 vim_setenv((char_u *)"VIM", p);
4355 didset_vim = TRUE;
4356 }
4357 }
4358 return p;
4359}
4360
4361/*
4362 * Check if the directory "vimdir/<version>" or "vimdir/runtime" exists.
4363 * Return NULL if not, return its name in allocated memory otherwise.
4364 */
4365 static char_u *
4366vim_version_dir(vimdir)
4367 char_u *vimdir;
4368{
4369 char_u *p;
4370
4371 if (vimdir == NULL || *vimdir == NUL)
4372 return NULL;
4373 p = concat_fnames(vimdir, (char_u *)VIM_VERSION_NODOT, TRUE);
4374 if (p != NULL && mch_isdir(p))
4375 return p;
4376 vim_free(p);
4377 p = concat_fnames(vimdir, (char_u *)RUNTIME_DIRNAME, TRUE);
4378 if (p != NULL && mch_isdir(p))
4379 return p;
4380 vim_free(p);
4381 return NULL;
4382}
4383
4384/*
4385 * If the string between "p" and "pend" ends in "name/", return "pend" minus
4386 * the length of "name/". Otherwise return "pend".
4387 */
4388 static char_u *
4389remove_tail(p, pend, name)
4390 char_u *p;
4391 char_u *pend;
4392 char_u *name;
4393{
4394 int len = (int)STRLEN(name) + 1;
4395 char_u *newend = pend - len;
4396
4397 if (newend >= p
4398 && fnamencmp(newend, name, len - 1) == 0
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004399 && (newend == p || after_pathsep(p, newend)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004400 return newend;
4401 return pend;
4402}
4403
Bram Moolenaar071d4272004-06-13 20:20:40 +00004404/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004405 * Our portable version of setenv.
4406 */
4407 void
4408vim_setenv(name, val)
4409 char_u *name;
4410 char_u *val;
4411{
4412#ifdef HAVE_SETENV
4413 mch_setenv((char *)name, (char *)val, 1);
4414#else
4415 char_u *envbuf;
4416
4417 /*
4418 * Putenv does not copy the string, it has to remain
4419 * valid. The allocated memory will never be freed.
4420 */
4421 envbuf = alloc((unsigned)(STRLEN(name) + STRLEN(val) + 2));
4422 if (envbuf != NULL)
4423 {
4424 sprintf((char *)envbuf, "%s=%s", name, val);
4425 putenv((char *)envbuf);
4426 }
4427#endif
Bram Moolenaar011a34d2012-02-29 13:49:09 +01004428#ifdef FEAT_GETTEXT
4429 /*
4430 * When setting $VIMRUNTIME adjust the directory to find message
4431 * translations to $VIMRUNTIME/lang.
4432 */
4433 if (*val != NUL && STRICMP(name, "VIMRUNTIME") == 0)
4434 {
4435 char_u *buf = concat_str(val, (char_u *)"/lang");
4436
4437 if (buf != NULL)
4438 {
4439 bindtextdomain(VIMPACKAGE, (char *)buf);
4440 vim_free(buf);
4441 }
4442 }
4443#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004444}
4445
4446#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
4447/*
4448 * Function given to ExpandGeneric() to obtain an environment variable name.
4449 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004450 char_u *
4451get_env_name(xp, idx)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00004452 expand_T *xp UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004453 int idx;
4454{
4455# if defined(AMIGA) || defined(__MRC__) || defined(__SC__)
4456 /*
4457 * No environ[] on the Amiga and on the Mac (using MPW).
4458 */
4459 return NULL;
4460# else
4461# ifndef __WIN32__
4462 /* Borland C++ 5.2 has this in a header file. */
4463 extern char **environ;
4464# endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00004465# define ENVNAMELEN 100
4466 static char_u name[ENVNAMELEN];
Bram Moolenaar071d4272004-06-13 20:20:40 +00004467 char_u *str;
4468 int n;
4469
4470 str = (char_u *)environ[idx];
4471 if (str == NULL)
4472 return NULL;
4473
Bram Moolenaar21cf8232004-07-16 20:18:37 +00004474 for (n = 0; n < ENVNAMELEN - 1; ++n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004475 {
4476 if (str[n] == '=' || str[n] == NUL)
4477 break;
4478 name[n] = str[n];
4479 }
4480 name[n] = NUL;
4481 return name;
4482# endif
4483}
4484#endif
4485
4486/*
4487 * Replace home directory by "~" in each space or comma separated file name in
4488 * 'src'.
4489 * If anything fails (except when out of space) dst equals src.
4490 */
4491 void
4492home_replace(buf, src, dst, dstlen, one)
4493 buf_T *buf; /* when not NULL, check for help files */
4494 char_u *src; /* input file name */
4495 char_u *dst; /* where to put the result */
4496 int dstlen; /* maximum length of the result */
4497 int one; /* if TRUE, only replace one file name, include
4498 spaces and commas in the file name. */
4499{
4500 size_t dirlen = 0, envlen = 0;
4501 size_t len;
Bram Moolenaar9158f9e2012-06-20 14:02:27 +02004502 char_u *homedir_env, *homedir_env_orig;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004503 char_u *p;
4504
4505 if (src == NULL)
4506 {
4507 *dst = NUL;
4508 return;
4509 }
4510
4511 /*
4512 * If the file is a help file, remove the path completely.
4513 */
4514 if (buf != NULL && buf->b_help)
4515 {
4516 STRCPY(dst, gettail(src));
4517 return;
4518 }
4519
4520 /*
4521 * We check both the value of the $HOME environment variable and the
4522 * "real" home directory.
4523 */
4524 if (homedir != NULL)
4525 dirlen = STRLEN(homedir);
4526
4527#ifdef VMS
Bram Moolenaar9158f9e2012-06-20 14:02:27 +02004528 homedir_env_orig = homedir_env = mch_getenv((char_u *)"SYS$LOGIN");
Bram Moolenaar071d4272004-06-13 20:20:40 +00004529#else
Bram Moolenaar9158f9e2012-06-20 14:02:27 +02004530 homedir_env_orig = homedir_env = mch_getenv((char_u *)"HOME");
4531#endif
4532#if defined(FEAT_MODIFY_FNAME) || defined(WIN3264)
4533 if (vim_strchr(homedir_env, '~') != NULL)
4534 {
4535 int usedlen = 0;
4536 int flen;
4537 char_u *fbuf = NULL;
4538
4539 flen = (int)STRLEN(homedir_env);
4540 (void)modify_fname(":p", &usedlen, &homedir_env, &fbuf, &flen);
4541 flen = (int)STRLEN(homedir_env);
4542 if (flen > 0 && vim_ispathsep(homedir_env[flen - 1]))
4543 /* Remove the trailing / that is added to a directory. */
4544 homedir_env[flen - 1] = NUL;
4545 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004546#endif
4547
4548 if (homedir_env != NULL && *homedir_env == NUL)
4549 homedir_env = NULL;
4550 if (homedir_env != NULL)
4551 envlen = STRLEN(homedir_env);
4552
4553 if (!one)
4554 src = skipwhite(src);
4555 while (*src && dstlen > 0)
4556 {
4557 /*
4558 * Here we are at the beginning of a file name.
4559 * First, check to see if the beginning of the file name matches
4560 * $HOME or the "real" home directory. Check that there is a '/'
4561 * after the match (so that if e.g. the file is "/home/pieter/bla",
4562 * and the home directory is "/home/piet", the file does not end up
4563 * as "~er/bla" (which would seem to indicate the file "bla" in user
4564 * er's home directory)).
4565 */
4566 p = homedir;
4567 len = dirlen;
4568 for (;;)
4569 {
4570 if ( len
4571 && fnamencmp(src, p, len) == 0
4572 && (vim_ispathsep(src[len])
4573 || (!one && (src[len] == ',' || src[len] == ' '))
4574 || src[len] == NUL))
4575 {
4576 src += len;
4577 if (--dstlen > 0)
4578 *dst++ = '~';
4579
4580 /*
4581 * If it's just the home directory, add "/".
4582 */
4583 if (!vim_ispathsep(src[0]) && --dstlen > 0)
4584 *dst++ = '/';
4585 break;
4586 }
4587 if (p == homedir_env)
4588 break;
4589 p = homedir_env;
4590 len = envlen;
4591 }
4592
4593 /* if (!one) skip to separator: space or comma */
4594 while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
4595 *dst++ = *src++;
4596 /* skip separator */
4597 while ((*src == ' ' || *src == ',') && --dstlen > 0)
4598 *dst++ = *src++;
4599 }
4600 /* if (dstlen == 0) out of space, what to do??? */
4601
4602 *dst = NUL;
Bram Moolenaar9158f9e2012-06-20 14:02:27 +02004603
4604 if (homedir_env != homedir_env_orig)
4605 vim_free(homedir_env);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004606}
4607
4608/*
4609 * Like home_replace, store the replaced string in allocated memory.
4610 * When something fails, NULL is returned.
4611 */
4612 char_u *
4613home_replace_save(buf, src)
4614 buf_T *buf; /* when not NULL, check for help files */
4615 char_u *src; /* input file name */
4616{
4617 char_u *dst;
4618 unsigned len;
4619
4620 len = 3; /* space for "~/" and trailing NUL */
4621 if (src != NULL) /* just in case */
4622 len += (unsigned)STRLEN(src);
4623 dst = alloc(len);
4624 if (dst != NULL)
4625 home_replace(buf, src, dst, len, TRUE);
4626 return dst;
4627}
4628
4629/*
4630 * Compare two file names and return:
4631 * FPC_SAME if they both exist and are the same file.
4632 * FPC_SAMEX if they both don't exist and have the same file name.
4633 * FPC_DIFF if they both exist and are different files.
4634 * FPC_NOTX if they both don't exist.
4635 * FPC_DIFFX if one of them doesn't exist.
4636 * For the first name environment variables are expanded
4637 */
4638 int
4639fullpathcmp(s1, s2, checkname)
4640 char_u *s1, *s2;
4641 int checkname; /* when both don't exist, check file names */
4642{
4643#ifdef UNIX
4644 char_u exp1[MAXPATHL];
4645 char_u full1[MAXPATHL];
4646 char_u full2[MAXPATHL];
4647 struct stat st1, st2;
4648 int r1, r2;
4649
4650 expand_env(s1, exp1, MAXPATHL);
4651 r1 = mch_stat((char *)exp1, &st1);
4652 r2 = mch_stat((char *)s2, &st2);
4653 if (r1 != 0 && r2 != 0)
4654 {
4655 /* if mch_stat() doesn't work, may compare the names */
4656 if (checkname)
4657 {
4658 if (fnamecmp(exp1, s2) == 0)
4659 return FPC_SAMEX;
4660 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4661 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4662 if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
4663 return FPC_SAMEX;
4664 }
4665 return FPC_NOTX;
4666 }
4667 if (r1 != 0 || r2 != 0)
4668 return FPC_DIFFX;
4669 if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
4670 return FPC_SAME;
4671 return FPC_DIFF;
4672#else
4673 char_u *exp1; /* expanded s1 */
4674 char_u *full1; /* full path of s1 */
4675 char_u *full2; /* full path of s2 */
4676 int retval = FPC_DIFF;
4677 int r1, r2;
4678
4679 /* allocate one buffer to store three paths (alloc()/free() is slow!) */
4680 if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
4681 {
4682 full1 = exp1 + MAXPATHL;
4683 full2 = full1 + MAXPATHL;
4684
4685 expand_env(s1, exp1, MAXPATHL);
4686 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4687 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4688
4689 /* If vim_FullName() fails, the file probably doesn't exist. */
4690 if (r1 != OK && r2 != OK)
4691 {
4692 if (checkname && fnamecmp(exp1, s2) == 0)
4693 retval = FPC_SAMEX;
4694 else
4695 retval = FPC_NOTX;
4696 }
4697 else if (r1 != OK || r2 != OK)
4698 retval = FPC_DIFFX;
4699 else if (fnamecmp(full1, full2))
4700 retval = FPC_DIFF;
4701 else
4702 retval = FPC_SAME;
4703 vim_free(exp1);
4704 }
4705 return retval;
4706#endif
4707}
4708
4709/*
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004710 * Get the tail of a path: the file name.
Bram Moolenaar31710262010-08-13 13:36:15 +02004711 * When the path ends in a path separator the tail is the NUL after it.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004712 * Fail safe: never returns NULL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004713 */
4714 char_u *
4715gettail(fname)
4716 char_u *fname;
4717{
4718 char_u *p1, *p2;
4719
4720 if (fname == NULL)
4721 return (char_u *)"";
4722 for (p1 = p2 = fname; *p2; ) /* find last part of path */
4723 {
4724 if (vim_ispathsep(*p2))
4725 p1 = p2 + 1;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004726 mb_ptr_adv(p2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004727 }
4728 return p1;
4729}
4730
Bram Moolenaar31710262010-08-13 13:36:15 +02004731#if defined(FEAT_SEARCHPATH)
4732static char_u *gettail_dir __ARGS((char_u *fname));
4733
4734/*
4735 * Return the end of the directory name, on the first path
4736 * separator:
4737 * "/path/file", "/path/dir/", "/path//dir", "/file"
4738 * ^ ^ ^ ^
4739 */
4740 static char_u *
4741gettail_dir(fname)
4742 char_u *fname;
4743{
4744 char_u *dir_end = fname;
4745 char_u *next_dir_end = fname;
4746 int look_for_sep = TRUE;
4747 char_u *p;
4748
4749 for (p = fname; *p != NUL; )
4750 {
4751 if (vim_ispathsep(*p))
4752 {
4753 if (look_for_sep)
4754 {
4755 next_dir_end = p;
4756 look_for_sep = FALSE;
4757 }
4758 }
4759 else
4760 {
4761 if (!look_for_sep)
4762 dir_end = next_dir_end;
4763 look_for_sep = TRUE;
4764 }
4765 mb_ptr_adv(p);
4766 }
4767 return dir_end;
4768}
4769#endif
4770
Bram Moolenaar071d4272004-06-13 20:20:40 +00004771/*
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004772 * Get pointer to tail of "fname", including path separators. Putting a NUL
4773 * here leaves the directory name. Takes care of "c:/" and "//".
4774 * Always returns a valid pointer.
4775 */
4776 char_u *
4777gettail_sep(fname)
4778 char_u *fname;
4779{
4780 char_u *p;
4781 char_u *t;
4782
4783 p = get_past_head(fname); /* don't remove the '/' from "c:/file" */
4784 t = gettail(fname);
4785 while (t > p && after_pathsep(fname, t))
4786 --t;
4787#ifdef VMS
4788 /* path separator is part of the path */
4789 ++t;
4790#endif
4791 return t;
4792}
4793
4794/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004795 * get the next path component (just after the next path separator).
4796 */
4797 char_u *
4798getnextcomp(fname)
4799 char_u *fname;
4800{
4801 while (*fname && !vim_ispathsep(*fname))
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004802 mb_ptr_adv(fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004803 if (*fname)
4804 ++fname;
4805 return fname;
4806}
4807
Bram Moolenaar071d4272004-06-13 20:20:40 +00004808/*
4809 * Get a pointer to one character past the head of a path name.
4810 * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
4811 * If there is no head, path is returned.
4812 */
4813 char_u *
4814get_past_head(path)
4815 char_u *path;
4816{
4817 char_u *retval;
4818
4819#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
4820 /* may skip "c:" */
4821 if (isalpha(path[0]) && path[1] == ':')
4822 retval = path + 2;
4823 else
4824 retval = path;
4825#else
4826# if defined(AMIGA)
4827 /* may skip "label:" */
4828 retval = vim_strchr(path, ':');
4829 if (retval == NULL)
4830 retval = path;
4831# else /* Unix */
4832 retval = path;
4833# endif
4834#endif
4835
4836 while (vim_ispathsep(*retval))
4837 ++retval;
4838
4839 return retval;
4840}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004841
4842/*
4843 * return TRUE if 'c' is a path separator.
4844 */
4845 int
4846vim_ispathsep(c)
4847 int c;
4848{
Bram Moolenaare60acc12011-05-10 16:41:25 +02004849#ifdef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00004850 return (c == '/'); /* UNIX has ':' inside file names */
Bram Moolenaare60acc12011-05-10 16:41:25 +02004851#else
4852# ifdef BACKSLASH_IN_FILENAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00004853 return (c == ':' || c == '/' || c == '\\');
Bram Moolenaare60acc12011-05-10 16:41:25 +02004854# else
4855# ifdef VMS
Bram Moolenaar071d4272004-06-13 20:20:40 +00004856 /* server"user passwd"::device:[full.path.name]fname.extension;version" */
4857 return (c == ':' || c == '[' || c == ']' || c == '/'
4858 || c == '<' || c == '>' || c == '"' );
Bram Moolenaare60acc12011-05-10 16:41:25 +02004859# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004860 return (c == ':' || c == '/');
Bram Moolenaare60acc12011-05-10 16:41:25 +02004861# endif /* VMS */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004862# endif
Bram Moolenaare60acc12011-05-10 16:41:25 +02004863#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004864}
4865
4866#if defined(FEAT_SEARCHPATH) || defined(PROTO)
4867/*
4868 * return TRUE if 'c' is a path list separator.
4869 */
4870 int
4871vim_ispathlistsep(c)
4872 int c;
4873{
4874#ifdef UNIX
4875 return (c == ':');
4876#else
Bram Moolenaar25394022007-05-10 19:06:20 +00004877 return (c == ';'); /* might not be right for every system... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004878#endif
4879}
4880#endif
4881
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004882#if defined(FEAT_GUI_TABLINE) || defined(FEAT_WINDOWS) \
4883 || defined(FEAT_EVAL) || defined(PROTO)
4884/*
4885 * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
4886 * It's done in-place.
4887 */
4888 void
4889shorten_dir(str)
4890 char_u *str;
4891{
4892 char_u *tail, *s, *d;
4893 int skip = FALSE;
4894
4895 tail = gettail(str);
4896 d = str;
4897 for (s = str; ; ++s)
4898 {
4899 if (s >= tail) /* copy the whole tail */
4900 {
4901 *d++ = *s;
4902 if (*s == NUL)
4903 break;
4904 }
4905 else if (vim_ispathsep(*s)) /* copy '/' and next char */
4906 {
4907 *d++ = *s;
4908 skip = FALSE;
4909 }
4910 else if (!skip)
4911 {
4912 *d++ = *s; /* copy next char */
4913 if (*s != '~' && *s != '.') /* and leading "~" and "." */
4914 skip = TRUE;
4915# ifdef FEAT_MBYTE
4916 if (has_mbyte)
4917 {
4918 int l = mb_ptr2len(s);
4919
4920 while (--l > 0)
Bram Moolenaarb6baca52006-08-15 20:24:14 +00004921 *d++ = *++s;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004922 }
4923# endif
4924 }
4925 }
4926}
4927#endif
4928
Bram Moolenaar900b4d72005-12-12 22:05:50 +00004929/*
4930 * Return TRUE if the directory of "fname" exists, FALSE otherwise.
4931 * Also returns TRUE if there is no directory name.
4932 * "fname" must be writable!.
4933 */
4934 int
4935dir_of_file_exists(fname)
4936 char_u *fname;
4937{
4938 char_u *p;
4939 int c;
4940 int retval;
4941
4942 p = gettail_sep(fname);
4943 if (p == fname)
4944 return TRUE;
4945 c = *p;
4946 *p = NUL;
4947 retval = mch_isdir(fname);
4948 *p = c;
4949 return retval;
4950}
4951
Bram Moolenaar071d4272004-06-13 20:20:40 +00004952#if (defined(CASE_INSENSITIVE_FILENAME) && defined(BACKSLASH_IN_FILENAME)) \
4953 || defined(PROTO)
4954/*
4955 * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally.
4956 */
4957 int
4958vim_fnamecmp(x, y)
4959 char_u *x, *y;
4960{
4961 return vim_fnamencmp(x, y, MAXPATHL);
4962}
4963
4964 int
4965vim_fnamencmp(x, y, len)
4966 char_u *x, *y;
4967 size_t len;
4968{
4969 while (len > 0 && *x && *y)
4970 {
4971 if (TOLOWER_LOC(*x) != TOLOWER_LOC(*y)
4972 && !(*x == '/' && *y == '\\')
4973 && !(*x == '\\' && *y == '/'))
4974 break;
4975 ++x;
4976 ++y;
4977 --len;
4978 }
4979 if (len == 0)
4980 return 0;
4981 return (*x - *y);
4982}
4983#endif
4984
4985/*
4986 * Concatenate file names fname1 and fname2 into allocated memory.
Bram Moolenaar25394022007-05-10 19:06:20 +00004987 * Only add a '/' or '\\' when 'sep' is TRUE and it is necessary.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004988 */
4989 char_u *
4990concat_fnames(fname1, fname2, sep)
4991 char_u *fname1;
4992 char_u *fname2;
4993 int sep;
4994{
4995 char_u *dest;
4996
4997 dest = alloc((unsigned)(STRLEN(fname1) + STRLEN(fname2) + 3));
4998 if (dest != NULL)
4999 {
5000 STRCPY(dest, fname1);
5001 if (sep)
5002 add_pathsep(dest);
5003 STRCAT(dest, fname2);
5004 }
5005 return dest;
5006}
5007
Bram Moolenaard6754642005-01-17 22:18:45 +00005008/*
5009 * Concatenate two strings and return the result in allocated memory.
5010 * Returns NULL when out of memory.
5011 */
5012 char_u *
5013concat_str(str1, str2)
5014 char_u *str1;
5015 char_u *str2;
5016{
5017 char_u *dest;
5018 size_t l = STRLEN(str1);
5019
5020 dest = alloc((unsigned)(l + STRLEN(str2) + 1L));
5021 if (dest != NULL)
5022 {
5023 STRCPY(dest, str1);
5024 STRCPY(dest + l, str2);
5025 }
5026 return dest;
5027}
Bram Moolenaard6754642005-01-17 22:18:45 +00005028
Bram Moolenaar071d4272004-06-13 20:20:40 +00005029/*
5030 * Add a path separator to a file name, unless it already ends in a path
5031 * separator.
5032 */
5033 void
5034add_pathsep(p)
5035 char_u *p;
5036{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005037 if (*p != NUL && !after_pathsep(p, p + STRLEN(p)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005038 STRCAT(p, PATHSEPSTR);
5039}
5040
5041/*
5042 * FullName_save - Make an allocated copy of a full file name.
5043 * Returns NULL when out of memory.
5044 */
5045 char_u *
5046FullName_save(fname, force)
5047 char_u *fname;
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +02005048 int force; /* force expansion, even when it already looks
5049 * like a full path name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005050{
5051 char_u *buf;
5052 char_u *new_fname = NULL;
5053
5054 if (fname == NULL)
5055 return NULL;
5056
5057 buf = alloc((unsigned)MAXPATHL);
5058 if (buf != NULL)
5059 {
5060 if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
5061 new_fname = vim_strsave(buf);
5062 else
5063 new_fname = vim_strsave(fname);
5064 vim_free(buf);
5065 }
5066 return new_fname;
5067}
5068
5069#if defined(FEAT_CINDENT) || defined(FEAT_SYN_HL)
5070
5071static char_u *skip_string __ARGS((char_u *p));
5072
5073/*
5074 * Find the start of a comment, not knowing if we are in a comment right now.
5075 * Search starts at w_cursor.lnum and goes backwards.
5076 */
5077 pos_T *
5078find_start_comment(ind_maxcomment) /* XXX */
5079 int ind_maxcomment;
5080{
5081 pos_T *pos;
5082 char_u *line;
5083 char_u *p;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005084 int cur_maxcomment = ind_maxcomment;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005085
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005086 for (;;)
5087 {
5088 pos = findmatchlimit(NULL, '*', FM_BACKWARD, cur_maxcomment);
5089 if (pos == NULL)
5090 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005091
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005092 /*
5093 * Check if the comment start we found is inside a string.
5094 * If it is then restrict the search to below this line and try again.
5095 */
5096 line = ml_get(pos->lnum);
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00005097 for (p = line; *p && (colnr_T)(p - line) < pos->col; ++p)
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005098 p = skip_string(p);
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00005099 if ((colnr_T)(p - line) <= pos->col)
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005100 break;
5101 cur_maxcomment = curwin->w_cursor.lnum - pos->lnum - 1;
5102 if (cur_maxcomment <= 0)
5103 {
5104 pos = NULL;
5105 break;
5106 }
5107 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005108 return pos;
5109}
5110
5111/*
5112 * Skip to the end of a "string" and a 'c' character.
5113 * If there is no string or character, return argument unmodified.
5114 */
5115 static char_u *
5116skip_string(p)
5117 char_u *p;
5118{
5119 int i;
5120
5121 /*
5122 * We loop, because strings may be concatenated: "date""time".
5123 */
5124 for ( ; ; ++p)
5125 {
5126 if (p[0] == '\'') /* 'c' or '\n' or '\000' */
5127 {
5128 if (!p[1]) /* ' at end of line */
5129 break;
5130 i = 2;
5131 if (p[1] == '\\') /* '\n' or '\000' */
5132 {
5133 ++i;
5134 while (vim_isdigit(p[i - 1])) /* '\000' */
5135 ++i;
5136 }
5137 if (p[i] == '\'') /* check for trailing ' */
5138 {
5139 p += i;
5140 continue;
5141 }
5142 }
5143 else if (p[0] == '"') /* start of string */
5144 {
5145 for (++p; p[0]; ++p)
5146 {
5147 if (p[0] == '\\' && p[1] != NUL)
5148 ++p;
5149 else if (p[0] == '"') /* end of string */
5150 break;
5151 }
5152 if (p[0] == '"')
5153 continue;
5154 }
5155 break; /* no string found */
5156 }
5157 if (!*p)
5158 --p; /* backup from NUL */
5159 return p;
5160}
5161#endif /* FEAT_CINDENT || FEAT_SYN_HL */
5162
5163#if defined(FEAT_CINDENT) || defined(PROTO)
5164
5165/*
5166 * Do C or expression indenting on the current line.
5167 */
5168 void
5169do_c_expr_indent()
5170{
5171# ifdef FEAT_EVAL
5172 if (*curbuf->b_p_inde != NUL)
5173 fixthisline(get_expr_indent);
5174 else
5175# endif
5176 fixthisline(get_c_indent);
5177}
5178
5179/*
5180 * Functions for C-indenting.
5181 * Most of this originally comes from Eric Fischer.
5182 */
5183/*
5184 * Below "XXX" means that this function may unlock the current line.
5185 */
5186
5187static char_u *cin_skipcomment __ARGS((char_u *));
5188static int cin_nocode __ARGS((char_u *));
5189static pos_T *find_line_comment __ARGS((void));
5190static int cin_islabel_skip __ARGS((char_u **));
5191static int cin_isdefault __ARGS((char_u *));
5192static char_u *after_label __ARGS((char_u *l));
5193static int get_indent_nolabel __ARGS((linenr_T lnum));
5194static int skip_label __ARGS((linenr_T, char_u **pp, int ind_maxcomment));
5195static int cin_first_id_amount __ARGS((void));
5196static int cin_get_equal_amount __ARGS((linenr_T lnum));
5197static int cin_ispreproc __ARGS((char_u *));
5198static int cin_ispreproc_cont __ARGS((char_u **pp, linenr_T *lnump));
5199static int cin_iscomment __ARGS((char_u *));
5200static int cin_islinecomment __ARGS((char_u *));
5201static int cin_isterminated __ARGS((char_u *, int, int));
5202static int cin_isinit __ARGS((void));
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005203static int cin_isfuncdecl __ARGS((char_u **, linenr_T, linenr_T, int, int));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005204static int cin_isif __ARGS((char_u *));
5205static int cin_iselse __ARGS((char_u *));
5206static int cin_isdo __ARGS((char_u *));
5207static int cin_iswhileofdo __ARGS((char_u *, linenr_T, int));
Bram Moolenaarb345d492012-04-09 20:42:26 +02005208static int cin_is_if_for_while_before_offset __ARGS((char_u *line, int *poffset));
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005209static int cin_iswhileofdo_end __ARGS((int terminated, int ind_maxparen, int ind_maxcomment));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005210static int cin_isbreak __ARGS((char_u *));
Bram Moolenaare7c56862007-08-04 10:14:52 +00005211static int cin_is_cpp_baseclass __ARGS((colnr_T *col));
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005212static int get_baseclass_amount __ARGS((int col, int ind_maxparen, int ind_maxcomment, int ind_cpp_baseclass));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005213static int cin_ends_in __ARGS((char_u *, char_u *, char_u *));
5214static int cin_skip2pos __ARGS((pos_T *trypos));
5215static pos_T *find_start_brace __ARGS((int));
5216static pos_T *find_match_paren __ARGS((int, int));
5217static int corr_ind_maxparen __ARGS((int ind_maxparen, pos_T *startpos));
5218static int find_last_paren __ARGS((char_u *l, int start, int end));
5219static int find_match __ARGS((int lookfor, linenr_T ourscope, int ind_maxparen, int ind_maxcomment));
Bram Moolenaared38b0a2011-05-25 15:16:18 +02005220static int cin_is_cpp_namespace __ARGS((char_u *));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005221
Bram Moolenaar39353fd2007-03-27 09:02:11 +00005222static int ind_hash_comment = 0; /* # starts a comment */
5223
Bram Moolenaar071d4272004-06-13 20:20:40 +00005224/*
5225 * Skip over white space and C comments within the line.
Bram Moolenaar39353fd2007-03-27 09:02:11 +00005226 * Also skip over Perl/shell comments if desired.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005227 */
5228 static char_u *
5229cin_skipcomment(s)
5230 char_u *s;
5231{
5232 while (*s)
5233 {
Bram Moolenaar39353fd2007-03-27 09:02:11 +00005234 char_u *prev_s = s;
5235
Bram Moolenaar071d4272004-06-13 20:20:40 +00005236 s = skipwhite(s);
Bram Moolenaar39353fd2007-03-27 09:02:11 +00005237
5238 /* Perl/shell # comment comment continues until eol. Require a space
5239 * before # to avoid recognizing $#array. */
5240 if (ind_hash_comment != 0 && s != prev_s && *s == '#')
5241 {
5242 s += STRLEN(s);
5243 break;
5244 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005245 if (*s != '/')
5246 break;
5247 ++s;
5248 if (*s == '/') /* slash-slash comment continues till eol */
5249 {
5250 s += STRLEN(s);
5251 break;
5252 }
5253 if (*s != '*')
5254 break;
5255 for (++s; *s; ++s) /* skip slash-star comment */
5256 if (s[0] == '*' && s[1] == '/')
5257 {
5258 s += 2;
5259 break;
5260 }
5261 }
5262 return s;
5263}
5264
5265/*
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005266 * Return TRUE if there is no code at *s. White space and comments are
Bram Moolenaar071d4272004-06-13 20:20:40 +00005267 * not considered code.
5268 */
5269 static int
5270cin_nocode(s)
5271 char_u *s;
5272{
5273 return *cin_skipcomment(s) == NUL;
5274}
5275
5276/*
5277 * Check previous lines for a "//" line comment, skipping over blank lines.
5278 */
5279 static pos_T *
5280find_line_comment() /* XXX */
5281{
5282 static pos_T pos;
5283 char_u *line;
5284 char_u *p;
5285
5286 pos = curwin->w_cursor;
5287 while (--pos.lnum > 0)
5288 {
5289 line = ml_get(pos.lnum);
5290 p = skipwhite(line);
5291 if (cin_islinecomment(p))
5292 {
5293 pos.col = (int)(p - line);
5294 return &pos;
5295 }
5296 if (*p != NUL)
5297 break;
5298 }
5299 return NULL;
5300}
5301
5302/*
5303 * Check if string matches "label:"; move to character after ':' if true.
5304 */
5305 static int
5306cin_islabel_skip(s)
5307 char_u **s;
5308{
5309 if (!vim_isIDc(**s)) /* need at least one ID character */
5310 return FALSE;
5311
5312 while (vim_isIDc(**s))
5313 (*s)++;
5314
5315 *s = cin_skipcomment(*s);
5316
5317 /* "::" is not a label, it's C++ */
5318 return (**s == ':' && *++*s != ':');
5319}
5320
5321/*
5322 * Recognize a label: "label:".
5323 * Note: curwin->w_cursor must be where we are looking for the label.
5324 */
5325 int
5326cin_islabel(ind_maxcomment) /* XXX */
5327 int ind_maxcomment;
5328{
5329 char_u *s;
5330
5331 s = cin_skipcomment(ml_get_curline());
5332
5333 /*
5334 * Exclude "default" from labels, since it should be indented
5335 * like a switch label. Same for C++ scope declarations.
5336 */
5337 if (cin_isdefault(s))
5338 return FALSE;
5339 if (cin_isscopedecl(s))
5340 return FALSE;
5341
5342 if (cin_islabel_skip(&s))
5343 {
5344 /*
5345 * Only accept a label if the previous line is terminated or is a case
5346 * label.
5347 */
5348 pos_T cursor_save;
5349 pos_T *trypos;
5350 char_u *line;
5351
5352 cursor_save = curwin->w_cursor;
5353 while (curwin->w_cursor.lnum > 1)
5354 {
5355 --curwin->w_cursor.lnum;
5356
5357 /*
5358 * If we're in a comment now, skip to the start of the comment.
5359 */
5360 curwin->w_cursor.col = 0;
5361 if ((trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
5362 curwin->w_cursor = *trypos;
5363
5364 line = ml_get_curline();
5365 if (cin_ispreproc(line)) /* ignore #defines, #if, etc. */
5366 continue;
5367 if (*(line = cin_skipcomment(line)) == NUL)
5368 continue;
5369
5370 curwin->w_cursor = cursor_save;
5371 if (cin_isterminated(line, TRUE, FALSE)
5372 || cin_isscopedecl(line)
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005373 || cin_iscase(line, TRUE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005374 || (cin_islabel_skip(&line) && cin_nocode(line)))
5375 return TRUE;
5376 return FALSE;
5377 }
5378 curwin->w_cursor = cursor_save;
5379 return TRUE; /* label at start of file??? */
5380 }
5381 return FALSE;
5382}
5383
5384/*
5385 * Recognize structure initialization and enumerations.
5386 * Q&D-Implementation:
5387 * check for "=" at end or "[typedef] enum" at beginning of line.
5388 */
5389 static int
5390cin_isinit(void)
5391{
5392 char_u *s;
5393
5394 s = cin_skipcomment(ml_get_curline());
5395
5396 if (STRNCMP(s, "typedef", 7) == 0 && !vim_isIDc(s[7]))
5397 s = cin_skipcomment(s + 7);
5398
Bram Moolenaara5285652011-12-14 20:05:21 +01005399 if (STRNCMP(s, "static", 6) == 0 && !vim_isIDc(s[6]))
5400 s = cin_skipcomment(s + 6);
5401
Bram Moolenaar071d4272004-06-13 20:20:40 +00005402 if (STRNCMP(s, "enum", 4) == 0 && !vim_isIDc(s[4]))
5403 return TRUE;
5404
5405 if (cin_ends_in(s, (char_u *)"=", (char_u *)"{"))
5406 return TRUE;
5407
5408 return FALSE;
5409}
5410
5411/*
5412 * Recognize a switch label: "case .*:" or "default:".
5413 */
5414 int
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005415cin_iscase(s, strict)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005416 char_u *s;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005417 int strict; /* Allow relaxed check of case statement for JS */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005418{
5419 s = cin_skipcomment(s);
5420 if (STRNCMP(s, "case", 4) == 0 && !vim_isIDc(s[4]))
5421 {
5422 for (s += 4; *s; ++s)
5423 {
5424 s = cin_skipcomment(s);
5425 if (*s == ':')
5426 {
5427 if (s[1] == ':') /* skip over "::" for C++ */
5428 ++s;
5429 else
5430 return TRUE;
5431 }
5432 if (*s == '\'' && s[1] && s[2] == '\'')
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005433 s += 2; /* skip over ':' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005434 else if (*s == '/' && (s[1] == '*' || s[1] == '/'))
5435 return FALSE; /* stop at comment */
5436 else if (*s == '"')
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005437 {
5438 /* JS etc. */
5439 if (strict)
5440 return FALSE; /* stop at string */
5441 else
5442 return TRUE;
5443 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005444 }
5445 return FALSE;
5446 }
5447
5448 if (cin_isdefault(s))
5449 return TRUE;
5450 return FALSE;
5451}
5452
5453/*
5454 * Recognize a "default" switch label.
5455 */
5456 static int
5457cin_isdefault(s)
5458 char_u *s;
5459{
5460 return (STRNCMP(s, "default", 7) == 0
5461 && *(s = cin_skipcomment(s + 7)) == ':'
5462 && s[1] != ':');
5463}
5464
5465/*
Bram Moolenaar1a509df2010-08-01 17:59:57 +02005466 * Recognize a "public/private/protected" scope declaration label.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005467 */
5468 int
5469cin_isscopedecl(s)
5470 char_u *s;
5471{
5472 int i;
5473
5474 s = cin_skipcomment(s);
5475 if (STRNCMP(s, "public", 6) == 0)
5476 i = 6;
5477 else if (STRNCMP(s, "protected", 9) == 0)
5478 i = 9;
5479 else if (STRNCMP(s, "private", 7) == 0)
5480 i = 7;
5481 else
5482 return FALSE;
5483 return (*(s = cin_skipcomment(s + i)) == ':' && s[1] != ':');
5484}
5485
Bram Moolenaared38b0a2011-05-25 15:16:18 +02005486/* Maximum number of lines to search back for a "namespace" line. */
5487#define FIND_NAMESPACE_LIM 20
5488
5489/*
5490 * Recognize a "namespace" scope declaration.
5491 */
5492 static int
5493cin_is_cpp_namespace(s)
5494 char_u *s;
5495{
5496 char_u *p;
5497 int has_name = FALSE;
5498
5499 s = cin_skipcomment(s);
5500 if (STRNCMP(s, "namespace", 9) == 0 && (s[9] == NUL || !vim_iswordc(s[9])))
5501 {
5502 p = cin_skipcomment(skipwhite(s + 9));
5503 while (*p != NUL)
5504 {
5505 if (vim_iswhite(*p))
5506 {
5507 has_name = TRUE; /* found end of a name */
5508 p = cin_skipcomment(skipwhite(p));
5509 }
5510 else if (*p == '{')
5511 {
5512 break;
5513 }
5514 else if (vim_iswordc(*p))
5515 {
5516 if (has_name)
5517 return FALSE; /* word character after skipping past name */
5518 ++p;
5519 }
5520 else
5521 {
5522 return FALSE;
5523 }
5524 }
5525 return TRUE;
5526 }
5527 return FALSE;
5528}
5529
Bram Moolenaar071d4272004-06-13 20:20:40 +00005530/*
5531 * Return a pointer to the first non-empty non-comment character after a ':'.
5532 * Return NULL if not found.
5533 * case 234: a = b;
5534 * ^
5535 */
5536 static char_u *
5537after_label(l)
5538 char_u *l;
5539{
5540 for ( ; *l; ++l)
5541 {
5542 if (*l == ':')
5543 {
5544 if (l[1] == ':') /* skip over "::" for C++ */
5545 ++l;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005546 else if (!cin_iscase(l + 1, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005547 break;
5548 }
5549 else if (*l == '\'' && l[1] && l[2] == '\'')
5550 l += 2; /* skip over 'x' */
5551 }
5552 if (*l == NUL)
5553 return NULL;
5554 l = cin_skipcomment(l + 1);
5555 if (*l == NUL)
5556 return NULL;
5557 return l;
5558}
5559
5560/*
5561 * Get indent of line "lnum", skipping a label.
5562 * Return 0 if there is nothing after the label.
5563 */
5564 static int
5565get_indent_nolabel(lnum) /* XXX */
5566 linenr_T lnum;
5567{
5568 char_u *l;
5569 pos_T fp;
5570 colnr_T col;
5571 char_u *p;
5572
5573 l = ml_get(lnum);
5574 p = after_label(l);
5575 if (p == NULL)
5576 return 0;
5577
5578 fp.col = (colnr_T)(p - l);
5579 fp.lnum = lnum;
5580 getvcol(curwin, &fp, &col, NULL, NULL);
5581 return (int)col;
5582}
5583
5584/*
5585 * Find indent for line "lnum", ignoring any case or jump label.
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005586 * Also return a pointer to the text (after the label) in "pp".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005587 * label: if (asdf && asdfasdf)
5588 * ^
5589 */
5590 static int
5591skip_label(lnum, pp, ind_maxcomment)
5592 linenr_T lnum;
5593 char_u **pp;
5594 int ind_maxcomment;
5595{
5596 char_u *l;
5597 int amount;
5598 pos_T cursor_save;
5599
5600 cursor_save = curwin->w_cursor;
5601 curwin->w_cursor.lnum = lnum;
5602 l = ml_get_curline();
5603 /* XXX */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005604 if (cin_iscase(l, FALSE) || cin_isscopedecl(l)
5605 || cin_islabel(ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005606 {
5607 amount = get_indent_nolabel(lnum);
5608 l = after_label(ml_get_curline());
5609 if (l == NULL) /* just in case */
5610 l = ml_get_curline();
5611 }
5612 else
5613 {
5614 amount = get_indent();
5615 l = ml_get_curline();
5616 }
5617 *pp = l;
5618
5619 curwin->w_cursor = cursor_save;
5620 return amount;
5621}
5622
5623/*
5624 * Return the indent of the first variable name after a type in a declaration.
5625 * int a, indent of "a"
5626 * static struct foo b, indent of "b"
5627 * enum bla c, indent of "c"
5628 * Returns zero when it doesn't look like a declaration.
5629 */
5630 static int
5631cin_first_id_amount()
5632{
5633 char_u *line, *p, *s;
5634 int len;
5635 pos_T fp;
5636 colnr_T col;
5637
5638 line = ml_get_curline();
5639 p = skipwhite(line);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005640 len = (int)(skiptowhite(p) - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005641 if (len == 6 && STRNCMP(p, "static", 6) == 0)
5642 {
5643 p = skipwhite(p + 6);
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00005644 len = (int)(skiptowhite(p) - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005645 }
5646 if (len == 6 && STRNCMP(p, "struct", 6) == 0)
5647 p = skipwhite(p + 6);
5648 else if (len == 4 && STRNCMP(p, "enum", 4) == 0)
5649 p = skipwhite(p + 4);
5650 else if ((len == 8 && STRNCMP(p, "unsigned", 8) == 0)
5651 || (len == 6 && STRNCMP(p, "signed", 6) == 0))
5652 {
5653 s = skipwhite(p + len);
5654 if ((STRNCMP(s, "int", 3) == 0 && vim_iswhite(s[3]))
5655 || (STRNCMP(s, "long", 4) == 0 && vim_iswhite(s[4]))
5656 || (STRNCMP(s, "short", 5) == 0 && vim_iswhite(s[5]))
5657 || (STRNCMP(s, "char", 4) == 0 && vim_iswhite(s[4])))
5658 p = s;
5659 }
5660 for (len = 0; vim_isIDc(p[len]); ++len)
5661 ;
5662 if (len == 0 || !vim_iswhite(p[len]) || cin_nocode(p))
5663 return 0;
5664
5665 p = skipwhite(p + len);
5666 fp.lnum = curwin->w_cursor.lnum;
5667 fp.col = (colnr_T)(p - line);
5668 getvcol(curwin, &fp, &col, NULL, NULL);
5669 return (int)col;
5670}
5671
5672/*
5673 * Return the indent of the first non-blank after an equal sign.
5674 * char *foo = "here";
5675 * Return zero if no (useful) equal sign found.
5676 * Return -1 if the line above "lnum" ends in a backslash.
5677 * foo = "asdf\
5678 * asdf\
5679 * here";
5680 */
5681 static int
5682cin_get_equal_amount(lnum)
5683 linenr_T lnum;
5684{
5685 char_u *line;
5686 char_u *s;
5687 colnr_T col;
5688 pos_T fp;
5689
5690 if (lnum > 1)
5691 {
5692 line = ml_get(lnum - 1);
5693 if (*line != NUL && line[STRLEN(line) - 1] == '\\')
5694 return -1;
5695 }
5696
5697 line = s = ml_get(lnum);
5698 while (*s != NUL && vim_strchr((char_u *)"=;{}\"'", *s) == NULL)
5699 {
5700 if (cin_iscomment(s)) /* ignore comments */
5701 s = cin_skipcomment(s);
5702 else
5703 ++s;
5704 }
5705 if (*s != '=')
5706 return 0;
5707
5708 s = skipwhite(s + 1);
5709 if (cin_nocode(s))
5710 return 0;
5711
5712 if (*s == '"') /* nice alignment for continued strings */
5713 ++s;
5714
5715 fp.lnum = lnum;
5716 fp.col = (colnr_T)(s - line);
5717 getvcol(curwin, &fp, &col, NULL, NULL);
5718 return (int)col;
5719}
5720
5721/*
5722 * Recognize a preprocessor statement: Any line that starts with '#'.
5723 */
5724 static int
5725cin_ispreproc(s)
5726 char_u *s;
5727{
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005728 if (*skipwhite(s) == '#')
Bram Moolenaar071d4272004-06-13 20:20:40 +00005729 return TRUE;
5730 return FALSE;
5731}
5732
5733/*
5734 * Return TRUE if line "*pp" at "*lnump" is a preprocessor statement or a
5735 * continuation line of a preprocessor statement. Decrease "*lnump" to the
5736 * start and return the line in "*pp".
5737 */
5738 static int
5739cin_ispreproc_cont(pp, lnump)
5740 char_u **pp;
5741 linenr_T *lnump;
5742{
5743 char_u *line = *pp;
5744 linenr_T lnum = *lnump;
5745 int retval = FALSE;
5746
Bram Moolenaard8e9bb22005-07-09 21:14:46 +00005747 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005748 {
5749 if (cin_ispreproc(line))
5750 {
5751 retval = TRUE;
5752 *lnump = lnum;
5753 break;
5754 }
5755 if (lnum == 1)
5756 break;
5757 line = ml_get(--lnum);
5758 if (*line == NUL || line[STRLEN(line) - 1] != '\\')
5759 break;
5760 }
5761
5762 if (lnum != *lnump)
5763 *pp = ml_get(*lnump);
5764 return retval;
5765}
5766
5767/*
5768 * Recognize the start of a C or C++ comment.
5769 */
5770 static int
5771cin_iscomment(p)
5772 char_u *p;
5773{
5774 return (p[0] == '/' && (p[1] == '*' || p[1] == '/'));
5775}
5776
5777/*
5778 * Recognize the start of a "//" comment.
5779 */
5780 static int
5781cin_islinecomment(p)
5782 char_u *p;
5783{
5784 return (p[0] == '/' && p[1] == '/');
5785}
5786
5787/*
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005788 * Recognize a line that starts with '{' or '}', or ends with ';', ',', '{' or
5789 * '}'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005790 * Don't consider "} else" a terminated line.
Bram Moolenaar496f9512011-05-19 16:35:09 +02005791 * If a line begins with an "else", only consider it terminated if no unmatched
5792 * opening braces follow (handle "else { foo();" correctly).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005793 * Return the character terminating the line (ending char's have precedence if
5794 * both apply in order to determine initializations).
5795 */
5796 static int
5797cin_isterminated(s, incl_open, incl_comma)
5798 char_u *s;
5799 int incl_open; /* include '{' at the end as terminator */
5800 int incl_comma; /* recognize a trailing comma */
5801{
Bram Moolenaar496f9512011-05-19 16:35:09 +02005802 char_u found_start = 0;
5803 unsigned n_open = 0;
5804 int is_else = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005805
5806 s = cin_skipcomment(s);
5807
5808 if (*s == '{' || (*s == '}' && !cin_iselse(s)))
5809 found_start = *s;
5810
Bram Moolenaar496f9512011-05-19 16:35:09 +02005811 if (!found_start)
5812 is_else = cin_iselse(s);
5813
Bram Moolenaar071d4272004-06-13 20:20:40 +00005814 while (*s)
5815 {
5816 /* skip over comments, "" strings and 'c'haracters */
5817 s = skip_string(cin_skipcomment(s));
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005818 if (*s == '}' && n_open > 0)
5819 --n_open;
Bram Moolenaar496f9512011-05-19 16:35:09 +02005820 if ((!is_else || n_open == 0)
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005821 && (*s == ';' || *s == '}' || (incl_comma && *s == ','))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005822 && cin_nocode(s + 1))
5823 return *s;
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005824 else if (*s == '{')
5825 {
5826 if (incl_open && cin_nocode(s + 1))
5827 return *s;
5828 else
5829 ++n_open;
5830 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005831
5832 if (*s)
5833 s++;
5834 }
5835 return found_start;
5836}
5837
5838/*
5839 * Recognize the basic picture of a function declaration -- it needs to
5840 * have an open paren somewhere and a close paren at the end of the line and
5841 * no semicolons anywhere.
5842 * When a line ends in a comma we continue looking in the next line.
5843 * "sp" points to a string with the line. When looking at other lines it must
5844 * be restored to the line. When it's NULL fetch lines here.
5845 * "lnum" is where we start looking.
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005846 * "min_lnum" is the line before which we will not be looking.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005847 */
5848 static int
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005849cin_isfuncdecl(sp, first_lnum, min_lnum, ind_maxparen, ind_maxcomment)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005850 char_u **sp;
5851 linenr_T first_lnum;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005852 linenr_T min_lnum;
5853 int ind_maxparen;
5854 int ind_maxcomment;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005855{
5856 char_u *s;
5857 linenr_T lnum = first_lnum;
5858 int retval = FALSE;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005859 pos_T *trypos;
5860 int just_started = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005861
5862 if (sp == NULL)
5863 s = ml_get(lnum);
5864 else
5865 s = *sp;
5866
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005867 if (find_last_paren(s, '(', ')')
5868 && (trypos = find_match_paren(ind_maxparen, ind_maxcomment)) != NULL)
5869 {
5870 lnum = trypos->lnum;
5871 if (lnum < min_lnum)
5872 return FALSE;
5873
5874 s = ml_get(lnum);
5875 }
5876
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005877 /* Ignore line starting with #. */
5878 if (cin_ispreproc(s))
5879 return FALSE;
5880
Bram Moolenaar071d4272004-06-13 20:20:40 +00005881 while (*s && *s != '(' && *s != ';' && *s != '\'' && *s != '"')
5882 {
5883 if (cin_iscomment(s)) /* ignore comments */
5884 s = cin_skipcomment(s);
5885 else
5886 ++s;
5887 }
5888 if (*s != '(')
5889 return FALSE; /* ';', ' or " before any () or no '(' */
5890
5891 while (*s && *s != ';' && *s != '\'' && *s != '"')
5892 {
5893 if (*s == ')' && cin_nocode(s + 1))
5894 {
5895 /* ')' at the end: may have found a match
5896 * Check for he previous line not to end in a backslash:
5897 * #if defined(x) && \
5898 * defined(y)
5899 */
5900 lnum = first_lnum - 1;
5901 s = ml_get(lnum);
5902 if (*s == NUL || s[STRLEN(s) - 1] != '\\')
5903 retval = TRUE;
5904 goto done;
5905 }
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005906 if ((*s == ',' && cin_nocode(s + 1)) || s[1] == NUL || cin_nocode(s))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005907 {
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005908 int comma = (*s == ',');
5909
5910 /* ',' at the end: continue looking in the next line.
5911 * At the end: check for ',' in the next line, for this style:
5912 * func(arg1
5913 * , arg2) */
5914 for (;;)
5915 {
5916 if (lnum >= curbuf->b_ml.ml_line_count)
5917 break;
5918 s = ml_get(++lnum);
5919 if (!cin_ispreproc(s))
5920 break;
5921 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005922 if (lnum >= curbuf->b_ml.ml_line_count)
5923 break;
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005924 /* Require a comma at end of the line or a comma or ')' at the
5925 * start of next line. */
5926 s = skipwhite(s);
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005927 if (!just_started && (!comma && *s != ',' && *s != ')'))
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005928 break;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005929 just_started = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005930 }
5931 else if (cin_iscomment(s)) /* ignore comments */
5932 s = cin_skipcomment(s);
5933 else
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005934 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005935 ++s;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005936 just_started = FALSE;
5937 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005938 }
5939
5940done:
5941 if (lnum != first_lnum && sp != NULL)
5942 *sp = ml_get(first_lnum);
5943
5944 return retval;
5945}
5946
5947 static int
5948cin_isif(p)
5949 char_u *p;
5950{
5951 return (STRNCMP(p, "if", 2) == 0 && !vim_isIDc(p[2]));
5952}
5953
5954 static int
5955cin_iselse(p)
5956 char_u *p;
5957{
5958 if (*p == '}') /* accept "} else" */
5959 p = cin_skipcomment(p + 1);
5960 return (STRNCMP(p, "else", 4) == 0 && !vim_isIDc(p[4]));
5961}
5962
5963 static int
5964cin_isdo(p)
5965 char_u *p;
5966{
5967 return (STRNCMP(p, "do", 2) == 0 && !vim_isIDc(p[2]));
5968}
5969
5970/*
5971 * Check if this is a "while" that should have a matching "do".
5972 * We only accept a "while (condition) ;", with only white space between the
5973 * ')' and ';'. The condition may be spread over several lines.
5974 */
5975 static int
5976cin_iswhileofdo(p, lnum, ind_maxparen) /* XXX */
5977 char_u *p;
5978 linenr_T lnum;
5979 int ind_maxparen;
5980{
5981 pos_T cursor_save;
5982 pos_T *trypos;
5983 int retval = FALSE;
5984
5985 p = cin_skipcomment(p);
5986 if (*p == '}') /* accept "} while (cond);" */
5987 p = cin_skipcomment(p + 1);
5988 if (STRNCMP(p, "while", 5) == 0 && !vim_isIDc(p[5]))
5989 {
5990 cursor_save = curwin->w_cursor;
5991 curwin->w_cursor.lnum = lnum;
5992 curwin->w_cursor.col = 0;
5993 p = ml_get_curline();
5994 while (*p && *p != 'w') /* skip any '}', until the 'w' of the "while" */
5995 {
5996 ++p;
5997 ++curwin->w_cursor.col;
5998 }
5999 if ((trypos = findmatchlimit(NULL, 0, 0, ind_maxparen)) != NULL
6000 && *cin_skipcomment(ml_get_pos(trypos) + 1) == ';')
6001 retval = TRUE;
6002 curwin->w_cursor = cursor_save;
6003 }
6004 return retval;
6005}
6006
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006007/*
Bram Moolenaarb345d492012-04-09 20:42:26 +02006008 * Check whether in "p" there is an "if", "for" or "while" before "*poffset".
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006009 * Return 0 if there is none.
6010 * Otherwise return !0 and update "*poffset" to point to the place where the
6011 * string was found.
6012 */
6013 static int
Bram Moolenaarb345d492012-04-09 20:42:26 +02006014cin_is_if_for_while_before_offset(line, poffset)
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006015 char_u *line;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006016 int *poffset;
6017{
Bram Moolenaarb345d492012-04-09 20:42:26 +02006018 int offset = *poffset;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006019
6020 if (offset-- < 2)
6021 return 0;
6022 while (offset > 2 && vim_iswhite(line[offset]))
6023 --offset;
6024
6025 offset -= 1;
6026 if (!STRNCMP(line + offset, "if", 2))
6027 goto probablyFound;
6028
6029 if (offset >= 1)
6030 {
6031 offset -= 1;
6032 if (!STRNCMP(line + offset, "for", 3))
6033 goto probablyFound;
6034
6035 if (offset >= 2)
6036 {
6037 offset -= 2;
6038 if (!STRNCMP(line + offset, "while", 5))
6039 goto probablyFound;
6040 }
6041 }
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006042 return 0;
Bram Moolenaarb345d492012-04-09 20:42:26 +02006043
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006044probablyFound:
6045 if (!offset || !vim_isIDc(line[offset - 1]))
6046 {
6047 *poffset = offset;
6048 return 1;
6049 }
6050 return 0;
6051}
6052
6053/*
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006054 * Return TRUE if we are at the end of a do-while.
6055 * do
6056 * nothing;
6057 * while (foo
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00006058 * && bar); <-- here
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006059 * Adjust the cursor to the line with "while".
6060 */
6061 static int
6062cin_iswhileofdo_end(terminated, ind_maxparen, ind_maxcomment)
6063 int terminated;
6064 int ind_maxparen;
6065 int ind_maxcomment;
6066{
6067 char_u *line;
6068 char_u *p;
6069 char_u *s;
6070 pos_T *trypos;
6071 int i;
6072
6073 if (terminated != ';') /* there must be a ';' at the end */
6074 return FALSE;
6075
6076 p = line = ml_get_curline();
6077 while (*p != NUL)
6078 {
6079 p = cin_skipcomment(p);
6080 if (*p == ')')
6081 {
6082 s = skipwhite(p + 1);
6083 if (*s == ';' && cin_nocode(s + 1))
6084 {
6085 /* Found ");" at end of the line, now check there is "while"
6086 * before the matching '('. XXX */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006087 i = (int)(p - line);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006088 curwin->w_cursor.col = i;
6089 trypos = find_match_paren(ind_maxparen, ind_maxcomment);
6090 if (trypos != NULL)
6091 {
6092 s = cin_skipcomment(ml_get(trypos->lnum));
6093 if (*s == '}') /* accept "} while (cond);" */
6094 s = cin_skipcomment(s + 1);
6095 if (STRNCMP(s, "while", 5) == 0 && !vim_isIDc(s[5]))
6096 {
6097 curwin->w_cursor.lnum = trypos->lnum;
6098 return TRUE;
6099 }
6100 }
6101
6102 /* Searching may have made "line" invalid, get it again. */
6103 line = ml_get_curline();
6104 p = line + i;
6105 }
6106 }
6107 if (*p != NUL)
6108 ++p;
6109 }
6110 return FALSE;
6111}
6112
Bram Moolenaar071d4272004-06-13 20:20:40 +00006113 static int
6114cin_isbreak(p)
6115 char_u *p;
6116{
6117 return (STRNCMP(p, "break", 5) == 0 && !vim_isIDc(p[5]));
6118}
6119
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006120/*
6121 * Find the position of a C++ base-class declaration or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006122 * constructor-initialization. eg:
6123 *
6124 * class MyClass :
6125 * baseClass <-- here
6126 * class MyClass : public baseClass,
6127 * anotherBaseClass <-- here (should probably lineup ??)
6128 * MyClass::MyClass(...) :
6129 * baseClass(...) <-- here (constructor-initialization)
Bram Moolenaar18144c82006-04-12 21:52:12 +00006130 *
6131 * This is a lot of guessing. Watch out for "cond ? func() : foo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00006132 */
6133 static int
Bram Moolenaare7c56862007-08-04 10:14:52 +00006134cin_is_cpp_baseclass(col)
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006135 colnr_T *col; /* return: column to align with */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006136{
6137 char_u *s;
6138 int class_or_struct, lookfor_ctor_init, cpp_base_class;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006139 linenr_T lnum = curwin->w_cursor.lnum;
Bram Moolenaare7c56862007-08-04 10:14:52 +00006140 char_u *line = ml_get_curline();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006141
6142 *col = 0;
6143
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006144 s = skipwhite(line);
6145 if (*s == '#') /* skip #define FOO x ? (x) : x */
6146 return FALSE;
6147 s = cin_skipcomment(s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006148 if (*s == NUL)
6149 return FALSE;
6150
6151 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
6152
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006153 /* Search for a line starting with '#', empty, ending in ';' or containing
6154 * '{' or '}' and start below it. This handles the following situations:
6155 * a = cond ?
6156 * func() :
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00006157 * asdf;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006158 * func::foo()
6159 * : something
6160 * {}
6161 * Foo::Foo (int one, int two)
6162 * : something(4),
6163 * somethingelse(3)
6164 * {}
6165 */
6166 while (lnum > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006167 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00006168 line = ml_get(lnum - 1);
6169 s = skipwhite(line);
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006170 if (*s == '#' || *s == NUL)
6171 break;
6172 while (*s != NUL)
6173 {
6174 s = cin_skipcomment(s);
6175 if (*s == '{' || *s == '}'
6176 || (*s == ';' && cin_nocode(s + 1)))
6177 break;
6178 if (*s != NUL)
6179 ++s;
6180 }
6181 if (*s != NUL)
6182 break;
6183 --lnum;
6184 }
6185
Bram Moolenaare7c56862007-08-04 10:14:52 +00006186 line = ml_get(lnum);
6187 s = cin_skipcomment(line);
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006188 for (;;)
6189 {
6190 if (*s == NUL)
6191 {
6192 if (lnum == curwin->w_cursor.lnum)
6193 break;
6194 /* Continue in the cursor line. */
Bram Moolenaare7c56862007-08-04 10:14:52 +00006195 line = ml_get(++lnum);
6196 s = cin_skipcomment(line);
6197 if (*s == NUL)
6198 continue;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006199 }
6200
Bram Moolenaaraede6ce2011-05-10 11:56:30 +02006201 if (s[0] == '"')
6202 s = skip_string(s) + 1;
6203 else if (s[0] == ':')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006204 {
6205 if (s[1] == ':')
6206 {
6207 /* skip double colon. It can't be a constructor
6208 * initialization any more */
6209 lookfor_ctor_init = FALSE;
6210 s = cin_skipcomment(s + 2);
6211 }
6212 else if (lookfor_ctor_init || class_or_struct)
6213 {
6214 /* we have something found, that looks like the start of
Bram Moolenaare21877a2008-02-13 09:58:14 +00006215 * cpp-base-class-declaration or constructor-initialization */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006216 cpp_base_class = TRUE;
6217 lookfor_ctor_init = class_or_struct = FALSE;
6218 *col = 0;
6219 s = cin_skipcomment(s + 1);
6220 }
6221 else
6222 s = cin_skipcomment(s + 1);
6223 }
6224 else if ((STRNCMP(s, "class", 5) == 0 && !vim_isIDc(s[5]))
6225 || (STRNCMP(s, "struct", 6) == 0 && !vim_isIDc(s[6])))
6226 {
6227 class_or_struct = TRUE;
6228 lookfor_ctor_init = FALSE;
6229
6230 if (*s == 'c')
6231 s = cin_skipcomment(s + 5);
6232 else
6233 s = cin_skipcomment(s + 6);
6234 }
6235 else
6236 {
6237 if (s[0] == '{' || s[0] == '}' || s[0] == ';')
6238 {
6239 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
6240 }
6241 else if (s[0] == ')')
6242 {
6243 /* Constructor-initialization is assumed if we come across
6244 * something like "):" */
6245 class_or_struct = FALSE;
6246 lookfor_ctor_init = TRUE;
6247 }
Bram Moolenaar18144c82006-04-12 21:52:12 +00006248 else if (s[0] == '?')
6249 {
6250 /* Avoid seeing '() :' after '?' as constructor init. */
6251 return FALSE;
6252 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006253 else if (!vim_isIDc(s[0]))
6254 {
6255 /* if it is not an identifier, we are wrong */
6256 class_or_struct = FALSE;
6257 lookfor_ctor_init = FALSE;
6258 }
6259 else if (*col == 0)
6260 {
6261 /* it can't be a constructor-initialization any more */
6262 lookfor_ctor_init = FALSE;
6263
6264 /* the first statement starts here: lineup with this one... */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006265 if (cpp_base_class)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006266 *col = (colnr_T)(s - line);
6267 }
6268
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006269 /* When the line ends in a comma don't align with it. */
6270 if (lnum == curwin->w_cursor.lnum && *s == ',' && cin_nocode(s + 1))
6271 *col = 0;
6272
Bram Moolenaar071d4272004-06-13 20:20:40 +00006273 s = cin_skipcomment(s + 1);
6274 }
6275 }
6276
6277 return cpp_base_class;
6278}
6279
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006280 static int
6281get_baseclass_amount(col, ind_maxparen, ind_maxcomment, ind_cpp_baseclass)
6282 int col;
6283 int ind_maxparen;
6284 int ind_maxcomment;
6285 int ind_cpp_baseclass;
6286{
6287 int amount;
6288 colnr_T vcol;
6289 pos_T *trypos;
6290
6291 if (col == 0)
6292 {
6293 amount = get_indent();
6294 if (find_last_paren(ml_get_curline(), '(', ')')
6295 && (trypos = find_match_paren(ind_maxparen,
6296 ind_maxcomment)) != NULL)
6297 amount = get_indent_lnum(trypos->lnum); /* XXX */
6298 if (!cin_ends_in(ml_get_curline(), (char_u *)",", NULL))
6299 amount += ind_cpp_baseclass;
6300 }
6301 else
6302 {
6303 curwin->w_cursor.col = col;
6304 getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
6305 amount = (int)vcol;
6306 }
6307 if (amount < ind_cpp_baseclass)
6308 amount = ind_cpp_baseclass;
6309 return amount;
6310}
6311
Bram Moolenaar071d4272004-06-13 20:20:40 +00006312/*
6313 * Return TRUE if string "s" ends with the string "find", possibly followed by
6314 * white space and comments. Skip strings and comments.
6315 * Ignore "ignore" after "find" if it's not NULL.
6316 */
6317 static int
6318cin_ends_in(s, find, ignore)
6319 char_u *s;
6320 char_u *find;
6321 char_u *ignore;
6322{
6323 char_u *p = s;
6324 char_u *r;
6325 int len = (int)STRLEN(find);
6326
6327 while (*p != NUL)
6328 {
6329 p = cin_skipcomment(p);
6330 if (STRNCMP(p, find, len) == 0)
6331 {
6332 r = skipwhite(p + len);
6333 if (ignore != NULL && STRNCMP(r, ignore, STRLEN(ignore)) == 0)
6334 r = skipwhite(r + STRLEN(ignore));
6335 if (cin_nocode(r))
6336 return TRUE;
6337 }
6338 if (*p != NUL)
6339 ++p;
6340 }
6341 return FALSE;
6342}
6343
6344/*
6345 * Skip strings, chars and comments until at or past "trypos".
6346 * Return the column found.
6347 */
6348 static int
6349cin_skip2pos(trypos)
6350 pos_T *trypos;
6351{
6352 char_u *line;
6353 char_u *p;
6354
6355 p = line = ml_get(trypos->lnum);
6356 while (*p && (colnr_T)(p - line) < trypos->col)
6357 {
6358 if (cin_iscomment(p))
6359 p = cin_skipcomment(p);
6360 else
6361 {
6362 p = skip_string(p);
6363 ++p;
6364 }
6365 }
6366 return (int)(p - line);
6367}
6368
6369/*
6370 * Find the '{' at the start of the block we are in.
6371 * Return NULL if no match found.
6372 * Ignore a '{' that is in a comment, makes indenting the next three lines
6373 * work. */
6374/* foo() */
6375/* { */
6376/* } */
6377
6378 static pos_T *
6379find_start_brace(ind_maxcomment) /* XXX */
6380 int ind_maxcomment;
6381{
6382 pos_T cursor_save;
6383 pos_T *trypos;
6384 pos_T *pos;
6385 static pos_T pos_copy;
6386
6387 cursor_save = curwin->w_cursor;
6388 while ((trypos = findmatchlimit(NULL, '{', FM_BLOCKSTOP, 0)) != NULL)
6389 {
6390 pos_copy = *trypos; /* copy pos_T, next findmatch will change it */
6391 trypos = &pos_copy;
6392 curwin->w_cursor = *trypos;
6393 pos = NULL;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006394 /* ignore the { if it's in a // or / * * / comment */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006395 if ((colnr_T)cin_skip2pos(trypos) == trypos->col
6396 && (pos = find_start_comment(ind_maxcomment)) == NULL) /* XXX */
6397 break;
6398 if (pos != NULL)
6399 curwin->w_cursor.lnum = pos->lnum;
6400 }
6401 curwin->w_cursor = cursor_save;
6402 return trypos;
6403}
6404
6405/*
6406 * Find the matching '(', failing if it is in a comment.
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006407 * Return NULL if no match found.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006408 */
6409 static pos_T *
6410find_match_paren(ind_maxparen, ind_maxcomment) /* XXX */
6411 int ind_maxparen;
6412 int ind_maxcomment;
6413{
6414 pos_T cursor_save;
6415 pos_T *trypos;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006416 static pos_T pos_copy;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006417
6418 cursor_save = curwin->w_cursor;
6419 if ((trypos = findmatchlimit(NULL, '(', 0, ind_maxparen)) != NULL)
6420 {
6421 /* check if the ( is in a // comment */
6422 if ((colnr_T)cin_skip2pos(trypos) > trypos->col)
6423 trypos = NULL;
6424 else
6425 {
6426 pos_copy = *trypos; /* copy trypos, findmatch will change it */
6427 trypos = &pos_copy;
6428 curwin->w_cursor = *trypos;
6429 if (find_start_comment(ind_maxcomment) != NULL) /* XXX */
6430 trypos = NULL;
6431 }
6432 }
6433 curwin->w_cursor = cursor_save;
6434 return trypos;
6435}
6436
6437/*
6438 * Return ind_maxparen corrected for the difference in line number between the
6439 * cursor position and "startpos". This makes sure that searching for a
6440 * matching paren above the cursor line doesn't find a match because of
6441 * looking a few lines further.
6442 */
6443 static int
6444corr_ind_maxparen(ind_maxparen, startpos)
6445 int ind_maxparen;
6446 pos_T *startpos;
6447{
6448 long n = (long)startpos->lnum - (long)curwin->w_cursor.lnum;
6449
6450 if (n > 0 && n < ind_maxparen / 2)
6451 return ind_maxparen - (int)n;
6452 return ind_maxparen;
6453}
6454
6455/*
6456 * Set w_cursor.col to the column number of the last unmatched ')' or '{' in
Bram Moolenaar6d8f9c62011-11-30 13:03:28 +01006457 * line "l". "l" must point to the start of the line.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006458 */
6459 static int
6460find_last_paren(l, start, end)
6461 char_u *l;
6462 int start, end;
6463{
6464 int i;
6465 int retval = FALSE;
6466 int open_count = 0;
6467
6468 curwin->w_cursor.col = 0; /* default is start of line */
6469
Bram Moolenaar6d8f9c62011-11-30 13:03:28 +01006470 for (i = 0; l[i] != NUL; i++)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006471 {
6472 i = (int)(cin_skipcomment(l + i) - l); /* ignore parens in comments */
6473 i = (int)(skip_string(l + i) - l); /* ignore parens in quotes */
6474 if (l[i] == start)
6475 ++open_count;
6476 else if (l[i] == end)
6477 {
6478 if (open_count > 0)
6479 --open_count;
6480 else
6481 {
6482 curwin->w_cursor.col = i;
6483 retval = TRUE;
6484 }
6485 }
6486 }
6487 return retval;
6488}
6489
6490 int
6491get_c_indent()
6492{
6493 /*
6494 * spaces from a block's opening brace the prevailing indent for that
6495 * block should be
6496 */
6497 int ind_level = curbuf->b_p_sw;
6498
6499 /*
6500 * spaces from the edge of the line an open brace that's at the end of a
6501 * line is imagined to be.
6502 */
6503 int ind_open_imag = 0;
6504
6505 /*
Bram Moolenaar1a509df2010-08-01 17:59:57 +02006506 * spaces from the prevailing indent for a line that is not preceded by
Bram Moolenaar071d4272004-06-13 20:20:40 +00006507 * an opening brace.
6508 */
6509 int ind_no_brace = 0;
6510
6511 /*
6512 * column where the first { of a function should be located }
6513 */
6514 int ind_first_open = 0;
6515
6516 /*
6517 * spaces from the prevailing indent a leftmost open brace should be
6518 * located
6519 */
6520 int ind_open_extra = 0;
6521
6522 /*
6523 * spaces from the matching open brace (real location for one at the left
6524 * edge; imaginary location from one that ends a line) the matching close
6525 * brace should be located
6526 */
6527 int ind_close_extra = 0;
6528
6529 /*
6530 * spaces from the edge of the line an open brace sitting in the leftmost
6531 * column is imagined to be
6532 */
6533 int ind_open_left_imag = 0;
6534
6535 /*
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006536 * Spaces jump labels should be shifted to the left if N is non-negative,
6537 * otherwise the jump label will be put to column 1.
6538 */
6539 int ind_jump_label = -1;
6540
6541 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006542 * spaces from the switch() indent a "case xx" label should be located
6543 */
6544 int ind_case = curbuf->b_p_sw;
6545
6546 /*
6547 * spaces from the "case xx:" code after a switch() should be located
6548 */
6549 int ind_case_code = curbuf->b_p_sw;
6550
6551 /*
6552 * lineup break at end of case in switch() with case label
6553 */
6554 int ind_case_break = 0;
6555
6556 /*
6557 * spaces from the class declaration indent a scope declaration label
6558 * should be located
6559 */
6560 int ind_scopedecl = curbuf->b_p_sw;
6561
6562 /*
6563 * spaces from the scope declaration label code should be located
6564 */
6565 int ind_scopedecl_code = curbuf->b_p_sw;
6566
6567 /*
6568 * amount K&R-style parameters should be indented
6569 */
6570 int ind_param = curbuf->b_p_sw;
6571
6572 /*
6573 * amount a function type spec should be indented
6574 */
6575 int ind_func_type = curbuf->b_p_sw;
6576
6577 /*
6578 * amount a cpp base class declaration or constructor initialization
6579 * should be indented
6580 */
6581 int ind_cpp_baseclass = curbuf->b_p_sw;
6582
6583 /*
6584 * additional spaces beyond the prevailing indent a continuation line
6585 * should be located
6586 */
6587 int ind_continuation = curbuf->b_p_sw;
6588
6589 /*
6590 * spaces from the indent of the line with an unclosed parentheses
6591 */
6592 int ind_unclosed = curbuf->b_p_sw * 2;
6593
6594 /*
6595 * spaces from the indent of the line with an unclosed parentheses, which
6596 * itself is also unclosed
6597 */
6598 int ind_unclosed2 = curbuf->b_p_sw;
6599
6600 /*
6601 * suppress ignoring spaces from the indent of a line starting with an
6602 * unclosed parentheses.
6603 */
6604 int ind_unclosed_noignore = 0;
6605
6606 /*
6607 * If the opening paren is the last nonwhite character on the line, and
6608 * ind_unclosed_wrapped is nonzero, use this indent relative to the outer
6609 * context (for very long lines).
6610 */
6611 int ind_unclosed_wrapped = 0;
6612
6613 /*
6614 * suppress ignoring white space when lining up with the character after
6615 * an unclosed parentheses.
6616 */
6617 int ind_unclosed_whiteok = 0;
6618
6619 /*
6620 * indent a closing parentheses under the line start of the matching
6621 * opening parentheses.
6622 */
6623 int ind_matching_paren = 0;
6624
6625 /*
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006626 * indent a closing parentheses under the previous line.
6627 */
6628 int ind_paren_prev = 0;
6629
6630 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006631 * Extra indent for comments.
6632 */
6633 int ind_comment = 0;
6634
6635 /*
6636 * spaces from the comment opener when there is nothing after it.
6637 */
6638 int ind_in_comment = 3;
6639
6640 /*
6641 * boolean: if non-zero, use ind_in_comment even if there is something
6642 * after the comment opener.
6643 */
6644 int ind_in_comment2 = 0;
6645
6646 /*
6647 * max lines to search for an open paren
6648 */
6649 int ind_maxparen = 20;
6650
6651 /*
6652 * max lines to search for an open comment
6653 */
6654 int ind_maxcomment = 70;
6655
6656 /*
6657 * handle braces for java code
6658 */
6659 int ind_java = 0;
6660
6661 /*
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006662 * not to confuse JS object properties with labels
6663 */
6664 int ind_js = 0;
6665
6666 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006667 * handle blocked cases correctly
6668 */
6669 int ind_keep_case_label = 0;
6670
Bram Moolenaared38b0a2011-05-25 15:16:18 +02006671 /*
6672 * handle C++ namespace
6673 */
6674 int ind_cpp_namespace = 0;
6675
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006676 /*
6677 * handle continuation lines containing conditions of if(), for() and
6678 * while()
6679 */
6680 int ind_if_for_while = 0;
6681
Bram Moolenaar071d4272004-06-13 20:20:40 +00006682 pos_T cur_curpos;
6683 int amount;
6684 int scope_amount;
Bram Moolenaarb21e5842006-04-16 18:30:08 +00006685 int cur_amount = MAXCOL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006686 colnr_T col;
6687 char_u *theline;
6688 char_u *linecopy;
6689 pos_T *trypos;
6690 pos_T *tryposBrace = NULL;
6691 pos_T our_paren_pos;
6692 char_u *start;
6693 int start_brace;
Bram Moolenaare21877a2008-02-13 09:58:14 +00006694#define BRACE_IN_COL0 1 /* '{' is in column 0 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006695#define BRACE_AT_START 2 /* '{' is at start of line */
6696#define BRACE_AT_END 3 /* '{' is at end of line */
6697 linenr_T ourscope;
6698 char_u *l;
6699 char_u *look;
6700 char_u terminated;
6701 int lookfor;
6702#define LOOKFOR_INITIAL 0
6703#define LOOKFOR_IF 1
6704#define LOOKFOR_DO 2
6705#define LOOKFOR_CASE 3
6706#define LOOKFOR_ANY 4
6707#define LOOKFOR_TERM 5
6708#define LOOKFOR_UNTERM 6
6709#define LOOKFOR_SCOPEDECL 7
6710#define LOOKFOR_NOBREAK 8
6711#define LOOKFOR_CPP_BASECLASS 9
6712#define LOOKFOR_ENUM_OR_INIT 10
6713
6714 int whilelevel;
6715 linenr_T lnum;
6716 char_u *options;
Bram Moolenaar48d27922012-06-13 13:40:48 +02006717 char_u *digits;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006718 int fraction = 0; /* init for GCC */
6719 int divider;
6720 int n;
6721 int iscase;
6722 int lookfor_break;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02006723 int lookfor_cpp_namespace = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006724 int cont_amount = 0; /* amount for continuation line */
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006725 int original_line_islabel;
Bram Moolenaare79d1532011-10-04 18:03:47 +02006726 int added_to_amount = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006727
6728 for (options = curbuf->b_p_cino; *options; )
6729 {
6730 l = options++;
6731 if (*options == '-')
6732 ++options;
Bram Moolenaar48d27922012-06-13 13:40:48 +02006733 digits = options; /* remember where the digits start */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006734 n = getdigits(&options);
6735 divider = 0;
6736 if (*options == '.') /* ".5s" means a fraction */
6737 {
6738 fraction = atol((char *)++options);
6739 while (VIM_ISDIGIT(*options))
6740 {
6741 ++options;
6742 if (divider)
6743 divider *= 10;
6744 else
6745 divider = 10;
6746 }
6747 }
6748 if (*options == 's') /* "2s" means two times 'shiftwidth' */
6749 {
Bram Moolenaar48d27922012-06-13 13:40:48 +02006750 if (options == digits)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006751 n = curbuf->b_p_sw; /* just "s" is one 'shiftwidth' */
6752 else
6753 {
6754 n *= curbuf->b_p_sw;
6755 if (divider)
6756 n += (curbuf->b_p_sw * fraction + divider / 2) / divider;
6757 }
6758 ++options;
6759 }
6760 if (l[1] == '-')
6761 n = -n;
6762 /* When adding an entry here, also update the default 'cinoptions' in
Bram Moolenaar39353fd2007-03-27 09:02:11 +00006763 * doc/indent.txt, and add explanation for it! */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006764 switch (*l)
6765 {
6766 case '>': ind_level = n; break;
6767 case 'e': ind_open_imag = n; break;
6768 case 'n': ind_no_brace = n; break;
6769 case 'f': ind_first_open = n; break;
6770 case '{': ind_open_extra = n; break;
6771 case '}': ind_close_extra = n; break;
6772 case '^': ind_open_left_imag = n; break;
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006773 case 'L': ind_jump_label = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006774 case ':': ind_case = n; break;
6775 case '=': ind_case_code = n; break;
6776 case 'b': ind_case_break = n; break;
6777 case 'p': ind_param = n; break;
6778 case 't': ind_func_type = n; break;
6779 case '/': ind_comment = n; break;
6780 case 'c': ind_in_comment = n; break;
6781 case 'C': ind_in_comment2 = n; break;
6782 case 'i': ind_cpp_baseclass = n; break;
6783 case '+': ind_continuation = n; break;
6784 case '(': ind_unclosed = n; break;
6785 case 'u': ind_unclosed2 = n; break;
6786 case 'U': ind_unclosed_noignore = n; break;
6787 case 'W': ind_unclosed_wrapped = n; break;
6788 case 'w': ind_unclosed_whiteok = n; break;
6789 case 'm': ind_matching_paren = n; break;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006790 case 'M': ind_paren_prev = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006791 case ')': ind_maxparen = n; break;
6792 case '*': ind_maxcomment = n; break;
6793 case 'g': ind_scopedecl = n; break;
6794 case 'h': ind_scopedecl_code = n; break;
6795 case 'j': ind_java = n; break;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006796 case 'J': ind_js = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006797 case 'l': ind_keep_case_label = n; break;
Bram Moolenaar39353fd2007-03-27 09:02:11 +00006798 case '#': ind_hash_comment = n; break;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02006799 case 'N': ind_cpp_namespace = n; break;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006800 case 'k': ind_if_for_while = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006801 }
Bram Moolenaardfdf3c42010-03-23 18:22:46 +01006802 if (*options == ',')
6803 ++options;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006804 }
6805
6806 /* remember where the cursor was when we started */
6807 cur_curpos = curwin->w_cursor;
6808
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006809 /* if we are at line 1 0 is fine, right? */
6810 if (cur_curpos.lnum == 1)
6811 return 0;
6812
Bram Moolenaar071d4272004-06-13 20:20:40 +00006813 /* Get a copy of the current contents of the line.
6814 * This is required, because only the most recent line obtained with
6815 * ml_get is valid! */
6816 linecopy = vim_strsave(ml_get(cur_curpos.lnum));
6817 if (linecopy == NULL)
6818 return 0;
6819
6820 /*
6821 * In insert mode and the cursor is on a ')' truncate the line at the
6822 * cursor position. We don't want to line up with the matching '(' when
6823 * inserting new stuff.
6824 * For unknown reasons the cursor might be past the end of the line, thus
6825 * check for that.
6826 */
6827 if ((State & INSERT)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006828 && curwin->w_cursor.col < (colnr_T)STRLEN(linecopy)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006829 && linecopy[curwin->w_cursor.col] == ')')
6830 linecopy[curwin->w_cursor.col] = NUL;
6831
6832 theline = skipwhite(linecopy);
6833
6834 /* move the cursor to the start of the line */
6835
6836 curwin->w_cursor.col = 0;
6837
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006838 original_line_islabel = cin_islabel(ind_maxcomment); /* XXX */
6839
Bram Moolenaar071d4272004-06-13 20:20:40 +00006840 /*
6841 * #defines and so on always go at the left when included in 'cinkeys'.
6842 */
6843 if (*theline == '#' && (*linecopy == '#' || in_cinkeys('#', ' ', TRUE)))
6844 {
6845 amount = 0;
6846 }
6847
6848 /*
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006849 * Is it a non-case label? Then that goes at the left margin too unless:
6850 * - JS flag is set.
6851 * - 'L' item has a positive value.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006852 */
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006853 else if (original_line_islabel && !ind_js && ind_jump_label < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006854 {
6855 amount = 0;
6856 }
6857
6858 /*
6859 * If we're inside a "//" comment and there is a "//" comment in a
6860 * previous line, lineup with that one.
6861 */
6862 else if (cin_islinecomment(theline)
6863 && (trypos = find_line_comment()) != NULL) /* XXX */
6864 {
6865 /* find how indented the line beginning the comment is */
6866 getvcol(curwin, trypos, &col, NULL, NULL);
6867 amount = col;
6868 }
6869
6870 /*
6871 * If we're inside a comment and not looking at the start of the
6872 * comment, try using the 'comments' option.
6873 */
6874 else if (!cin_iscomment(theline)
6875 && (trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
6876 {
6877 int lead_start_len = 2;
6878 int lead_middle_len = 1;
6879 char_u lead_start[COM_MAX_LEN]; /* start-comment string */
6880 char_u lead_middle[COM_MAX_LEN]; /* middle-comment string */
6881 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
6882 char_u *p;
6883 int start_align = 0;
6884 int start_off = 0;
6885 int done = FALSE;
6886
6887 /* find how indented the line beginning the comment is */
6888 getvcol(curwin, trypos, &col, NULL, NULL);
6889 amount = col;
Bram Moolenaar4aa97422011-04-11 14:27:38 +02006890 *lead_start = NUL;
6891 *lead_middle = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006892
6893 p = curbuf->b_p_com;
6894 while (*p != NUL)
6895 {
6896 int align = 0;
6897 int off = 0;
6898 int what = 0;
6899
6900 while (*p != NUL && *p != ':')
6901 {
6902 if (*p == COM_START || *p == COM_END || *p == COM_MIDDLE)
6903 what = *p++;
6904 else if (*p == COM_LEFT || *p == COM_RIGHT)
6905 align = *p++;
6906 else if (VIM_ISDIGIT(*p) || *p == '-')
6907 off = getdigits(&p);
6908 else
6909 ++p;
6910 }
6911
6912 if (*p == ':')
6913 ++p;
6914 (void)copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
6915 if (what == COM_START)
6916 {
6917 STRCPY(lead_start, lead_end);
6918 lead_start_len = (int)STRLEN(lead_start);
6919 start_off = off;
6920 start_align = align;
6921 }
6922 else if (what == COM_MIDDLE)
6923 {
6924 STRCPY(lead_middle, lead_end);
6925 lead_middle_len = (int)STRLEN(lead_middle);
6926 }
6927 else if (what == COM_END)
6928 {
6929 /* If our line starts with the middle comment string, line it
6930 * up with the comment opener per the 'comments' option. */
6931 if (STRNCMP(theline, lead_middle, lead_middle_len) == 0
6932 && STRNCMP(theline, lead_end, STRLEN(lead_end)) != 0)
6933 {
6934 done = TRUE;
6935 if (curwin->w_cursor.lnum > 1)
6936 {
6937 /* If the start comment string matches in the previous
Bram Moolenaare21877a2008-02-13 09:58:14 +00006938 * line, use the indent of that line plus offset. If
Bram Moolenaar071d4272004-06-13 20:20:40 +00006939 * the middle comment string matches in the previous
6940 * line, use the indent of that line. XXX */
6941 look = skipwhite(ml_get(curwin->w_cursor.lnum - 1));
6942 if (STRNCMP(look, lead_start, lead_start_len) == 0)
6943 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6944 else if (STRNCMP(look, lead_middle,
6945 lead_middle_len) == 0)
6946 {
6947 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6948 break;
6949 }
6950 /* If the start comment string doesn't match with the
6951 * start of the comment, skip this entry. XXX */
6952 else if (STRNCMP(ml_get(trypos->lnum) + trypos->col,
6953 lead_start, lead_start_len) != 0)
6954 continue;
6955 }
6956 if (start_off != 0)
6957 amount += start_off;
6958 else if (start_align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006959 amount += vim_strsize(lead_start)
6960 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006961 break;
6962 }
6963
6964 /* If our line starts with the end comment string, line it up
6965 * with the middle comment */
6966 if (STRNCMP(theline, lead_middle, lead_middle_len) != 0
6967 && STRNCMP(theline, lead_end, STRLEN(lead_end)) == 0)
6968 {
6969 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6970 /* XXX */
6971 if (off != 0)
6972 amount += off;
6973 else if (align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006974 amount += vim_strsize(lead_start)
6975 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006976 done = TRUE;
6977 break;
6978 }
6979 }
6980 }
6981
6982 /* If our line starts with an asterisk, line up with the
6983 * asterisk in the comment opener; otherwise, line up
6984 * with the first character of the comment text.
6985 */
6986 if (done)
6987 ;
6988 else if (theline[0] == '*')
6989 amount += 1;
6990 else
6991 {
6992 /*
6993 * If we are more than one line away from the comment opener, take
6994 * the indent of the previous non-empty line. If 'cino' has "CO"
6995 * and we are just below the comment opener and there are any
6996 * white characters after it line up with the text after it;
6997 * otherwise, add the amount specified by "c" in 'cino'
6998 */
6999 amount = -1;
7000 for (lnum = cur_curpos.lnum - 1; lnum > trypos->lnum; --lnum)
7001 {
7002 if (linewhite(lnum)) /* skip blank lines */
7003 continue;
7004 amount = get_indent_lnum(lnum); /* XXX */
7005 break;
7006 }
7007 if (amount == -1) /* use the comment opener */
7008 {
7009 if (!ind_in_comment2)
7010 {
7011 start = ml_get(trypos->lnum);
7012 look = start + trypos->col + 2; /* skip / and * */
7013 if (*look != NUL) /* if something after it */
7014 trypos->col = (colnr_T)(skipwhite(look) - start);
7015 }
7016 getvcol(curwin, trypos, &col, NULL, NULL);
7017 amount = col;
7018 if (ind_in_comment2 || *look == NUL)
7019 amount += ind_in_comment;
7020 }
7021 }
7022 }
7023
7024 /*
7025 * Are we inside parentheses or braces?
7026 */ /* XXX */
7027 else if (((trypos = find_match_paren(ind_maxparen, ind_maxcomment)) != NULL
7028 && ind_java == 0)
7029 || (tryposBrace = find_start_brace(ind_maxcomment)) != NULL
7030 || trypos != NULL)
7031 {
7032 if (trypos != NULL && tryposBrace != NULL)
7033 {
7034 /* Both an unmatched '(' and '{' is found. Use the one which is
7035 * closer to the current cursor position, set the other to NULL. */
7036 if (trypos->lnum != tryposBrace->lnum
7037 ? trypos->lnum < tryposBrace->lnum
7038 : trypos->col < tryposBrace->col)
7039 trypos = NULL;
7040 else
7041 tryposBrace = NULL;
7042 }
7043
7044 if (trypos != NULL)
7045 {
7046 /*
7047 * If the matching paren is more than one line away, use the indent of
7048 * a previous non-empty line that matches the same paren.
7049 */
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007050 if (theline[0] == ')' && ind_paren_prev)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007051 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007052 /* Line up with the start of the matching paren line. */
7053 amount = get_indent_lnum(curwin->w_cursor.lnum - 1); /* XXX */
7054 }
7055 else
7056 {
7057 amount = -1;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007058 our_paren_pos = *trypos;
7059 for (lnum = cur_curpos.lnum - 1; lnum > our_paren_pos.lnum; --lnum)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007060 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007061 l = skipwhite(ml_get(lnum));
7062 if (cin_nocode(l)) /* skip comment lines */
7063 continue;
7064 if (cin_ispreproc_cont(&l, &lnum))
7065 continue; /* ignore #define, #if, etc. */
7066 curwin->w_cursor.lnum = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007067
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007068 /* Skip a comment. XXX */
7069 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
7070 {
7071 lnum = trypos->lnum + 1;
7072 continue;
7073 }
7074
7075 /* XXX */
7076 if ((trypos = find_match_paren(
7077 corr_ind_maxparen(ind_maxparen, &cur_curpos),
Bram Moolenaar071d4272004-06-13 20:20:40 +00007078 ind_maxcomment)) != NULL
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007079 && trypos->lnum == our_paren_pos.lnum
7080 && trypos->col == our_paren_pos.col)
7081 {
7082 amount = get_indent_lnum(lnum); /* XXX */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007083
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007084 if (theline[0] == ')')
7085 {
7086 if (our_paren_pos.lnum != lnum
7087 && cur_amount > amount)
7088 cur_amount = amount;
7089 amount = -1;
7090 }
7091 break;
7092 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007093 }
7094 }
7095
7096 /*
7097 * Line up with line where the matching paren is. XXX
7098 * If the line starts with a '(' or the indent for unclosed
7099 * parentheses is zero, line up with the unclosed parentheses.
7100 */
7101 if (amount == -1)
7102 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007103 int ignore_paren_col = 0;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007104 int is_if_for_while = 0;
7105
7106 if (ind_if_for_while)
7107 {
7108 /* Look for the outermost opening parenthesis on this line
7109 * and check whether it belongs to an "if", "for" or "while". */
7110
7111 pos_T cursor_save = curwin->w_cursor;
7112 pos_T outermost;
7113 char_u *line;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007114
7115 trypos = &our_paren_pos;
7116 do {
7117 outermost = *trypos;
7118 curwin->w_cursor.lnum = outermost.lnum;
7119 curwin->w_cursor.col = outermost.col;
7120
7121 trypos = find_match_paren(ind_maxparen, ind_maxcomment);
7122 } while (trypos && trypos->lnum == outermost.lnum);
7123
7124 curwin->w_cursor = cursor_save;
7125
7126 line = ml_get(outermost.lnum);
7127
7128 is_if_for_while =
Bram Moolenaarb345d492012-04-09 20:42:26 +02007129 cin_is_if_for_while_before_offset(line, &outermost.col);
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007130 }
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007131
Bram Moolenaar071d4272004-06-13 20:20:40 +00007132 amount = skip_label(our_paren_pos.lnum, &look, ind_maxcomment);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007133 look = skipwhite(look);
7134 if (*look == '(')
7135 {
7136 linenr_T save_lnum = curwin->w_cursor.lnum;
7137 char_u *line;
7138 int look_col;
7139
7140 /* Ignore a '(' in front of the line that has a match before
7141 * our matching '('. */
7142 curwin->w_cursor.lnum = our_paren_pos.lnum;
7143 line = ml_get_curline();
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007144 look_col = (int)(look - line);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007145 curwin->w_cursor.col = look_col + 1;
7146 if ((trypos = findmatchlimit(NULL, ')', 0, ind_maxparen))
7147 != NULL
7148 && trypos->lnum == our_paren_pos.lnum
7149 && trypos->col < our_paren_pos.col)
7150 ignore_paren_col = trypos->col + 1;
7151
7152 curwin->w_cursor.lnum = save_lnum;
7153 look = ml_get(our_paren_pos.lnum) + look_col;
7154 }
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007155 if (theline[0] == ')' || (ind_unclosed == 0 && is_if_for_while == 0)
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007156 || (!ind_unclosed_noignore && *look == '('
7157 && ignore_paren_col == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007158 {
7159 /*
7160 * If we're looking at a close paren, line up right there;
7161 * otherwise, line up with the next (non-white) character.
7162 * When ind_unclosed_wrapped is set and the matching paren is
7163 * the last nonwhite character of the line, use either the
7164 * indent of the current line or the indentation of the next
7165 * outer paren and add ind_unclosed_wrapped (for very long
7166 * lines).
7167 */
7168 if (theline[0] != ')')
7169 {
7170 cur_amount = MAXCOL;
7171 l = ml_get(our_paren_pos.lnum);
7172 if (ind_unclosed_wrapped
7173 && cin_ends_in(l, (char_u *)"(", NULL))
7174 {
7175 /* look for opening unmatched paren, indent one level
7176 * for each additional level */
7177 n = 1;
7178 for (col = 0; col < our_paren_pos.col; ++col)
7179 {
7180 switch (l[col])
7181 {
7182 case '(':
7183 case '{': ++n;
7184 break;
7185
7186 case ')':
7187 case '}': if (n > 1)
7188 --n;
7189 break;
7190 }
7191 }
7192
7193 our_paren_pos.col = 0;
7194 amount += n * ind_unclosed_wrapped;
7195 }
7196 else if (ind_unclosed_whiteok)
7197 our_paren_pos.col++;
7198 else
7199 {
7200 col = our_paren_pos.col + 1;
7201 while (vim_iswhite(l[col]))
7202 col++;
7203 if (l[col] != NUL) /* In case of trailing space */
7204 our_paren_pos.col = col;
7205 else
7206 our_paren_pos.col++;
7207 }
7208 }
7209
7210 /*
7211 * Find how indented the paren is, or the character after it
7212 * if we did the above "if".
7213 */
7214 if (our_paren_pos.col > 0)
7215 {
7216 getvcol(curwin, &our_paren_pos, &col, NULL, NULL);
7217 if (cur_amount > (int)col)
7218 cur_amount = col;
7219 }
7220 }
7221
7222 if (theline[0] == ')' && ind_matching_paren)
7223 {
7224 /* Line up with the start of the matching paren line. */
7225 }
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007226 else if ((ind_unclosed == 0 && is_if_for_while == 0)
7227 || (!ind_unclosed_noignore
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007228 && *look == '(' && ignore_paren_col == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007229 {
7230 if (cur_amount != MAXCOL)
7231 amount = cur_amount;
7232 }
7233 else
7234 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007235 /* Add ind_unclosed2 for each '(' before our matching one, but
7236 * ignore (void) before the line (ignore_paren_col). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007237 col = our_paren_pos.col;
Bram Moolenaarb21e5842006-04-16 18:30:08 +00007238 while ((int)our_paren_pos.col > ignore_paren_col)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007239 {
7240 --our_paren_pos.col;
7241 switch (*ml_get_pos(&our_paren_pos))
7242 {
7243 case '(': amount += ind_unclosed2;
7244 col = our_paren_pos.col;
7245 break;
7246 case ')': amount -= ind_unclosed2;
7247 col = MAXCOL;
7248 break;
7249 }
7250 }
7251
7252 /* Use ind_unclosed once, when the first '(' is not inside
7253 * braces */
7254 if (col == MAXCOL)
7255 amount += ind_unclosed;
7256 else
7257 {
7258 curwin->w_cursor.lnum = our_paren_pos.lnum;
7259 curwin->w_cursor.col = col;
Bram Moolenaar367bec82011-04-11 14:26:19 +02007260 if (find_match_paren(ind_maxparen, ind_maxcomment) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007261 amount += ind_unclosed2;
7262 else
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007263 {
7264 if (is_if_for_while)
7265 amount += ind_if_for_while;
7266 else
7267 amount += ind_unclosed;
7268 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007269 }
7270 /*
7271 * For a line starting with ')' use the minimum of the two
7272 * positions, to avoid giving it more indent than the previous
7273 * lines:
7274 * func_long_name( if (x
7275 * arg && yy
7276 * ) ^ not here ) ^ not here
7277 */
7278 if (cur_amount < amount)
7279 amount = cur_amount;
7280 }
7281 }
7282
7283 /* add extra indent for a comment */
7284 if (cin_iscomment(theline))
7285 amount += ind_comment;
7286 }
7287
7288 /*
7289 * Are we at least inside braces, then?
7290 */
7291 else
7292 {
7293 trypos = tryposBrace;
7294
7295 ourscope = trypos->lnum;
7296 start = ml_get(ourscope);
7297
7298 /*
7299 * Now figure out how indented the line is in general.
7300 * If the brace was at the start of the line, we use that;
7301 * otherwise, check out the indentation of the line as
7302 * a whole and then add the "imaginary indent" to that.
7303 */
7304 look = skipwhite(start);
7305 if (*look == '{')
7306 {
7307 getvcol(curwin, trypos, &col, NULL, NULL);
7308 amount = col;
7309 if (*start == '{')
7310 start_brace = BRACE_IN_COL0;
7311 else
7312 start_brace = BRACE_AT_START;
7313 }
7314 else
7315 {
7316 /*
7317 * that opening brace might have been on a continuation
7318 * line. if so, find the start of the line.
7319 */
7320 curwin->w_cursor.lnum = ourscope;
7321
7322 /*
7323 * position the cursor over the rightmost paren, so that
7324 * matching it will take us back to the start of the line.
7325 */
7326 lnum = ourscope;
7327 if (find_last_paren(start, '(', ')')
7328 && (trypos = find_match_paren(ind_maxparen,
7329 ind_maxcomment)) != NULL)
7330 lnum = trypos->lnum;
7331
7332 /*
7333 * It could have been something like
7334 * case 1: if (asdf &&
7335 * ldfd) {
7336 * }
7337 */
Bram Moolenaar6ec154b2011-06-12 21:51:08 +02007338 if (ind_js || (ind_keep_case_label
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007339 && cin_iscase(skipwhite(ml_get_curline()), FALSE)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007340 amount = get_indent();
7341 else
7342 amount = skip_label(lnum, &l, ind_maxcomment);
7343
7344 start_brace = BRACE_AT_END;
7345 }
7346
7347 /*
7348 * if we're looking at a closing brace, that's where
7349 * we want to be. otherwise, add the amount of room
7350 * that an indent is supposed to be.
7351 */
7352 if (theline[0] == '}')
7353 {
7354 /*
7355 * they may want closing braces to line up with something
7356 * other than the open brace. indulge them, if so.
7357 */
7358 amount += ind_close_extra;
7359 }
7360 else
7361 {
7362 /*
7363 * If we're looking at an "else", try to find an "if"
7364 * to match it with.
7365 * If we're looking at a "while", try to find a "do"
7366 * to match it with.
7367 */
7368 lookfor = LOOKFOR_INITIAL;
7369 if (cin_iselse(theline))
7370 lookfor = LOOKFOR_IF;
7371 else if (cin_iswhileofdo(theline, cur_curpos.lnum, ind_maxparen))
7372 /* XXX */
7373 lookfor = LOOKFOR_DO;
7374 if (lookfor != LOOKFOR_INITIAL)
7375 {
7376 curwin->w_cursor.lnum = cur_curpos.lnum;
7377 if (find_match(lookfor, ourscope, ind_maxparen,
7378 ind_maxcomment) == OK)
7379 {
7380 amount = get_indent(); /* XXX */
7381 goto theend;
7382 }
7383 }
7384
7385 /*
7386 * We get here if we are not on an "while-of-do" or "else" (or
7387 * failed to find a matching "if").
7388 * Search backwards for something to line up with.
7389 * First set amount for when we don't find anything.
7390 */
7391
7392 /*
7393 * if the '{' is _really_ at the left margin, use the imaginary
7394 * location of a left-margin brace. Otherwise, correct the
7395 * location for ind_open_extra.
7396 */
7397
7398 if (start_brace == BRACE_IN_COL0) /* '{' is in column 0 */
7399 {
7400 amount = ind_open_left_imag;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007401 lookfor_cpp_namespace = TRUE;
7402 }
7403 else if (start_brace == BRACE_AT_START &&
7404 lookfor_cpp_namespace) /* '{' is at start */
7405 {
7406
7407 lookfor_cpp_namespace = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007408 }
7409 else
7410 {
7411 if (start_brace == BRACE_AT_END) /* '{' is at end of line */
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007412 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007413 amount += ind_open_imag;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007414
7415 l = skipwhite(ml_get_curline());
7416 if (cin_is_cpp_namespace(l))
7417 amount += ind_cpp_namespace;
7418 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007419 else
7420 {
7421 /* Compensate for adding ind_open_extra later. */
7422 amount -= ind_open_extra;
7423 if (amount < 0)
7424 amount = 0;
7425 }
7426 }
7427
7428 lookfor_break = FALSE;
7429
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007430 if (cin_iscase(theline, FALSE)) /* it's a switch() label */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007431 {
7432 lookfor = LOOKFOR_CASE; /* find a previous switch() label */
7433 amount += ind_case;
7434 }
7435 else if (cin_isscopedecl(theline)) /* private:, ... */
7436 {
7437 lookfor = LOOKFOR_SCOPEDECL; /* class decl is this block */
7438 amount += ind_scopedecl;
7439 }
7440 else
7441 {
7442 if (ind_case_break && cin_isbreak(theline)) /* break; ... */
7443 lookfor_break = TRUE;
7444
7445 lookfor = LOOKFOR_INITIAL;
7446 amount += ind_level; /* ind_level from start of block */
7447 }
7448 scope_amount = amount;
7449 whilelevel = 0;
7450
7451 /*
7452 * Search backwards. If we find something we recognize, line up
7453 * with that.
7454 *
7455 * if we're looking at an open brace, indent
7456 * the usual amount relative to the conditional
7457 * that opens the block.
7458 */
7459 curwin->w_cursor = cur_curpos;
7460 for (;;)
7461 {
7462 curwin->w_cursor.lnum--;
7463 curwin->w_cursor.col = 0;
7464
7465 /*
7466 * If we went all the way back to the start of our scope, line
7467 * up with it.
7468 */
7469 if (curwin->w_cursor.lnum <= ourscope)
7470 {
7471 /* we reached end of scope:
7472 * if looking for a enum or structure initialization
7473 * go further back:
7474 * if it is an initializer (enum xxx or xxx =), then
7475 * don't add ind_continuation, otherwise it is a variable
7476 * declaration:
7477 * int x,
7478 * here; <-- add ind_continuation
7479 */
7480 if (lookfor == LOOKFOR_ENUM_OR_INIT)
7481 {
7482 if (curwin->w_cursor.lnum == 0
7483 || curwin->w_cursor.lnum
7484 < ourscope - ind_maxparen)
7485 {
7486 /* nothing found (abuse ind_maxparen as limit)
7487 * assume terminated line (i.e. a variable
7488 * initialization) */
7489 if (cont_amount > 0)
7490 amount = cont_amount;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007491 else if (!ind_js)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007492 amount += ind_continuation;
7493 break;
7494 }
7495
7496 l = ml_get_curline();
7497
7498 /*
7499 * If we're in a comment now, skip to the start of the
7500 * comment.
7501 */
7502 trypos = find_start_comment(ind_maxcomment);
7503 if (trypos != NULL)
7504 {
7505 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007506 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007507 continue;
7508 }
7509
7510 /*
7511 * Skip preprocessor directives and blank lines.
7512 */
7513 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7514 continue;
7515
7516 if (cin_nocode(l))
7517 continue;
7518
7519 terminated = cin_isterminated(l, FALSE, TRUE);
7520
7521 /*
7522 * If we are at top level and the line looks like a
7523 * function declaration, we are done
7524 * (it's a variable declaration).
7525 */
7526 if (start_brace != BRACE_IN_COL0
Bram Moolenaarc367faa2011-12-14 20:21:35 +01007527 || !cin_isfuncdecl(&l, curwin->w_cursor.lnum,
7528 0, ind_maxparen, ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007529 {
7530 /* if the line is terminated with another ','
7531 * it is a continued variable initialization.
7532 * don't add extra indent.
7533 * TODO: does not work, if a function
7534 * declaration is split over multiple lines:
7535 * cin_isfuncdecl returns FALSE then.
7536 */
7537 if (terminated == ',')
7538 break;
7539
7540 /* if it es a enum declaration or an assignment,
7541 * we are done.
7542 */
7543 if (terminated != ';' && cin_isinit())
7544 break;
7545
7546 /* nothing useful found */
7547 if (terminated == 0 || terminated == '{')
7548 continue;
7549 }
7550
7551 if (terminated != ';')
7552 {
7553 /* Skip parens and braces. Position the cursor
7554 * over the rightmost paren, so that matching it
7555 * will take us back to the start of the line.
7556 */ /* XXX */
7557 trypos = NULL;
7558 if (find_last_paren(l, '(', ')'))
7559 trypos = find_match_paren(ind_maxparen,
7560 ind_maxcomment);
7561
7562 if (trypos == NULL && find_last_paren(l, '{', '}'))
7563 trypos = find_start_brace(ind_maxcomment);
7564
7565 if (trypos != NULL)
7566 {
7567 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007568 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007569 continue;
7570 }
7571 }
7572
7573 /* it's a variable declaration, add indentation
7574 * like in
7575 * int a,
7576 * b;
7577 */
7578 if (cont_amount > 0)
7579 amount = cont_amount;
7580 else
7581 amount += ind_continuation;
7582 }
7583 else if (lookfor == LOOKFOR_UNTERM)
7584 {
7585 if (cont_amount > 0)
7586 amount = cont_amount;
7587 else
7588 amount += ind_continuation;
7589 }
Bram Moolenaare79d1532011-10-04 18:03:47 +02007590 else
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007591 {
Bram Moolenaare79d1532011-10-04 18:03:47 +02007592 if (lookfor != LOOKFOR_TERM
Bram Moolenaar071d4272004-06-13 20:20:40 +00007593 && lookfor != LOOKFOR_CPP_BASECLASS)
Bram Moolenaare79d1532011-10-04 18:03:47 +02007594 {
7595 amount = scope_amount;
7596 if (theline[0] == '{')
7597 {
7598 amount += ind_open_extra;
7599 added_to_amount = ind_open_extra;
7600 }
7601 }
7602
7603 if (lookfor_cpp_namespace)
7604 {
7605 /*
7606 * Looking for C++ namespace, need to look further
7607 * back.
7608 */
7609 if (curwin->w_cursor.lnum == ourscope)
7610 continue;
7611
7612 if (curwin->w_cursor.lnum == 0
7613 || curwin->w_cursor.lnum
7614 < ourscope - FIND_NAMESPACE_LIM)
7615 break;
7616
7617 l = ml_get_curline();
7618
7619 /* If we're in a comment now, skip to the start of
7620 * the comment. */
7621 trypos = find_start_comment(ind_maxcomment);
7622 if (trypos != NULL)
7623 {
7624 curwin->w_cursor.lnum = trypos->lnum + 1;
7625 curwin->w_cursor.col = 0;
7626 continue;
7627 }
7628
7629 /* Skip preprocessor directives and blank lines. */
7630 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7631 continue;
7632
7633 /* Finally the actual check for "namespace". */
7634 if (cin_is_cpp_namespace(l))
7635 {
7636 amount += ind_cpp_namespace - added_to_amount;
7637 break;
7638 }
7639
7640 if (cin_nocode(l))
7641 continue;
7642 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007643 }
7644 break;
7645 }
7646
7647 /*
7648 * If we're in a comment now, skip to the start of the comment.
7649 */ /* XXX */
7650 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
7651 {
7652 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007653 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007654 continue;
7655 }
7656
7657 l = ml_get_curline();
7658
7659 /*
7660 * If this is a switch() label, may line up relative to that.
Bram Moolenaar18144c82006-04-12 21:52:12 +00007661 * If this is a C++ scope declaration, do the same.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007662 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007663 iscase = cin_iscase(l, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007664 if (iscase || cin_isscopedecl(l))
7665 {
7666 /* we are only looking for cpp base class
7667 * declaration/initialization any longer */
7668 if (lookfor == LOOKFOR_CPP_BASECLASS)
7669 break;
7670
7671 /* When looking for a "do" we are not interested in
7672 * labels. */
7673 if (whilelevel > 0)
7674 continue;
7675
7676 /*
7677 * case xx:
7678 * c = 99 + <- this indent plus continuation
7679 *-> here;
7680 */
7681 if (lookfor == LOOKFOR_UNTERM
7682 || lookfor == LOOKFOR_ENUM_OR_INIT)
7683 {
7684 if (cont_amount > 0)
7685 amount = cont_amount;
7686 else
7687 amount += ind_continuation;
7688 break;
7689 }
7690
7691 /*
7692 * case xx: <- line up with this case
7693 * x = 333;
7694 * case yy:
7695 */
7696 if ( (iscase && lookfor == LOOKFOR_CASE)
7697 || (iscase && lookfor_break)
7698 || (!iscase && lookfor == LOOKFOR_SCOPEDECL))
7699 {
7700 /*
7701 * Check that this case label is not for another
7702 * switch()
7703 */ /* XXX */
7704 if ((trypos = find_start_brace(ind_maxcomment)) ==
7705 NULL || trypos->lnum == ourscope)
7706 {
7707 amount = get_indent(); /* XXX */
7708 break;
7709 }
7710 continue;
7711 }
7712
7713 n = get_indent_nolabel(curwin->w_cursor.lnum); /* XXX */
7714
7715 /*
7716 * case xx: if (cond) <- line up with this if
7717 * y = y + 1;
7718 * -> s = 99;
7719 *
7720 * case xx:
7721 * if (cond) <- line up with this line
7722 * y = y + 1;
7723 * -> s = 99;
7724 */
7725 if (lookfor == LOOKFOR_TERM)
7726 {
7727 if (n)
7728 amount = n;
7729
7730 if (!lookfor_break)
7731 break;
7732 }
7733
7734 /*
7735 * case xx: x = x + 1; <- line up with this x
7736 * -> y = y + 1;
7737 *
7738 * case xx: if (cond) <- line up with this if
7739 * -> y = y + 1;
7740 */
7741 if (n)
7742 {
7743 amount = n;
7744 l = after_label(ml_get_curline());
7745 if (l != NULL && cin_is_cinword(l))
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007746 {
7747 if (theline[0] == '{')
7748 amount += ind_open_extra;
7749 else
7750 amount += ind_level + ind_no_brace;
7751 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007752 break;
7753 }
7754
7755 /*
7756 * Try to get the indent of a statement before the switch
7757 * label. If nothing is found, line up relative to the
7758 * switch label.
7759 * break; <- may line up with this line
7760 * case xx:
7761 * -> y = 1;
7762 */
7763 scope_amount = get_indent() + (iscase /* XXX */
7764 ? ind_case_code : ind_scopedecl_code);
7765 lookfor = ind_case_break ? LOOKFOR_NOBREAK : LOOKFOR_ANY;
7766 continue;
7767 }
7768
7769 /*
7770 * Looking for a switch() label or C++ scope declaration,
7771 * ignore other lines, skip {}-blocks.
7772 */
7773 if (lookfor == LOOKFOR_CASE || lookfor == LOOKFOR_SCOPEDECL)
7774 {
7775 if (find_last_paren(l, '{', '}') && (trypos =
7776 find_start_brace(ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007777 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007778 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007779 curwin->w_cursor.col = 0;
7780 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007781 continue;
7782 }
7783
7784 /*
7785 * Ignore jump labels with nothing after them.
7786 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007787 if (!ind_js && cin_islabel(ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007788 {
7789 l = after_label(ml_get_curline());
7790 if (l == NULL || cin_nocode(l))
7791 continue;
7792 }
7793
7794 /*
7795 * Ignore #defines, #if, etc.
7796 * Ignore comment and empty lines.
7797 * (need to get the line again, cin_islabel() may have
7798 * unlocked it)
7799 */
7800 l = ml_get_curline();
7801 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum)
7802 || cin_nocode(l))
7803 continue;
7804
7805 /*
7806 * Are we at the start of a cpp base class declaration or
7807 * constructor initialization?
7808 */ /* XXX */
Bram Moolenaar18144c82006-04-12 21:52:12 +00007809 n = FALSE;
7810 if (lookfor != LOOKFOR_TERM && ind_cpp_baseclass > 0)
7811 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00007812 n = cin_is_cpp_baseclass(&col);
Bram Moolenaar18144c82006-04-12 21:52:12 +00007813 l = ml_get_curline();
7814 }
7815 if (n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007816 {
7817 if (lookfor == LOOKFOR_UNTERM)
7818 {
7819 if (cont_amount > 0)
7820 amount = cont_amount;
7821 else
7822 amount += ind_continuation;
7823 }
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007824 else if (theline[0] == '{')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007825 {
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007826 /* Need to find start of the declaration. */
7827 lookfor = LOOKFOR_UNTERM;
7828 ind_continuation = 0;
7829 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007830 }
7831 else
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007832 /* XXX */
7833 amount = get_baseclass_amount(col, ind_maxparen,
7834 ind_maxcomment, ind_cpp_baseclass);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007835 break;
7836 }
7837 else if (lookfor == LOOKFOR_CPP_BASECLASS)
7838 {
7839 /* only look, whether there is a cpp base class
Bram Moolenaar18144c82006-04-12 21:52:12 +00007840 * declaration or initialization before the opening brace.
7841 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007842 if (cin_isterminated(l, TRUE, FALSE))
7843 break;
7844 else
7845 continue;
7846 }
7847
7848 /*
7849 * What happens next depends on the line being terminated.
7850 * If terminated with a ',' only consider it terminating if
Bram Moolenaar25394022007-05-10 19:06:20 +00007851 * there is another unterminated statement behind, eg:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007852 * 123,
7853 * sizeof
7854 * here
7855 * Otherwise check whether it is a enumeration or structure
7856 * initialisation (not indented) or a variable declaration
7857 * (indented).
7858 */
7859 terminated = cin_isterminated(l, FALSE, TRUE);
7860
7861 if (terminated == 0 || (lookfor != LOOKFOR_UNTERM
7862 && terminated == ','))
7863 {
7864 /*
7865 * if we're in the middle of a paren thing,
7866 * go back to the line that starts it so
7867 * we can get the right prevailing indent
7868 * if ( foo &&
7869 * bar )
7870 */
7871 /*
7872 * position the cursor over the rightmost paren, so that
7873 * matching it will take us back to the start of the line.
7874 */
7875 (void)find_last_paren(l, '(', ')');
7876 trypos = find_match_paren(
7877 corr_ind_maxparen(ind_maxparen, &cur_curpos),
7878 ind_maxcomment);
7879
7880 /*
7881 * If we are looking for ',', we also look for matching
7882 * braces.
7883 */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007884 if (trypos == NULL && terminated == ','
7885 && find_last_paren(l, '{', '}'))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007886 trypos = find_start_brace(ind_maxcomment);
7887
7888 if (trypos != NULL)
7889 {
7890 /*
7891 * Check if we are on a case label now. This is
7892 * handled above.
7893 * case xx: if ( asdf &&
7894 * asdf)
7895 */
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007896 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007897 l = ml_get_curline();
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007898 if (cin_iscase(l, FALSE) || cin_isscopedecl(l))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007899 {
7900 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007901 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007902 continue;
7903 }
7904 }
7905
7906 /*
7907 * Skip over continuation lines to find the one to get the
7908 * indent from
7909 * char *usethis = "bla\
7910 * bla",
7911 * here;
7912 */
7913 if (terminated == ',')
7914 {
7915 while (curwin->w_cursor.lnum > 1)
7916 {
7917 l = ml_get(curwin->w_cursor.lnum - 1);
7918 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
7919 break;
7920 --curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007921 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007922 }
7923 }
7924
7925 /*
7926 * Get indent and pointer to text for current line,
7927 * ignoring any jump label. XXX
7928 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007929 if (!ind_js)
7930 cur_amount = skip_label(curwin->w_cursor.lnum,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007931 &l, ind_maxcomment);
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007932 else
7933 cur_amount = get_indent();
Bram Moolenaar071d4272004-06-13 20:20:40 +00007934 /*
7935 * If this is just above the line we are indenting, and it
7936 * starts with a '{', line it up with this line.
7937 * while (not)
7938 * -> {
7939 * }
7940 */
7941 if (terminated != ',' && lookfor != LOOKFOR_TERM
7942 && theline[0] == '{')
7943 {
7944 amount = cur_amount;
7945 /*
7946 * Only add ind_open_extra when the current line
7947 * doesn't start with a '{', which must have a match
7948 * in the same line (scope is the same). Probably:
7949 * { 1, 2 },
7950 * -> { 3, 4 }
7951 */
7952 if (*skipwhite(l) != '{')
7953 amount += ind_open_extra;
7954
7955 if (ind_cpp_baseclass)
7956 {
7957 /* have to look back, whether it is a cpp base
7958 * class declaration or initialization */
7959 lookfor = LOOKFOR_CPP_BASECLASS;
7960 continue;
7961 }
7962 break;
7963 }
7964
7965 /*
7966 * Check if we are after an "if", "while", etc.
7967 * Also allow " } else".
7968 */
7969 if (cin_is_cinword(l) || cin_iselse(skipwhite(l)))
7970 {
7971 /*
7972 * Found an unterminated line after an if (), line up
7973 * with the last one.
7974 * if (cond)
7975 * 100 +
7976 * -> here;
7977 */
7978 if (lookfor == LOOKFOR_UNTERM
7979 || lookfor == LOOKFOR_ENUM_OR_INIT)
7980 {
7981 if (cont_amount > 0)
7982 amount = cont_amount;
7983 else
7984 amount += ind_continuation;
7985 break;
7986 }
7987
7988 /*
7989 * If this is just above the line we are indenting, we
7990 * are finished.
7991 * while (not)
7992 * -> here;
7993 * Otherwise this indent can be used when the line
7994 * before this is terminated.
7995 * yyy;
7996 * if (stat)
7997 * while (not)
7998 * xxx;
7999 * -> here;
8000 */
8001 amount = cur_amount;
8002 if (theline[0] == '{')
8003 amount += ind_open_extra;
8004 if (lookfor != LOOKFOR_TERM)
8005 {
8006 amount += ind_level + ind_no_brace;
8007 break;
8008 }
8009
8010 /*
8011 * Special trick: when expecting the while () after a
8012 * do, line up with the while()
8013 * do
8014 * x = 1;
8015 * -> here
8016 */
8017 l = skipwhite(ml_get_curline());
8018 if (cin_isdo(l))
8019 {
8020 if (whilelevel == 0)
8021 break;
8022 --whilelevel;
8023 }
8024
8025 /*
8026 * When searching for a terminated line, don't use the
Bram Moolenaar334adf02011-05-25 13:34:04 +02008027 * one between the "if" and the matching "else".
Bram Moolenaar071d4272004-06-13 20:20:40 +00008028 * Need to use the scope of this "else". XXX
8029 * If whilelevel != 0 continue looking for a "do {".
8030 */
Bram Moolenaar334adf02011-05-25 13:34:04 +02008031 if (cin_iselse(l) && whilelevel == 0)
8032 {
8033 /* If we're looking at "} else", let's make sure we
8034 * find the opening brace of the enclosing scope,
8035 * not the one from "if () {". */
8036 if (*l == '}')
8037 curwin->w_cursor.col =
Bram Moolenaar9b83c2f2011-05-25 17:29:44 +02008038 (colnr_T)(l - ml_get_curline()) + 1;
Bram Moolenaar334adf02011-05-25 13:34:04 +02008039
8040 if ((trypos = find_start_brace(ind_maxcomment))
8041 == NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00008042 || find_match(LOOKFOR_IF, trypos->lnum,
Bram Moolenaar334adf02011-05-25 13:34:04 +02008043 ind_maxparen, ind_maxcomment) == FAIL)
8044 break;
8045 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008046 }
8047
8048 /*
8049 * If we're below an unterminated line that is not an
8050 * "if" or something, we may line up with this line or
Bram Moolenaar25394022007-05-10 19:06:20 +00008051 * add something for a continuation line, depending on
Bram Moolenaar071d4272004-06-13 20:20:40 +00008052 * the line before this one.
8053 */
8054 else
8055 {
8056 /*
8057 * Found two unterminated lines on a row, line up with
8058 * the last one.
8059 * c = 99 +
8060 * 100 +
8061 * -> here;
8062 */
8063 if (lookfor == LOOKFOR_UNTERM)
8064 {
8065 /* When line ends in a comma add extra indent */
8066 if (terminated == ',')
8067 amount += ind_continuation;
8068 break;
8069 }
8070
8071 if (lookfor == LOOKFOR_ENUM_OR_INIT)
8072 {
8073 /* Found two lines ending in ',', lineup with the
8074 * lowest one, but check for cpp base class
8075 * declaration/initialization, if it is an
8076 * opening brace or we are looking just for
8077 * enumerations/initializations. */
8078 if (terminated == ',')
8079 {
8080 if (ind_cpp_baseclass == 0)
8081 break;
8082
8083 lookfor = LOOKFOR_CPP_BASECLASS;
8084 continue;
8085 }
8086
8087 /* Ignore unterminated lines in between, but
8088 * reduce indent. */
8089 if (amount > cur_amount)
8090 amount = cur_amount;
8091 }
8092 else
8093 {
8094 /*
8095 * Found first unterminated line on a row, may
8096 * line up with this line, remember its indent
8097 * 100 +
8098 * -> here;
8099 */
8100 amount = cur_amount;
8101
8102 /*
8103 * If previous line ends in ',', check whether we
8104 * are in an initialization or enum
8105 * struct xxx =
8106 * {
8107 * sizeof a,
8108 * 124 };
8109 * or a normal possible continuation line.
8110 * but only, of no other statement has been found
8111 * yet.
8112 */
8113 if (lookfor == LOOKFOR_INITIAL && terminated == ',')
8114 {
8115 lookfor = LOOKFOR_ENUM_OR_INIT;
8116 cont_amount = cin_first_id_amount();
8117 }
8118 else
8119 {
8120 if (lookfor == LOOKFOR_INITIAL
8121 && *l != NUL
8122 && l[STRLEN(l) - 1] == '\\')
8123 /* XXX */
8124 cont_amount = cin_get_equal_amount(
8125 curwin->w_cursor.lnum);
8126 if (lookfor != LOOKFOR_TERM)
8127 lookfor = LOOKFOR_UNTERM;
8128 }
8129 }
8130 }
8131 }
8132
8133 /*
8134 * Check if we are after a while (cond);
8135 * If so: Ignore until the matching "do".
8136 */
8137 /* XXX */
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00008138 else if (cin_iswhileofdo_end(terminated, ind_maxparen,
8139 ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008140 {
8141 /*
8142 * Found an unterminated line after a while ();, line up
8143 * with the last one.
8144 * while (cond);
8145 * 100 + <- line up with this one
8146 * -> here;
8147 */
8148 if (lookfor == LOOKFOR_UNTERM
8149 || lookfor == LOOKFOR_ENUM_OR_INIT)
8150 {
8151 if (cont_amount > 0)
8152 amount = cont_amount;
8153 else
8154 amount += ind_continuation;
8155 break;
8156 }
8157
8158 if (whilelevel == 0)
8159 {
8160 lookfor = LOOKFOR_TERM;
8161 amount = get_indent(); /* XXX */
8162 if (theline[0] == '{')
8163 amount += ind_open_extra;
8164 }
8165 ++whilelevel;
8166 }
8167
8168 /*
8169 * We are after a "normal" statement.
8170 * If we had another statement we can stop now and use the
8171 * indent of that other statement.
8172 * Otherwise the indent of the current statement may be used,
8173 * search backwards for the next "normal" statement.
8174 */
8175 else
8176 {
8177 /*
8178 * Skip single break line, if before a switch label. It
8179 * may be lined up with the case label.
8180 */
8181 if (lookfor == LOOKFOR_NOBREAK
8182 && cin_isbreak(skipwhite(ml_get_curline())))
8183 {
8184 lookfor = LOOKFOR_ANY;
8185 continue;
8186 }
8187
8188 /*
8189 * Handle "do {" line.
8190 */
8191 if (whilelevel > 0)
8192 {
8193 l = cin_skipcomment(ml_get_curline());
8194 if (cin_isdo(l))
8195 {
8196 amount = get_indent(); /* XXX */
8197 --whilelevel;
8198 continue;
8199 }
8200 }
8201
8202 /*
8203 * Found a terminated line above an unterminated line. Add
8204 * the amount for a continuation line.
8205 * x = 1;
8206 * y = foo +
8207 * -> here;
8208 * or
8209 * int x = 1;
8210 * int foo,
8211 * -> here;
8212 */
8213 if (lookfor == LOOKFOR_UNTERM
8214 || lookfor == LOOKFOR_ENUM_OR_INIT)
8215 {
8216 if (cont_amount > 0)
8217 amount = cont_amount;
8218 else
8219 amount += ind_continuation;
8220 break;
8221 }
8222
8223 /*
8224 * Found a terminated line above a terminated line or "if"
8225 * etc. line. Use the amount of the line below us.
8226 * x = 1; x = 1;
8227 * if (asdf) y = 2;
8228 * while (asdf) ->here;
8229 * here;
8230 * ->foo;
8231 */
8232 if (lookfor == LOOKFOR_TERM)
8233 {
8234 if (!lookfor_break && whilelevel == 0)
8235 break;
8236 }
8237
8238 /*
8239 * First line above the one we're indenting is terminated.
8240 * To know what needs to be done look further backward for
8241 * a terminated line.
8242 */
8243 else
8244 {
8245 /*
8246 * position the cursor over the rightmost paren, so
8247 * that matching it will take us back to the start of
8248 * the line. Helps for:
8249 * func(asdr,
8250 * asdfasdf);
8251 * here;
8252 */
8253term_again:
8254 l = ml_get_curline();
8255 if (find_last_paren(l, '(', ')')
8256 && (trypos = find_match_paren(ind_maxparen,
8257 ind_maxcomment)) != NULL)
8258 {
8259 /*
8260 * Check if we are on a case label now. This is
8261 * handled above.
8262 * case xx: if ( asdf &&
8263 * asdf)
8264 */
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008265 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008266 l = ml_get_curline();
Bram Moolenaar3acfc302010-07-11 17:23:02 +02008267 if (cin_iscase(l, FALSE) || cin_isscopedecl(l))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008268 {
8269 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008270 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008271 continue;
8272 }
8273 }
8274
8275 /* When aligning with the case statement, don't align
8276 * with a statement after it.
8277 * case 1: { <-- don't use this { position
8278 * stat;
8279 * }
8280 * case 2:
8281 * stat;
8282 * }
8283 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02008284 iscase = (ind_keep_case_label && cin_iscase(l, FALSE));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008285
8286 /*
8287 * Get indent and pointer to text for current line,
8288 * ignoring any jump label.
8289 */
8290 amount = skip_label(curwin->w_cursor.lnum,
8291 &l, ind_maxcomment);
8292
8293 if (theline[0] == '{')
8294 amount += ind_open_extra;
8295 /* See remark above: "Only add ind_open_extra.." */
Bram Moolenaar18144c82006-04-12 21:52:12 +00008296 l = skipwhite(l);
8297 if (*l == '{')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008298 amount -= ind_open_extra;
8299 lookfor = iscase ? LOOKFOR_ANY : LOOKFOR_TERM;
8300
8301 /*
Bram Moolenaar18144c82006-04-12 21:52:12 +00008302 * When a terminated line starts with "else" skip to
8303 * the matching "if":
8304 * else 3;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008305 * indent this;
Bram Moolenaar18144c82006-04-12 21:52:12 +00008306 * Need to use the scope of this "else". XXX
8307 * If whilelevel != 0 continue looking for a "do {".
8308 */
8309 if (lookfor == LOOKFOR_TERM
8310 && *l != '}'
8311 && cin_iselse(l)
8312 && whilelevel == 0)
8313 {
8314 if ((trypos = find_start_brace(ind_maxcomment))
8315 == NULL
8316 || find_match(LOOKFOR_IF, trypos->lnum,
8317 ind_maxparen, ind_maxcomment) == FAIL)
8318 break;
8319 continue;
8320 }
8321
8322 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008323 * If we're at the end of a block, skip to the start of
8324 * that block.
8325 */
Bram Moolenaar6d8f9c62011-11-30 13:03:28 +01008326 l = ml_get_curline();
Bram Moolenaar50f42ca2011-07-15 14:12:30 +02008327 if (find_last_paren(l, '{', '}')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008328 && (trypos = find_start_brace(ind_maxcomment))
8329 != NULL) /* XXX */
8330 {
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008331 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008332 /* if not "else {" check for terminated again */
8333 /* but skip block for "} else {" */
8334 l = cin_skipcomment(ml_get_curline());
8335 if (*l == '}' || !cin_iselse(l))
8336 goto term_again;
8337 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008338 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008339 }
8340 }
8341 }
8342 }
8343 }
8344 }
8345
8346 /* add extra indent for a comment */
8347 if (cin_iscomment(theline))
8348 amount += ind_comment;
Bram Moolenaar02c707a2010-07-17 17:12:06 +02008349
8350 /* subtract extra left-shift for jump labels */
8351 if (ind_jump_label > 0 && original_line_islabel)
8352 amount -= ind_jump_label;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008353 }
8354
8355 /*
8356 * ok -- we're not inside any sort of structure at all!
8357 *
8358 * this means we're at the top level, and everything should
8359 * basically just match where the previous line is, except
8360 * for the lines immediately following a function declaration,
8361 * which are K&R-style parameters and need to be indented.
8362 */
8363 else
8364 {
8365 /*
8366 * if our line starts with an open brace, forget about any
8367 * prevailing indent and make sure it looks like the start
8368 * of a function
8369 */
8370
8371 if (theline[0] == '{')
8372 {
8373 amount = ind_first_open;
8374 }
8375
8376 /*
8377 * If the NEXT line is a function declaration, the current
8378 * line needs to be indented as a function type spec.
Bram Moolenaar1a89bbe2010-03-02 12:38:22 +01008379 * Don't do this if the current line looks like a comment or if the
8380 * current line is terminated, ie. ends in ';', or if the current line
8381 * contains { or }: "void f() {\n if (1)"
Bram Moolenaar071d4272004-06-13 20:20:40 +00008382 */
8383 else if (cur_curpos.lnum < curbuf->b_ml.ml_line_count
8384 && !cin_nocode(theline)
Bram Moolenaar1a89bbe2010-03-02 12:38:22 +01008385 && vim_strchr(theline, '{') == NULL
8386 && vim_strchr(theline, '}') == NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00008387 && !cin_ends_in(theline, (char_u *)":", NULL)
8388 && !cin_ends_in(theline, (char_u *)",", NULL)
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008389 && cin_isfuncdecl(NULL, cur_curpos.lnum + 1,
8390 cur_curpos.lnum + 1,
8391 ind_maxparen, ind_maxcomment)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008392 && !cin_isterminated(theline, FALSE, TRUE))
8393 {
8394 amount = ind_func_type;
8395 }
8396 else
8397 {
8398 amount = 0;
8399 curwin->w_cursor = cur_curpos;
8400
8401 /* search backwards until we find something we recognize */
8402
8403 while (curwin->w_cursor.lnum > 1)
8404 {
8405 curwin->w_cursor.lnum--;
8406 curwin->w_cursor.col = 0;
8407
8408 l = ml_get_curline();
8409
8410 /*
8411 * If we're in a comment now, skip to the start of the comment.
8412 */ /* XXX */
8413 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
8414 {
8415 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008416 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008417 continue;
8418 }
8419
8420 /*
Bram Moolenaar18144c82006-04-12 21:52:12 +00008421 * Are we at the start of a cpp base class declaration or
8422 * constructor initialization?
Bram Moolenaar071d4272004-06-13 20:20:40 +00008423 */ /* XXX */
Bram Moolenaar18144c82006-04-12 21:52:12 +00008424 n = FALSE;
8425 if (ind_cpp_baseclass != 0 && theline[0] != '{')
8426 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00008427 n = cin_is_cpp_baseclass(&col);
Bram Moolenaar18144c82006-04-12 21:52:12 +00008428 l = ml_get_curline();
8429 }
8430 if (n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008431 {
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00008432 /* XXX */
8433 amount = get_baseclass_amount(col, ind_maxparen,
8434 ind_maxcomment, ind_cpp_baseclass);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008435 break;
8436 }
8437
8438 /*
8439 * Skip preprocessor directives and blank lines.
8440 */
8441 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
8442 continue;
8443
8444 if (cin_nocode(l))
8445 continue;
8446
8447 /*
8448 * If the previous line ends in ',', use one level of
8449 * indentation:
8450 * int foo,
8451 * bar;
8452 * do this before checking for '}' in case of eg.
8453 * enum foobar
8454 * {
8455 * ...
8456 * } foo,
8457 * bar;
8458 */
8459 n = 0;
8460 if (cin_ends_in(l, (char_u *)",", NULL)
8461 || (*l != NUL && (n = l[STRLEN(l) - 1]) == '\\'))
8462 {
8463 /* take us back to opening paren */
8464 if (find_last_paren(l, '(', ')')
8465 && (trypos = find_match_paren(ind_maxparen,
8466 ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008467 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008468
8469 /* For a line ending in ',' that is a continuation line go
8470 * back to the first line with a backslash:
8471 * char *foo = "bla\
8472 * bla",
8473 * here;
8474 */
8475 while (n == 0 && curwin->w_cursor.lnum > 1)
8476 {
8477 l = ml_get(curwin->w_cursor.lnum - 1);
8478 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
8479 break;
8480 --curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008481 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008482 }
8483
8484 amount = get_indent(); /* XXX */
8485
8486 if (amount == 0)
8487 amount = cin_first_id_amount();
8488 if (amount == 0)
8489 amount = ind_continuation;
8490 break;
8491 }
8492
8493 /*
8494 * If the line looks like a function declaration, and we're
8495 * not in a comment, put it the left margin.
8496 */
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008497 if (cin_isfuncdecl(NULL, cur_curpos.lnum, 0,
8498 ind_maxparen, ind_maxcomment)) /* XXX */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008499 break;
8500 l = ml_get_curline();
8501
8502 /*
8503 * Finding the closing '}' of a previous function. Put
8504 * current line at the left margin. For when 'cino' has "fs".
8505 */
8506 if (*skipwhite(l) == '}')
8507 break;
8508
8509 /* (matching {)
8510 * If the previous line ends on '};' (maybe followed by
8511 * comments) align at column 0. For example:
8512 * char *string_array[] = { "foo",
8513 * / * x * / "b};ar" }; / * foobar * /
8514 */
8515 if (cin_ends_in(l, (char_u *)"};", NULL))
8516 break;
8517
8518 /*
Bram Moolenaar3388bb42011-11-30 17:20:23 +01008519 * Find a line only has a semicolon that belongs to a previous
8520 * line ending in '}', e.g. before an #endif. Don't increase
8521 * indent then.
8522 */
8523 if (*(look = skipwhite(l)) == ';' && cin_nocode(look + 1))
8524 {
8525 pos_T curpos_save = curwin->w_cursor;
8526
8527 while (curwin->w_cursor.lnum > 1)
8528 {
8529 look = ml_get(--curwin->w_cursor.lnum);
8530 if (!(cin_nocode(look) || cin_ispreproc_cont(
8531 &look, &curwin->w_cursor.lnum)))
8532 break;
8533 }
8534 if (curwin->w_cursor.lnum > 0
8535 && cin_ends_in(look, (char_u *)"}", NULL))
8536 break;
8537
8538 curwin->w_cursor = curpos_save;
8539 }
8540
8541 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008542 * If the PREVIOUS line is a function declaration, the current
8543 * line (and the ones that follow) needs to be indented as
8544 * parameters.
8545 */
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008546 if (cin_isfuncdecl(&l, curwin->w_cursor.lnum, 0,
8547 ind_maxparen, ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008548 {
8549 amount = ind_param;
8550 break;
8551 }
8552
8553 /*
8554 * If the previous line ends in ';' and the line before the
8555 * previous line ends in ',' or '\', ident to column zero:
8556 * int foo,
8557 * bar;
8558 * indent_to_0 here;
8559 */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00008560 if (cin_ends_in(l, (char_u *)";", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008561 {
8562 l = ml_get(curwin->w_cursor.lnum - 1);
8563 if (cin_ends_in(l, (char_u *)",", NULL)
8564 || (*l != NUL && l[STRLEN(l) - 1] == '\\'))
8565 break;
8566 l = ml_get_curline();
8567 }
8568
8569 /*
8570 * Doesn't look like anything interesting -- so just
8571 * use the indent of this line.
8572 *
8573 * Position the cursor over the rightmost paren, so that
8574 * matching it will take us back to the start of the line.
8575 */
8576 find_last_paren(l, '(', ')');
8577
8578 if ((trypos = find_match_paren(ind_maxparen,
8579 ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008580 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008581 amount = get_indent(); /* XXX */
8582 break;
8583 }
8584
8585 /* add extra indent for a comment */
8586 if (cin_iscomment(theline))
8587 amount += ind_comment;
8588
8589 /* add extra indent if the previous line ended in a backslash:
8590 * "asdfasdf\
8591 * here";
8592 * char *foo = "asdf\
8593 * here";
8594 */
8595 if (cur_curpos.lnum > 1)
8596 {
8597 l = ml_get(cur_curpos.lnum - 1);
8598 if (*l != NUL && l[STRLEN(l) - 1] == '\\')
8599 {
8600 cur_amount = cin_get_equal_amount(cur_curpos.lnum - 1);
8601 if (cur_amount > 0)
8602 amount = cur_amount;
8603 else if (cur_amount == 0)
8604 amount += ind_continuation;
8605 }
8606 }
8607 }
8608 }
8609
8610theend:
8611 /* put the cursor back where it belongs */
8612 curwin->w_cursor = cur_curpos;
8613
8614 vim_free(linecopy);
8615
8616 if (amount < 0)
8617 return 0;
8618 return amount;
8619}
8620
8621 static int
8622find_match(lookfor, ourscope, ind_maxparen, ind_maxcomment)
8623 int lookfor;
8624 linenr_T ourscope;
8625 int ind_maxparen;
8626 int ind_maxcomment;
8627{
8628 char_u *look;
8629 pos_T *theirscope;
8630 char_u *mightbeif;
8631 int elselevel;
8632 int whilelevel;
8633
8634 if (lookfor == LOOKFOR_IF)
8635 {
8636 elselevel = 1;
8637 whilelevel = 0;
8638 }
8639 else
8640 {
8641 elselevel = 0;
8642 whilelevel = 1;
8643 }
8644
8645 curwin->w_cursor.col = 0;
8646
8647 while (curwin->w_cursor.lnum > ourscope + 1)
8648 {
8649 curwin->w_cursor.lnum--;
8650 curwin->w_cursor.col = 0;
8651
8652 look = cin_skipcomment(ml_get_curline());
8653 if (cin_iselse(look)
8654 || cin_isif(look)
8655 || cin_isdo(look) /* XXX */
8656 || cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
8657 {
8658 /*
8659 * if we've gone outside the braces entirely,
8660 * we must be out of scope...
8661 */
8662 theirscope = find_start_brace(ind_maxcomment); /* XXX */
8663 if (theirscope == NULL)
8664 break;
8665
8666 /*
8667 * and if the brace enclosing this is further
8668 * back than the one enclosing the else, we're
8669 * out of luck too.
8670 */
8671 if (theirscope->lnum < ourscope)
8672 break;
8673
8674 /*
8675 * and if they're enclosed in a *deeper* brace,
8676 * then we can ignore it because it's in a
8677 * different scope...
8678 */
8679 if (theirscope->lnum > ourscope)
8680 continue;
8681
8682 /*
8683 * if it was an "else" (that's not an "else if")
8684 * then we need to go back to another if, so
8685 * increment elselevel
8686 */
8687 look = cin_skipcomment(ml_get_curline());
8688 if (cin_iselse(look))
8689 {
8690 mightbeif = cin_skipcomment(look + 4);
8691 if (!cin_isif(mightbeif))
8692 ++elselevel;
8693 continue;
8694 }
8695
8696 /*
8697 * if it was a "while" then we need to go back to
8698 * another "do", so increment whilelevel. XXX
8699 */
8700 if (cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
8701 {
8702 ++whilelevel;
8703 continue;
8704 }
8705
8706 /* If it's an "if" decrement elselevel */
8707 look = cin_skipcomment(ml_get_curline());
8708 if (cin_isif(look))
8709 {
8710 elselevel--;
8711 /*
8712 * When looking for an "if" ignore "while"s that
8713 * get in the way.
8714 */
8715 if (elselevel == 0 && lookfor == LOOKFOR_IF)
8716 whilelevel = 0;
8717 }
8718
8719 /* If it's a "do" decrement whilelevel */
8720 if (cin_isdo(look))
8721 whilelevel--;
8722
8723 /*
8724 * if we've used up all the elses, then
8725 * this must be the if that we want!
8726 * match the indent level of that if.
8727 */
8728 if (elselevel <= 0 && whilelevel <= 0)
8729 {
8730 return OK;
8731 }
8732 }
8733 }
8734 return FAIL;
8735}
8736
8737# if defined(FEAT_EVAL) || defined(PROTO)
8738/*
8739 * Get indent level from 'indentexpr'.
8740 */
8741 int
8742get_expr_indent()
8743{
8744 int indent;
8745 pos_T pos;
8746 int save_State;
Bram Moolenaard1f56e62006-02-22 21:25:37 +00008747 int use_sandbox = was_set_insecurely((char_u *)"indentexpr",
8748 OPT_LOCAL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008749
8750 pos = curwin->w_cursor;
8751 set_vim_var_nr(VV_LNUM, curwin->w_cursor.lnum);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00008752 if (use_sandbox)
8753 ++sandbox;
8754 ++textlock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008755 indent = eval_to_number(curbuf->b_p_inde);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00008756 if (use_sandbox)
8757 --sandbox;
8758 --textlock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008759
8760 /* Restore the cursor position so that 'indentexpr' doesn't need to.
8761 * Pretend to be in Insert mode, allow cursor past end of line for "o"
8762 * command. */
8763 save_State = State;
8764 State = INSERT;
8765 curwin->w_cursor = pos;
8766 check_cursor();
8767 State = save_State;
8768
8769 /* If there is an error, just keep the current indent. */
8770 if (indent < 0)
8771 indent = get_indent();
8772
8773 return indent;
8774}
8775# endif
8776
8777#endif /* FEAT_CINDENT */
8778
8779#if defined(FEAT_LISP) || defined(PROTO)
8780
8781static int lisp_match __ARGS((char_u *p));
8782
8783 static int
8784lisp_match(p)
8785 char_u *p;
8786{
8787 char_u buf[LSIZE];
8788 int len;
8789 char_u *word = p_lispwords;
8790
8791 while (*word != NUL)
8792 {
8793 (void)copy_option_part(&word, buf, LSIZE, ",");
8794 len = (int)STRLEN(buf);
8795 if (STRNCMP(buf, p, len) == 0 && p[len] == ' ')
8796 return TRUE;
8797 }
8798 return FALSE;
8799}
8800
8801/*
8802 * When 'p' is present in 'cpoptions, a Vi compatible method is used.
8803 * The incompatible newer method is quite a bit better at indenting
8804 * code in lisp-like languages than the traditional one; it's still
8805 * mostly heuristics however -- Dirk van Deun, dirk@rave.org
8806 *
8807 * TODO:
8808 * Findmatch() should be adapted for lisp, also to make showmatch
8809 * work correctly: now (v5.3) it seems all C/C++ oriented:
8810 * - it does not recognize the #\( and #\) notations as character literals
8811 * - it doesn't know about comments starting with a semicolon
8812 * - it incorrectly interprets '(' as a character literal
8813 * All this messes up get_lisp_indent in some rare cases.
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008814 * Update from Sergey Khorev:
8815 * I tried to fix the first two issues.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008816 */
8817 int
8818get_lisp_indent()
8819{
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008820 pos_T *pos, realpos, paren;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008821 int amount;
8822 char_u *that;
8823 colnr_T col;
8824 colnr_T firsttry;
8825 int parencount, quotecount;
8826 int vi_lisp;
8827
8828 /* Set vi_lisp to use the vi-compatible method */
8829 vi_lisp = (vim_strchr(p_cpo, CPO_LISP) != NULL);
8830
8831 realpos = curwin->w_cursor;
8832 curwin->w_cursor.col = 0;
8833
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008834 if ((pos = findmatch(NULL, '(')) == NULL)
8835 pos = findmatch(NULL, '[');
8836 else
8837 {
8838 paren = *pos;
8839 pos = findmatch(NULL, '[');
8840 if (pos == NULL || ltp(pos, &paren))
8841 pos = &paren;
8842 }
8843 if (pos != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008844 {
8845 /* Extra trick: Take the indent of the first previous non-white
8846 * line that is at the same () level. */
8847 amount = -1;
8848 parencount = 0;
8849
8850 while (--curwin->w_cursor.lnum >= pos->lnum)
8851 {
8852 if (linewhite(curwin->w_cursor.lnum))
8853 continue;
8854 for (that = ml_get_curline(); *that != NUL; ++that)
8855 {
8856 if (*that == ';')
8857 {
8858 while (*(that + 1) != NUL)
8859 ++that;
8860 continue;
8861 }
8862 if (*that == '\\')
8863 {
8864 if (*(that + 1) != NUL)
8865 ++that;
8866 continue;
8867 }
8868 if (*that == '"' && *(that + 1) != NUL)
8869 {
Bram Moolenaar15ff6c12006-09-15 18:18:09 +00008870 while (*++that && *that != '"')
8871 {
8872 /* skipping escaped characters in the string */
8873 if (*that == '\\')
8874 {
8875 if (*++that == NUL)
8876 break;
8877 if (that[1] == NUL)
8878 {
8879 ++that;
8880 break;
8881 }
8882 }
8883 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008884 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008885 if (*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008886 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008887 else if (*that == ')' || *that == ']')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008888 --parencount;
8889 }
8890 if (parencount == 0)
8891 {
8892 amount = get_indent();
8893 break;
8894 }
8895 }
8896
8897 if (amount == -1)
8898 {
8899 curwin->w_cursor.lnum = pos->lnum;
8900 curwin->w_cursor.col = pos->col;
8901 col = pos->col;
8902
8903 that = ml_get_curline();
8904
8905 if (vi_lisp && get_indent() == 0)
8906 amount = 2;
8907 else
8908 {
8909 amount = 0;
8910 while (*that && col)
8911 {
8912 amount += lbr_chartabsize_adv(&that, (colnr_T)amount);
8913 col--;
8914 }
8915
8916 /*
8917 * Some keywords require "body" indenting rules (the
8918 * non-standard-lisp ones are Scheme special forms):
8919 *
8920 * (let ((a 1)) instead (let ((a 1))
8921 * (...)) of (...))
8922 */
8923
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008924 if (!vi_lisp && (*that == '(' || *that == '[')
8925 && lisp_match(that + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008926 amount += 2;
8927 else
8928 {
8929 that++;
8930 amount++;
8931 firsttry = amount;
8932
8933 while (vim_iswhite(*that))
8934 {
8935 amount += lbr_chartabsize(that, (colnr_T)amount);
8936 ++that;
8937 }
8938
8939 if (*that && *that != ';') /* not a comment line */
8940 {
Bram Moolenaare21877a2008-02-13 09:58:14 +00008941 /* test *that != '(' to accommodate first let/do
Bram Moolenaar071d4272004-06-13 20:20:40 +00008942 * argument if it is more than one line */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008943 if (!vi_lisp && *that != '(' && *that != '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008944 firsttry++;
8945
8946 parencount = 0;
8947 quotecount = 0;
8948
8949 if (vi_lisp
8950 || (*that != '"'
8951 && *that != '\''
8952 && *that != '#'
8953 && (*that < '0' || *that > '9')))
8954 {
8955 while (*that
8956 && (!vim_iswhite(*that)
8957 || quotecount
8958 || parencount)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008959 && (!((*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008960 && !quotecount
8961 && !parencount
8962 && vi_lisp)))
8963 {
8964 if (*that == '"')
8965 quotecount = !quotecount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008966 if ((*that == '(' || *that == '[')
8967 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008968 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008969 if ((*that == ')' || *that == ']')
8970 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008971 --parencount;
8972 if (*that == '\\' && *(that+1) != NUL)
8973 amount += lbr_chartabsize_adv(&that,
8974 (colnr_T)amount);
8975 amount += lbr_chartabsize_adv(&that,
8976 (colnr_T)amount);
8977 }
8978 }
8979 while (vim_iswhite(*that))
8980 {
8981 amount += lbr_chartabsize(that, (colnr_T)amount);
8982 that++;
8983 }
8984 if (!*that || *that == ';')
8985 amount = firsttry;
8986 }
8987 }
8988 }
8989 }
8990 }
8991 else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008992 amount = 0; /* no matching '(' or '[' found, use zero indent */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008993
8994 curwin->w_cursor = realpos;
8995
8996 return amount;
8997}
8998#endif /* FEAT_LISP */
8999
9000 void
9001prepare_to_exit()
9002{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00009003#if defined(SIGHUP) && defined(SIG_IGN)
9004 /* Ignore SIGHUP, because a dropped connection causes a read error, which
9005 * makes Vim exit and then handling SIGHUP causes various reentrance
9006 * problems. */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00009007 signal(SIGHUP, SIG_IGN);
9008#endif
9009
Bram Moolenaar071d4272004-06-13 20:20:40 +00009010#ifdef FEAT_GUI
9011 if (gui.in_use)
9012 {
9013 gui.dying = TRUE;
9014 out_trash(); /* trash any pending output */
9015 }
9016 else
9017#endif
9018 {
9019 windgoto((int)Rows - 1, 0);
9020
9021 /*
9022 * Switch terminal mode back now, so messages end up on the "normal"
9023 * screen (if there are two screens).
9024 */
9025 settmode(TMODE_COOK);
9026#ifdef WIN3264
9027 if (can_end_termcap_mode(FALSE) == TRUE)
9028#endif
9029 stoptermcap();
9030 out_flush();
9031 }
9032}
9033
9034/*
9035 * Preserve files and exit.
9036 * When called IObuff must contain a message.
9037 */
9038 void
9039preserve_exit()
9040{
9041 buf_T *buf;
9042
9043 prepare_to_exit();
9044
Bram Moolenaar4770d092006-01-12 23:22:24 +00009045 /* Setting this will prevent free() calls. That avoids calling free()
9046 * recursively when free() was invoked with a bad pointer. */
9047 really_exiting = TRUE;
9048
Bram Moolenaar071d4272004-06-13 20:20:40 +00009049 out_str(IObuff);
9050 screen_start(); /* don't know where cursor is now */
9051 out_flush();
9052
9053 ml_close_notmod(); /* close all not-modified buffers */
9054
9055 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
9056 {
9057 if (buf->b_ml.ml_mfp != NULL && buf->b_ml.ml_mfp->mf_fname != NULL)
9058 {
9059 OUT_STR(_("Vim: preserving files...\n"));
9060 screen_start(); /* don't know where cursor is now */
9061 out_flush();
9062 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
9063 break;
9064 }
9065 }
9066
9067 ml_close_all(FALSE); /* close all memfiles, without deleting */
9068
9069 OUT_STR(_("Vim: Finished.\n"));
9070
9071 getout(1);
9072}
9073
9074/*
9075 * return TRUE if "fname" exists.
9076 */
9077 int
9078vim_fexists(fname)
9079 char_u *fname;
9080{
9081 struct stat st;
9082
9083 if (mch_stat((char *)fname, &st))
9084 return FALSE;
9085 return TRUE;
9086}
9087
9088/*
9089 * Check for CTRL-C pressed, but only once in a while.
9090 * Should be used instead of ui_breakcheck() for functions that check for
9091 * each line in the file. Calling ui_breakcheck() each time takes too much
9092 * time, because it can be a system call.
9093 */
9094
9095#ifndef BREAKCHECK_SKIP
9096# ifdef FEAT_GUI /* assume the GUI only runs on fast computers */
9097# define BREAKCHECK_SKIP 200
9098# else
9099# define BREAKCHECK_SKIP 32
9100# endif
9101#endif
9102
9103static int breakcheck_count = 0;
9104
9105 void
9106line_breakcheck()
9107{
9108 if (++breakcheck_count >= BREAKCHECK_SKIP)
9109 {
9110 breakcheck_count = 0;
9111 ui_breakcheck();
9112 }
9113}
9114
9115/*
9116 * Like line_breakcheck() but check 10 times less often.
9117 */
9118 void
9119fast_breakcheck()
9120{
9121 if (++breakcheck_count >= BREAKCHECK_SKIP * 10)
9122 {
9123 breakcheck_count = 0;
9124 ui_breakcheck();
9125 }
9126}
9127
9128/*
Bram Moolenaard7834d32009-12-02 16:14:36 +00009129 * Invoke expand_wildcards() for one pattern.
9130 * Expand items like "%:h" before the expansion.
9131 * Returns OK or FAIL.
9132 */
9133 int
9134expand_wildcards_eval(pat, num_file, file, flags)
9135 char_u **pat; /* pointer to input pattern */
9136 int *num_file; /* resulting number of files */
9137 char_u ***file; /* array of resulting files */
9138 int flags; /* EW_DIR, etc. */
9139{
9140 int ret = FAIL;
9141 char_u *eval_pat = NULL;
9142 char_u *exp_pat = *pat;
9143 char_u *ignored_msg;
9144 int usedlen;
9145
9146 if (*exp_pat == '%' || *exp_pat == '#' || *exp_pat == '<')
9147 {
9148 ++emsg_off;
9149 eval_pat = eval_vars(exp_pat, exp_pat, &usedlen,
9150 NULL, &ignored_msg, NULL);
9151 --emsg_off;
9152 if (eval_pat != NULL)
9153 exp_pat = concat_str(eval_pat, exp_pat + usedlen);
9154 }
9155
9156 if (exp_pat != NULL)
9157 ret = expand_wildcards(1, &exp_pat, num_file, file, flags);
9158
9159 if (eval_pat != NULL)
9160 {
9161 vim_free(exp_pat);
9162 vim_free(eval_pat);
9163 }
9164
9165 return ret;
9166}
9167
9168/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00009169 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching
9170 * 'wildignore'.
Bram Moolenaar9e193ac2010-07-19 23:11:27 +02009171 * Returns OK or FAIL. When FAIL then "num_file" won't be set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009172 */
9173 int
9174expand_wildcards(num_pat, pat, num_file, file, flags)
9175 int num_pat; /* number of input patterns */
9176 char_u **pat; /* array of input patterns */
9177 int *num_file; /* resulting number of files */
9178 char_u ***file; /* array of resulting files */
9179 int flags; /* EW_DIR, etc. */
9180{
9181 int retval;
9182 int i, j;
9183 char_u *p;
9184 int non_suf_match; /* number without matching suffix */
9185
9186 retval = gen_expand_wildcards(num_pat, pat, num_file, file, flags);
9187
9188 /* When keeping all matches, return here */
Bram Moolenaar9e193ac2010-07-19 23:11:27 +02009189 if ((flags & EW_KEEPALL) || retval == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009190 return retval;
9191
9192#ifdef FEAT_WILDIGN
9193 /*
9194 * Remove names that match 'wildignore'.
9195 */
9196 if (*p_wig)
9197 {
9198 char_u *ffname;
9199
9200 /* check all files in (*file)[] */
9201 for (i = 0; i < *num_file; ++i)
9202 {
9203 ffname = FullName_save((*file)[i], FALSE);
9204 if (ffname == NULL) /* out of memory */
9205 break;
9206# ifdef VMS
9207 vms_remove_version(ffname);
9208# endif
9209 if (match_file_list(p_wig, (*file)[i], ffname))
9210 {
9211 /* remove this matching file from the list */
9212 vim_free((*file)[i]);
9213 for (j = i; j + 1 < *num_file; ++j)
9214 (*file)[j] = (*file)[j + 1];
9215 --*num_file;
9216 --i;
9217 }
9218 vim_free(ffname);
9219 }
9220 }
9221#endif
9222
9223 /*
9224 * Move the names where 'suffixes' match to the end.
9225 */
9226 if (*num_file > 1)
9227 {
9228 non_suf_match = 0;
9229 for (i = 0; i < *num_file; ++i)
9230 {
9231 if (!match_suffix((*file)[i]))
9232 {
9233 /*
9234 * Move the name without matching suffix to the front
9235 * of the list.
9236 */
9237 p = (*file)[i];
9238 for (j = i; j > non_suf_match; --j)
9239 (*file)[j] = (*file)[j - 1];
9240 (*file)[non_suf_match++] = p;
9241 }
9242 }
9243 }
9244
9245 return retval;
9246}
9247
9248/*
9249 * Return TRUE if "fname" matches with an entry in 'suffixes'.
9250 */
9251 int
9252match_suffix(fname)
9253 char_u *fname;
9254{
9255 int fnamelen, setsuflen;
9256 char_u *setsuf;
9257#define MAXSUFLEN 30 /* maximum length of a file suffix */
9258 char_u suf_buf[MAXSUFLEN];
9259
9260 fnamelen = (int)STRLEN(fname);
9261 setsuflen = 0;
9262 for (setsuf = p_su; *setsuf; )
9263 {
9264 setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
Bram Moolenaar055a2ba2009-07-14 19:40:21 +00009265 if (setsuflen == 0)
9266 {
9267 char_u *tail = gettail(fname);
9268
9269 /* empty entry: match name without a '.' */
9270 if (vim_strchr(tail, '.') == NULL)
9271 {
9272 setsuflen = 1;
9273 break;
9274 }
9275 }
9276 else
9277 {
9278 if (fnamelen >= setsuflen
9279 && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
9280 (size_t)setsuflen) == 0)
9281 break;
9282 setsuflen = 0;
9283 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009284 }
9285 return (setsuflen != 0);
9286}
9287
9288#if !defined(NO_EXPANDPATH) || defined(PROTO)
9289
9290# ifdef VIM_BACKTICK
9291static int vim_backtick __ARGS((char_u *p));
9292static int expand_backtick __ARGS((garray_T *gap, char_u *pat, int flags));
9293# endif
9294
9295# if defined(MSDOS) || defined(FEAT_GUI_W16) || defined(WIN3264)
9296/*
9297 * File name expansion code for MS-DOS, Win16 and Win32. It's here because
9298 * it's shared between these systems.
9299 */
9300# if defined(DJGPP) || defined(PROTO)
9301# define _cdecl /* DJGPP doesn't have this */
9302# else
9303# ifdef __BORLANDC__
9304# define _cdecl _RTLENTRYF
9305# endif
9306# endif
9307
9308/*
9309 * comparison function for qsort in dos_expandpath()
9310 */
9311 static int _cdecl
9312pstrcmp(const void *a, const void *b)
9313{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00009314 return (pathcmp(*(char **)a, *(char **)b, -1));
Bram Moolenaar071d4272004-06-13 20:20:40 +00009315}
9316
9317# ifndef WIN3264
9318 static void
9319namelowcpy(
9320 char_u *d,
9321 char_u *s)
9322{
9323# ifdef DJGPP
9324 if (USE_LONG_FNAME) /* don't lower case on Windows 95/NT systems */
9325 while (*s)
9326 *d++ = *s++;
9327 else
9328# endif
9329 while (*s)
9330 *d++ = TOLOWER_LOC(*s++);
9331 *d = NUL;
9332}
9333# endif
9334
9335/*
Bram Moolenaar231334e2005-07-25 20:46:57 +00009336 * Recursively expand one path component into all matching files and/or
9337 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009338 * Return the number of matches found.
9339 * "path" has backslashes before chars that are not to be expanded, starting
9340 * at "path[wildoff]".
Bram Moolenaar231334e2005-07-25 20:46:57 +00009341 * Return the number of matches found.
9342 * NOTE: much of this is identical to unix_expandpath(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00009343 */
9344 static int
9345dos_expandpath(
9346 garray_T *gap,
9347 char_u *path,
9348 int wildoff,
Bram Moolenaar231334e2005-07-25 20:46:57 +00009349 int flags, /* EW_* flags */
Bram Moolenaar25394022007-05-10 19:06:20 +00009350 int didstar) /* expanded "**" once already */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009351{
Bram Moolenaar231334e2005-07-25 20:46:57 +00009352 char_u *buf;
9353 char_u *path_end;
9354 char_u *p, *s, *e;
9355 int start_len = gap->ga_len;
9356 char_u *pat;
9357 regmatch_T regmatch;
9358 int starts_with_dot;
9359 int matches;
9360 int len;
9361 int starstar = FALSE;
9362 static int stardepth = 0; /* depth for "**" expansion */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009363#ifdef WIN3264
9364 WIN32_FIND_DATA fb;
9365 HANDLE hFind = (HANDLE)0;
9366# ifdef FEAT_MBYTE
9367 WIN32_FIND_DATAW wfb;
9368 WCHAR *wn = NULL; /* UCS-2 name, NULL when not used. */
9369# endif
9370#else
9371 struct ffblk fb;
9372#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009373 char_u *matchname;
Bram Moolenaar231334e2005-07-25 20:46:57 +00009374 int ok;
9375
9376 /* Expanding "**" may take a long time, check for CTRL-C. */
9377 if (stardepth > 0)
9378 {
9379 ui_breakcheck();
9380 if (got_int)
9381 return 0;
9382 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009383
9384 /* make room for file name */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009385 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009386 if (buf == NULL)
9387 return 0;
9388
9389 /*
9390 * Find the first part in the path name that contains a wildcard or a ~1.
9391 * Copy it into buf, including the preceding characters.
9392 */
9393 p = buf;
9394 s = buf;
9395 e = NULL;
9396 path_end = path;
9397 while (*path_end != NUL)
9398 {
9399 /* May ignore a wildcard that has a backslash before it; it will
9400 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
9401 if (path_end >= path + wildoff && rem_backslash(path_end))
9402 *p++ = *path_end++;
9403 else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
9404 {
9405 if (e != NULL)
9406 break;
9407 s = p + 1;
9408 }
9409 else if (path_end >= path + wildoff
9410 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
9411 e = p;
9412#ifdef FEAT_MBYTE
9413 if (has_mbyte)
9414 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00009415 len = (*mb_ptr2len)(path_end);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009416 STRNCPY(p, path_end, len);
9417 p += len;
9418 path_end += len;
9419 }
9420 else
9421#endif
9422 *p++ = *path_end++;
9423 }
9424 e = p;
9425 *e = NUL;
9426
9427 /* now we have one wildcard component between s and e */
9428 /* Remove backslashes between "wildoff" and the start of the wildcard
9429 * component. */
9430 for (p = buf + wildoff; p < s; ++p)
9431 if (rem_backslash(p))
9432 {
Bram Moolenaar8c8de832008-06-24 22:58:06 +00009433 STRMOVE(p, p + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009434 --e;
9435 --s;
9436 }
9437
Bram Moolenaar231334e2005-07-25 20:46:57 +00009438 /* Check for "**" between "s" and "e". */
9439 for (p = s; p < e; ++p)
9440 if (p[0] == '*' && p[1] == '*')
9441 starstar = TRUE;
9442
Bram Moolenaar071d4272004-06-13 20:20:40 +00009443 starts_with_dot = (*s == '.');
9444 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
9445 if (pat == NULL)
9446 {
9447 vim_free(buf);
9448 return 0;
9449 }
9450
9451 /* compile the regexp into a program */
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009452 if (flags & (EW_NOERROR | EW_NOTWILD))
Bram Moolenaarb5609832011-07-20 15:04:58 +02009453 ++emsg_silent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009454 regmatch.rm_ic = TRUE; /* Always ignore case */
9455 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009456 if (flags & (EW_NOERROR | EW_NOTWILD))
Bram Moolenaarb5609832011-07-20 15:04:58 +02009457 --emsg_silent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009458 vim_free(pat);
9459
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009460 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009461 {
9462 vim_free(buf);
9463 return 0;
9464 }
9465
9466 /* remember the pattern or file name being looked for */
9467 matchname = vim_strsave(s);
9468
Bram Moolenaar231334e2005-07-25 20:46:57 +00009469 /* If "**" is by itself, this is the first time we encounter it and more
9470 * is following then find matches without any directory. */
9471 if (!didstar && stardepth < 100 && starstar && e - s == 2
9472 && *path_end == '/')
9473 {
9474 STRCPY(s, path_end + 1);
9475 ++stardepth;
9476 (void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
9477 --stardepth;
9478 }
9479
Bram Moolenaar071d4272004-06-13 20:20:40 +00009480 /* Scan all files in the directory with "dir/ *.*" */
9481 STRCPY(s, "*.*");
9482#ifdef WIN3264
9483# ifdef FEAT_MBYTE
9484 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
9485 {
9486 /* The active codepage differs from 'encoding'. Attempt using the
9487 * wide function. If it fails because it is not implemented fall back
9488 * to the non-wide version (for Windows 98) */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009489 wn = enc_to_utf16(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009490 if (wn != NULL)
9491 {
9492 hFind = FindFirstFileW(wn, &wfb);
9493 if (hFind == INVALID_HANDLE_VALUE
9494 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
9495 {
9496 vim_free(wn);
9497 wn = NULL;
9498 }
9499 }
9500 }
9501
9502 if (wn == NULL)
9503# endif
9504 hFind = FindFirstFile(buf, &fb);
9505 ok = (hFind != INVALID_HANDLE_VALUE);
9506#else
9507 /* If we are expanding wildcards we try both files and directories */
9508 ok = (findfirst((char *)buf, &fb,
9509 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
9510#endif
9511
9512 while (ok)
9513 {
9514#ifdef WIN3264
9515# ifdef FEAT_MBYTE
9516 if (wn != NULL)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009517 p = utf16_to_enc(wfb.cFileName, NULL); /* p is allocated here */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009518 else
9519# endif
9520 p = (char_u *)fb.cFileName;
9521#else
9522 p = (char_u *)fb.ff_name;
9523#endif
9524 /* Ignore entries starting with a dot, unless when asked for. Accept
9525 * all entries found with "matchname". */
9526 if ((p[0] != '.' || starts_with_dot)
9527 && (matchname == NULL
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009528 || (regmatch.regprog != NULL
9529 && vim_regexec(&regmatch, p, (colnr_T)0))
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009530 || ((flags & EW_NOTWILD)
9531 && fnamencmp(path + (s - buf), p, e - s) == 0)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009532 {
9533#ifdef WIN3264
9534 STRCPY(s, p);
9535#else
9536 namelowcpy(s, p);
9537#endif
9538 len = (int)STRLEN(buf);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009539
9540 if (starstar && stardepth < 100)
9541 {
9542 /* For "**" in the pattern first go deeper in the tree to
9543 * find matches. */
9544 STRCPY(buf + len, "/**");
9545 STRCPY(buf + len + 3, path_end);
9546 ++stardepth;
9547 (void)dos_expandpath(gap, buf, len + 1, flags, TRUE);
9548 --stardepth;
9549 }
9550
Bram Moolenaar071d4272004-06-13 20:20:40 +00009551 STRCPY(buf + len, path_end);
9552 if (mch_has_exp_wildcard(path_end))
9553 {
9554 /* need to expand another component of the path */
9555 /* remove backslashes for the remaining components only */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009556 (void)dos_expandpath(gap, buf, len + 1, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009557 }
9558 else
9559 {
9560 /* no more wildcards, check if there is a match */
9561 /* remove backslashes for the remaining components only */
9562 if (*path_end != 0)
9563 backslash_halve(buf + len + 1);
9564 if (mch_getperm(buf) >= 0) /* add existing file */
9565 addfile(gap, buf, flags);
9566 }
9567 }
9568
9569#ifdef WIN3264
9570# ifdef FEAT_MBYTE
9571 if (wn != NULL)
9572 {
9573 vim_free(p);
9574 ok = FindNextFileW(hFind, &wfb);
9575 }
9576 else
9577# endif
9578 ok = FindNextFile(hFind, &fb);
9579#else
9580 ok = (findnext(&fb) == 0);
9581#endif
9582
9583 /* If no more matches and no match was used, try expanding the name
9584 * itself. Finds the long name of a short filename. */
9585 if (!ok && matchname != NULL && gap->ga_len == start_len)
9586 {
9587 STRCPY(s, matchname);
9588#ifdef WIN3264
9589 FindClose(hFind);
9590# ifdef FEAT_MBYTE
9591 if (wn != NULL)
9592 {
9593 vim_free(wn);
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009594 wn = enc_to_utf16(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009595 if (wn != NULL)
9596 hFind = FindFirstFileW(wn, &wfb);
9597 }
9598 if (wn == NULL)
9599# endif
9600 hFind = FindFirstFile(buf, &fb);
9601 ok = (hFind != INVALID_HANDLE_VALUE);
9602#else
9603 ok = (findfirst((char *)buf, &fb,
9604 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
9605#endif
9606 vim_free(matchname);
9607 matchname = NULL;
9608 }
9609 }
9610
9611#ifdef WIN3264
9612 FindClose(hFind);
9613# ifdef FEAT_MBYTE
9614 vim_free(wn);
9615# endif
9616#endif
9617 vim_free(buf);
9618 vim_free(regmatch.regprog);
9619 vim_free(matchname);
9620
9621 matches = gap->ga_len - start_len;
9622 if (matches > 0)
9623 qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
9624 sizeof(char_u *), pstrcmp);
9625 return matches;
9626}
9627
9628 int
9629mch_expandpath(
9630 garray_T *gap,
9631 char_u *path,
9632 int flags) /* EW_* flags */
9633{
Bram Moolenaar231334e2005-07-25 20:46:57 +00009634 return dos_expandpath(gap, path, 0, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009635}
9636# endif /* MSDOS || FEAT_GUI_W16 || WIN3264 */
9637
Bram Moolenaar231334e2005-07-25 20:46:57 +00009638#if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
9639 || defined(PROTO)
9640/*
9641 * Unix style wildcard expansion code.
9642 * It's here because it's used both for Unix and Mac.
9643 */
9644static int pstrcmp __ARGS((const void *, const void *));
9645
9646 static int
9647pstrcmp(a, b)
9648 const void *a, *b;
9649{
9650 return (pathcmp(*(char **)a, *(char **)b, -1));
9651}
9652
9653/*
9654 * Recursively expand one path component into all matching files and/or
9655 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
9656 * "path" has backslashes before chars that are not to be expanded, starting
9657 * at "path + wildoff".
9658 * Return the number of matches found.
9659 * NOTE: much of this is identical to dos_expandpath(), keep in sync!
9660 */
9661 int
9662unix_expandpath(gap, path, wildoff, flags, didstar)
9663 garray_T *gap;
9664 char_u *path;
9665 int wildoff;
9666 int flags; /* EW_* flags */
9667 int didstar; /* expanded "**" once already */
9668{
9669 char_u *buf;
9670 char_u *path_end;
9671 char_u *p, *s, *e;
9672 int start_len = gap->ga_len;
9673 char_u *pat;
9674 regmatch_T regmatch;
9675 int starts_with_dot;
9676 int matches;
9677 int len;
9678 int starstar = FALSE;
9679 static int stardepth = 0; /* depth for "**" expansion */
9680
9681 DIR *dirp;
9682 struct dirent *dp;
9683
9684 /* Expanding "**" may take a long time, check for CTRL-C. */
9685 if (stardepth > 0)
9686 {
9687 ui_breakcheck();
9688 if (got_int)
9689 return 0;
9690 }
9691
9692 /* make room for file name */
9693 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
9694 if (buf == NULL)
9695 return 0;
9696
9697 /*
9698 * Find the first part in the path name that contains a wildcard.
Bram Moolenaar2d0b92f2012-04-30 21:09:43 +02009699 * When EW_ICASE is set every letter is considered to be a wildcard.
Bram Moolenaar231334e2005-07-25 20:46:57 +00009700 * Copy it into "buf", including the preceding characters.
9701 */
9702 p = buf;
9703 s = buf;
9704 e = NULL;
9705 path_end = path;
9706 while (*path_end != NUL)
9707 {
9708 /* May ignore a wildcard that has a backslash before it; it will
9709 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
9710 if (path_end >= path + wildoff && rem_backslash(path_end))
9711 *p++ = *path_end++;
9712 else if (*path_end == '/')
9713 {
9714 if (e != NULL)
9715 break;
9716 s = p + 1;
9717 }
9718 else if (path_end >= path + wildoff
Bram Moolenaar2d0b92f2012-04-30 21:09:43 +02009719 && (vim_strchr((char_u *)"*?[{~$", *path_end) != NULL
9720#ifndef CASE_INSENSITIVE_FILENAME
9721 || ((flags & EW_ICASE)
9722 && isalpha(PTR2CHAR(path_end)))
9723#endif
9724 ))
Bram Moolenaar231334e2005-07-25 20:46:57 +00009725 e = p;
9726#ifdef FEAT_MBYTE
9727 if (has_mbyte)
9728 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00009729 len = (*mb_ptr2len)(path_end);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009730 STRNCPY(p, path_end, len);
9731 p += len;
9732 path_end += len;
9733 }
9734 else
9735#endif
9736 *p++ = *path_end++;
9737 }
9738 e = p;
9739 *e = NUL;
9740
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009741 /* Now we have one wildcard component between "s" and "e". */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009742 /* Remove backslashes between "wildoff" and the start of the wildcard
9743 * component. */
9744 for (p = buf + wildoff; p < s; ++p)
9745 if (rem_backslash(p))
9746 {
Bram Moolenaar8c8de832008-06-24 22:58:06 +00009747 STRMOVE(p, p + 1);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009748 --e;
9749 --s;
9750 }
9751
9752 /* Check for "**" between "s" and "e". */
9753 for (p = s; p < e; ++p)
9754 if (p[0] == '*' && p[1] == '*')
9755 starstar = TRUE;
9756
9757 /* convert the file pattern to a regexp pattern */
9758 starts_with_dot = (*s == '.');
9759 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
9760 if (pat == NULL)
9761 {
9762 vim_free(buf);
9763 return 0;
9764 }
9765
9766 /* compile the regexp into a program */
Bram Moolenaarcc016f52005-12-10 20:23:46 +00009767#ifdef CASE_INSENSITIVE_FILENAME
Bram Moolenaar231334e2005-07-25 20:46:57 +00009768 regmatch.rm_ic = TRUE; /* Behave like Terminal.app */
9769#else
Bram Moolenaar94950a92010-12-02 16:01:29 +01009770 if (flags & EW_ICASE)
9771 regmatch.rm_ic = TRUE; /* 'wildignorecase' set */
9772 else
9773 regmatch.rm_ic = FALSE; /* Don't ignore case */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009774#endif
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009775 if (flags & (EW_NOERROR | EW_NOTWILD))
9776 ++emsg_silent;
Bram Moolenaar231334e2005-07-25 20:46:57 +00009777 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009778 if (flags & (EW_NOERROR | EW_NOTWILD))
9779 --emsg_silent;
Bram Moolenaar231334e2005-07-25 20:46:57 +00009780 vim_free(pat);
9781
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009782 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
Bram Moolenaar231334e2005-07-25 20:46:57 +00009783 {
9784 vim_free(buf);
9785 return 0;
9786 }
9787
9788 /* If "**" is by itself, this is the first time we encounter it and more
9789 * is following then find matches without any directory. */
9790 if (!didstar && stardepth < 100 && starstar && e - s == 2
9791 && *path_end == '/')
9792 {
9793 STRCPY(s, path_end + 1);
9794 ++stardepth;
9795 (void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
9796 --stardepth;
9797 }
9798
9799 /* open the directory for scanning */
9800 *s = NUL;
9801 dirp = opendir(*buf == NUL ? "." : (char *)buf);
9802
9803 /* Find all matching entries */
9804 if (dirp != NULL)
9805 {
9806 for (;;)
9807 {
9808 dp = readdir(dirp);
9809 if (dp == NULL)
9810 break;
9811 if ((dp->d_name[0] != '.' || starts_with_dot)
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009812 && ((regmatch.regprog != NULL && vim_regexec(&regmatch,
9813 (char_u *)dp->d_name, (colnr_T)0))
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009814 || ((flags & EW_NOTWILD)
9815 && fnamencmp(path + (s - buf), dp->d_name, e - s) == 0)))
Bram Moolenaar231334e2005-07-25 20:46:57 +00009816 {
9817 STRCPY(s, dp->d_name);
9818 len = STRLEN(buf);
9819
9820 if (starstar && stardepth < 100)
9821 {
9822 /* For "**" in the pattern first go deeper in the tree to
9823 * find matches. */
9824 STRCPY(buf + len, "/**");
9825 STRCPY(buf + len + 3, path_end);
9826 ++stardepth;
9827 (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
9828 --stardepth;
9829 }
9830
9831 STRCPY(buf + len, path_end);
9832 if (mch_has_exp_wildcard(path_end)) /* handle more wildcards */
9833 {
9834 /* need to expand another component of the path */
9835 /* remove backslashes for the remaining components only */
9836 (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
9837 }
9838 else
9839 {
9840 /* no more wildcards, check if there is a match */
9841 /* remove backslashes for the remaining components only */
9842 if (*path_end != NUL)
9843 backslash_halve(buf + len + 1);
9844 if (mch_getperm(buf) >= 0) /* add existing file */
9845 {
Bram Moolenaar95e9b492006-03-15 23:04:43 +00009846#ifdef MACOS_CONVERT
Bram Moolenaar231334e2005-07-25 20:46:57 +00009847 size_t precomp_len = STRLEN(buf)+1;
9848 char_u *precomp_buf =
9849 mac_precompose_path(buf, precomp_len, &precomp_len);
Bram Moolenaar95e9b492006-03-15 23:04:43 +00009850
Bram Moolenaar231334e2005-07-25 20:46:57 +00009851 if (precomp_buf)
9852 {
9853 mch_memmove(buf, precomp_buf, precomp_len);
9854 vim_free(precomp_buf);
9855 }
9856#endif
9857 addfile(gap, buf, flags);
9858 }
9859 }
9860 }
9861 }
9862
9863 closedir(dirp);
9864 }
9865
9866 vim_free(buf);
9867 vim_free(regmatch.regprog);
9868
9869 matches = gap->ga_len - start_len;
9870 if (matches > 0)
9871 qsort(((char_u **)gap->ga_data) + start_len, matches,
9872 sizeof(char_u *), pstrcmp);
9873 return matches;
9874}
9875#endif
9876
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009877#if defined(FEAT_SEARCHPATH)
9878static int find_previous_pathsep __ARGS((char_u *path, char_u **psep));
9879static int is_unique __ARGS((char_u *maybe_unique, garray_T *gap, int i));
Bram Moolenaar162bd912010-07-28 22:29:10 +02009880static void expand_path_option __ARGS((char_u *curdir, garray_T *gap));
9881static char_u *get_path_cutoff __ARGS((char_u *fname, garray_T *gap));
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009882static void uniquefy_paths __ARGS((garray_T *gap, char_u *pattern));
9883static int expand_in_path __ARGS((garray_T *gap, char_u *pattern, int flags));
9884
9885/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009886 * Moves "*psep" back to the previous path separator in "path".
9887 * Returns FAIL is "*psep" ends up at the beginning of "path".
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009888 */
9889 static int
9890find_previous_pathsep(path, psep)
9891 char_u *path;
9892 char_u **psep;
9893{
9894 /* skip the current separator */
9895 if (*psep > path && vim_ispathsep(**psep))
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009896 --*psep;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009897
9898 /* find the previous separator */
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009899 while (*psep > path)
9900 {
9901 if (vim_ispathsep(**psep))
9902 return OK;
9903 mb_ptr_back(path, *psep);
9904 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009905
9906 return FAIL;
9907}
9908
9909/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009910 * Returns TRUE if "maybe_unique" is unique wrt other_paths in "gap".
9911 * "maybe_unique" is the end portion of "((char_u **)gap->ga_data)[i]".
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009912 */
9913 static int
9914is_unique(maybe_unique, gap, i)
9915 char_u *maybe_unique;
9916 garray_T *gap;
9917 int i;
9918{
9919 int j;
9920 int candidate_len;
9921 int other_path_len;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009922 char_u **other_paths = (char_u **)gap->ga_data;
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009923 char_u *rival;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009924
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009925 for (j = 0; j < gap->ga_len; j++)
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009926 {
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009927 if (j == i)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009928 continue; /* don't compare it with itself */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009929
Bram Moolenaar624c7aa2010-07-16 20:38:52 +02009930 candidate_len = (int)STRLEN(maybe_unique);
9931 other_path_len = (int)STRLEN(other_paths[j]);
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009932 if (other_path_len < candidate_len)
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009933 continue; /* it's different when it's shorter */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009934
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009935 rival = other_paths[j] + other_path_len - candidate_len;
Bram Moolenaarda9836c2010-08-16 21:53:27 +02009936 if (fnamecmp(maybe_unique, rival) == 0
9937 && (rival == other_paths[j] || vim_ispathsep(*(rival - 1))))
Bram Moolenaar162bd912010-07-28 22:29:10 +02009938 return FALSE; /* match */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009939 }
9940
Bram Moolenaar162bd912010-07-28 22:29:10 +02009941 return TRUE; /* no match found */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009942}
9943
9944/*
Bram Moolenaar1a509df2010-08-01 17:59:57 +02009945 * Split the 'path' option into an array of strings in garray_T. Relative
Bram Moolenaar162bd912010-07-28 22:29:10 +02009946 * paths are expanded to their equivalent fullpath. This includes the "."
9947 * (relative to current buffer directory) and empty path (relative to current
9948 * directory) notations.
9949 *
9950 * TODO: handle upward search (;) and path limiter (**N) notations by
9951 * expanding each into their equivalent path(s).
9952 */
9953 static void
9954expand_path_option(curdir, gap)
9955 char_u *curdir;
9956 garray_T *gap;
9957{
9958 char_u *path_option = *curbuf->b_p_path == NUL
9959 ? p_path : curbuf->b_p_path;
9960 char_u *buf;
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009961 char_u *p;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009962 int len;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009963
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +02009964 if ((buf = alloc((int)MAXPATHL)) == NULL)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009965 return;
9966
9967 while (*path_option != NUL)
9968 {
9969 copy_option_part(&path_option, buf, MAXPATHL, " ,");
9970
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009971 if (buf[0] == '.' && (buf[1] == NUL || vim_ispathsep(buf[1])))
Bram Moolenaar162bd912010-07-28 22:29:10 +02009972 {
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009973 /* Relative to current buffer:
9974 * "/path/file" + "." -> "/path/"
9975 * "/path/file" + "./subdir" -> "/path/subdir" */
Bram Moolenaar162bd912010-07-28 22:29:10 +02009976 if (curbuf->b_ffname == NULL)
9977 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009978 p = gettail(curbuf->b_ffname);
9979 len = (int)(p - curbuf->b_ffname);
9980 if (len + (int)STRLEN(buf) >= MAXPATHL)
9981 continue;
9982 if (buf[1] == NUL)
9983 buf[len] = NUL;
9984 else
9985 STRMOVE(buf + len, buf + 2);
9986 mch_memmove(buf, curbuf->b_ffname, len);
9987 simplify_filename(buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009988 }
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009989 else if (buf[0] == NUL)
9990 /* relative to current directory */
Bram Moolenaar162bd912010-07-28 22:29:10 +02009991 STRCPY(buf, curdir);
Bram Moolenaar84f888a2010-08-05 21:40:16 +02009992 else if (path_with_url(buf))
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009993 /* URL can't be used here */
Bram Moolenaar84f888a2010-08-05 21:40:16 +02009994 continue;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009995 else if (!mch_isFullName(buf))
9996 {
9997 /* Expand relative path to their full path equivalent */
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009998 len = (int)STRLEN(curdir);
9999 if (len + (int)STRLEN(buf) + 3 > MAXPATHL)
Bram Moolenaar162bd912010-07-28 22:29:10 +020010000 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010001 STRMOVE(buf + len + 1, buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010002 STRCPY(buf, curdir);
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010003 buf[len] = PATHSEP;
Bram Moolenaar57adda12010-08-03 22:11:29 +020010004 simplify_filename(buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010005 }
10006
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010007 if (ga_grow(gap, 1) == FAIL)
10008 break;
10009 p = vim_strsave(buf);
10010 if (p == NULL)
10011 break;
10012 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010013 }
10014
10015 vim_free(buf);
10016}
10017
10018/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010019 * Returns a pointer to the file or directory name in "fname" that matches the
10020 * longest path in "ga"p, or NULL if there is no match. For example:
Bram Moolenaar162bd912010-07-28 22:29:10 +020010021 *
10022 * path: /foo/bar/baz
10023 * fname: /foo/bar/baz/quux.txt
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010024 * returns: ^this
Bram Moolenaar162bd912010-07-28 22:29:10 +020010025 */
10026 static char_u *
10027get_path_cutoff(fname, gap)
10028 char_u *fname;
10029 garray_T *gap;
10030{
10031 int i;
10032 int maxlen = 0;
10033 char_u **path_part = (char_u **)gap->ga_data;
10034 char_u *cutoff = NULL;
10035
10036 for (i = 0; i < gap->ga_len; i++)
10037 {
10038 int j = 0;
10039
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010040 while ((fname[j] == path_part[i][j]
Bram Moolenaar2d7c47d2010-08-10 19:50:26 +020010041# if defined(MSWIN) || defined(MSDOS)
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010042 || (vim_ispathsep(fname[j]) && vim_ispathsep(path_part[i][j]))
10043#endif
10044 ) && fname[j] != NUL && path_part[i][j] != NUL)
Bram Moolenaar162bd912010-07-28 22:29:10 +020010045 j++;
10046 if (j > maxlen)
10047 {
10048 maxlen = j;
10049 cutoff = &fname[j];
10050 }
10051 }
10052
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010053 /* skip to the file or directory name */
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010054 if (cutoff != NULL)
Bram Moolenaar31710262010-08-13 13:36:15 +020010055 while (vim_ispathsep(*cutoff))
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010056 mb_ptr_adv(cutoff);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010057
10058 return cutoff;
10059}
10060
10061/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010062 * Sorts, removes duplicates and modifies all the fullpath names in "gap" so
10063 * that they are unique with respect to each other while conserving the part
10064 * that matches the pattern. Beware, this is at least O(n^2) wrt "gap->ga_len".
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010065 */
10066 static void
10067uniquefy_paths(gap, pattern)
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +020010068 garray_T *gap;
10069 char_u *pattern;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010070{
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +020010071 int i;
10072 int len;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010073 char_u **fnames = (char_u **)gap->ga_data;
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010074 int sort_again = FALSE;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010075 char_u *pat;
10076 char_u *file_pattern;
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010077 char_u *curdir;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010078 regmatch_T regmatch;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010079 garray_T path_ga;
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010080 char_u **in_curdir = NULL;
10081 char_u *short_name;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010082
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +020010083 remove_duplicates(gap);
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010084 ga_init2(&path_ga, (int)sizeof(char_u *), 1);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010085
10086 /*
10087 * We need to prepend a '*' at the beginning of file_pattern so that the
10088 * regex matches anywhere in the path. FIXME: is this valid for all
Bram Moolenaarb31e4382010-07-24 16:01:56 +020010089 * possible patterns?
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010090 */
Bram Moolenaar624c7aa2010-07-16 20:38:52 +020010091 len = (int)STRLEN(pattern);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010092 file_pattern = alloc(len + 2);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010093 if (file_pattern == NULL)
10094 return;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010095 file_pattern[0] = '*';
Bram Moolenaar162bd912010-07-28 22:29:10 +020010096 file_pattern[1] = NUL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010097 STRCAT(file_pattern, pattern);
10098 pat = file_pat_to_reg_pat(file_pattern, NULL, NULL, TRUE);
10099 vim_free(file_pattern);
Bram Moolenaarb31e4382010-07-24 16:01:56 +020010100 if (pat == NULL)
10101 return;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010102
Bram Moolenaarb31e4382010-07-24 16:01:56 +020010103 regmatch.rm_ic = TRUE; /* always ignore case */
10104 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
10105 vim_free(pat);
10106 if (regmatch.regprog == NULL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010107 return;
10108
Bram Moolenaar162bd912010-07-28 22:29:10 +020010109 if ((curdir = alloc((int)(MAXPATHL))) == NULL)
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010110 goto theend;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010111 mch_dirname(curdir, MAXPATHL);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010112 expand_path_option(curdir, &path_ga);
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010113
10114 in_curdir = (char_u **)alloc_clear(gap->ga_len * sizeof(char_u *));
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010115 if (in_curdir == NULL)
10116 goto theend;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010117
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010118 for (i = 0; i < gap->ga_len && !got_int; i++)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010119 {
Bram Moolenaar162bd912010-07-28 22:29:10 +020010120 char_u *path = fnames[i];
10121 int is_in_curdir;
Bram Moolenaar31710262010-08-13 13:36:15 +020010122 char_u *dir_end = gettail_dir(path);
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010123 char_u *pathsep_p;
10124 char_u *path_cutoff;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010125
Bram Moolenaar624c7aa2010-07-16 20:38:52 +020010126 len = (int)STRLEN(path);
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010127 is_in_curdir = fnamencmp(curdir, path, dir_end - path) == 0
Bram Moolenaar162bd912010-07-28 22:29:10 +020010128 && curdir[dir_end - path] == NUL;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010129 if (is_in_curdir)
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010130 in_curdir[i] = vim_strsave(path);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010131
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010132 /* Shorten the filename while maintaining its uniqueness */
10133 path_cutoff = get_path_cutoff(path, &path_ga);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010134
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010135 /* we start at the end of the path */
10136 pathsep_p = path + len - 1;
10137
10138 while (find_previous_pathsep(path, &pathsep_p))
10139 if (vim_regexec(&regmatch, pathsep_p + 1, (colnr_T)0)
10140 && is_unique(pathsep_p + 1, gap, i)
10141 && path_cutoff != NULL && pathsep_p + 1 >= path_cutoff)
10142 {
10143 sort_again = TRUE;
10144 mch_memmove(path, pathsep_p + 1, STRLEN(pathsep_p));
10145 break;
10146 }
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010147
10148 if (mch_isFullName(path))
10149 {
10150 /*
10151 * Last resort: shorten relative to curdir if possible.
10152 * 'possible' means:
10153 * 1. It is under the current directory.
10154 * 2. The result is actually shorter than the original.
10155 *
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010156 * Before curdir After
10157 * /foo/bar/file.txt /foo/bar ./file.txt
10158 * c:\foo\bar\file.txt c:\foo\bar .\file.txt
10159 * /file.txt / /file.txt
10160 * c:\file.txt c:\ .\file.txt
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010161 */
10162 short_name = shorten_fname(path, curdir);
Bram Moolenaar31710262010-08-13 13:36:15 +020010163 if (short_name != NULL && short_name > path + 1
10164#if defined(MSWIN) || defined(MSDOS)
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010165 /* On windows,
Bram Moolenaar31710262010-08-13 13:36:15 +020010166 * shorten_fname("c:\a\a.txt", "c:\a\b")
Bram Moolenaar31710262010-08-13 13:36:15 +020010167 * returns "\a\a.txt", which is not really the short
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010168 * name, hence: */
Bram Moolenaar31710262010-08-13 13:36:15 +020010169 && !vim_ispathsep(*short_name)
10170#endif
10171 )
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010172 {
10173 STRCPY(path, ".");
10174 add_pathsep(path);
Bram Moolenaarcda000e2010-08-14 13:34:39 +020010175 STRMOVE(path + STRLEN(path), short_name);
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010176 }
10177 }
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010178 ui_breakcheck();
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010179 }
10180
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010181 /* Shorten filenames in /in/current/directory/{filename} */
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010182 for (i = 0; i < gap->ga_len && !got_int; i++)
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010183 {
10184 char_u *rel_path;
10185 char_u *path = in_curdir[i];
10186
10187 if (path == NULL)
10188 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010189
10190 /* If the {filename} is not unique, change it to ./{filename}.
10191 * Else reduce it to {filename} */
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010192 short_name = shorten_fname(path, curdir);
10193 if (short_name == NULL)
10194 short_name = path;
10195 if (is_unique(short_name, gap, i))
10196 {
10197 STRCPY(fnames[i], short_name);
10198 continue;
10199 }
10200
10201 rel_path = alloc((int)(STRLEN(short_name) + STRLEN(PATHSEPSTR) + 2));
10202 if (rel_path == NULL)
10203 goto theend;
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010204 STRCPY(rel_path, ".");
10205 add_pathsep(rel_path);
10206 STRCAT(rel_path, short_name);
10207
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010208 vim_free(fnames[i]);
10209 fnames[i] = rel_path;
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010210 sort_again = TRUE;
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010211 ui_breakcheck();
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010212 }
10213
Bram Moolenaar162bd912010-07-28 22:29:10 +020010214theend:
10215 vim_free(curdir);
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010216 if (in_curdir != NULL)
10217 {
10218 for (i = 0; i < gap->ga_len; i++)
10219 vim_free(in_curdir[i]);
10220 vim_free(in_curdir);
10221 }
Bram Moolenaar162bd912010-07-28 22:29:10 +020010222 ga_clear_strings(&path_ga);
Bram Moolenaarb31e4382010-07-24 16:01:56 +020010223 vim_free(regmatch.regprog);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010224
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010225 if (sort_again)
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +020010226 remove_duplicates(gap);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010227}
10228
10229/*
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010230 * Calls globpath() with 'path' values for the given pattern and stores the
10231 * result in "gap".
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010232 * Returns the total number of matches.
10233 */
10234 static int
10235expand_in_path(gap, pattern, flags)
10236 garray_T *gap;
10237 char_u *pattern;
10238 int flags; /* EW_* flags */
10239{
Bram Moolenaar162bd912010-07-28 22:29:10 +020010240 char_u *curdir;
10241 garray_T path_ga;
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010242 char_u *files = NULL;
10243 char_u *s; /* start */
10244 char_u *e; /* end */
10245 char_u *paths = NULL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010246
Bram Moolenaar7f0f6212010-08-03 22:21:00 +020010247 if ((curdir = alloc((unsigned)MAXPATHL)) == NULL)
Bram Moolenaar162bd912010-07-28 22:29:10 +020010248 return 0;
10249 mch_dirname(curdir, MAXPATHL);
10250
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010251 ga_init2(&path_ga, (int)sizeof(char_u *), 1);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010252 expand_path_option(curdir, &path_ga);
10253 vim_free(curdir);
Bram Moolenaar006d2b02010-08-04 12:39:44 +020010254 if (path_ga.ga_len == 0)
10255 return 0;
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010256
10257 paths = ga_concat_strings(&path_ga);
10258 ga_clear_strings(&path_ga);
10259 if (paths == NULL)
Bram Moolenaar7f0f6212010-08-03 22:21:00 +020010260 return 0;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010261
Bram Moolenaar94950a92010-12-02 16:01:29 +010010262 files = globpath(paths, pattern, (flags & EW_ICASE) ? WILD_ICASE : 0);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010263 vim_free(paths);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010264 if (files == NULL)
10265 return 0;
10266
10267 /* Copy each path in files into gap */
10268 s = e = files;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010269 while (*s != NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010270 {
Bram Moolenaar162bd912010-07-28 22:29:10 +020010271 while (*e != '\n' && *e != NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010272 e++;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010273 if (*e == NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010274 {
10275 addfile(gap, s, flags);
10276 break;
10277 }
10278 else
10279 {
10280 /* *e is '\n' */
Bram Moolenaar162bd912010-07-28 22:29:10 +020010281 *e = NUL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010282 addfile(gap, s, flags);
10283 e++;
10284 s = e;
10285 }
10286 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010287 vim_free(files);
10288
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010289 return gap->ga_len;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010290}
10291#endif
10292
Bram Moolenaar1587a1e2010-07-29 20:59:59 +020010293#if defined(FEAT_SEARCHPATH) || defined(FEAT_CMDL_COMPL) || defined(PROTO)
10294/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010295 * Sort "gap" and remove duplicate entries. "gap" is expected to contain a
10296 * list of file names in allocated memory.
Bram Moolenaar1587a1e2010-07-29 20:59:59 +020010297 */
10298 void
10299remove_duplicates(gap)
10300 garray_T *gap;
10301{
10302 int i;
10303 int j;
10304 char_u **fnames = (char_u **)gap->ga_data;
10305
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010306 sort_strings(fnames, gap->ga_len);
Bram Moolenaar1587a1e2010-07-29 20:59:59 +020010307 for (i = gap->ga_len - 1; i > 0; --i)
10308 if (fnamecmp(fnames[i - 1], fnames[i]) == 0)
10309 {
10310 vim_free(fnames[i]);
10311 for (j = i + 1; j < gap->ga_len; ++j)
10312 fnames[j - 1] = fnames[j];
10313 --gap->ga_len;
10314 }
10315}
10316#endif
10317
Bram Moolenaar071d4272004-06-13 20:20:40 +000010318/*
10319 * Generic wildcard expansion code.
10320 *
10321 * Characters in "pat" that should not be expanded must be preceded with a
10322 * backslash. E.g., "/path\ with\ spaces/my\*star*"
10323 *
10324 * Return FAIL when no single file was found. In this case "num_file" is not
10325 * set, and "file" may contain an error message.
10326 * Return OK when some files found. "num_file" is set to the number of
10327 * matches, "file" to the array of matches. Call FreeWild() later.
10328 */
10329 int
10330gen_expand_wildcards(num_pat, pat, num_file, file, flags)
10331 int num_pat; /* number of input patterns */
10332 char_u **pat; /* array of input patterns */
10333 int *num_file; /* resulting number of files */
10334 char_u ***file; /* array of resulting files */
10335 int flags; /* EW_* flags */
10336{
10337 int i;
10338 garray_T ga;
10339 char_u *p;
10340 static int recursive = FALSE;
10341 int add_pat;
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010342#if defined(FEAT_SEARCHPATH)
10343 int did_expand_in_path = FALSE;
10344#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000010345
10346 /*
10347 * expand_env() is called to expand things like "~user". If this fails,
10348 * it calls ExpandOne(), which brings us back here. In this case, always
10349 * call the machine specific expansion function, if possible. Otherwise,
10350 * return FAIL.
10351 */
10352 if (recursive)
10353#ifdef SPECIAL_WILDCHAR
10354 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
10355#else
10356 return FAIL;
10357#endif
10358
10359#ifdef SPECIAL_WILDCHAR
10360 /*
10361 * If there are any special wildcard characters which we cannot handle
10362 * here, call machine specific function for all the expansion. This
10363 * avoids starting the shell for each argument separately.
10364 * For `=expr` do use the internal function.
10365 */
10366 for (i = 0; i < num_pat; i++)
10367 {
10368 if (vim_strpbrk(pat[i], (char_u *)SPECIAL_WILDCHAR) != NULL
10369# ifdef VIM_BACKTICK
10370 && !(vim_backtick(pat[i]) && pat[i][1] == '=')
10371# endif
10372 )
10373 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
10374 }
10375#endif
10376
10377 recursive = TRUE;
10378
10379 /*
10380 * The matching file names are stored in a growarray. Init it empty.
10381 */
10382 ga_init2(&ga, (int)sizeof(char_u *), 30);
10383
10384 for (i = 0; i < num_pat; ++i)
10385 {
10386 add_pat = -1;
10387 p = pat[i];
10388
10389#ifdef VIM_BACKTICK
10390 if (vim_backtick(p))
10391 add_pat = expand_backtick(&ga, p, flags);
10392 else
10393#endif
10394 {
10395 /*
10396 * First expand environment variables, "~/" and "~user/".
10397 */
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010398 if (vim_strchr(p, '$') != NULL || *p == '~')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010399 {
Bram Moolenaar9f0545d2007-09-26 20:36:32 +000010400 p = expand_env_save_opt(p, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010401 if (p == NULL)
10402 p = pat[i];
10403#ifdef UNIX
10404 /*
10405 * On Unix, if expand_env() can't expand an environment
10406 * variable, use the shell to do that. Discard previously
10407 * found file names and start all over again.
10408 */
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010409 else if (vim_strchr(p, '$') != NULL || *p == '~')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010410 {
10411 vim_free(p);
Bram Moolenaar782027e2009-06-24 14:25:49 +000010412 ga_clear_strings(&ga);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010413 i = mch_expand_wildcards(num_pat, pat, num_file, file,
10414 flags);
10415 recursive = FALSE;
10416 return i;
10417 }
10418#endif
10419 }
10420
10421 /*
10422 * If there are wildcards: Expand file names and add each match to
10423 * the list. If there is no match, and EW_NOTFOUND is given, add
10424 * the pattern.
10425 * If there are no wildcards: Add the file name if it exists or
10426 * when EW_NOTFOUND is given.
10427 */
10428 if (mch_has_exp_wildcard(p))
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010429 {
10430#if defined(FEAT_SEARCHPATH)
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010431 if ((flags & EW_PATH)
10432 && !mch_isFullName(p)
10433 && !(p[0] == '.'
10434 && (vim_ispathsep(p[1])
10435 || (p[1] == '.' && vim_ispathsep(p[2]))))
10436 )
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010437 {
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010438 /* :find completion where 'path' is used.
10439 * Recursiveness is OK here. */
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010440 recursive = FALSE;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010441 add_pat = expand_in_path(&ga, p, flags);
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010442 recursive = TRUE;
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010443 did_expand_in_path = TRUE;
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010444 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010445 else
10446#endif
10447 add_pat = mch_expandpath(&ga, p, flags);
10448 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010449 }
10450
10451 if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
10452 {
10453 char_u *t = backslash_halve_save(p);
10454
10455#if defined(MACOS_CLASSIC)
10456 slash_to_colon(t);
10457#endif
10458 /* When EW_NOTFOUND is used, always add files and dirs. Makes
10459 * "vim c:/" work. */
10460 if (flags & EW_NOTFOUND)
10461 addfile(&ga, t, flags | EW_DIR | EW_FILE);
10462 else if (mch_getperm(t) >= 0)
10463 addfile(&ga, t, flags);
10464 vim_free(t);
10465 }
10466
Bram Moolenaarb28ebbc2010-07-14 16:59:57 +020010467#if defined(FEAT_SEARCHPATH)
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010468 if (did_expand_in_path && ga.ga_len > 0 && (flags & EW_PATH))
Bram Moolenaarb28ebbc2010-07-14 16:59:57 +020010469 uniquefy_paths(&ga, p);
10470#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000010471 if (p != pat[i])
10472 vim_free(p);
10473 }
10474
10475 *num_file = ga.ga_len;
10476 *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data : (char_u **)"";
10477
10478 recursive = FALSE;
10479
10480 return (ga.ga_data != NULL) ? OK : FAIL;
10481}
10482
10483# ifdef VIM_BACKTICK
10484
10485/*
10486 * Return TRUE if we can expand this backtick thing here.
10487 */
10488 static int
10489vim_backtick(p)
10490 char_u *p;
10491{
10492 return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
10493}
10494
10495/*
10496 * Expand an item in `backticks` by executing it as a command.
10497 * Currently only works when pat[] starts and ends with a `.
10498 * Returns number of file names found.
10499 */
10500 static int
10501expand_backtick(gap, pat, flags)
10502 garray_T *gap;
10503 char_u *pat;
10504 int flags; /* EW_* flags */
10505{
10506 char_u *p;
10507 char_u *cmd;
10508 char_u *buffer;
10509 int cnt = 0;
10510 int i;
10511
10512 /* Create the command: lop off the backticks. */
10513 cmd = vim_strnsave(pat + 1, (int)STRLEN(pat) - 2);
10514 if (cmd == NULL)
10515 return 0;
10516
10517#ifdef FEAT_EVAL
10518 if (*cmd == '=') /* `={expr}`: Expand expression */
Bram Moolenaar362e1a32006-03-06 23:29:24 +000010519 buffer = eval_to_string(cmd + 1, &p, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010520 else
10521#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010522 buffer = get_cmd_output(cmd, NULL,
10523 (flags & EW_SILENT) ? SHELL_SILENT : 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010524 vim_free(cmd);
10525 if (buffer == NULL)
10526 return 0;
10527
10528 cmd = buffer;
10529 while (*cmd != NUL)
10530 {
10531 cmd = skipwhite(cmd); /* skip over white space */
10532 p = cmd;
10533 while (*p != NUL && *p != '\r' && *p != '\n') /* skip over entry */
10534 ++p;
10535 /* add an entry if it is not empty */
10536 if (p > cmd)
10537 {
10538 i = *p;
10539 *p = NUL;
10540 addfile(gap, cmd, flags);
10541 *p = i;
10542 ++cnt;
10543 }
10544 cmd = p;
10545 while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
10546 ++cmd;
10547 }
10548
10549 vim_free(buffer);
10550 return cnt;
10551}
10552# endif /* VIM_BACKTICK */
10553
10554/*
10555 * Add a file to a file list. Accepted flags:
10556 * EW_DIR add directories
10557 * EW_FILE add files
Bram Moolenaar1f35bf92006-03-07 22:38:47 +000010558 * EW_EXEC add executable files
Bram Moolenaar071d4272004-06-13 20:20:40 +000010559 * EW_NOTFOUND add even when it doesn't exist
10560 * EW_ADDSLASH add slash after directory name
10561 */
10562 void
10563addfile(gap, f, flags)
10564 garray_T *gap;
10565 char_u *f; /* filename */
10566 int flags;
10567{
10568 char_u *p;
10569 int isdir;
10570
10571 /* if the file/dir doesn't exist, may not add it */
10572 if (!(flags & EW_NOTFOUND) && mch_getperm(f) < 0)
10573 return;
10574
10575#ifdef FNAME_ILLEGAL
10576 /* if the file/dir contains illegal characters, don't add it */
10577 if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
10578 return;
10579#endif
10580
10581 isdir = mch_isdir(f);
10582 if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
10583 return;
10584
Bram Moolenaar1f35bf92006-03-07 22:38:47 +000010585 /* If the file isn't executable, may not add it. Do accept directories. */
10586 if (!isdir && (flags & EW_EXEC) && !mch_can_exe(f))
10587 return;
10588
Bram Moolenaar071d4272004-06-13 20:20:40 +000010589 /* Make room for another item in the file list. */
10590 if (ga_grow(gap, 1) == FAIL)
10591 return;
10592
10593 p = alloc((unsigned)(STRLEN(f) + 1 + isdir));
10594 if (p == NULL)
10595 return;
10596
10597 STRCPY(p, f);
10598#ifdef BACKSLASH_IN_FILENAME
10599 slash_adjust(p);
10600#endif
10601 /*
10602 * Append a slash or backslash after directory names if none is present.
10603 */
10604#ifndef DONT_ADD_PATHSEP_TO_DIR
10605 if (isdir && (flags & EW_ADDSLASH))
10606 add_pathsep(p);
10607#endif
10608 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010609}
10610#endif /* !NO_EXPANDPATH */
10611
10612#if defined(VIM_BACKTICK) || defined(FEAT_EVAL) || defined(PROTO)
10613
10614#ifndef SEEK_SET
10615# define SEEK_SET 0
10616#endif
10617#ifndef SEEK_END
10618# define SEEK_END 2
10619#endif
10620
10621/*
10622 * Get the stdout of an external command.
10623 * Returns an allocated string, or NULL for error.
10624 */
10625 char_u *
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010626get_cmd_output(cmd, infile, flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010627 char_u *cmd;
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010628 char_u *infile; /* optional input file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010629 int flags; /* can be SHELL_SILENT */
10630{
10631 char_u *tempname;
10632 char_u *command;
10633 char_u *buffer = NULL;
10634 int len;
10635 int i = 0;
10636 FILE *fd;
10637
10638 if (check_restricted() || check_secure())
10639 return NULL;
10640
10641 /* get a name for the temp file */
10642 if ((tempname = vim_tempname('o')) == NULL)
10643 {
10644 EMSG(_(e_notmp));
10645 return NULL;
10646 }
10647
10648 /* Add the redirection stuff */
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010649 command = make_filter_cmd(cmd, infile, tempname);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010650 if (command == NULL)
10651 goto done;
10652
10653 /*
10654 * Call the shell to execute the command (errors are ignored).
10655 * Don't check timestamps here.
10656 */
10657 ++no_check_timestamps;
10658 call_shell(command, SHELL_DOOUT | SHELL_EXPAND | flags);
10659 --no_check_timestamps;
10660
10661 vim_free(command);
10662
10663 /*
10664 * read the names from the file into memory
10665 */
10666# ifdef VMS
Bram Moolenaar25394022007-05-10 19:06:20 +000010667 /* created temporary file is not always readable as binary */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010668 fd = mch_fopen((char *)tempname, "r");
10669# else
10670 fd = mch_fopen((char *)tempname, READBIN);
10671# endif
10672
10673 if (fd == NULL)
10674 {
10675 EMSG2(_(e_notopen), tempname);
10676 goto done;
10677 }
10678
10679 fseek(fd, 0L, SEEK_END);
10680 len = ftell(fd); /* get size of temp file */
10681 fseek(fd, 0L, SEEK_SET);
10682
10683 buffer = alloc(len + 1);
10684 if (buffer != NULL)
10685 i = (int)fread((char *)buffer, (size_t)1, (size_t)len, fd);
10686 fclose(fd);
10687 mch_remove(tempname);
10688 if (buffer == NULL)
10689 goto done;
10690#ifdef VMS
10691 len = i; /* VMS doesn't give us what we asked for... */
10692#endif
10693 if (i != len)
10694 {
10695 EMSG2(_(e_notread), tempname);
10696 vim_free(buffer);
10697 buffer = NULL;
10698 }
10699 else
Bram Moolenaar162bd912010-07-28 22:29:10 +020010700 buffer[len] = NUL; /* make sure the buffer is terminated */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010701
10702done:
10703 vim_free(tempname);
10704 return buffer;
10705}
10706#endif
10707
10708/*
10709 * Free the list of files returned by expand_wildcards() or other expansion
10710 * functions.
10711 */
10712 void
10713FreeWild(count, files)
10714 int count;
10715 char_u **files;
10716{
Bram Moolenaarfc1421e2006-04-20 22:17:20 +000010717 if (count <= 0 || files == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010718 return;
10719#if defined(__EMX__) && defined(__ALWAYS_HAS_TRAILING_NULL_POINTER) /* XXX */
10720 /*
10721 * Is this still OK for when other functions than expand_wildcards() have
10722 * been used???
10723 */
10724 _fnexplodefree((char **)files);
10725#else
10726 while (count--)
10727 vim_free(files[count]);
10728 vim_free(files);
10729#endif
10730}
10731
10732/*
Bram Moolenaara9dc3752010-07-11 20:46:53 +020010733 * Return TRUE when need to go to Insert mode because of 'insertmode'.
Bram Moolenaar071d4272004-06-13 20:20:40 +000010734 * Don't do this when still processing a command or a mapping.
10735 * Don't do this when inside a ":normal" command.
10736 */
10737 int
10738goto_im()
10739{
10740 return (p_im && stuff_empty() && typebuf_typed());
10741}