blob: a84b3c3d8a07361591c3a58dc443efb56ad4d72c [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);
Bram Moolenaard12f8112012-06-20 17:56:09 +02004540 (void)modify_fname((char_u *)":p", &usedlen,
4541 &homedir_env, &fbuf, &flen);
Bram Moolenaar9158f9e2012-06-20 14:02:27 +02004542 flen = (int)STRLEN(homedir_env);
4543 if (flen > 0 && vim_ispathsep(homedir_env[flen - 1]))
4544 /* Remove the trailing / that is added to a directory. */
4545 homedir_env[flen - 1] = NUL;
4546 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004547#endif
4548
4549 if (homedir_env != NULL && *homedir_env == NUL)
4550 homedir_env = NULL;
4551 if (homedir_env != NULL)
4552 envlen = STRLEN(homedir_env);
4553
4554 if (!one)
4555 src = skipwhite(src);
4556 while (*src && dstlen > 0)
4557 {
4558 /*
4559 * Here we are at the beginning of a file name.
4560 * First, check to see if the beginning of the file name matches
4561 * $HOME or the "real" home directory. Check that there is a '/'
4562 * after the match (so that if e.g. the file is "/home/pieter/bla",
4563 * and the home directory is "/home/piet", the file does not end up
4564 * as "~er/bla" (which would seem to indicate the file "bla" in user
4565 * er's home directory)).
4566 */
4567 p = homedir;
4568 len = dirlen;
4569 for (;;)
4570 {
4571 if ( len
4572 && fnamencmp(src, p, len) == 0
4573 && (vim_ispathsep(src[len])
4574 || (!one && (src[len] == ',' || src[len] == ' '))
4575 || src[len] == NUL))
4576 {
4577 src += len;
4578 if (--dstlen > 0)
4579 *dst++ = '~';
4580
4581 /*
4582 * If it's just the home directory, add "/".
4583 */
4584 if (!vim_ispathsep(src[0]) && --dstlen > 0)
4585 *dst++ = '/';
4586 break;
4587 }
4588 if (p == homedir_env)
4589 break;
4590 p = homedir_env;
4591 len = envlen;
4592 }
4593
4594 /* if (!one) skip to separator: space or comma */
4595 while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
4596 *dst++ = *src++;
4597 /* skip separator */
4598 while ((*src == ' ' || *src == ',') && --dstlen > 0)
4599 *dst++ = *src++;
4600 }
4601 /* if (dstlen == 0) out of space, what to do??? */
4602
4603 *dst = NUL;
Bram Moolenaar9158f9e2012-06-20 14:02:27 +02004604
4605 if (homedir_env != homedir_env_orig)
4606 vim_free(homedir_env);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004607}
4608
4609/*
4610 * Like home_replace, store the replaced string in allocated memory.
4611 * When something fails, NULL is returned.
4612 */
4613 char_u *
4614home_replace_save(buf, src)
4615 buf_T *buf; /* when not NULL, check for help files */
4616 char_u *src; /* input file name */
4617{
4618 char_u *dst;
4619 unsigned len;
4620
4621 len = 3; /* space for "~/" and trailing NUL */
4622 if (src != NULL) /* just in case */
4623 len += (unsigned)STRLEN(src);
4624 dst = alloc(len);
4625 if (dst != NULL)
4626 home_replace(buf, src, dst, len, TRUE);
4627 return dst;
4628}
4629
4630/*
4631 * Compare two file names and return:
4632 * FPC_SAME if they both exist and are the same file.
4633 * FPC_SAMEX if they both don't exist and have the same file name.
4634 * FPC_DIFF if they both exist and are different files.
4635 * FPC_NOTX if they both don't exist.
4636 * FPC_DIFFX if one of them doesn't exist.
4637 * For the first name environment variables are expanded
4638 */
4639 int
4640fullpathcmp(s1, s2, checkname)
4641 char_u *s1, *s2;
4642 int checkname; /* when both don't exist, check file names */
4643{
4644#ifdef UNIX
4645 char_u exp1[MAXPATHL];
4646 char_u full1[MAXPATHL];
4647 char_u full2[MAXPATHL];
4648 struct stat st1, st2;
4649 int r1, r2;
4650
4651 expand_env(s1, exp1, MAXPATHL);
4652 r1 = mch_stat((char *)exp1, &st1);
4653 r2 = mch_stat((char *)s2, &st2);
4654 if (r1 != 0 && r2 != 0)
4655 {
4656 /* if mch_stat() doesn't work, may compare the names */
4657 if (checkname)
4658 {
4659 if (fnamecmp(exp1, s2) == 0)
4660 return FPC_SAMEX;
4661 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4662 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4663 if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
4664 return FPC_SAMEX;
4665 }
4666 return FPC_NOTX;
4667 }
4668 if (r1 != 0 || r2 != 0)
4669 return FPC_DIFFX;
4670 if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
4671 return FPC_SAME;
4672 return FPC_DIFF;
4673#else
4674 char_u *exp1; /* expanded s1 */
4675 char_u *full1; /* full path of s1 */
4676 char_u *full2; /* full path of s2 */
4677 int retval = FPC_DIFF;
4678 int r1, r2;
4679
4680 /* allocate one buffer to store three paths (alloc()/free() is slow!) */
4681 if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
4682 {
4683 full1 = exp1 + MAXPATHL;
4684 full2 = full1 + MAXPATHL;
4685
4686 expand_env(s1, exp1, MAXPATHL);
4687 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4688 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4689
4690 /* If vim_FullName() fails, the file probably doesn't exist. */
4691 if (r1 != OK && r2 != OK)
4692 {
4693 if (checkname && fnamecmp(exp1, s2) == 0)
4694 retval = FPC_SAMEX;
4695 else
4696 retval = FPC_NOTX;
4697 }
4698 else if (r1 != OK || r2 != OK)
4699 retval = FPC_DIFFX;
4700 else if (fnamecmp(full1, full2))
4701 retval = FPC_DIFF;
4702 else
4703 retval = FPC_SAME;
4704 vim_free(exp1);
4705 }
4706 return retval;
4707#endif
4708}
4709
4710/*
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004711 * Get the tail of a path: the file name.
Bram Moolenaar31710262010-08-13 13:36:15 +02004712 * When the path ends in a path separator the tail is the NUL after it.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004713 * Fail safe: never returns NULL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004714 */
4715 char_u *
4716gettail(fname)
4717 char_u *fname;
4718{
4719 char_u *p1, *p2;
4720
4721 if (fname == NULL)
4722 return (char_u *)"";
4723 for (p1 = p2 = fname; *p2; ) /* find last part of path */
4724 {
4725 if (vim_ispathsep(*p2))
4726 p1 = p2 + 1;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004727 mb_ptr_adv(p2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004728 }
4729 return p1;
4730}
4731
Bram Moolenaar31710262010-08-13 13:36:15 +02004732#if defined(FEAT_SEARCHPATH)
4733static char_u *gettail_dir __ARGS((char_u *fname));
4734
4735/*
4736 * Return the end of the directory name, on the first path
4737 * separator:
4738 * "/path/file", "/path/dir/", "/path//dir", "/file"
4739 * ^ ^ ^ ^
4740 */
4741 static char_u *
4742gettail_dir(fname)
4743 char_u *fname;
4744{
4745 char_u *dir_end = fname;
4746 char_u *next_dir_end = fname;
4747 int look_for_sep = TRUE;
4748 char_u *p;
4749
4750 for (p = fname; *p != NUL; )
4751 {
4752 if (vim_ispathsep(*p))
4753 {
4754 if (look_for_sep)
4755 {
4756 next_dir_end = p;
4757 look_for_sep = FALSE;
4758 }
4759 }
4760 else
4761 {
4762 if (!look_for_sep)
4763 dir_end = next_dir_end;
4764 look_for_sep = TRUE;
4765 }
4766 mb_ptr_adv(p);
4767 }
4768 return dir_end;
4769}
4770#endif
4771
Bram Moolenaar071d4272004-06-13 20:20:40 +00004772/*
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004773 * Get pointer to tail of "fname", including path separators. Putting a NUL
4774 * here leaves the directory name. Takes care of "c:/" and "//".
4775 * Always returns a valid pointer.
4776 */
4777 char_u *
4778gettail_sep(fname)
4779 char_u *fname;
4780{
4781 char_u *p;
4782 char_u *t;
4783
4784 p = get_past_head(fname); /* don't remove the '/' from "c:/file" */
4785 t = gettail(fname);
4786 while (t > p && after_pathsep(fname, t))
4787 --t;
4788#ifdef VMS
4789 /* path separator is part of the path */
4790 ++t;
4791#endif
4792 return t;
4793}
4794
4795/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004796 * get the next path component (just after the next path separator).
4797 */
4798 char_u *
4799getnextcomp(fname)
4800 char_u *fname;
4801{
4802 while (*fname && !vim_ispathsep(*fname))
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004803 mb_ptr_adv(fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004804 if (*fname)
4805 ++fname;
4806 return fname;
4807}
4808
Bram Moolenaar071d4272004-06-13 20:20:40 +00004809/*
4810 * Get a pointer to one character past the head of a path name.
4811 * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
4812 * If there is no head, path is returned.
4813 */
4814 char_u *
4815get_past_head(path)
4816 char_u *path;
4817{
4818 char_u *retval;
4819
4820#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
4821 /* may skip "c:" */
4822 if (isalpha(path[0]) && path[1] == ':')
4823 retval = path + 2;
4824 else
4825 retval = path;
4826#else
4827# if defined(AMIGA)
4828 /* may skip "label:" */
4829 retval = vim_strchr(path, ':');
4830 if (retval == NULL)
4831 retval = path;
4832# else /* Unix */
4833 retval = path;
4834# endif
4835#endif
4836
4837 while (vim_ispathsep(*retval))
4838 ++retval;
4839
4840 return retval;
4841}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004842
4843/*
4844 * return TRUE if 'c' is a path separator.
4845 */
4846 int
4847vim_ispathsep(c)
4848 int c;
4849{
Bram Moolenaare60acc12011-05-10 16:41:25 +02004850#ifdef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00004851 return (c == '/'); /* UNIX has ':' inside file names */
Bram Moolenaare60acc12011-05-10 16:41:25 +02004852#else
4853# ifdef BACKSLASH_IN_FILENAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00004854 return (c == ':' || c == '/' || c == '\\');
Bram Moolenaare60acc12011-05-10 16:41:25 +02004855# else
4856# ifdef VMS
Bram Moolenaar071d4272004-06-13 20:20:40 +00004857 /* server"user passwd"::device:[full.path.name]fname.extension;version" */
4858 return (c == ':' || c == '[' || c == ']' || c == '/'
4859 || c == '<' || c == '>' || c == '"' );
Bram Moolenaare60acc12011-05-10 16:41:25 +02004860# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004861 return (c == ':' || c == '/');
Bram Moolenaare60acc12011-05-10 16:41:25 +02004862# endif /* VMS */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004863# endif
Bram Moolenaare60acc12011-05-10 16:41:25 +02004864#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004865}
4866
4867#if defined(FEAT_SEARCHPATH) || defined(PROTO)
4868/*
4869 * return TRUE if 'c' is a path list separator.
4870 */
4871 int
4872vim_ispathlistsep(c)
4873 int c;
4874{
4875#ifdef UNIX
4876 return (c == ':');
4877#else
Bram Moolenaar25394022007-05-10 19:06:20 +00004878 return (c == ';'); /* might not be right for every system... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004879#endif
4880}
4881#endif
4882
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004883#if defined(FEAT_GUI_TABLINE) || defined(FEAT_WINDOWS) \
4884 || defined(FEAT_EVAL) || defined(PROTO)
4885/*
4886 * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
4887 * It's done in-place.
4888 */
4889 void
4890shorten_dir(str)
4891 char_u *str;
4892{
4893 char_u *tail, *s, *d;
4894 int skip = FALSE;
4895
4896 tail = gettail(str);
4897 d = str;
4898 for (s = str; ; ++s)
4899 {
4900 if (s >= tail) /* copy the whole tail */
4901 {
4902 *d++ = *s;
4903 if (*s == NUL)
4904 break;
4905 }
4906 else if (vim_ispathsep(*s)) /* copy '/' and next char */
4907 {
4908 *d++ = *s;
4909 skip = FALSE;
4910 }
4911 else if (!skip)
4912 {
4913 *d++ = *s; /* copy next char */
4914 if (*s != '~' && *s != '.') /* and leading "~" and "." */
4915 skip = TRUE;
4916# ifdef FEAT_MBYTE
4917 if (has_mbyte)
4918 {
4919 int l = mb_ptr2len(s);
4920
4921 while (--l > 0)
Bram Moolenaarb6baca52006-08-15 20:24:14 +00004922 *d++ = *++s;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004923 }
4924# endif
4925 }
4926 }
4927}
4928#endif
4929
Bram Moolenaar900b4d72005-12-12 22:05:50 +00004930/*
4931 * Return TRUE if the directory of "fname" exists, FALSE otherwise.
4932 * Also returns TRUE if there is no directory name.
4933 * "fname" must be writable!.
4934 */
4935 int
4936dir_of_file_exists(fname)
4937 char_u *fname;
4938{
4939 char_u *p;
4940 int c;
4941 int retval;
4942
4943 p = gettail_sep(fname);
4944 if (p == fname)
4945 return TRUE;
4946 c = *p;
4947 *p = NUL;
4948 retval = mch_isdir(fname);
4949 *p = c;
4950 return retval;
4951}
4952
Bram Moolenaar071d4272004-06-13 20:20:40 +00004953#if (defined(CASE_INSENSITIVE_FILENAME) && defined(BACKSLASH_IN_FILENAME)) \
4954 || defined(PROTO)
4955/*
4956 * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally.
4957 */
4958 int
4959vim_fnamecmp(x, y)
4960 char_u *x, *y;
4961{
4962 return vim_fnamencmp(x, y, MAXPATHL);
4963}
4964
4965 int
4966vim_fnamencmp(x, y, len)
4967 char_u *x, *y;
4968 size_t len;
4969{
4970 while (len > 0 && *x && *y)
4971 {
4972 if (TOLOWER_LOC(*x) != TOLOWER_LOC(*y)
4973 && !(*x == '/' && *y == '\\')
4974 && !(*x == '\\' && *y == '/'))
4975 break;
4976 ++x;
4977 ++y;
4978 --len;
4979 }
4980 if (len == 0)
4981 return 0;
4982 return (*x - *y);
4983}
4984#endif
4985
4986/*
4987 * Concatenate file names fname1 and fname2 into allocated memory.
Bram Moolenaar25394022007-05-10 19:06:20 +00004988 * Only add a '/' or '\\' when 'sep' is TRUE and it is necessary.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004989 */
4990 char_u *
4991concat_fnames(fname1, fname2, sep)
4992 char_u *fname1;
4993 char_u *fname2;
4994 int sep;
4995{
4996 char_u *dest;
4997
4998 dest = alloc((unsigned)(STRLEN(fname1) + STRLEN(fname2) + 3));
4999 if (dest != NULL)
5000 {
5001 STRCPY(dest, fname1);
5002 if (sep)
5003 add_pathsep(dest);
5004 STRCAT(dest, fname2);
5005 }
5006 return dest;
5007}
5008
Bram Moolenaard6754642005-01-17 22:18:45 +00005009/*
5010 * Concatenate two strings and return the result in allocated memory.
5011 * Returns NULL when out of memory.
5012 */
5013 char_u *
5014concat_str(str1, str2)
5015 char_u *str1;
5016 char_u *str2;
5017{
5018 char_u *dest;
5019 size_t l = STRLEN(str1);
5020
5021 dest = alloc((unsigned)(l + STRLEN(str2) + 1L));
5022 if (dest != NULL)
5023 {
5024 STRCPY(dest, str1);
5025 STRCPY(dest + l, str2);
5026 }
5027 return dest;
5028}
Bram Moolenaard6754642005-01-17 22:18:45 +00005029
Bram Moolenaar071d4272004-06-13 20:20:40 +00005030/*
5031 * Add a path separator to a file name, unless it already ends in a path
5032 * separator.
5033 */
5034 void
5035add_pathsep(p)
5036 char_u *p;
5037{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005038 if (*p != NUL && !after_pathsep(p, p + STRLEN(p)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005039 STRCAT(p, PATHSEPSTR);
5040}
5041
5042/*
5043 * FullName_save - Make an allocated copy of a full file name.
5044 * Returns NULL when out of memory.
5045 */
5046 char_u *
5047FullName_save(fname, force)
5048 char_u *fname;
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +02005049 int force; /* force expansion, even when it already looks
5050 * like a full path name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005051{
5052 char_u *buf;
5053 char_u *new_fname = NULL;
5054
5055 if (fname == NULL)
5056 return NULL;
5057
5058 buf = alloc((unsigned)MAXPATHL);
5059 if (buf != NULL)
5060 {
5061 if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
5062 new_fname = vim_strsave(buf);
5063 else
5064 new_fname = vim_strsave(fname);
5065 vim_free(buf);
5066 }
5067 return new_fname;
5068}
5069
5070#if defined(FEAT_CINDENT) || defined(FEAT_SYN_HL)
5071
5072static char_u *skip_string __ARGS((char_u *p));
5073
5074/*
5075 * Find the start of a comment, not knowing if we are in a comment right now.
5076 * Search starts at w_cursor.lnum and goes backwards.
5077 */
5078 pos_T *
5079find_start_comment(ind_maxcomment) /* XXX */
5080 int ind_maxcomment;
5081{
5082 pos_T *pos;
5083 char_u *line;
5084 char_u *p;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005085 int cur_maxcomment = ind_maxcomment;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005086
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005087 for (;;)
5088 {
5089 pos = findmatchlimit(NULL, '*', FM_BACKWARD, cur_maxcomment);
5090 if (pos == NULL)
5091 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005092
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005093 /*
5094 * Check if the comment start we found is inside a string.
5095 * If it is then restrict the search to below this line and try again.
5096 */
5097 line = ml_get(pos->lnum);
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00005098 for (p = line; *p && (colnr_T)(p - line) < pos->col; ++p)
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005099 p = skip_string(p);
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00005100 if ((colnr_T)(p - line) <= pos->col)
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005101 break;
5102 cur_maxcomment = curwin->w_cursor.lnum - pos->lnum - 1;
5103 if (cur_maxcomment <= 0)
5104 {
5105 pos = NULL;
5106 break;
5107 }
5108 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005109 return pos;
5110}
5111
5112/*
5113 * Skip to the end of a "string" and a 'c' character.
5114 * If there is no string or character, return argument unmodified.
5115 */
5116 static char_u *
5117skip_string(p)
5118 char_u *p;
5119{
5120 int i;
5121
5122 /*
5123 * We loop, because strings may be concatenated: "date""time".
5124 */
5125 for ( ; ; ++p)
5126 {
5127 if (p[0] == '\'') /* 'c' or '\n' or '\000' */
5128 {
5129 if (!p[1]) /* ' at end of line */
5130 break;
5131 i = 2;
5132 if (p[1] == '\\') /* '\n' or '\000' */
5133 {
5134 ++i;
5135 while (vim_isdigit(p[i - 1])) /* '\000' */
5136 ++i;
5137 }
5138 if (p[i] == '\'') /* check for trailing ' */
5139 {
5140 p += i;
5141 continue;
5142 }
5143 }
5144 else if (p[0] == '"') /* start of string */
5145 {
5146 for (++p; p[0]; ++p)
5147 {
5148 if (p[0] == '\\' && p[1] != NUL)
5149 ++p;
5150 else if (p[0] == '"') /* end of string */
5151 break;
5152 }
5153 if (p[0] == '"')
5154 continue;
5155 }
5156 break; /* no string found */
5157 }
5158 if (!*p)
5159 --p; /* backup from NUL */
5160 return p;
5161}
5162#endif /* FEAT_CINDENT || FEAT_SYN_HL */
5163
5164#if defined(FEAT_CINDENT) || defined(PROTO)
5165
5166/*
5167 * Do C or expression indenting on the current line.
5168 */
5169 void
5170do_c_expr_indent()
5171{
5172# ifdef FEAT_EVAL
5173 if (*curbuf->b_p_inde != NUL)
5174 fixthisline(get_expr_indent);
5175 else
5176# endif
5177 fixthisline(get_c_indent);
5178}
5179
5180/*
5181 * Functions for C-indenting.
5182 * Most of this originally comes from Eric Fischer.
5183 */
5184/*
5185 * Below "XXX" means that this function may unlock the current line.
5186 */
5187
5188static char_u *cin_skipcomment __ARGS((char_u *));
5189static int cin_nocode __ARGS((char_u *));
5190static pos_T *find_line_comment __ARGS((void));
5191static int cin_islabel_skip __ARGS((char_u **));
5192static int cin_isdefault __ARGS((char_u *));
5193static char_u *after_label __ARGS((char_u *l));
5194static int get_indent_nolabel __ARGS((linenr_T lnum));
5195static int skip_label __ARGS((linenr_T, char_u **pp, int ind_maxcomment));
5196static int cin_first_id_amount __ARGS((void));
5197static int cin_get_equal_amount __ARGS((linenr_T lnum));
5198static int cin_ispreproc __ARGS((char_u *));
5199static int cin_ispreproc_cont __ARGS((char_u **pp, linenr_T *lnump));
5200static int cin_iscomment __ARGS((char_u *));
5201static int cin_islinecomment __ARGS((char_u *));
5202static int cin_isterminated __ARGS((char_u *, int, int));
5203static int cin_isinit __ARGS((void));
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005204static int cin_isfuncdecl __ARGS((char_u **, linenr_T, linenr_T, int, int));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005205static int cin_isif __ARGS((char_u *));
5206static int cin_iselse __ARGS((char_u *));
5207static int cin_isdo __ARGS((char_u *));
5208static int cin_iswhileofdo __ARGS((char_u *, linenr_T, int));
Bram Moolenaarb345d492012-04-09 20:42:26 +02005209static int cin_is_if_for_while_before_offset __ARGS((char_u *line, int *poffset));
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005210static int cin_iswhileofdo_end __ARGS((int terminated, int ind_maxparen, int ind_maxcomment));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005211static int cin_isbreak __ARGS((char_u *));
Bram Moolenaare7c56862007-08-04 10:14:52 +00005212static int cin_is_cpp_baseclass __ARGS((colnr_T *col));
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005213static int get_baseclass_amount __ARGS((int col, int ind_maxparen, int ind_maxcomment, int ind_cpp_baseclass));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005214static int cin_ends_in __ARGS((char_u *, char_u *, char_u *));
5215static int cin_skip2pos __ARGS((pos_T *trypos));
5216static pos_T *find_start_brace __ARGS((int));
5217static pos_T *find_match_paren __ARGS((int, int));
5218static int corr_ind_maxparen __ARGS((int ind_maxparen, pos_T *startpos));
5219static int find_last_paren __ARGS((char_u *l, int start, int end));
5220static int find_match __ARGS((int lookfor, linenr_T ourscope, int ind_maxparen, int ind_maxcomment));
Bram Moolenaared38b0a2011-05-25 15:16:18 +02005221static int cin_is_cpp_namespace __ARGS((char_u *));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005222
Bram Moolenaar39353fd2007-03-27 09:02:11 +00005223static int ind_hash_comment = 0; /* # starts a comment */
5224
Bram Moolenaar071d4272004-06-13 20:20:40 +00005225/*
5226 * Skip over white space and C comments within the line.
Bram Moolenaar39353fd2007-03-27 09:02:11 +00005227 * Also skip over Perl/shell comments if desired.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005228 */
5229 static char_u *
5230cin_skipcomment(s)
5231 char_u *s;
5232{
5233 while (*s)
5234 {
Bram Moolenaar39353fd2007-03-27 09:02:11 +00005235 char_u *prev_s = s;
5236
Bram Moolenaar071d4272004-06-13 20:20:40 +00005237 s = skipwhite(s);
Bram Moolenaar39353fd2007-03-27 09:02:11 +00005238
5239 /* Perl/shell # comment comment continues until eol. Require a space
5240 * before # to avoid recognizing $#array. */
5241 if (ind_hash_comment != 0 && s != prev_s && *s == '#')
5242 {
5243 s += STRLEN(s);
5244 break;
5245 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005246 if (*s != '/')
5247 break;
5248 ++s;
5249 if (*s == '/') /* slash-slash comment continues till eol */
5250 {
5251 s += STRLEN(s);
5252 break;
5253 }
5254 if (*s != '*')
5255 break;
5256 for (++s; *s; ++s) /* skip slash-star comment */
5257 if (s[0] == '*' && s[1] == '/')
5258 {
5259 s += 2;
5260 break;
5261 }
5262 }
5263 return s;
5264}
5265
5266/*
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005267 * Return TRUE if there is no code at *s. White space and comments are
Bram Moolenaar071d4272004-06-13 20:20:40 +00005268 * not considered code.
5269 */
5270 static int
5271cin_nocode(s)
5272 char_u *s;
5273{
5274 return *cin_skipcomment(s) == NUL;
5275}
5276
5277/*
5278 * Check previous lines for a "//" line comment, skipping over blank lines.
5279 */
5280 static pos_T *
5281find_line_comment() /* XXX */
5282{
5283 static pos_T pos;
5284 char_u *line;
5285 char_u *p;
5286
5287 pos = curwin->w_cursor;
5288 while (--pos.lnum > 0)
5289 {
5290 line = ml_get(pos.lnum);
5291 p = skipwhite(line);
5292 if (cin_islinecomment(p))
5293 {
5294 pos.col = (int)(p - line);
5295 return &pos;
5296 }
5297 if (*p != NUL)
5298 break;
5299 }
5300 return NULL;
5301}
5302
5303/*
5304 * Check if string matches "label:"; move to character after ':' if true.
5305 */
5306 static int
5307cin_islabel_skip(s)
5308 char_u **s;
5309{
5310 if (!vim_isIDc(**s)) /* need at least one ID character */
5311 return FALSE;
5312
5313 while (vim_isIDc(**s))
5314 (*s)++;
5315
5316 *s = cin_skipcomment(*s);
5317
5318 /* "::" is not a label, it's C++ */
5319 return (**s == ':' && *++*s != ':');
5320}
5321
5322/*
5323 * Recognize a label: "label:".
5324 * Note: curwin->w_cursor must be where we are looking for the label.
5325 */
5326 int
5327cin_islabel(ind_maxcomment) /* XXX */
5328 int ind_maxcomment;
5329{
5330 char_u *s;
5331
5332 s = cin_skipcomment(ml_get_curline());
5333
5334 /*
5335 * Exclude "default" from labels, since it should be indented
5336 * like a switch label. Same for C++ scope declarations.
5337 */
5338 if (cin_isdefault(s))
5339 return FALSE;
5340 if (cin_isscopedecl(s))
5341 return FALSE;
5342
5343 if (cin_islabel_skip(&s))
5344 {
5345 /*
5346 * Only accept a label if the previous line is terminated or is a case
5347 * label.
5348 */
5349 pos_T cursor_save;
5350 pos_T *trypos;
5351 char_u *line;
5352
5353 cursor_save = curwin->w_cursor;
5354 while (curwin->w_cursor.lnum > 1)
5355 {
5356 --curwin->w_cursor.lnum;
5357
5358 /*
5359 * If we're in a comment now, skip to the start of the comment.
5360 */
5361 curwin->w_cursor.col = 0;
5362 if ((trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
5363 curwin->w_cursor = *trypos;
5364
5365 line = ml_get_curline();
5366 if (cin_ispreproc(line)) /* ignore #defines, #if, etc. */
5367 continue;
5368 if (*(line = cin_skipcomment(line)) == NUL)
5369 continue;
5370
5371 curwin->w_cursor = cursor_save;
5372 if (cin_isterminated(line, TRUE, FALSE)
5373 || cin_isscopedecl(line)
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005374 || cin_iscase(line, TRUE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005375 || (cin_islabel_skip(&line) && cin_nocode(line)))
5376 return TRUE;
5377 return FALSE;
5378 }
5379 curwin->w_cursor = cursor_save;
5380 return TRUE; /* label at start of file??? */
5381 }
5382 return FALSE;
5383}
5384
5385/*
5386 * Recognize structure initialization and enumerations.
5387 * Q&D-Implementation:
5388 * check for "=" at end or "[typedef] enum" at beginning of line.
5389 */
5390 static int
5391cin_isinit(void)
5392{
5393 char_u *s;
5394
5395 s = cin_skipcomment(ml_get_curline());
5396
5397 if (STRNCMP(s, "typedef", 7) == 0 && !vim_isIDc(s[7]))
5398 s = cin_skipcomment(s + 7);
5399
Bram Moolenaara5285652011-12-14 20:05:21 +01005400 if (STRNCMP(s, "static", 6) == 0 && !vim_isIDc(s[6]))
5401 s = cin_skipcomment(s + 6);
5402
Bram Moolenaar071d4272004-06-13 20:20:40 +00005403 if (STRNCMP(s, "enum", 4) == 0 && !vim_isIDc(s[4]))
5404 return TRUE;
5405
5406 if (cin_ends_in(s, (char_u *)"=", (char_u *)"{"))
5407 return TRUE;
5408
5409 return FALSE;
5410}
5411
5412/*
5413 * Recognize a switch label: "case .*:" or "default:".
5414 */
5415 int
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005416cin_iscase(s, strict)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005417 char_u *s;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005418 int strict; /* Allow relaxed check of case statement for JS */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005419{
5420 s = cin_skipcomment(s);
5421 if (STRNCMP(s, "case", 4) == 0 && !vim_isIDc(s[4]))
5422 {
5423 for (s += 4; *s; ++s)
5424 {
5425 s = cin_skipcomment(s);
5426 if (*s == ':')
5427 {
5428 if (s[1] == ':') /* skip over "::" for C++ */
5429 ++s;
5430 else
5431 return TRUE;
5432 }
5433 if (*s == '\'' && s[1] && s[2] == '\'')
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005434 s += 2; /* skip over ':' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005435 else if (*s == '/' && (s[1] == '*' || s[1] == '/'))
5436 return FALSE; /* stop at comment */
5437 else if (*s == '"')
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005438 {
5439 /* JS etc. */
5440 if (strict)
5441 return FALSE; /* stop at string */
5442 else
5443 return TRUE;
5444 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005445 }
5446 return FALSE;
5447 }
5448
5449 if (cin_isdefault(s))
5450 return TRUE;
5451 return FALSE;
5452}
5453
5454/*
5455 * Recognize a "default" switch label.
5456 */
5457 static int
5458cin_isdefault(s)
5459 char_u *s;
5460{
5461 return (STRNCMP(s, "default", 7) == 0
5462 && *(s = cin_skipcomment(s + 7)) == ':'
5463 && s[1] != ':');
5464}
5465
5466/*
Bram Moolenaar1a509df2010-08-01 17:59:57 +02005467 * Recognize a "public/private/protected" scope declaration label.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005468 */
5469 int
5470cin_isscopedecl(s)
5471 char_u *s;
5472{
5473 int i;
5474
5475 s = cin_skipcomment(s);
5476 if (STRNCMP(s, "public", 6) == 0)
5477 i = 6;
5478 else if (STRNCMP(s, "protected", 9) == 0)
5479 i = 9;
5480 else if (STRNCMP(s, "private", 7) == 0)
5481 i = 7;
5482 else
5483 return FALSE;
5484 return (*(s = cin_skipcomment(s + i)) == ':' && s[1] != ':');
5485}
5486
Bram Moolenaared38b0a2011-05-25 15:16:18 +02005487/* Maximum number of lines to search back for a "namespace" line. */
5488#define FIND_NAMESPACE_LIM 20
5489
5490/*
5491 * Recognize a "namespace" scope declaration.
5492 */
5493 static int
5494cin_is_cpp_namespace(s)
5495 char_u *s;
5496{
5497 char_u *p;
5498 int has_name = FALSE;
5499
5500 s = cin_skipcomment(s);
5501 if (STRNCMP(s, "namespace", 9) == 0 && (s[9] == NUL || !vim_iswordc(s[9])))
5502 {
5503 p = cin_skipcomment(skipwhite(s + 9));
5504 while (*p != NUL)
5505 {
5506 if (vim_iswhite(*p))
5507 {
5508 has_name = TRUE; /* found end of a name */
5509 p = cin_skipcomment(skipwhite(p));
5510 }
5511 else if (*p == '{')
5512 {
5513 break;
5514 }
5515 else if (vim_iswordc(*p))
5516 {
5517 if (has_name)
5518 return FALSE; /* word character after skipping past name */
5519 ++p;
5520 }
5521 else
5522 {
5523 return FALSE;
5524 }
5525 }
5526 return TRUE;
5527 }
5528 return FALSE;
5529}
5530
Bram Moolenaar071d4272004-06-13 20:20:40 +00005531/*
5532 * Return a pointer to the first non-empty non-comment character after a ':'.
5533 * Return NULL if not found.
5534 * case 234: a = b;
5535 * ^
5536 */
5537 static char_u *
5538after_label(l)
5539 char_u *l;
5540{
5541 for ( ; *l; ++l)
5542 {
5543 if (*l == ':')
5544 {
5545 if (l[1] == ':') /* skip over "::" for C++ */
5546 ++l;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005547 else if (!cin_iscase(l + 1, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005548 break;
5549 }
5550 else if (*l == '\'' && l[1] && l[2] == '\'')
5551 l += 2; /* skip over 'x' */
5552 }
5553 if (*l == NUL)
5554 return NULL;
5555 l = cin_skipcomment(l + 1);
5556 if (*l == NUL)
5557 return NULL;
5558 return l;
5559}
5560
5561/*
5562 * Get indent of line "lnum", skipping a label.
5563 * Return 0 if there is nothing after the label.
5564 */
5565 static int
5566get_indent_nolabel(lnum) /* XXX */
5567 linenr_T lnum;
5568{
5569 char_u *l;
5570 pos_T fp;
5571 colnr_T col;
5572 char_u *p;
5573
5574 l = ml_get(lnum);
5575 p = after_label(l);
5576 if (p == NULL)
5577 return 0;
5578
5579 fp.col = (colnr_T)(p - l);
5580 fp.lnum = lnum;
5581 getvcol(curwin, &fp, &col, NULL, NULL);
5582 return (int)col;
5583}
5584
5585/*
5586 * Find indent for line "lnum", ignoring any case or jump label.
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005587 * Also return a pointer to the text (after the label) in "pp".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005588 * label: if (asdf && asdfasdf)
5589 * ^
5590 */
5591 static int
5592skip_label(lnum, pp, ind_maxcomment)
5593 linenr_T lnum;
5594 char_u **pp;
5595 int ind_maxcomment;
5596{
5597 char_u *l;
5598 int amount;
5599 pos_T cursor_save;
5600
5601 cursor_save = curwin->w_cursor;
5602 curwin->w_cursor.lnum = lnum;
5603 l = ml_get_curline();
5604 /* XXX */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005605 if (cin_iscase(l, FALSE) || cin_isscopedecl(l)
5606 || cin_islabel(ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005607 {
5608 amount = get_indent_nolabel(lnum);
5609 l = after_label(ml_get_curline());
5610 if (l == NULL) /* just in case */
5611 l = ml_get_curline();
5612 }
5613 else
5614 {
5615 amount = get_indent();
5616 l = ml_get_curline();
5617 }
5618 *pp = l;
5619
5620 curwin->w_cursor = cursor_save;
5621 return amount;
5622}
5623
5624/*
5625 * Return the indent of the first variable name after a type in a declaration.
5626 * int a, indent of "a"
5627 * static struct foo b, indent of "b"
5628 * enum bla c, indent of "c"
5629 * Returns zero when it doesn't look like a declaration.
5630 */
5631 static int
5632cin_first_id_amount()
5633{
5634 char_u *line, *p, *s;
5635 int len;
5636 pos_T fp;
5637 colnr_T col;
5638
5639 line = ml_get_curline();
5640 p = skipwhite(line);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005641 len = (int)(skiptowhite(p) - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005642 if (len == 6 && STRNCMP(p, "static", 6) == 0)
5643 {
5644 p = skipwhite(p + 6);
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00005645 len = (int)(skiptowhite(p) - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005646 }
5647 if (len == 6 && STRNCMP(p, "struct", 6) == 0)
5648 p = skipwhite(p + 6);
5649 else if (len == 4 && STRNCMP(p, "enum", 4) == 0)
5650 p = skipwhite(p + 4);
5651 else if ((len == 8 && STRNCMP(p, "unsigned", 8) == 0)
5652 || (len == 6 && STRNCMP(p, "signed", 6) == 0))
5653 {
5654 s = skipwhite(p + len);
5655 if ((STRNCMP(s, "int", 3) == 0 && vim_iswhite(s[3]))
5656 || (STRNCMP(s, "long", 4) == 0 && vim_iswhite(s[4]))
5657 || (STRNCMP(s, "short", 5) == 0 && vim_iswhite(s[5]))
5658 || (STRNCMP(s, "char", 4) == 0 && vim_iswhite(s[4])))
5659 p = s;
5660 }
5661 for (len = 0; vim_isIDc(p[len]); ++len)
5662 ;
5663 if (len == 0 || !vim_iswhite(p[len]) || cin_nocode(p))
5664 return 0;
5665
5666 p = skipwhite(p + len);
5667 fp.lnum = curwin->w_cursor.lnum;
5668 fp.col = (colnr_T)(p - line);
5669 getvcol(curwin, &fp, &col, NULL, NULL);
5670 return (int)col;
5671}
5672
5673/*
5674 * Return the indent of the first non-blank after an equal sign.
5675 * char *foo = "here";
5676 * Return zero if no (useful) equal sign found.
5677 * Return -1 if the line above "lnum" ends in a backslash.
5678 * foo = "asdf\
5679 * asdf\
5680 * here";
5681 */
5682 static int
5683cin_get_equal_amount(lnum)
5684 linenr_T lnum;
5685{
5686 char_u *line;
5687 char_u *s;
5688 colnr_T col;
5689 pos_T fp;
5690
5691 if (lnum > 1)
5692 {
5693 line = ml_get(lnum - 1);
5694 if (*line != NUL && line[STRLEN(line) - 1] == '\\')
5695 return -1;
5696 }
5697
5698 line = s = ml_get(lnum);
5699 while (*s != NUL && vim_strchr((char_u *)"=;{}\"'", *s) == NULL)
5700 {
5701 if (cin_iscomment(s)) /* ignore comments */
5702 s = cin_skipcomment(s);
5703 else
5704 ++s;
5705 }
5706 if (*s != '=')
5707 return 0;
5708
5709 s = skipwhite(s + 1);
5710 if (cin_nocode(s))
5711 return 0;
5712
5713 if (*s == '"') /* nice alignment for continued strings */
5714 ++s;
5715
5716 fp.lnum = lnum;
5717 fp.col = (colnr_T)(s - line);
5718 getvcol(curwin, &fp, &col, NULL, NULL);
5719 return (int)col;
5720}
5721
5722/*
5723 * Recognize a preprocessor statement: Any line that starts with '#'.
5724 */
5725 static int
5726cin_ispreproc(s)
5727 char_u *s;
5728{
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005729 if (*skipwhite(s) == '#')
Bram Moolenaar071d4272004-06-13 20:20:40 +00005730 return TRUE;
5731 return FALSE;
5732}
5733
5734/*
5735 * Return TRUE if line "*pp" at "*lnump" is a preprocessor statement or a
5736 * continuation line of a preprocessor statement. Decrease "*lnump" to the
5737 * start and return the line in "*pp".
5738 */
5739 static int
5740cin_ispreproc_cont(pp, lnump)
5741 char_u **pp;
5742 linenr_T *lnump;
5743{
5744 char_u *line = *pp;
5745 linenr_T lnum = *lnump;
5746 int retval = FALSE;
5747
Bram Moolenaard8e9bb22005-07-09 21:14:46 +00005748 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005749 {
5750 if (cin_ispreproc(line))
5751 {
5752 retval = TRUE;
5753 *lnump = lnum;
5754 break;
5755 }
5756 if (lnum == 1)
5757 break;
5758 line = ml_get(--lnum);
5759 if (*line == NUL || line[STRLEN(line) - 1] != '\\')
5760 break;
5761 }
5762
5763 if (lnum != *lnump)
5764 *pp = ml_get(*lnump);
5765 return retval;
5766}
5767
5768/*
5769 * Recognize the start of a C or C++ comment.
5770 */
5771 static int
5772cin_iscomment(p)
5773 char_u *p;
5774{
5775 return (p[0] == '/' && (p[1] == '*' || p[1] == '/'));
5776}
5777
5778/*
5779 * Recognize the start of a "//" comment.
5780 */
5781 static int
5782cin_islinecomment(p)
5783 char_u *p;
5784{
5785 return (p[0] == '/' && p[1] == '/');
5786}
5787
5788/*
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005789 * Recognize a line that starts with '{' or '}', or ends with ';', ',', '{' or
5790 * '}'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005791 * Don't consider "} else" a terminated line.
Bram Moolenaar496f9512011-05-19 16:35:09 +02005792 * If a line begins with an "else", only consider it terminated if no unmatched
5793 * opening braces follow (handle "else { foo();" correctly).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005794 * Return the character terminating the line (ending char's have precedence if
5795 * both apply in order to determine initializations).
5796 */
5797 static int
5798cin_isterminated(s, incl_open, incl_comma)
5799 char_u *s;
5800 int incl_open; /* include '{' at the end as terminator */
5801 int incl_comma; /* recognize a trailing comma */
5802{
Bram Moolenaar496f9512011-05-19 16:35:09 +02005803 char_u found_start = 0;
5804 unsigned n_open = 0;
5805 int is_else = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005806
5807 s = cin_skipcomment(s);
5808
5809 if (*s == '{' || (*s == '}' && !cin_iselse(s)))
5810 found_start = *s;
5811
Bram Moolenaar496f9512011-05-19 16:35:09 +02005812 if (!found_start)
5813 is_else = cin_iselse(s);
5814
Bram Moolenaar071d4272004-06-13 20:20:40 +00005815 while (*s)
5816 {
5817 /* skip over comments, "" strings and 'c'haracters */
5818 s = skip_string(cin_skipcomment(s));
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005819 if (*s == '}' && n_open > 0)
5820 --n_open;
Bram Moolenaar496f9512011-05-19 16:35:09 +02005821 if ((!is_else || n_open == 0)
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005822 && (*s == ';' || *s == '}' || (incl_comma && *s == ','))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005823 && cin_nocode(s + 1))
5824 return *s;
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005825 else if (*s == '{')
5826 {
5827 if (incl_open && cin_nocode(s + 1))
5828 return *s;
5829 else
5830 ++n_open;
5831 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005832
5833 if (*s)
5834 s++;
5835 }
5836 return found_start;
5837}
5838
5839/*
5840 * Recognize the basic picture of a function declaration -- it needs to
5841 * have an open paren somewhere and a close paren at the end of the line and
5842 * no semicolons anywhere.
5843 * When a line ends in a comma we continue looking in the next line.
5844 * "sp" points to a string with the line. When looking at other lines it must
5845 * be restored to the line. When it's NULL fetch lines here.
5846 * "lnum" is where we start looking.
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005847 * "min_lnum" is the line before which we will not be looking.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005848 */
5849 static int
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005850cin_isfuncdecl(sp, first_lnum, min_lnum, ind_maxparen, ind_maxcomment)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005851 char_u **sp;
5852 linenr_T first_lnum;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005853 linenr_T min_lnum;
5854 int ind_maxparen;
5855 int ind_maxcomment;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005856{
5857 char_u *s;
5858 linenr_T lnum = first_lnum;
5859 int retval = FALSE;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005860 pos_T *trypos;
5861 int just_started = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005862
5863 if (sp == NULL)
5864 s = ml_get(lnum);
5865 else
5866 s = *sp;
5867
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005868 if (find_last_paren(s, '(', ')')
5869 && (trypos = find_match_paren(ind_maxparen, ind_maxcomment)) != NULL)
5870 {
5871 lnum = trypos->lnum;
5872 if (lnum < min_lnum)
5873 return FALSE;
5874
5875 s = ml_get(lnum);
5876 }
5877
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005878 /* Ignore line starting with #. */
5879 if (cin_ispreproc(s))
5880 return FALSE;
5881
Bram Moolenaar071d4272004-06-13 20:20:40 +00005882 while (*s && *s != '(' && *s != ';' && *s != '\'' && *s != '"')
5883 {
5884 if (cin_iscomment(s)) /* ignore comments */
5885 s = cin_skipcomment(s);
5886 else
5887 ++s;
5888 }
5889 if (*s != '(')
5890 return FALSE; /* ';', ' or " before any () or no '(' */
5891
5892 while (*s && *s != ';' && *s != '\'' && *s != '"')
5893 {
5894 if (*s == ')' && cin_nocode(s + 1))
5895 {
5896 /* ')' at the end: may have found a match
5897 * Check for he previous line not to end in a backslash:
5898 * #if defined(x) && \
5899 * defined(y)
5900 */
5901 lnum = first_lnum - 1;
5902 s = ml_get(lnum);
5903 if (*s == NUL || s[STRLEN(s) - 1] != '\\')
5904 retval = TRUE;
5905 goto done;
5906 }
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005907 if ((*s == ',' && cin_nocode(s + 1)) || s[1] == NUL || cin_nocode(s))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005908 {
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005909 int comma = (*s == ',');
5910
5911 /* ',' at the end: continue looking in the next line.
5912 * At the end: check for ',' in the next line, for this style:
5913 * func(arg1
5914 * , arg2) */
5915 for (;;)
5916 {
5917 if (lnum >= curbuf->b_ml.ml_line_count)
5918 break;
5919 s = ml_get(++lnum);
5920 if (!cin_ispreproc(s))
5921 break;
5922 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005923 if (lnum >= curbuf->b_ml.ml_line_count)
5924 break;
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005925 /* Require a comma at end of the line or a comma or ')' at the
5926 * start of next line. */
5927 s = skipwhite(s);
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005928 if (!just_started && (!comma && *s != ',' && *s != ')'))
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005929 break;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005930 just_started = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005931 }
5932 else if (cin_iscomment(s)) /* ignore comments */
5933 s = cin_skipcomment(s);
5934 else
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005935 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005936 ++s;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005937 just_started = FALSE;
5938 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005939 }
5940
5941done:
5942 if (lnum != first_lnum && sp != NULL)
5943 *sp = ml_get(first_lnum);
5944
5945 return retval;
5946}
5947
5948 static int
5949cin_isif(p)
5950 char_u *p;
5951{
5952 return (STRNCMP(p, "if", 2) == 0 && !vim_isIDc(p[2]));
5953}
5954
5955 static int
5956cin_iselse(p)
5957 char_u *p;
5958{
5959 if (*p == '}') /* accept "} else" */
5960 p = cin_skipcomment(p + 1);
5961 return (STRNCMP(p, "else", 4) == 0 && !vim_isIDc(p[4]));
5962}
5963
5964 static int
5965cin_isdo(p)
5966 char_u *p;
5967{
5968 return (STRNCMP(p, "do", 2) == 0 && !vim_isIDc(p[2]));
5969}
5970
5971/*
5972 * Check if this is a "while" that should have a matching "do".
5973 * We only accept a "while (condition) ;", with only white space between the
5974 * ')' and ';'. The condition may be spread over several lines.
5975 */
5976 static int
5977cin_iswhileofdo(p, lnum, ind_maxparen) /* XXX */
5978 char_u *p;
5979 linenr_T lnum;
5980 int ind_maxparen;
5981{
5982 pos_T cursor_save;
5983 pos_T *trypos;
5984 int retval = FALSE;
5985
5986 p = cin_skipcomment(p);
5987 if (*p == '}') /* accept "} while (cond);" */
5988 p = cin_skipcomment(p + 1);
5989 if (STRNCMP(p, "while", 5) == 0 && !vim_isIDc(p[5]))
5990 {
5991 cursor_save = curwin->w_cursor;
5992 curwin->w_cursor.lnum = lnum;
5993 curwin->w_cursor.col = 0;
5994 p = ml_get_curline();
5995 while (*p && *p != 'w') /* skip any '}', until the 'w' of the "while" */
5996 {
5997 ++p;
5998 ++curwin->w_cursor.col;
5999 }
6000 if ((trypos = findmatchlimit(NULL, 0, 0, ind_maxparen)) != NULL
6001 && *cin_skipcomment(ml_get_pos(trypos) + 1) == ';')
6002 retval = TRUE;
6003 curwin->w_cursor = cursor_save;
6004 }
6005 return retval;
6006}
6007
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006008/*
Bram Moolenaarb345d492012-04-09 20:42:26 +02006009 * Check whether in "p" there is an "if", "for" or "while" before "*poffset".
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006010 * Return 0 if there is none.
6011 * Otherwise return !0 and update "*poffset" to point to the place where the
6012 * string was found.
6013 */
6014 static int
Bram Moolenaarb345d492012-04-09 20:42:26 +02006015cin_is_if_for_while_before_offset(line, poffset)
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006016 char_u *line;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006017 int *poffset;
6018{
Bram Moolenaarb345d492012-04-09 20:42:26 +02006019 int offset = *poffset;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006020
6021 if (offset-- < 2)
6022 return 0;
6023 while (offset > 2 && vim_iswhite(line[offset]))
6024 --offset;
6025
6026 offset -= 1;
6027 if (!STRNCMP(line + offset, "if", 2))
6028 goto probablyFound;
6029
6030 if (offset >= 1)
6031 {
6032 offset -= 1;
6033 if (!STRNCMP(line + offset, "for", 3))
6034 goto probablyFound;
6035
6036 if (offset >= 2)
6037 {
6038 offset -= 2;
6039 if (!STRNCMP(line + offset, "while", 5))
6040 goto probablyFound;
6041 }
6042 }
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006043 return 0;
Bram Moolenaarb345d492012-04-09 20:42:26 +02006044
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006045probablyFound:
6046 if (!offset || !vim_isIDc(line[offset - 1]))
6047 {
6048 *poffset = offset;
6049 return 1;
6050 }
6051 return 0;
6052}
6053
6054/*
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006055 * Return TRUE if we are at the end of a do-while.
6056 * do
6057 * nothing;
6058 * while (foo
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00006059 * && bar); <-- here
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006060 * Adjust the cursor to the line with "while".
6061 */
6062 static int
6063cin_iswhileofdo_end(terminated, ind_maxparen, ind_maxcomment)
6064 int terminated;
6065 int ind_maxparen;
6066 int ind_maxcomment;
6067{
6068 char_u *line;
6069 char_u *p;
6070 char_u *s;
6071 pos_T *trypos;
6072 int i;
6073
6074 if (terminated != ';') /* there must be a ';' at the end */
6075 return FALSE;
6076
6077 p = line = ml_get_curline();
6078 while (*p != NUL)
6079 {
6080 p = cin_skipcomment(p);
6081 if (*p == ')')
6082 {
6083 s = skipwhite(p + 1);
6084 if (*s == ';' && cin_nocode(s + 1))
6085 {
6086 /* Found ");" at end of the line, now check there is "while"
6087 * before the matching '('. XXX */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006088 i = (int)(p - line);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006089 curwin->w_cursor.col = i;
6090 trypos = find_match_paren(ind_maxparen, ind_maxcomment);
6091 if (trypos != NULL)
6092 {
6093 s = cin_skipcomment(ml_get(trypos->lnum));
6094 if (*s == '}') /* accept "} while (cond);" */
6095 s = cin_skipcomment(s + 1);
6096 if (STRNCMP(s, "while", 5) == 0 && !vim_isIDc(s[5]))
6097 {
6098 curwin->w_cursor.lnum = trypos->lnum;
6099 return TRUE;
6100 }
6101 }
6102
6103 /* Searching may have made "line" invalid, get it again. */
6104 line = ml_get_curline();
6105 p = line + i;
6106 }
6107 }
6108 if (*p != NUL)
6109 ++p;
6110 }
6111 return FALSE;
6112}
6113
Bram Moolenaar071d4272004-06-13 20:20:40 +00006114 static int
6115cin_isbreak(p)
6116 char_u *p;
6117{
6118 return (STRNCMP(p, "break", 5) == 0 && !vim_isIDc(p[5]));
6119}
6120
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006121/*
6122 * Find the position of a C++ base-class declaration or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006123 * constructor-initialization. eg:
6124 *
6125 * class MyClass :
6126 * baseClass <-- here
6127 * class MyClass : public baseClass,
6128 * anotherBaseClass <-- here (should probably lineup ??)
6129 * MyClass::MyClass(...) :
6130 * baseClass(...) <-- here (constructor-initialization)
Bram Moolenaar18144c82006-04-12 21:52:12 +00006131 *
6132 * This is a lot of guessing. Watch out for "cond ? func() : foo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00006133 */
6134 static int
Bram Moolenaare7c56862007-08-04 10:14:52 +00006135cin_is_cpp_baseclass(col)
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006136 colnr_T *col; /* return: column to align with */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006137{
6138 char_u *s;
6139 int class_or_struct, lookfor_ctor_init, cpp_base_class;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006140 linenr_T lnum = curwin->w_cursor.lnum;
Bram Moolenaare7c56862007-08-04 10:14:52 +00006141 char_u *line = ml_get_curline();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006142
6143 *col = 0;
6144
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006145 s = skipwhite(line);
6146 if (*s == '#') /* skip #define FOO x ? (x) : x */
6147 return FALSE;
6148 s = cin_skipcomment(s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006149 if (*s == NUL)
6150 return FALSE;
6151
6152 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
6153
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006154 /* Search for a line starting with '#', empty, ending in ';' or containing
6155 * '{' or '}' and start below it. This handles the following situations:
6156 * a = cond ?
6157 * func() :
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00006158 * asdf;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006159 * func::foo()
6160 * : something
6161 * {}
6162 * Foo::Foo (int one, int two)
6163 * : something(4),
6164 * somethingelse(3)
6165 * {}
6166 */
6167 while (lnum > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006168 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00006169 line = ml_get(lnum - 1);
6170 s = skipwhite(line);
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006171 if (*s == '#' || *s == NUL)
6172 break;
6173 while (*s != NUL)
6174 {
6175 s = cin_skipcomment(s);
6176 if (*s == '{' || *s == '}'
6177 || (*s == ';' && cin_nocode(s + 1)))
6178 break;
6179 if (*s != NUL)
6180 ++s;
6181 }
6182 if (*s != NUL)
6183 break;
6184 --lnum;
6185 }
6186
Bram Moolenaare7c56862007-08-04 10:14:52 +00006187 line = ml_get(lnum);
6188 s = cin_skipcomment(line);
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006189 for (;;)
6190 {
6191 if (*s == NUL)
6192 {
6193 if (lnum == curwin->w_cursor.lnum)
6194 break;
6195 /* Continue in the cursor line. */
Bram Moolenaare7c56862007-08-04 10:14:52 +00006196 line = ml_get(++lnum);
6197 s = cin_skipcomment(line);
6198 if (*s == NUL)
6199 continue;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006200 }
6201
Bram Moolenaaraede6ce2011-05-10 11:56:30 +02006202 if (s[0] == '"')
6203 s = skip_string(s) + 1;
6204 else if (s[0] == ':')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006205 {
6206 if (s[1] == ':')
6207 {
6208 /* skip double colon. It can't be a constructor
6209 * initialization any more */
6210 lookfor_ctor_init = FALSE;
6211 s = cin_skipcomment(s + 2);
6212 }
6213 else if (lookfor_ctor_init || class_or_struct)
6214 {
6215 /* we have something found, that looks like the start of
Bram Moolenaare21877a2008-02-13 09:58:14 +00006216 * cpp-base-class-declaration or constructor-initialization */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006217 cpp_base_class = TRUE;
6218 lookfor_ctor_init = class_or_struct = FALSE;
6219 *col = 0;
6220 s = cin_skipcomment(s + 1);
6221 }
6222 else
6223 s = cin_skipcomment(s + 1);
6224 }
6225 else if ((STRNCMP(s, "class", 5) == 0 && !vim_isIDc(s[5]))
6226 || (STRNCMP(s, "struct", 6) == 0 && !vim_isIDc(s[6])))
6227 {
6228 class_or_struct = TRUE;
6229 lookfor_ctor_init = FALSE;
6230
6231 if (*s == 'c')
6232 s = cin_skipcomment(s + 5);
6233 else
6234 s = cin_skipcomment(s + 6);
6235 }
6236 else
6237 {
6238 if (s[0] == '{' || s[0] == '}' || s[0] == ';')
6239 {
6240 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
6241 }
6242 else if (s[0] == ')')
6243 {
6244 /* Constructor-initialization is assumed if we come across
6245 * something like "):" */
6246 class_or_struct = FALSE;
6247 lookfor_ctor_init = TRUE;
6248 }
Bram Moolenaar18144c82006-04-12 21:52:12 +00006249 else if (s[0] == '?')
6250 {
6251 /* Avoid seeing '() :' after '?' as constructor init. */
6252 return FALSE;
6253 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006254 else if (!vim_isIDc(s[0]))
6255 {
6256 /* if it is not an identifier, we are wrong */
6257 class_or_struct = FALSE;
6258 lookfor_ctor_init = FALSE;
6259 }
6260 else if (*col == 0)
6261 {
6262 /* it can't be a constructor-initialization any more */
6263 lookfor_ctor_init = FALSE;
6264
6265 /* the first statement starts here: lineup with this one... */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006266 if (cpp_base_class)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006267 *col = (colnr_T)(s - line);
6268 }
6269
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006270 /* When the line ends in a comma don't align with it. */
6271 if (lnum == curwin->w_cursor.lnum && *s == ',' && cin_nocode(s + 1))
6272 *col = 0;
6273
Bram Moolenaar071d4272004-06-13 20:20:40 +00006274 s = cin_skipcomment(s + 1);
6275 }
6276 }
6277
6278 return cpp_base_class;
6279}
6280
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006281 static int
6282get_baseclass_amount(col, ind_maxparen, ind_maxcomment, ind_cpp_baseclass)
6283 int col;
6284 int ind_maxparen;
6285 int ind_maxcomment;
6286 int ind_cpp_baseclass;
6287{
6288 int amount;
6289 colnr_T vcol;
6290 pos_T *trypos;
6291
6292 if (col == 0)
6293 {
6294 amount = get_indent();
6295 if (find_last_paren(ml_get_curline(), '(', ')')
6296 && (trypos = find_match_paren(ind_maxparen,
6297 ind_maxcomment)) != NULL)
6298 amount = get_indent_lnum(trypos->lnum); /* XXX */
6299 if (!cin_ends_in(ml_get_curline(), (char_u *)",", NULL))
6300 amount += ind_cpp_baseclass;
6301 }
6302 else
6303 {
6304 curwin->w_cursor.col = col;
6305 getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
6306 amount = (int)vcol;
6307 }
6308 if (amount < ind_cpp_baseclass)
6309 amount = ind_cpp_baseclass;
6310 return amount;
6311}
6312
Bram Moolenaar071d4272004-06-13 20:20:40 +00006313/*
6314 * Return TRUE if string "s" ends with the string "find", possibly followed by
6315 * white space and comments. Skip strings and comments.
6316 * Ignore "ignore" after "find" if it's not NULL.
6317 */
6318 static int
6319cin_ends_in(s, find, ignore)
6320 char_u *s;
6321 char_u *find;
6322 char_u *ignore;
6323{
6324 char_u *p = s;
6325 char_u *r;
6326 int len = (int)STRLEN(find);
6327
6328 while (*p != NUL)
6329 {
6330 p = cin_skipcomment(p);
6331 if (STRNCMP(p, find, len) == 0)
6332 {
6333 r = skipwhite(p + len);
6334 if (ignore != NULL && STRNCMP(r, ignore, STRLEN(ignore)) == 0)
6335 r = skipwhite(r + STRLEN(ignore));
6336 if (cin_nocode(r))
6337 return TRUE;
6338 }
6339 if (*p != NUL)
6340 ++p;
6341 }
6342 return FALSE;
6343}
6344
6345/*
6346 * Skip strings, chars and comments until at or past "trypos".
6347 * Return the column found.
6348 */
6349 static int
6350cin_skip2pos(trypos)
6351 pos_T *trypos;
6352{
6353 char_u *line;
6354 char_u *p;
6355
6356 p = line = ml_get(trypos->lnum);
6357 while (*p && (colnr_T)(p - line) < trypos->col)
6358 {
6359 if (cin_iscomment(p))
6360 p = cin_skipcomment(p);
6361 else
6362 {
6363 p = skip_string(p);
6364 ++p;
6365 }
6366 }
6367 return (int)(p - line);
6368}
6369
6370/*
6371 * Find the '{' at the start of the block we are in.
6372 * Return NULL if no match found.
6373 * Ignore a '{' that is in a comment, makes indenting the next three lines
6374 * work. */
6375/* foo() */
6376/* { */
6377/* } */
6378
6379 static pos_T *
6380find_start_brace(ind_maxcomment) /* XXX */
6381 int ind_maxcomment;
6382{
6383 pos_T cursor_save;
6384 pos_T *trypos;
6385 pos_T *pos;
6386 static pos_T pos_copy;
6387
6388 cursor_save = curwin->w_cursor;
6389 while ((trypos = findmatchlimit(NULL, '{', FM_BLOCKSTOP, 0)) != NULL)
6390 {
6391 pos_copy = *trypos; /* copy pos_T, next findmatch will change it */
6392 trypos = &pos_copy;
6393 curwin->w_cursor = *trypos;
6394 pos = NULL;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006395 /* ignore the { if it's in a // or / * * / comment */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006396 if ((colnr_T)cin_skip2pos(trypos) == trypos->col
6397 && (pos = find_start_comment(ind_maxcomment)) == NULL) /* XXX */
6398 break;
6399 if (pos != NULL)
6400 curwin->w_cursor.lnum = pos->lnum;
6401 }
6402 curwin->w_cursor = cursor_save;
6403 return trypos;
6404}
6405
6406/*
6407 * Find the matching '(', failing if it is in a comment.
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006408 * Return NULL if no match found.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006409 */
6410 static pos_T *
6411find_match_paren(ind_maxparen, ind_maxcomment) /* XXX */
6412 int ind_maxparen;
6413 int ind_maxcomment;
6414{
6415 pos_T cursor_save;
6416 pos_T *trypos;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006417 static pos_T pos_copy;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006418
6419 cursor_save = curwin->w_cursor;
6420 if ((trypos = findmatchlimit(NULL, '(', 0, ind_maxparen)) != NULL)
6421 {
6422 /* check if the ( is in a // comment */
6423 if ((colnr_T)cin_skip2pos(trypos) > trypos->col)
6424 trypos = NULL;
6425 else
6426 {
6427 pos_copy = *trypos; /* copy trypos, findmatch will change it */
6428 trypos = &pos_copy;
6429 curwin->w_cursor = *trypos;
6430 if (find_start_comment(ind_maxcomment) != NULL) /* XXX */
6431 trypos = NULL;
6432 }
6433 }
6434 curwin->w_cursor = cursor_save;
6435 return trypos;
6436}
6437
6438/*
6439 * Return ind_maxparen corrected for the difference in line number between the
6440 * cursor position and "startpos". This makes sure that searching for a
6441 * matching paren above the cursor line doesn't find a match because of
6442 * looking a few lines further.
6443 */
6444 static int
6445corr_ind_maxparen(ind_maxparen, startpos)
6446 int ind_maxparen;
6447 pos_T *startpos;
6448{
6449 long n = (long)startpos->lnum - (long)curwin->w_cursor.lnum;
6450
6451 if (n > 0 && n < ind_maxparen / 2)
6452 return ind_maxparen - (int)n;
6453 return ind_maxparen;
6454}
6455
6456/*
6457 * Set w_cursor.col to the column number of the last unmatched ')' or '{' in
Bram Moolenaar6d8f9c62011-11-30 13:03:28 +01006458 * line "l". "l" must point to the start of the line.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006459 */
6460 static int
6461find_last_paren(l, start, end)
6462 char_u *l;
6463 int start, end;
6464{
6465 int i;
6466 int retval = FALSE;
6467 int open_count = 0;
6468
6469 curwin->w_cursor.col = 0; /* default is start of line */
6470
Bram Moolenaar6d8f9c62011-11-30 13:03:28 +01006471 for (i = 0; l[i] != NUL; i++)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006472 {
6473 i = (int)(cin_skipcomment(l + i) - l); /* ignore parens in comments */
6474 i = (int)(skip_string(l + i) - l); /* ignore parens in quotes */
6475 if (l[i] == start)
6476 ++open_count;
6477 else if (l[i] == end)
6478 {
6479 if (open_count > 0)
6480 --open_count;
6481 else
6482 {
6483 curwin->w_cursor.col = i;
6484 retval = TRUE;
6485 }
6486 }
6487 }
6488 return retval;
6489}
6490
6491 int
6492get_c_indent()
6493{
6494 /*
6495 * spaces from a block's opening brace the prevailing indent for that
6496 * block should be
6497 */
6498 int ind_level = curbuf->b_p_sw;
6499
6500 /*
6501 * spaces from the edge of the line an open brace that's at the end of a
6502 * line is imagined to be.
6503 */
6504 int ind_open_imag = 0;
6505
6506 /*
Bram Moolenaar1a509df2010-08-01 17:59:57 +02006507 * spaces from the prevailing indent for a line that is not preceded by
Bram Moolenaar071d4272004-06-13 20:20:40 +00006508 * an opening brace.
6509 */
6510 int ind_no_brace = 0;
6511
6512 /*
6513 * column where the first { of a function should be located }
6514 */
6515 int ind_first_open = 0;
6516
6517 /*
6518 * spaces from the prevailing indent a leftmost open brace should be
6519 * located
6520 */
6521 int ind_open_extra = 0;
6522
6523 /*
6524 * spaces from the matching open brace (real location for one at the left
6525 * edge; imaginary location from one that ends a line) the matching close
6526 * brace should be located
6527 */
6528 int ind_close_extra = 0;
6529
6530 /*
6531 * spaces from the edge of the line an open brace sitting in the leftmost
6532 * column is imagined to be
6533 */
6534 int ind_open_left_imag = 0;
6535
6536 /*
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006537 * Spaces jump labels should be shifted to the left if N is non-negative,
6538 * otherwise the jump label will be put to column 1.
6539 */
6540 int ind_jump_label = -1;
6541
6542 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006543 * spaces from the switch() indent a "case xx" label should be located
6544 */
6545 int ind_case = curbuf->b_p_sw;
6546
6547 /*
6548 * spaces from the "case xx:" code after a switch() should be located
6549 */
6550 int ind_case_code = curbuf->b_p_sw;
6551
6552 /*
6553 * lineup break at end of case in switch() with case label
6554 */
6555 int ind_case_break = 0;
6556
6557 /*
6558 * spaces from the class declaration indent a scope declaration label
6559 * should be located
6560 */
6561 int ind_scopedecl = curbuf->b_p_sw;
6562
6563 /*
6564 * spaces from the scope declaration label code should be located
6565 */
6566 int ind_scopedecl_code = curbuf->b_p_sw;
6567
6568 /*
6569 * amount K&R-style parameters should be indented
6570 */
6571 int ind_param = curbuf->b_p_sw;
6572
6573 /*
6574 * amount a function type spec should be indented
6575 */
6576 int ind_func_type = curbuf->b_p_sw;
6577
6578 /*
6579 * amount a cpp base class declaration or constructor initialization
6580 * should be indented
6581 */
6582 int ind_cpp_baseclass = curbuf->b_p_sw;
6583
6584 /*
6585 * additional spaces beyond the prevailing indent a continuation line
6586 * should be located
6587 */
6588 int ind_continuation = curbuf->b_p_sw;
6589
6590 /*
6591 * spaces from the indent of the line with an unclosed parentheses
6592 */
6593 int ind_unclosed = curbuf->b_p_sw * 2;
6594
6595 /*
6596 * spaces from the indent of the line with an unclosed parentheses, which
6597 * itself is also unclosed
6598 */
6599 int ind_unclosed2 = curbuf->b_p_sw;
6600
6601 /*
6602 * suppress ignoring spaces from the indent of a line starting with an
6603 * unclosed parentheses.
6604 */
6605 int ind_unclosed_noignore = 0;
6606
6607 /*
6608 * If the opening paren is the last nonwhite character on the line, and
6609 * ind_unclosed_wrapped is nonzero, use this indent relative to the outer
6610 * context (for very long lines).
6611 */
6612 int ind_unclosed_wrapped = 0;
6613
6614 /*
6615 * suppress ignoring white space when lining up with the character after
6616 * an unclosed parentheses.
6617 */
6618 int ind_unclosed_whiteok = 0;
6619
6620 /*
6621 * indent a closing parentheses under the line start of the matching
6622 * opening parentheses.
6623 */
6624 int ind_matching_paren = 0;
6625
6626 /*
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006627 * indent a closing parentheses under the previous line.
6628 */
6629 int ind_paren_prev = 0;
6630
6631 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006632 * Extra indent for comments.
6633 */
6634 int ind_comment = 0;
6635
6636 /*
6637 * spaces from the comment opener when there is nothing after it.
6638 */
6639 int ind_in_comment = 3;
6640
6641 /*
6642 * boolean: if non-zero, use ind_in_comment even if there is something
6643 * after the comment opener.
6644 */
6645 int ind_in_comment2 = 0;
6646
6647 /*
6648 * max lines to search for an open paren
6649 */
6650 int ind_maxparen = 20;
6651
6652 /*
6653 * max lines to search for an open comment
6654 */
6655 int ind_maxcomment = 70;
6656
6657 /*
6658 * handle braces for java code
6659 */
6660 int ind_java = 0;
6661
6662 /*
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006663 * not to confuse JS object properties with labels
6664 */
6665 int ind_js = 0;
6666
6667 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006668 * handle blocked cases correctly
6669 */
6670 int ind_keep_case_label = 0;
6671
Bram Moolenaared38b0a2011-05-25 15:16:18 +02006672 /*
6673 * handle C++ namespace
6674 */
6675 int ind_cpp_namespace = 0;
6676
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006677 /*
6678 * handle continuation lines containing conditions of if(), for() and
6679 * while()
6680 */
6681 int ind_if_for_while = 0;
6682
Bram Moolenaar071d4272004-06-13 20:20:40 +00006683 pos_T cur_curpos;
6684 int amount;
6685 int scope_amount;
Bram Moolenaarb21e5842006-04-16 18:30:08 +00006686 int cur_amount = MAXCOL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006687 colnr_T col;
6688 char_u *theline;
6689 char_u *linecopy;
6690 pos_T *trypos;
6691 pos_T *tryposBrace = NULL;
6692 pos_T our_paren_pos;
6693 char_u *start;
6694 int start_brace;
Bram Moolenaare21877a2008-02-13 09:58:14 +00006695#define BRACE_IN_COL0 1 /* '{' is in column 0 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006696#define BRACE_AT_START 2 /* '{' is at start of line */
6697#define BRACE_AT_END 3 /* '{' is at end of line */
6698 linenr_T ourscope;
6699 char_u *l;
6700 char_u *look;
6701 char_u terminated;
6702 int lookfor;
6703#define LOOKFOR_INITIAL 0
6704#define LOOKFOR_IF 1
6705#define LOOKFOR_DO 2
6706#define LOOKFOR_CASE 3
6707#define LOOKFOR_ANY 4
6708#define LOOKFOR_TERM 5
6709#define LOOKFOR_UNTERM 6
6710#define LOOKFOR_SCOPEDECL 7
6711#define LOOKFOR_NOBREAK 8
6712#define LOOKFOR_CPP_BASECLASS 9
6713#define LOOKFOR_ENUM_OR_INIT 10
6714
6715 int whilelevel;
6716 linenr_T lnum;
6717 char_u *options;
Bram Moolenaar48d27922012-06-13 13:40:48 +02006718 char_u *digits;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006719 int fraction = 0; /* init for GCC */
6720 int divider;
6721 int n;
6722 int iscase;
6723 int lookfor_break;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02006724 int lookfor_cpp_namespace = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006725 int cont_amount = 0; /* amount for continuation line */
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006726 int original_line_islabel;
Bram Moolenaare79d1532011-10-04 18:03:47 +02006727 int added_to_amount = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006728
6729 for (options = curbuf->b_p_cino; *options; )
6730 {
6731 l = options++;
6732 if (*options == '-')
6733 ++options;
Bram Moolenaar48d27922012-06-13 13:40:48 +02006734 digits = options; /* remember where the digits start */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006735 n = getdigits(&options);
6736 divider = 0;
6737 if (*options == '.') /* ".5s" means a fraction */
6738 {
6739 fraction = atol((char *)++options);
6740 while (VIM_ISDIGIT(*options))
6741 {
6742 ++options;
6743 if (divider)
6744 divider *= 10;
6745 else
6746 divider = 10;
6747 }
6748 }
6749 if (*options == 's') /* "2s" means two times 'shiftwidth' */
6750 {
Bram Moolenaar48d27922012-06-13 13:40:48 +02006751 if (options == digits)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006752 n = curbuf->b_p_sw; /* just "s" is one 'shiftwidth' */
6753 else
6754 {
6755 n *= curbuf->b_p_sw;
6756 if (divider)
6757 n += (curbuf->b_p_sw * fraction + divider / 2) / divider;
6758 }
6759 ++options;
6760 }
6761 if (l[1] == '-')
6762 n = -n;
6763 /* When adding an entry here, also update the default 'cinoptions' in
Bram Moolenaar39353fd2007-03-27 09:02:11 +00006764 * doc/indent.txt, and add explanation for it! */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006765 switch (*l)
6766 {
6767 case '>': ind_level = n; break;
6768 case 'e': ind_open_imag = n; break;
6769 case 'n': ind_no_brace = n; break;
6770 case 'f': ind_first_open = n; break;
6771 case '{': ind_open_extra = n; break;
6772 case '}': ind_close_extra = n; break;
6773 case '^': ind_open_left_imag = n; break;
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006774 case 'L': ind_jump_label = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006775 case ':': ind_case = n; break;
6776 case '=': ind_case_code = n; break;
6777 case 'b': ind_case_break = n; break;
6778 case 'p': ind_param = n; break;
6779 case 't': ind_func_type = n; break;
6780 case '/': ind_comment = n; break;
6781 case 'c': ind_in_comment = n; break;
6782 case 'C': ind_in_comment2 = n; break;
6783 case 'i': ind_cpp_baseclass = n; break;
6784 case '+': ind_continuation = n; break;
6785 case '(': ind_unclosed = n; break;
6786 case 'u': ind_unclosed2 = n; break;
6787 case 'U': ind_unclosed_noignore = n; break;
6788 case 'W': ind_unclosed_wrapped = n; break;
6789 case 'w': ind_unclosed_whiteok = n; break;
6790 case 'm': ind_matching_paren = n; break;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006791 case 'M': ind_paren_prev = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006792 case ')': ind_maxparen = n; break;
6793 case '*': ind_maxcomment = n; break;
6794 case 'g': ind_scopedecl = n; break;
6795 case 'h': ind_scopedecl_code = n; break;
6796 case 'j': ind_java = n; break;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006797 case 'J': ind_js = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006798 case 'l': ind_keep_case_label = n; break;
Bram Moolenaar39353fd2007-03-27 09:02:11 +00006799 case '#': ind_hash_comment = n; break;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02006800 case 'N': ind_cpp_namespace = n; break;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006801 case 'k': ind_if_for_while = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006802 }
Bram Moolenaardfdf3c42010-03-23 18:22:46 +01006803 if (*options == ',')
6804 ++options;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006805 }
6806
6807 /* remember where the cursor was when we started */
6808 cur_curpos = curwin->w_cursor;
6809
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006810 /* if we are at line 1 0 is fine, right? */
6811 if (cur_curpos.lnum == 1)
6812 return 0;
6813
Bram Moolenaar071d4272004-06-13 20:20:40 +00006814 /* Get a copy of the current contents of the line.
6815 * This is required, because only the most recent line obtained with
6816 * ml_get is valid! */
6817 linecopy = vim_strsave(ml_get(cur_curpos.lnum));
6818 if (linecopy == NULL)
6819 return 0;
6820
6821 /*
6822 * In insert mode and the cursor is on a ')' truncate the line at the
6823 * cursor position. We don't want to line up with the matching '(' when
6824 * inserting new stuff.
6825 * For unknown reasons the cursor might be past the end of the line, thus
6826 * check for that.
6827 */
6828 if ((State & INSERT)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006829 && curwin->w_cursor.col < (colnr_T)STRLEN(linecopy)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006830 && linecopy[curwin->w_cursor.col] == ')')
6831 linecopy[curwin->w_cursor.col] = NUL;
6832
6833 theline = skipwhite(linecopy);
6834
6835 /* move the cursor to the start of the line */
6836
6837 curwin->w_cursor.col = 0;
6838
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006839 original_line_islabel = cin_islabel(ind_maxcomment); /* XXX */
6840
Bram Moolenaar071d4272004-06-13 20:20:40 +00006841 /*
6842 * #defines and so on always go at the left when included in 'cinkeys'.
6843 */
6844 if (*theline == '#' && (*linecopy == '#' || in_cinkeys('#', ' ', TRUE)))
6845 {
6846 amount = 0;
6847 }
6848
6849 /*
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006850 * Is it a non-case label? Then that goes at the left margin too unless:
6851 * - JS flag is set.
6852 * - 'L' item has a positive value.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006853 */
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006854 else if (original_line_islabel && !ind_js && ind_jump_label < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006855 {
6856 amount = 0;
6857 }
6858
6859 /*
6860 * If we're inside a "//" comment and there is a "//" comment in a
6861 * previous line, lineup with that one.
6862 */
6863 else if (cin_islinecomment(theline)
6864 && (trypos = find_line_comment()) != NULL) /* XXX */
6865 {
6866 /* find how indented the line beginning the comment is */
6867 getvcol(curwin, trypos, &col, NULL, NULL);
6868 amount = col;
6869 }
6870
6871 /*
6872 * If we're inside a comment and not looking at the start of the
6873 * comment, try using the 'comments' option.
6874 */
6875 else if (!cin_iscomment(theline)
6876 && (trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
6877 {
6878 int lead_start_len = 2;
6879 int lead_middle_len = 1;
6880 char_u lead_start[COM_MAX_LEN]; /* start-comment string */
6881 char_u lead_middle[COM_MAX_LEN]; /* middle-comment string */
6882 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
6883 char_u *p;
6884 int start_align = 0;
6885 int start_off = 0;
6886 int done = FALSE;
6887
6888 /* find how indented the line beginning the comment is */
6889 getvcol(curwin, trypos, &col, NULL, NULL);
6890 amount = col;
Bram Moolenaar4aa97422011-04-11 14:27:38 +02006891 *lead_start = NUL;
6892 *lead_middle = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006893
6894 p = curbuf->b_p_com;
6895 while (*p != NUL)
6896 {
6897 int align = 0;
6898 int off = 0;
6899 int what = 0;
6900
6901 while (*p != NUL && *p != ':')
6902 {
6903 if (*p == COM_START || *p == COM_END || *p == COM_MIDDLE)
6904 what = *p++;
6905 else if (*p == COM_LEFT || *p == COM_RIGHT)
6906 align = *p++;
6907 else if (VIM_ISDIGIT(*p) || *p == '-')
6908 off = getdigits(&p);
6909 else
6910 ++p;
6911 }
6912
6913 if (*p == ':')
6914 ++p;
6915 (void)copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
6916 if (what == COM_START)
6917 {
6918 STRCPY(lead_start, lead_end);
6919 lead_start_len = (int)STRLEN(lead_start);
6920 start_off = off;
6921 start_align = align;
6922 }
6923 else if (what == COM_MIDDLE)
6924 {
6925 STRCPY(lead_middle, lead_end);
6926 lead_middle_len = (int)STRLEN(lead_middle);
6927 }
6928 else if (what == COM_END)
6929 {
6930 /* If our line starts with the middle comment string, line it
6931 * up with the comment opener per the 'comments' option. */
6932 if (STRNCMP(theline, lead_middle, lead_middle_len) == 0
6933 && STRNCMP(theline, lead_end, STRLEN(lead_end)) != 0)
6934 {
6935 done = TRUE;
6936 if (curwin->w_cursor.lnum > 1)
6937 {
6938 /* If the start comment string matches in the previous
Bram Moolenaare21877a2008-02-13 09:58:14 +00006939 * line, use the indent of that line plus offset. If
Bram Moolenaar071d4272004-06-13 20:20:40 +00006940 * the middle comment string matches in the previous
6941 * line, use the indent of that line. XXX */
6942 look = skipwhite(ml_get(curwin->w_cursor.lnum - 1));
6943 if (STRNCMP(look, lead_start, lead_start_len) == 0)
6944 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6945 else if (STRNCMP(look, lead_middle,
6946 lead_middle_len) == 0)
6947 {
6948 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6949 break;
6950 }
6951 /* If the start comment string doesn't match with the
6952 * start of the comment, skip this entry. XXX */
6953 else if (STRNCMP(ml_get(trypos->lnum) + trypos->col,
6954 lead_start, lead_start_len) != 0)
6955 continue;
6956 }
6957 if (start_off != 0)
6958 amount += start_off;
6959 else if (start_align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006960 amount += vim_strsize(lead_start)
6961 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006962 break;
6963 }
6964
6965 /* If our line starts with the end comment string, line it up
6966 * with the middle comment */
6967 if (STRNCMP(theline, lead_middle, lead_middle_len) != 0
6968 && STRNCMP(theline, lead_end, STRLEN(lead_end)) == 0)
6969 {
6970 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6971 /* XXX */
6972 if (off != 0)
6973 amount += off;
6974 else if (align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006975 amount += vim_strsize(lead_start)
6976 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006977 done = TRUE;
6978 break;
6979 }
6980 }
6981 }
6982
6983 /* If our line starts with an asterisk, line up with the
6984 * asterisk in the comment opener; otherwise, line up
6985 * with the first character of the comment text.
6986 */
6987 if (done)
6988 ;
6989 else if (theline[0] == '*')
6990 amount += 1;
6991 else
6992 {
6993 /*
6994 * If we are more than one line away from the comment opener, take
6995 * the indent of the previous non-empty line. If 'cino' has "CO"
6996 * and we are just below the comment opener and there are any
6997 * white characters after it line up with the text after it;
6998 * otherwise, add the amount specified by "c" in 'cino'
6999 */
7000 amount = -1;
7001 for (lnum = cur_curpos.lnum - 1; lnum > trypos->lnum; --lnum)
7002 {
7003 if (linewhite(lnum)) /* skip blank lines */
7004 continue;
7005 amount = get_indent_lnum(lnum); /* XXX */
7006 break;
7007 }
7008 if (amount == -1) /* use the comment opener */
7009 {
7010 if (!ind_in_comment2)
7011 {
7012 start = ml_get(trypos->lnum);
7013 look = start + trypos->col + 2; /* skip / and * */
7014 if (*look != NUL) /* if something after it */
7015 trypos->col = (colnr_T)(skipwhite(look) - start);
7016 }
7017 getvcol(curwin, trypos, &col, NULL, NULL);
7018 amount = col;
7019 if (ind_in_comment2 || *look == NUL)
7020 amount += ind_in_comment;
7021 }
7022 }
7023 }
7024
7025 /*
7026 * Are we inside parentheses or braces?
7027 */ /* XXX */
7028 else if (((trypos = find_match_paren(ind_maxparen, ind_maxcomment)) != NULL
7029 && ind_java == 0)
7030 || (tryposBrace = find_start_brace(ind_maxcomment)) != NULL
7031 || trypos != NULL)
7032 {
7033 if (trypos != NULL && tryposBrace != NULL)
7034 {
7035 /* Both an unmatched '(' and '{' is found. Use the one which is
7036 * closer to the current cursor position, set the other to NULL. */
7037 if (trypos->lnum != tryposBrace->lnum
7038 ? trypos->lnum < tryposBrace->lnum
7039 : trypos->col < tryposBrace->col)
7040 trypos = NULL;
7041 else
7042 tryposBrace = NULL;
7043 }
7044
7045 if (trypos != NULL)
7046 {
7047 /*
7048 * If the matching paren is more than one line away, use the indent of
7049 * a previous non-empty line that matches the same paren.
7050 */
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007051 if (theline[0] == ')' && ind_paren_prev)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007052 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007053 /* Line up with the start of the matching paren line. */
7054 amount = get_indent_lnum(curwin->w_cursor.lnum - 1); /* XXX */
7055 }
7056 else
7057 {
7058 amount = -1;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007059 our_paren_pos = *trypos;
7060 for (lnum = cur_curpos.lnum - 1; lnum > our_paren_pos.lnum; --lnum)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007061 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007062 l = skipwhite(ml_get(lnum));
7063 if (cin_nocode(l)) /* skip comment lines */
7064 continue;
7065 if (cin_ispreproc_cont(&l, &lnum))
7066 continue; /* ignore #define, #if, etc. */
7067 curwin->w_cursor.lnum = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007068
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007069 /* Skip a comment. XXX */
7070 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
7071 {
7072 lnum = trypos->lnum + 1;
7073 continue;
7074 }
7075
7076 /* XXX */
7077 if ((trypos = find_match_paren(
7078 corr_ind_maxparen(ind_maxparen, &cur_curpos),
Bram Moolenaar071d4272004-06-13 20:20:40 +00007079 ind_maxcomment)) != NULL
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007080 && trypos->lnum == our_paren_pos.lnum
7081 && trypos->col == our_paren_pos.col)
7082 {
7083 amount = get_indent_lnum(lnum); /* XXX */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007084
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007085 if (theline[0] == ')')
7086 {
7087 if (our_paren_pos.lnum != lnum
7088 && cur_amount > amount)
7089 cur_amount = amount;
7090 amount = -1;
7091 }
7092 break;
7093 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007094 }
7095 }
7096
7097 /*
7098 * Line up with line where the matching paren is. XXX
7099 * If the line starts with a '(' or the indent for unclosed
7100 * parentheses is zero, line up with the unclosed parentheses.
7101 */
7102 if (amount == -1)
7103 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007104 int ignore_paren_col = 0;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007105 int is_if_for_while = 0;
7106
7107 if (ind_if_for_while)
7108 {
7109 /* Look for the outermost opening parenthesis on this line
7110 * and check whether it belongs to an "if", "for" or "while". */
7111
7112 pos_T cursor_save = curwin->w_cursor;
7113 pos_T outermost;
7114 char_u *line;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007115
7116 trypos = &our_paren_pos;
7117 do {
7118 outermost = *trypos;
7119 curwin->w_cursor.lnum = outermost.lnum;
7120 curwin->w_cursor.col = outermost.col;
7121
7122 trypos = find_match_paren(ind_maxparen, ind_maxcomment);
7123 } while (trypos && trypos->lnum == outermost.lnum);
7124
7125 curwin->w_cursor = cursor_save;
7126
7127 line = ml_get(outermost.lnum);
7128
7129 is_if_for_while =
Bram Moolenaarb345d492012-04-09 20:42:26 +02007130 cin_is_if_for_while_before_offset(line, &outermost.col);
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007131 }
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007132
Bram Moolenaar071d4272004-06-13 20:20:40 +00007133 amount = skip_label(our_paren_pos.lnum, &look, ind_maxcomment);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007134 look = skipwhite(look);
7135 if (*look == '(')
7136 {
7137 linenr_T save_lnum = curwin->w_cursor.lnum;
7138 char_u *line;
7139 int look_col;
7140
7141 /* Ignore a '(' in front of the line that has a match before
7142 * our matching '('. */
7143 curwin->w_cursor.lnum = our_paren_pos.lnum;
7144 line = ml_get_curline();
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007145 look_col = (int)(look - line);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007146 curwin->w_cursor.col = look_col + 1;
7147 if ((trypos = findmatchlimit(NULL, ')', 0, ind_maxparen))
7148 != NULL
7149 && trypos->lnum == our_paren_pos.lnum
7150 && trypos->col < our_paren_pos.col)
7151 ignore_paren_col = trypos->col + 1;
7152
7153 curwin->w_cursor.lnum = save_lnum;
7154 look = ml_get(our_paren_pos.lnum) + look_col;
7155 }
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007156 if (theline[0] == ')' || (ind_unclosed == 0 && is_if_for_while == 0)
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007157 || (!ind_unclosed_noignore && *look == '('
7158 && ignore_paren_col == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007159 {
7160 /*
7161 * If we're looking at a close paren, line up right there;
7162 * otherwise, line up with the next (non-white) character.
7163 * When ind_unclosed_wrapped is set and the matching paren is
7164 * the last nonwhite character of the line, use either the
7165 * indent of the current line or the indentation of the next
7166 * outer paren and add ind_unclosed_wrapped (for very long
7167 * lines).
7168 */
7169 if (theline[0] != ')')
7170 {
7171 cur_amount = MAXCOL;
7172 l = ml_get(our_paren_pos.lnum);
7173 if (ind_unclosed_wrapped
7174 && cin_ends_in(l, (char_u *)"(", NULL))
7175 {
7176 /* look for opening unmatched paren, indent one level
7177 * for each additional level */
7178 n = 1;
7179 for (col = 0; col < our_paren_pos.col; ++col)
7180 {
7181 switch (l[col])
7182 {
7183 case '(':
7184 case '{': ++n;
7185 break;
7186
7187 case ')':
7188 case '}': if (n > 1)
7189 --n;
7190 break;
7191 }
7192 }
7193
7194 our_paren_pos.col = 0;
7195 amount += n * ind_unclosed_wrapped;
7196 }
7197 else if (ind_unclosed_whiteok)
7198 our_paren_pos.col++;
7199 else
7200 {
7201 col = our_paren_pos.col + 1;
7202 while (vim_iswhite(l[col]))
7203 col++;
7204 if (l[col] != NUL) /* In case of trailing space */
7205 our_paren_pos.col = col;
7206 else
7207 our_paren_pos.col++;
7208 }
7209 }
7210
7211 /*
7212 * Find how indented the paren is, or the character after it
7213 * if we did the above "if".
7214 */
7215 if (our_paren_pos.col > 0)
7216 {
7217 getvcol(curwin, &our_paren_pos, &col, NULL, NULL);
7218 if (cur_amount > (int)col)
7219 cur_amount = col;
7220 }
7221 }
7222
7223 if (theline[0] == ')' && ind_matching_paren)
7224 {
7225 /* Line up with the start of the matching paren line. */
7226 }
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007227 else if ((ind_unclosed == 0 && is_if_for_while == 0)
7228 || (!ind_unclosed_noignore
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007229 && *look == '(' && ignore_paren_col == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007230 {
7231 if (cur_amount != MAXCOL)
7232 amount = cur_amount;
7233 }
7234 else
7235 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007236 /* Add ind_unclosed2 for each '(' before our matching one, but
7237 * ignore (void) before the line (ignore_paren_col). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007238 col = our_paren_pos.col;
Bram Moolenaarb21e5842006-04-16 18:30:08 +00007239 while ((int)our_paren_pos.col > ignore_paren_col)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007240 {
7241 --our_paren_pos.col;
7242 switch (*ml_get_pos(&our_paren_pos))
7243 {
7244 case '(': amount += ind_unclosed2;
7245 col = our_paren_pos.col;
7246 break;
7247 case ')': amount -= ind_unclosed2;
7248 col = MAXCOL;
7249 break;
7250 }
7251 }
7252
7253 /* Use ind_unclosed once, when the first '(' is not inside
7254 * braces */
7255 if (col == MAXCOL)
7256 amount += ind_unclosed;
7257 else
7258 {
7259 curwin->w_cursor.lnum = our_paren_pos.lnum;
7260 curwin->w_cursor.col = col;
Bram Moolenaar367bec82011-04-11 14:26:19 +02007261 if (find_match_paren(ind_maxparen, ind_maxcomment) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007262 amount += ind_unclosed2;
7263 else
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007264 {
7265 if (is_if_for_while)
7266 amount += ind_if_for_while;
7267 else
7268 amount += ind_unclosed;
7269 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007270 }
7271 /*
7272 * For a line starting with ')' use the minimum of the two
7273 * positions, to avoid giving it more indent than the previous
7274 * lines:
7275 * func_long_name( if (x
7276 * arg && yy
7277 * ) ^ not here ) ^ not here
7278 */
7279 if (cur_amount < amount)
7280 amount = cur_amount;
7281 }
7282 }
7283
7284 /* add extra indent for a comment */
7285 if (cin_iscomment(theline))
7286 amount += ind_comment;
7287 }
7288
7289 /*
7290 * Are we at least inside braces, then?
7291 */
7292 else
7293 {
7294 trypos = tryposBrace;
7295
7296 ourscope = trypos->lnum;
7297 start = ml_get(ourscope);
7298
7299 /*
7300 * Now figure out how indented the line is in general.
7301 * If the brace was at the start of the line, we use that;
7302 * otherwise, check out the indentation of the line as
7303 * a whole and then add the "imaginary indent" to that.
7304 */
7305 look = skipwhite(start);
7306 if (*look == '{')
7307 {
7308 getvcol(curwin, trypos, &col, NULL, NULL);
7309 amount = col;
7310 if (*start == '{')
7311 start_brace = BRACE_IN_COL0;
7312 else
7313 start_brace = BRACE_AT_START;
7314 }
7315 else
7316 {
7317 /*
7318 * that opening brace might have been on a continuation
7319 * line. if so, find the start of the line.
7320 */
7321 curwin->w_cursor.lnum = ourscope;
7322
7323 /*
7324 * position the cursor over the rightmost paren, so that
7325 * matching it will take us back to the start of the line.
7326 */
7327 lnum = ourscope;
7328 if (find_last_paren(start, '(', ')')
7329 && (trypos = find_match_paren(ind_maxparen,
7330 ind_maxcomment)) != NULL)
7331 lnum = trypos->lnum;
7332
7333 /*
7334 * It could have been something like
7335 * case 1: if (asdf &&
7336 * ldfd) {
7337 * }
7338 */
Bram Moolenaar6ec154b2011-06-12 21:51:08 +02007339 if (ind_js || (ind_keep_case_label
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007340 && cin_iscase(skipwhite(ml_get_curline()), FALSE)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007341 amount = get_indent();
7342 else
7343 amount = skip_label(lnum, &l, ind_maxcomment);
7344
7345 start_brace = BRACE_AT_END;
7346 }
7347
7348 /*
7349 * if we're looking at a closing brace, that's where
7350 * we want to be. otherwise, add the amount of room
7351 * that an indent is supposed to be.
7352 */
7353 if (theline[0] == '}')
7354 {
7355 /*
7356 * they may want closing braces to line up with something
7357 * other than the open brace. indulge them, if so.
7358 */
7359 amount += ind_close_extra;
7360 }
7361 else
7362 {
7363 /*
7364 * If we're looking at an "else", try to find an "if"
7365 * to match it with.
7366 * If we're looking at a "while", try to find a "do"
7367 * to match it with.
7368 */
7369 lookfor = LOOKFOR_INITIAL;
7370 if (cin_iselse(theline))
7371 lookfor = LOOKFOR_IF;
7372 else if (cin_iswhileofdo(theline, cur_curpos.lnum, ind_maxparen))
7373 /* XXX */
7374 lookfor = LOOKFOR_DO;
7375 if (lookfor != LOOKFOR_INITIAL)
7376 {
7377 curwin->w_cursor.lnum = cur_curpos.lnum;
7378 if (find_match(lookfor, ourscope, ind_maxparen,
7379 ind_maxcomment) == OK)
7380 {
7381 amount = get_indent(); /* XXX */
7382 goto theend;
7383 }
7384 }
7385
7386 /*
7387 * We get here if we are not on an "while-of-do" or "else" (or
7388 * failed to find a matching "if").
7389 * Search backwards for something to line up with.
7390 * First set amount for when we don't find anything.
7391 */
7392
7393 /*
7394 * if the '{' is _really_ at the left margin, use the imaginary
7395 * location of a left-margin brace. Otherwise, correct the
7396 * location for ind_open_extra.
7397 */
7398
7399 if (start_brace == BRACE_IN_COL0) /* '{' is in column 0 */
7400 {
7401 amount = ind_open_left_imag;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007402 lookfor_cpp_namespace = TRUE;
7403 }
7404 else if (start_brace == BRACE_AT_START &&
7405 lookfor_cpp_namespace) /* '{' is at start */
7406 {
7407
7408 lookfor_cpp_namespace = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007409 }
7410 else
7411 {
7412 if (start_brace == BRACE_AT_END) /* '{' is at end of line */
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007413 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007414 amount += ind_open_imag;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007415
7416 l = skipwhite(ml_get_curline());
7417 if (cin_is_cpp_namespace(l))
7418 amount += ind_cpp_namespace;
7419 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007420 else
7421 {
7422 /* Compensate for adding ind_open_extra later. */
7423 amount -= ind_open_extra;
7424 if (amount < 0)
7425 amount = 0;
7426 }
7427 }
7428
7429 lookfor_break = FALSE;
7430
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007431 if (cin_iscase(theline, FALSE)) /* it's a switch() label */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007432 {
7433 lookfor = LOOKFOR_CASE; /* find a previous switch() label */
7434 amount += ind_case;
7435 }
7436 else if (cin_isscopedecl(theline)) /* private:, ... */
7437 {
7438 lookfor = LOOKFOR_SCOPEDECL; /* class decl is this block */
7439 amount += ind_scopedecl;
7440 }
7441 else
7442 {
7443 if (ind_case_break && cin_isbreak(theline)) /* break; ... */
7444 lookfor_break = TRUE;
7445
7446 lookfor = LOOKFOR_INITIAL;
7447 amount += ind_level; /* ind_level from start of block */
7448 }
7449 scope_amount = amount;
7450 whilelevel = 0;
7451
7452 /*
7453 * Search backwards. If we find something we recognize, line up
7454 * with that.
7455 *
7456 * if we're looking at an open brace, indent
7457 * the usual amount relative to the conditional
7458 * that opens the block.
7459 */
7460 curwin->w_cursor = cur_curpos;
7461 for (;;)
7462 {
7463 curwin->w_cursor.lnum--;
7464 curwin->w_cursor.col = 0;
7465
7466 /*
7467 * If we went all the way back to the start of our scope, line
7468 * up with it.
7469 */
7470 if (curwin->w_cursor.lnum <= ourscope)
7471 {
7472 /* we reached end of scope:
7473 * if looking for a enum or structure initialization
7474 * go further back:
7475 * if it is an initializer (enum xxx or xxx =), then
7476 * don't add ind_continuation, otherwise it is a variable
7477 * declaration:
7478 * int x,
7479 * here; <-- add ind_continuation
7480 */
7481 if (lookfor == LOOKFOR_ENUM_OR_INIT)
7482 {
7483 if (curwin->w_cursor.lnum == 0
7484 || curwin->w_cursor.lnum
7485 < ourscope - ind_maxparen)
7486 {
7487 /* nothing found (abuse ind_maxparen as limit)
7488 * assume terminated line (i.e. a variable
7489 * initialization) */
7490 if (cont_amount > 0)
7491 amount = cont_amount;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007492 else if (!ind_js)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007493 amount += ind_continuation;
7494 break;
7495 }
7496
7497 l = ml_get_curline();
7498
7499 /*
7500 * If we're in a comment now, skip to the start of the
7501 * comment.
7502 */
7503 trypos = find_start_comment(ind_maxcomment);
7504 if (trypos != NULL)
7505 {
7506 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007507 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007508 continue;
7509 }
7510
7511 /*
7512 * Skip preprocessor directives and blank lines.
7513 */
7514 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7515 continue;
7516
7517 if (cin_nocode(l))
7518 continue;
7519
7520 terminated = cin_isterminated(l, FALSE, TRUE);
7521
7522 /*
7523 * If we are at top level and the line looks like a
7524 * function declaration, we are done
7525 * (it's a variable declaration).
7526 */
7527 if (start_brace != BRACE_IN_COL0
Bram Moolenaarc367faa2011-12-14 20:21:35 +01007528 || !cin_isfuncdecl(&l, curwin->w_cursor.lnum,
7529 0, ind_maxparen, ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007530 {
7531 /* if the line is terminated with another ','
7532 * it is a continued variable initialization.
7533 * don't add extra indent.
7534 * TODO: does not work, if a function
7535 * declaration is split over multiple lines:
7536 * cin_isfuncdecl returns FALSE then.
7537 */
7538 if (terminated == ',')
7539 break;
7540
7541 /* if it es a enum declaration or an assignment,
7542 * we are done.
7543 */
7544 if (terminated != ';' && cin_isinit())
7545 break;
7546
7547 /* nothing useful found */
7548 if (terminated == 0 || terminated == '{')
7549 continue;
7550 }
7551
7552 if (terminated != ';')
7553 {
7554 /* Skip parens and braces. Position the cursor
7555 * over the rightmost paren, so that matching it
7556 * will take us back to the start of the line.
7557 */ /* XXX */
7558 trypos = NULL;
7559 if (find_last_paren(l, '(', ')'))
7560 trypos = find_match_paren(ind_maxparen,
7561 ind_maxcomment);
7562
7563 if (trypos == NULL && find_last_paren(l, '{', '}'))
7564 trypos = find_start_brace(ind_maxcomment);
7565
7566 if (trypos != NULL)
7567 {
7568 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007569 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007570 continue;
7571 }
7572 }
7573
7574 /* it's a variable declaration, add indentation
7575 * like in
7576 * int a,
7577 * b;
7578 */
7579 if (cont_amount > 0)
7580 amount = cont_amount;
7581 else
7582 amount += ind_continuation;
7583 }
7584 else if (lookfor == LOOKFOR_UNTERM)
7585 {
7586 if (cont_amount > 0)
7587 amount = cont_amount;
7588 else
7589 amount += ind_continuation;
7590 }
Bram Moolenaare79d1532011-10-04 18:03:47 +02007591 else
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007592 {
Bram Moolenaare79d1532011-10-04 18:03:47 +02007593 if (lookfor != LOOKFOR_TERM
Bram Moolenaar071d4272004-06-13 20:20:40 +00007594 && lookfor != LOOKFOR_CPP_BASECLASS)
Bram Moolenaare79d1532011-10-04 18:03:47 +02007595 {
7596 amount = scope_amount;
7597 if (theline[0] == '{')
7598 {
7599 amount += ind_open_extra;
7600 added_to_amount = ind_open_extra;
7601 }
7602 }
7603
7604 if (lookfor_cpp_namespace)
7605 {
7606 /*
7607 * Looking for C++ namespace, need to look further
7608 * back.
7609 */
7610 if (curwin->w_cursor.lnum == ourscope)
7611 continue;
7612
7613 if (curwin->w_cursor.lnum == 0
7614 || curwin->w_cursor.lnum
7615 < ourscope - FIND_NAMESPACE_LIM)
7616 break;
7617
7618 l = ml_get_curline();
7619
7620 /* If we're in a comment now, skip to the start of
7621 * the comment. */
7622 trypos = find_start_comment(ind_maxcomment);
7623 if (trypos != NULL)
7624 {
7625 curwin->w_cursor.lnum = trypos->lnum + 1;
7626 curwin->w_cursor.col = 0;
7627 continue;
7628 }
7629
7630 /* Skip preprocessor directives and blank lines. */
7631 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7632 continue;
7633
7634 /* Finally the actual check for "namespace". */
7635 if (cin_is_cpp_namespace(l))
7636 {
7637 amount += ind_cpp_namespace - added_to_amount;
7638 break;
7639 }
7640
7641 if (cin_nocode(l))
7642 continue;
7643 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007644 }
7645 break;
7646 }
7647
7648 /*
7649 * If we're in a comment now, skip to the start of the comment.
7650 */ /* XXX */
7651 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
7652 {
7653 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007654 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007655 continue;
7656 }
7657
7658 l = ml_get_curline();
7659
7660 /*
7661 * If this is a switch() label, may line up relative to that.
Bram Moolenaar18144c82006-04-12 21:52:12 +00007662 * If this is a C++ scope declaration, do the same.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007663 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007664 iscase = cin_iscase(l, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007665 if (iscase || cin_isscopedecl(l))
7666 {
7667 /* we are only looking for cpp base class
7668 * declaration/initialization any longer */
7669 if (lookfor == LOOKFOR_CPP_BASECLASS)
7670 break;
7671
7672 /* When looking for a "do" we are not interested in
7673 * labels. */
7674 if (whilelevel > 0)
7675 continue;
7676
7677 /*
7678 * case xx:
7679 * c = 99 + <- this indent plus continuation
7680 *-> here;
7681 */
7682 if (lookfor == LOOKFOR_UNTERM
7683 || lookfor == LOOKFOR_ENUM_OR_INIT)
7684 {
7685 if (cont_amount > 0)
7686 amount = cont_amount;
7687 else
7688 amount += ind_continuation;
7689 break;
7690 }
7691
7692 /*
7693 * case xx: <- line up with this case
7694 * x = 333;
7695 * case yy:
7696 */
7697 if ( (iscase && lookfor == LOOKFOR_CASE)
7698 || (iscase && lookfor_break)
7699 || (!iscase && lookfor == LOOKFOR_SCOPEDECL))
7700 {
7701 /*
7702 * Check that this case label is not for another
7703 * switch()
7704 */ /* XXX */
7705 if ((trypos = find_start_brace(ind_maxcomment)) ==
7706 NULL || trypos->lnum == ourscope)
7707 {
7708 amount = get_indent(); /* XXX */
7709 break;
7710 }
7711 continue;
7712 }
7713
7714 n = get_indent_nolabel(curwin->w_cursor.lnum); /* XXX */
7715
7716 /*
7717 * case xx: if (cond) <- line up with this if
7718 * y = y + 1;
7719 * -> s = 99;
7720 *
7721 * case xx:
7722 * if (cond) <- line up with this line
7723 * y = y + 1;
7724 * -> s = 99;
7725 */
7726 if (lookfor == LOOKFOR_TERM)
7727 {
7728 if (n)
7729 amount = n;
7730
7731 if (!lookfor_break)
7732 break;
7733 }
7734
7735 /*
7736 * case xx: x = x + 1; <- line up with this x
7737 * -> y = y + 1;
7738 *
7739 * case xx: if (cond) <- line up with this if
7740 * -> y = y + 1;
7741 */
7742 if (n)
7743 {
7744 amount = n;
7745 l = after_label(ml_get_curline());
7746 if (l != NULL && cin_is_cinword(l))
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007747 {
7748 if (theline[0] == '{')
7749 amount += ind_open_extra;
7750 else
7751 amount += ind_level + ind_no_brace;
7752 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007753 break;
7754 }
7755
7756 /*
7757 * Try to get the indent of a statement before the switch
7758 * label. If nothing is found, line up relative to the
7759 * switch label.
7760 * break; <- may line up with this line
7761 * case xx:
7762 * -> y = 1;
7763 */
7764 scope_amount = get_indent() + (iscase /* XXX */
7765 ? ind_case_code : ind_scopedecl_code);
7766 lookfor = ind_case_break ? LOOKFOR_NOBREAK : LOOKFOR_ANY;
7767 continue;
7768 }
7769
7770 /*
7771 * Looking for a switch() label or C++ scope declaration,
7772 * ignore other lines, skip {}-blocks.
7773 */
7774 if (lookfor == LOOKFOR_CASE || lookfor == LOOKFOR_SCOPEDECL)
7775 {
7776 if (find_last_paren(l, '{', '}') && (trypos =
7777 find_start_brace(ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007778 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007779 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007780 curwin->w_cursor.col = 0;
7781 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007782 continue;
7783 }
7784
7785 /*
7786 * Ignore jump labels with nothing after them.
7787 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007788 if (!ind_js && cin_islabel(ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007789 {
7790 l = after_label(ml_get_curline());
7791 if (l == NULL || cin_nocode(l))
7792 continue;
7793 }
7794
7795 /*
7796 * Ignore #defines, #if, etc.
7797 * Ignore comment and empty lines.
7798 * (need to get the line again, cin_islabel() may have
7799 * unlocked it)
7800 */
7801 l = ml_get_curline();
7802 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum)
7803 || cin_nocode(l))
7804 continue;
7805
7806 /*
7807 * Are we at the start of a cpp base class declaration or
7808 * constructor initialization?
7809 */ /* XXX */
Bram Moolenaar18144c82006-04-12 21:52:12 +00007810 n = FALSE;
7811 if (lookfor != LOOKFOR_TERM && ind_cpp_baseclass > 0)
7812 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00007813 n = cin_is_cpp_baseclass(&col);
Bram Moolenaar18144c82006-04-12 21:52:12 +00007814 l = ml_get_curline();
7815 }
7816 if (n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007817 {
7818 if (lookfor == LOOKFOR_UNTERM)
7819 {
7820 if (cont_amount > 0)
7821 amount = cont_amount;
7822 else
7823 amount += ind_continuation;
7824 }
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007825 else if (theline[0] == '{')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007826 {
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007827 /* Need to find start of the declaration. */
7828 lookfor = LOOKFOR_UNTERM;
7829 ind_continuation = 0;
7830 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007831 }
7832 else
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007833 /* XXX */
7834 amount = get_baseclass_amount(col, ind_maxparen,
7835 ind_maxcomment, ind_cpp_baseclass);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007836 break;
7837 }
7838 else if (lookfor == LOOKFOR_CPP_BASECLASS)
7839 {
7840 /* only look, whether there is a cpp base class
Bram Moolenaar18144c82006-04-12 21:52:12 +00007841 * declaration or initialization before the opening brace.
7842 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007843 if (cin_isterminated(l, TRUE, FALSE))
7844 break;
7845 else
7846 continue;
7847 }
7848
7849 /*
7850 * What happens next depends on the line being terminated.
7851 * If terminated with a ',' only consider it terminating if
Bram Moolenaar25394022007-05-10 19:06:20 +00007852 * there is another unterminated statement behind, eg:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007853 * 123,
7854 * sizeof
7855 * here
7856 * Otherwise check whether it is a enumeration or structure
7857 * initialisation (not indented) or a variable declaration
7858 * (indented).
7859 */
7860 terminated = cin_isterminated(l, FALSE, TRUE);
7861
7862 if (terminated == 0 || (lookfor != LOOKFOR_UNTERM
7863 && terminated == ','))
7864 {
7865 /*
7866 * if we're in the middle of a paren thing,
7867 * go back to the line that starts it so
7868 * we can get the right prevailing indent
7869 * if ( foo &&
7870 * bar )
7871 */
7872 /*
7873 * position the cursor over the rightmost paren, so that
7874 * matching it will take us back to the start of the line.
7875 */
7876 (void)find_last_paren(l, '(', ')');
7877 trypos = find_match_paren(
7878 corr_ind_maxparen(ind_maxparen, &cur_curpos),
7879 ind_maxcomment);
7880
7881 /*
7882 * If we are looking for ',', we also look for matching
7883 * braces.
7884 */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007885 if (trypos == NULL && terminated == ','
7886 && find_last_paren(l, '{', '}'))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007887 trypos = find_start_brace(ind_maxcomment);
7888
7889 if (trypos != NULL)
7890 {
7891 /*
7892 * Check if we are on a case label now. This is
7893 * handled above.
7894 * case xx: if ( asdf &&
7895 * asdf)
7896 */
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007897 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007898 l = ml_get_curline();
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007899 if (cin_iscase(l, FALSE) || cin_isscopedecl(l))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007900 {
7901 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007902 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007903 continue;
7904 }
7905 }
7906
7907 /*
7908 * Skip over continuation lines to find the one to get the
7909 * indent from
7910 * char *usethis = "bla\
7911 * bla",
7912 * here;
7913 */
7914 if (terminated == ',')
7915 {
7916 while (curwin->w_cursor.lnum > 1)
7917 {
7918 l = ml_get(curwin->w_cursor.lnum - 1);
7919 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
7920 break;
7921 --curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007922 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007923 }
7924 }
7925
7926 /*
7927 * Get indent and pointer to text for current line,
7928 * ignoring any jump label. XXX
7929 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007930 if (!ind_js)
7931 cur_amount = skip_label(curwin->w_cursor.lnum,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007932 &l, ind_maxcomment);
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007933 else
7934 cur_amount = get_indent();
Bram Moolenaar071d4272004-06-13 20:20:40 +00007935 /*
7936 * If this is just above the line we are indenting, and it
7937 * starts with a '{', line it up with this line.
7938 * while (not)
7939 * -> {
7940 * }
7941 */
7942 if (terminated != ',' && lookfor != LOOKFOR_TERM
7943 && theline[0] == '{')
7944 {
7945 amount = cur_amount;
7946 /*
7947 * Only add ind_open_extra when the current line
7948 * doesn't start with a '{', which must have a match
7949 * in the same line (scope is the same). Probably:
7950 * { 1, 2 },
7951 * -> { 3, 4 }
7952 */
7953 if (*skipwhite(l) != '{')
7954 amount += ind_open_extra;
7955
7956 if (ind_cpp_baseclass)
7957 {
7958 /* have to look back, whether it is a cpp base
7959 * class declaration or initialization */
7960 lookfor = LOOKFOR_CPP_BASECLASS;
7961 continue;
7962 }
7963 break;
7964 }
7965
7966 /*
7967 * Check if we are after an "if", "while", etc.
7968 * Also allow " } else".
7969 */
7970 if (cin_is_cinword(l) || cin_iselse(skipwhite(l)))
7971 {
7972 /*
7973 * Found an unterminated line after an if (), line up
7974 * with the last one.
7975 * if (cond)
7976 * 100 +
7977 * -> here;
7978 */
7979 if (lookfor == LOOKFOR_UNTERM
7980 || lookfor == LOOKFOR_ENUM_OR_INIT)
7981 {
7982 if (cont_amount > 0)
7983 amount = cont_amount;
7984 else
7985 amount += ind_continuation;
7986 break;
7987 }
7988
7989 /*
7990 * If this is just above the line we are indenting, we
7991 * are finished.
7992 * while (not)
7993 * -> here;
7994 * Otherwise this indent can be used when the line
7995 * before this is terminated.
7996 * yyy;
7997 * if (stat)
7998 * while (not)
7999 * xxx;
8000 * -> here;
8001 */
8002 amount = cur_amount;
8003 if (theline[0] == '{')
8004 amount += ind_open_extra;
8005 if (lookfor != LOOKFOR_TERM)
8006 {
8007 amount += ind_level + ind_no_brace;
8008 break;
8009 }
8010
8011 /*
8012 * Special trick: when expecting the while () after a
8013 * do, line up with the while()
8014 * do
8015 * x = 1;
8016 * -> here
8017 */
8018 l = skipwhite(ml_get_curline());
8019 if (cin_isdo(l))
8020 {
8021 if (whilelevel == 0)
8022 break;
8023 --whilelevel;
8024 }
8025
8026 /*
8027 * When searching for a terminated line, don't use the
Bram Moolenaar334adf02011-05-25 13:34:04 +02008028 * one between the "if" and the matching "else".
Bram Moolenaar071d4272004-06-13 20:20:40 +00008029 * Need to use the scope of this "else". XXX
8030 * If whilelevel != 0 continue looking for a "do {".
8031 */
Bram Moolenaar334adf02011-05-25 13:34:04 +02008032 if (cin_iselse(l) && whilelevel == 0)
8033 {
8034 /* If we're looking at "} else", let's make sure we
8035 * find the opening brace of the enclosing scope,
8036 * not the one from "if () {". */
8037 if (*l == '}')
8038 curwin->w_cursor.col =
Bram Moolenaar9b83c2f2011-05-25 17:29:44 +02008039 (colnr_T)(l - ml_get_curline()) + 1;
Bram Moolenaar334adf02011-05-25 13:34:04 +02008040
8041 if ((trypos = find_start_brace(ind_maxcomment))
8042 == NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00008043 || find_match(LOOKFOR_IF, trypos->lnum,
Bram Moolenaar334adf02011-05-25 13:34:04 +02008044 ind_maxparen, ind_maxcomment) == FAIL)
8045 break;
8046 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008047 }
8048
8049 /*
8050 * If we're below an unterminated line that is not an
8051 * "if" or something, we may line up with this line or
Bram Moolenaar25394022007-05-10 19:06:20 +00008052 * add something for a continuation line, depending on
Bram Moolenaar071d4272004-06-13 20:20:40 +00008053 * the line before this one.
8054 */
8055 else
8056 {
8057 /*
8058 * Found two unterminated lines on a row, line up with
8059 * the last one.
8060 * c = 99 +
8061 * 100 +
8062 * -> here;
8063 */
8064 if (lookfor == LOOKFOR_UNTERM)
8065 {
8066 /* When line ends in a comma add extra indent */
8067 if (terminated == ',')
8068 amount += ind_continuation;
8069 break;
8070 }
8071
8072 if (lookfor == LOOKFOR_ENUM_OR_INIT)
8073 {
8074 /* Found two lines ending in ',', lineup with the
8075 * lowest one, but check for cpp base class
8076 * declaration/initialization, if it is an
8077 * opening brace or we are looking just for
8078 * enumerations/initializations. */
8079 if (terminated == ',')
8080 {
8081 if (ind_cpp_baseclass == 0)
8082 break;
8083
8084 lookfor = LOOKFOR_CPP_BASECLASS;
8085 continue;
8086 }
8087
8088 /* Ignore unterminated lines in between, but
8089 * reduce indent. */
8090 if (amount > cur_amount)
8091 amount = cur_amount;
8092 }
8093 else
8094 {
8095 /*
8096 * Found first unterminated line on a row, may
8097 * line up with this line, remember its indent
8098 * 100 +
8099 * -> here;
8100 */
8101 amount = cur_amount;
8102
8103 /*
8104 * If previous line ends in ',', check whether we
8105 * are in an initialization or enum
8106 * struct xxx =
8107 * {
8108 * sizeof a,
8109 * 124 };
8110 * or a normal possible continuation line.
8111 * but only, of no other statement has been found
8112 * yet.
8113 */
8114 if (lookfor == LOOKFOR_INITIAL && terminated == ',')
8115 {
8116 lookfor = LOOKFOR_ENUM_OR_INIT;
8117 cont_amount = cin_first_id_amount();
8118 }
8119 else
8120 {
8121 if (lookfor == LOOKFOR_INITIAL
8122 && *l != NUL
8123 && l[STRLEN(l) - 1] == '\\')
8124 /* XXX */
8125 cont_amount = cin_get_equal_amount(
8126 curwin->w_cursor.lnum);
8127 if (lookfor != LOOKFOR_TERM)
8128 lookfor = LOOKFOR_UNTERM;
8129 }
8130 }
8131 }
8132 }
8133
8134 /*
8135 * Check if we are after a while (cond);
8136 * If so: Ignore until the matching "do".
8137 */
8138 /* XXX */
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00008139 else if (cin_iswhileofdo_end(terminated, ind_maxparen,
8140 ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008141 {
8142 /*
8143 * Found an unterminated line after a while ();, line up
8144 * with the last one.
8145 * while (cond);
8146 * 100 + <- line up with this one
8147 * -> here;
8148 */
8149 if (lookfor == LOOKFOR_UNTERM
8150 || lookfor == LOOKFOR_ENUM_OR_INIT)
8151 {
8152 if (cont_amount > 0)
8153 amount = cont_amount;
8154 else
8155 amount += ind_continuation;
8156 break;
8157 }
8158
8159 if (whilelevel == 0)
8160 {
8161 lookfor = LOOKFOR_TERM;
8162 amount = get_indent(); /* XXX */
8163 if (theline[0] == '{')
8164 amount += ind_open_extra;
8165 }
8166 ++whilelevel;
8167 }
8168
8169 /*
8170 * We are after a "normal" statement.
8171 * If we had another statement we can stop now and use the
8172 * indent of that other statement.
8173 * Otherwise the indent of the current statement may be used,
8174 * search backwards for the next "normal" statement.
8175 */
8176 else
8177 {
8178 /*
8179 * Skip single break line, if before a switch label. It
8180 * may be lined up with the case label.
8181 */
8182 if (lookfor == LOOKFOR_NOBREAK
8183 && cin_isbreak(skipwhite(ml_get_curline())))
8184 {
8185 lookfor = LOOKFOR_ANY;
8186 continue;
8187 }
8188
8189 /*
8190 * Handle "do {" line.
8191 */
8192 if (whilelevel > 0)
8193 {
8194 l = cin_skipcomment(ml_get_curline());
8195 if (cin_isdo(l))
8196 {
8197 amount = get_indent(); /* XXX */
8198 --whilelevel;
8199 continue;
8200 }
8201 }
8202
8203 /*
8204 * Found a terminated line above an unterminated line. Add
8205 * the amount for a continuation line.
8206 * x = 1;
8207 * y = foo +
8208 * -> here;
8209 * or
8210 * int x = 1;
8211 * int foo,
8212 * -> here;
8213 */
8214 if (lookfor == LOOKFOR_UNTERM
8215 || lookfor == LOOKFOR_ENUM_OR_INIT)
8216 {
8217 if (cont_amount > 0)
8218 amount = cont_amount;
8219 else
8220 amount += ind_continuation;
8221 break;
8222 }
8223
8224 /*
8225 * Found a terminated line above a terminated line or "if"
8226 * etc. line. Use the amount of the line below us.
8227 * x = 1; x = 1;
8228 * if (asdf) y = 2;
8229 * while (asdf) ->here;
8230 * here;
8231 * ->foo;
8232 */
8233 if (lookfor == LOOKFOR_TERM)
8234 {
8235 if (!lookfor_break && whilelevel == 0)
8236 break;
8237 }
8238
8239 /*
8240 * First line above the one we're indenting is terminated.
8241 * To know what needs to be done look further backward for
8242 * a terminated line.
8243 */
8244 else
8245 {
8246 /*
8247 * position the cursor over the rightmost paren, so
8248 * that matching it will take us back to the start of
8249 * the line. Helps for:
8250 * func(asdr,
8251 * asdfasdf);
8252 * here;
8253 */
8254term_again:
8255 l = ml_get_curline();
8256 if (find_last_paren(l, '(', ')')
8257 && (trypos = find_match_paren(ind_maxparen,
8258 ind_maxcomment)) != NULL)
8259 {
8260 /*
8261 * Check if we are on a case label now. This is
8262 * handled above.
8263 * case xx: if ( asdf &&
8264 * asdf)
8265 */
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008266 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008267 l = ml_get_curline();
Bram Moolenaar3acfc302010-07-11 17:23:02 +02008268 if (cin_iscase(l, FALSE) || cin_isscopedecl(l))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008269 {
8270 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008271 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008272 continue;
8273 }
8274 }
8275
8276 /* When aligning with the case statement, don't align
8277 * with a statement after it.
8278 * case 1: { <-- don't use this { position
8279 * stat;
8280 * }
8281 * case 2:
8282 * stat;
8283 * }
8284 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02008285 iscase = (ind_keep_case_label && cin_iscase(l, FALSE));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008286
8287 /*
8288 * Get indent and pointer to text for current line,
8289 * ignoring any jump label.
8290 */
8291 amount = skip_label(curwin->w_cursor.lnum,
8292 &l, ind_maxcomment);
8293
8294 if (theline[0] == '{')
8295 amount += ind_open_extra;
8296 /* See remark above: "Only add ind_open_extra.." */
Bram Moolenaar18144c82006-04-12 21:52:12 +00008297 l = skipwhite(l);
8298 if (*l == '{')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008299 amount -= ind_open_extra;
8300 lookfor = iscase ? LOOKFOR_ANY : LOOKFOR_TERM;
8301
8302 /*
Bram Moolenaar18144c82006-04-12 21:52:12 +00008303 * When a terminated line starts with "else" skip to
8304 * the matching "if":
8305 * else 3;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008306 * indent this;
Bram Moolenaar18144c82006-04-12 21:52:12 +00008307 * Need to use the scope of this "else". XXX
8308 * If whilelevel != 0 continue looking for a "do {".
8309 */
8310 if (lookfor == LOOKFOR_TERM
8311 && *l != '}'
8312 && cin_iselse(l)
8313 && whilelevel == 0)
8314 {
8315 if ((trypos = find_start_brace(ind_maxcomment))
8316 == NULL
8317 || find_match(LOOKFOR_IF, trypos->lnum,
8318 ind_maxparen, ind_maxcomment) == FAIL)
8319 break;
8320 continue;
8321 }
8322
8323 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008324 * If we're at the end of a block, skip to the start of
8325 * that block.
8326 */
Bram Moolenaar6d8f9c62011-11-30 13:03:28 +01008327 l = ml_get_curline();
Bram Moolenaar50f42ca2011-07-15 14:12:30 +02008328 if (find_last_paren(l, '{', '}')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008329 && (trypos = find_start_brace(ind_maxcomment))
8330 != NULL) /* XXX */
8331 {
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008332 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008333 /* if not "else {" check for terminated again */
8334 /* but skip block for "} else {" */
8335 l = cin_skipcomment(ml_get_curline());
8336 if (*l == '}' || !cin_iselse(l))
8337 goto term_again;
8338 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008339 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008340 }
8341 }
8342 }
8343 }
8344 }
8345 }
8346
8347 /* add extra indent for a comment */
8348 if (cin_iscomment(theline))
8349 amount += ind_comment;
Bram Moolenaar02c707a2010-07-17 17:12:06 +02008350
8351 /* subtract extra left-shift for jump labels */
8352 if (ind_jump_label > 0 && original_line_islabel)
8353 amount -= ind_jump_label;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008354 }
8355
8356 /*
8357 * ok -- we're not inside any sort of structure at all!
8358 *
8359 * this means we're at the top level, and everything should
8360 * basically just match where the previous line is, except
8361 * for the lines immediately following a function declaration,
8362 * which are K&R-style parameters and need to be indented.
8363 */
8364 else
8365 {
8366 /*
8367 * if our line starts with an open brace, forget about any
8368 * prevailing indent and make sure it looks like the start
8369 * of a function
8370 */
8371
8372 if (theline[0] == '{')
8373 {
8374 amount = ind_first_open;
8375 }
8376
8377 /*
8378 * If the NEXT line is a function declaration, the current
8379 * line needs to be indented as a function type spec.
Bram Moolenaar1a89bbe2010-03-02 12:38:22 +01008380 * Don't do this if the current line looks like a comment or if the
8381 * current line is terminated, ie. ends in ';', or if the current line
8382 * contains { or }: "void f() {\n if (1)"
Bram Moolenaar071d4272004-06-13 20:20:40 +00008383 */
8384 else if (cur_curpos.lnum < curbuf->b_ml.ml_line_count
8385 && !cin_nocode(theline)
Bram Moolenaar1a89bbe2010-03-02 12:38:22 +01008386 && vim_strchr(theline, '{') == NULL
8387 && vim_strchr(theline, '}') == NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00008388 && !cin_ends_in(theline, (char_u *)":", NULL)
8389 && !cin_ends_in(theline, (char_u *)",", NULL)
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008390 && cin_isfuncdecl(NULL, cur_curpos.lnum + 1,
8391 cur_curpos.lnum + 1,
8392 ind_maxparen, ind_maxcomment)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008393 && !cin_isterminated(theline, FALSE, TRUE))
8394 {
8395 amount = ind_func_type;
8396 }
8397 else
8398 {
8399 amount = 0;
8400 curwin->w_cursor = cur_curpos;
8401
8402 /* search backwards until we find something we recognize */
8403
8404 while (curwin->w_cursor.lnum > 1)
8405 {
8406 curwin->w_cursor.lnum--;
8407 curwin->w_cursor.col = 0;
8408
8409 l = ml_get_curline();
8410
8411 /*
8412 * If we're in a comment now, skip to the start of the comment.
8413 */ /* XXX */
8414 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
8415 {
8416 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008417 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008418 continue;
8419 }
8420
8421 /*
Bram Moolenaar18144c82006-04-12 21:52:12 +00008422 * Are we at the start of a cpp base class declaration or
8423 * constructor initialization?
Bram Moolenaar071d4272004-06-13 20:20:40 +00008424 */ /* XXX */
Bram Moolenaar18144c82006-04-12 21:52:12 +00008425 n = FALSE;
8426 if (ind_cpp_baseclass != 0 && theline[0] != '{')
8427 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00008428 n = cin_is_cpp_baseclass(&col);
Bram Moolenaar18144c82006-04-12 21:52:12 +00008429 l = ml_get_curline();
8430 }
8431 if (n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008432 {
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00008433 /* XXX */
8434 amount = get_baseclass_amount(col, ind_maxparen,
8435 ind_maxcomment, ind_cpp_baseclass);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008436 break;
8437 }
8438
8439 /*
8440 * Skip preprocessor directives and blank lines.
8441 */
8442 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
8443 continue;
8444
8445 if (cin_nocode(l))
8446 continue;
8447
8448 /*
8449 * If the previous line ends in ',', use one level of
8450 * indentation:
8451 * int foo,
8452 * bar;
8453 * do this before checking for '}' in case of eg.
8454 * enum foobar
8455 * {
8456 * ...
8457 * } foo,
8458 * bar;
8459 */
8460 n = 0;
8461 if (cin_ends_in(l, (char_u *)",", NULL)
8462 || (*l != NUL && (n = l[STRLEN(l) - 1]) == '\\'))
8463 {
8464 /* take us back to opening paren */
8465 if (find_last_paren(l, '(', ')')
8466 && (trypos = find_match_paren(ind_maxparen,
8467 ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008468 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008469
8470 /* For a line ending in ',' that is a continuation line go
8471 * back to the first line with a backslash:
8472 * char *foo = "bla\
8473 * bla",
8474 * here;
8475 */
8476 while (n == 0 && curwin->w_cursor.lnum > 1)
8477 {
8478 l = ml_get(curwin->w_cursor.lnum - 1);
8479 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
8480 break;
8481 --curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008482 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008483 }
8484
8485 amount = get_indent(); /* XXX */
8486
8487 if (amount == 0)
8488 amount = cin_first_id_amount();
8489 if (amount == 0)
8490 amount = ind_continuation;
8491 break;
8492 }
8493
8494 /*
8495 * If the line looks like a function declaration, and we're
8496 * not in a comment, put it the left margin.
8497 */
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008498 if (cin_isfuncdecl(NULL, cur_curpos.lnum, 0,
8499 ind_maxparen, ind_maxcomment)) /* XXX */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008500 break;
8501 l = ml_get_curline();
8502
8503 /*
8504 * Finding the closing '}' of a previous function. Put
8505 * current line at the left margin. For when 'cino' has "fs".
8506 */
8507 if (*skipwhite(l) == '}')
8508 break;
8509
8510 /* (matching {)
8511 * If the previous line ends on '};' (maybe followed by
8512 * comments) align at column 0. For example:
8513 * char *string_array[] = { "foo",
8514 * / * x * / "b};ar" }; / * foobar * /
8515 */
8516 if (cin_ends_in(l, (char_u *)"};", NULL))
8517 break;
8518
8519 /*
Bram Moolenaar3388bb42011-11-30 17:20:23 +01008520 * Find a line only has a semicolon that belongs to a previous
8521 * line ending in '}', e.g. before an #endif. Don't increase
8522 * indent then.
8523 */
8524 if (*(look = skipwhite(l)) == ';' && cin_nocode(look + 1))
8525 {
8526 pos_T curpos_save = curwin->w_cursor;
8527
8528 while (curwin->w_cursor.lnum > 1)
8529 {
8530 look = ml_get(--curwin->w_cursor.lnum);
8531 if (!(cin_nocode(look) || cin_ispreproc_cont(
8532 &look, &curwin->w_cursor.lnum)))
8533 break;
8534 }
8535 if (curwin->w_cursor.lnum > 0
8536 && cin_ends_in(look, (char_u *)"}", NULL))
8537 break;
8538
8539 curwin->w_cursor = curpos_save;
8540 }
8541
8542 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008543 * If the PREVIOUS line is a function declaration, the current
8544 * line (and the ones that follow) needs to be indented as
8545 * parameters.
8546 */
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008547 if (cin_isfuncdecl(&l, curwin->w_cursor.lnum, 0,
8548 ind_maxparen, ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008549 {
8550 amount = ind_param;
8551 break;
8552 }
8553
8554 /*
8555 * If the previous line ends in ';' and the line before the
8556 * previous line ends in ',' or '\', ident to column zero:
8557 * int foo,
8558 * bar;
8559 * indent_to_0 here;
8560 */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00008561 if (cin_ends_in(l, (char_u *)";", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008562 {
8563 l = ml_get(curwin->w_cursor.lnum - 1);
8564 if (cin_ends_in(l, (char_u *)",", NULL)
8565 || (*l != NUL && l[STRLEN(l) - 1] == '\\'))
8566 break;
8567 l = ml_get_curline();
8568 }
8569
8570 /*
8571 * Doesn't look like anything interesting -- so just
8572 * use the indent of this line.
8573 *
8574 * Position the cursor over the rightmost paren, so that
8575 * matching it will take us back to the start of the line.
8576 */
8577 find_last_paren(l, '(', ')');
8578
8579 if ((trypos = find_match_paren(ind_maxparen,
8580 ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008581 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008582 amount = get_indent(); /* XXX */
8583 break;
8584 }
8585
8586 /* add extra indent for a comment */
8587 if (cin_iscomment(theline))
8588 amount += ind_comment;
8589
8590 /* add extra indent if the previous line ended in a backslash:
8591 * "asdfasdf\
8592 * here";
8593 * char *foo = "asdf\
8594 * here";
8595 */
8596 if (cur_curpos.lnum > 1)
8597 {
8598 l = ml_get(cur_curpos.lnum - 1);
8599 if (*l != NUL && l[STRLEN(l) - 1] == '\\')
8600 {
8601 cur_amount = cin_get_equal_amount(cur_curpos.lnum - 1);
8602 if (cur_amount > 0)
8603 amount = cur_amount;
8604 else if (cur_amount == 0)
8605 amount += ind_continuation;
8606 }
8607 }
8608 }
8609 }
8610
8611theend:
8612 /* put the cursor back where it belongs */
8613 curwin->w_cursor = cur_curpos;
8614
8615 vim_free(linecopy);
8616
8617 if (amount < 0)
8618 return 0;
8619 return amount;
8620}
8621
8622 static int
8623find_match(lookfor, ourscope, ind_maxparen, ind_maxcomment)
8624 int lookfor;
8625 linenr_T ourscope;
8626 int ind_maxparen;
8627 int ind_maxcomment;
8628{
8629 char_u *look;
8630 pos_T *theirscope;
8631 char_u *mightbeif;
8632 int elselevel;
8633 int whilelevel;
8634
8635 if (lookfor == LOOKFOR_IF)
8636 {
8637 elselevel = 1;
8638 whilelevel = 0;
8639 }
8640 else
8641 {
8642 elselevel = 0;
8643 whilelevel = 1;
8644 }
8645
8646 curwin->w_cursor.col = 0;
8647
8648 while (curwin->w_cursor.lnum > ourscope + 1)
8649 {
8650 curwin->w_cursor.lnum--;
8651 curwin->w_cursor.col = 0;
8652
8653 look = cin_skipcomment(ml_get_curline());
8654 if (cin_iselse(look)
8655 || cin_isif(look)
8656 || cin_isdo(look) /* XXX */
8657 || cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
8658 {
8659 /*
8660 * if we've gone outside the braces entirely,
8661 * we must be out of scope...
8662 */
8663 theirscope = find_start_brace(ind_maxcomment); /* XXX */
8664 if (theirscope == NULL)
8665 break;
8666
8667 /*
8668 * and if the brace enclosing this is further
8669 * back than the one enclosing the else, we're
8670 * out of luck too.
8671 */
8672 if (theirscope->lnum < ourscope)
8673 break;
8674
8675 /*
8676 * and if they're enclosed in a *deeper* brace,
8677 * then we can ignore it because it's in a
8678 * different scope...
8679 */
8680 if (theirscope->lnum > ourscope)
8681 continue;
8682
8683 /*
8684 * if it was an "else" (that's not an "else if")
8685 * then we need to go back to another if, so
8686 * increment elselevel
8687 */
8688 look = cin_skipcomment(ml_get_curline());
8689 if (cin_iselse(look))
8690 {
8691 mightbeif = cin_skipcomment(look + 4);
8692 if (!cin_isif(mightbeif))
8693 ++elselevel;
8694 continue;
8695 }
8696
8697 /*
8698 * if it was a "while" then we need to go back to
8699 * another "do", so increment whilelevel. XXX
8700 */
8701 if (cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
8702 {
8703 ++whilelevel;
8704 continue;
8705 }
8706
8707 /* If it's an "if" decrement elselevel */
8708 look = cin_skipcomment(ml_get_curline());
8709 if (cin_isif(look))
8710 {
8711 elselevel--;
8712 /*
8713 * When looking for an "if" ignore "while"s that
8714 * get in the way.
8715 */
8716 if (elselevel == 0 && lookfor == LOOKFOR_IF)
8717 whilelevel = 0;
8718 }
8719
8720 /* If it's a "do" decrement whilelevel */
8721 if (cin_isdo(look))
8722 whilelevel--;
8723
8724 /*
8725 * if we've used up all the elses, then
8726 * this must be the if that we want!
8727 * match the indent level of that if.
8728 */
8729 if (elselevel <= 0 && whilelevel <= 0)
8730 {
8731 return OK;
8732 }
8733 }
8734 }
8735 return FAIL;
8736}
8737
8738# if defined(FEAT_EVAL) || defined(PROTO)
8739/*
8740 * Get indent level from 'indentexpr'.
8741 */
8742 int
8743get_expr_indent()
8744{
8745 int indent;
8746 pos_T pos;
8747 int save_State;
Bram Moolenaard1f56e62006-02-22 21:25:37 +00008748 int use_sandbox = was_set_insecurely((char_u *)"indentexpr",
8749 OPT_LOCAL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008750
8751 pos = curwin->w_cursor;
8752 set_vim_var_nr(VV_LNUM, curwin->w_cursor.lnum);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00008753 if (use_sandbox)
8754 ++sandbox;
8755 ++textlock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008756 indent = eval_to_number(curbuf->b_p_inde);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00008757 if (use_sandbox)
8758 --sandbox;
8759 --textlock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008760
8761 /* Restore the cursor position so that 'indentexpr' doesn't need to.
8762 * Pretend to be in Insert mode, allow cursor past end of line for "o"
8763 * command. */
8764 save_State = State;
8765 State = INSERT;
8766 curwin->w_cursor = pos;
8767 check_cursor();
8768 State = save_State;
8769
8770 /* If there is an error, just keep the current indent. */
8771 if (indent < 0)
8772 indent = get_indent();
8773
8774 return indent;
8775}
8776# endif
8777
8778#endif /* FEAT_CINDENT */
8779
8780#if defined(FEAT_LISP) || defined(PROTO)
8781
8782static int lisp_match __ARGS((char_u *p));
8783
8784 static int
8785lisp_match(p)
8786 char_u *p;
8787{
8788 char_u buf[LSIZE];
8789 int len;
8790 char_u *word = p_lispwords;
8791
8792 while (*word != NUL)
8793 {
8794 (void)copy_option_part(&word, buf, LSIZE, ",");
8795 len = (int)STRLEN(buf);
8796 if (STRNCMP(buf, p, len) == 0 && p[len] == ' ')
8797 return TRUE;
8798 }
8799 return FALSE;
8800}
8801
8802/*
8803 * When 'p' is present in 'cpoptions, a Vi compatible method is used.
8804 * The incompatible newer method is quite a bit better at indenting
8805 * code in lisp-like languages than the traditional one; it's still
8806 * mostly heuristics however -- Dirk van Deun, dirk@rave.org
8807 *
8808 * TODO:
8809 * Findmatch() should be adapted for lisp, also to make showmatch
8810 * work correctly: now (v5.3) it seems all C/C++ oriented:
8811 * - it does not recognize the #\( and #\) notations as character literals
8812 * - it doesn't know about comments starting with a semicolon
8813 * - it incorrectly interprets '(' as a character literal
8814 * All this messes up get_lisp_indent in some rare cases.
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008815 * Update from Sergey Khorev:
8816 * I tried to fix the first two issues.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008817 */
8818 int
8819get_lisp_indent()
8820{
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008821 pos_T *pos, realpos, paren;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008822 int amount;
8823 char_u *that;
8824 colnr_T col;
8825 colnr_T firsttry;
8826 int parencount, quotecount;
8827 int vi_lisp;
8828
8829 /* Set vi_lisp to use the vi-compatible method */
8830 vi_lisp = (vim_strchr(p_cpo, CPO_LISP) != NULL);
8831
8832 realpos = curwin->w_cursor;
8833 curwin->w_cursor.col = 0;
8834
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008835 if ((pos = findmatch(NULL, '(')) == NULL)
8836 pos = findmatch(NULL, '[');
8837 else
8838 {
8839 paren = *pos;
8840 pos = findmatch(NULL, '[');
8841 if (pos == NULL || ltp(pos, &paren))
8842 pos = &paren;
8843 }
8844 if (pos != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008845 {
8846 /* Extra trick: Take the indent of the first previous non-white
8847 * line that is at the same () level. */
8848 amount = -1;
8849 parencount = 0;
8850
8851 while (--curwin->w_cursor.lnum >= pos->lnum)
8852 {
8853 if (linewhite(curwin->w_cursor.lnum))
8854 continue;
8855 for (that = ml_get_curline(); *that != NUL; ++that)
8856 {
8857 if (*that == ';')
8858 {
8859 while (*(that + 1) != NUL)
8860 ++that;
8861 continue;
8862 }
8863 if (*that == '\\')
8864 {
8865 if (*(that + 1) != NUL)
8866 ++that;
8867 continue;
8868 }
8869 if (*that == '"' && *(that + 1) != NUL)
8870 {
Bram Moolenaar15ff6c12006-09-15 18:18:09 +00008871 while (*++that && *that != '"')
8872 {
8873 /* skipping escaped characters in the string */
8874 if (*that == '\\')
8875 {
8876 if (*++that == NUL)
8877 break;
8878 if (that[1] == NUL)
8879 {
8880 ++that;
8881 break;
8882 }
8883 }
8884 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008885 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008886 if (*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008887 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008888 else if (*that == ')' || *that == ']')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008889 --parencount;
8890 }
8891 if (parencount == 0)
8892 {
8893 amount = get_indent();
8894 break;
8895 }
8896 }
8897
8898 if (amount == -1)
8899 {
8900 curwin->w_cursor.lnum = pos->lnum;
8901 curwin->w_cursor.col = pos->col;
8902 col = pos->col;
8903
8904 that = ml_get_curline();
8905
8906 if (vi_lisp && get_indent() == 0)
8907 amount = 2;
8908 else
8909 {
8910 amount = 0;
8911 while (*that && col)
8912 {
8913 amount += lbr_chartabsize_adv(&that, (colnr_T)amount);
8914 col--;
8915 }
8916
8917 /*
8918 * Some keywords require "body" indenting rules (the
8919 * non-standard-lisp ones are Scheme special forms):
8920 *
8921 * (let ((a 1)) instead (let ((a 1))
8922 * (...)) of (...))
8923 */
8924
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008925 if (!vi_lisp && (*that == '(' || *that == '[')
8926 && lisp_match(that + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008927 amount += 2;
8928 else
8929 {
8930 that++;
8931 amount++;
8932 firsttry = amount;
8933
8934 while (vim_iswhite(*that))
8935 {
8936 amount += lbr_chartabsize(that, (colnr_T)amount);
8937 ++that;
8938 }
8939
8940 if (*that && *that != ';') /* not a comment line */
8941 {
Bram Moolenaare21877a2008-02-13 09:58:14 +00008942 /* test *that != '(' to accommodate first let/do
Bram Moolenaar071d4272004-06-13 20:20:40 +00008943 * argument if it is more than one line */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008944 if (!vi_lisp && *that != '(' && *that != '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008945 firsttry++;
8946
8947 parencount = 0;
8948 quotecount = 0;
8949
8950 if (vi_lisp
8951 || (*that != '"'
8952 && *that != '\''
8953 && *that != '#'
8954 && (*that < '0' || *that > '9')))
8955 {
8956 while (*that
8957 && (!vim_iswhite(*that)
8958 || quotecount
8959 || parencount)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008960 && (!((*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008961 && !quotecount
8962 && !parencount
8963 && vi_lisp)))
8964 {
8965 if (*that == '"')
8966 quotecount = !quotecount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008967 if ((*that == '(' || *that == '[')
8968 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008969 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008970 if ((*that == ')' || *that == ']')
8971 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008972 --parencount;
8973 if (*that == '\\' && *(that+1) != NUL)
8974 amount += lbr_chartabsize_adv(&that,
8975 (colnr_T)amount);
8976 amount += lbr_chartabsize_adv(&that,
8977 (colnr_T)amount);
8978 }
8979 }
8980 while (vim_iswhite(*that))
8981 {
8982 amount += lbr_chartabsize(that, (colnr_T)amount);
8983 that++;
8984 }
8985 if (!*that || *that == ';')
8986 amount = firsttry;
8987 }
8988 }
8989 }
8990 }
8991 }
8992 else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008993 amount = 0; /* no matching '(' or '[' found, use zero indent */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008994
8995 curwin->w_cursor = realpos;
8996
8997 return amount;
8998}
8999#endif /* FEAT_LISP */
9000
9001 void
9002prepare_to_exit()
9003{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00009004#if defined(SIGHUP) && defined(SIG_IGN)
9005 /* Ignore SIGHUP, because a dropped connection causes a read error, which
9006 * makes Vim exit and then handling SIGHUP causes various reentrance
9007 * problems. */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00009008 signal(SIGHUP, SIG_IGN);
9009#endif
9010
Bram Moolenaar071d4272004-06-13 20:20:40 +00009011#ifdef FEAT_GUI
9012 if (gui.in_use)
9013 {
9014 gui.dying = TRUE;
9015 out_trash(); /* trash any pending output */
9016 }
9017 else
9018#endif
9019 {
9020 windgoto((int)Rows - 1, 0);
9021
9022 /*
9023 * Switch terminal mode back now, so messages end up on the "normal"
9024 * screen (if there are two screens).
9025 */
9026 settmode(TMODE_COOK);
9027#ifdef WIN3264
9028 if (can_end_termcap_mode(FALSE) == TRUE)
9029#endif
9030 stoptermcap();
9031 out_flush();
9032 }
9033}
9034
9035/*
9036 * Preserve files and exit.
9037 * When called IObuff must contain a message.
9038 */
9039 void
9040preserve_exit()
9041{
9042 buf_T *buf;
9043
9044 prepare_to_exit();
9045
Bram Moolenaar4770d092006-01-12 23:22:24 +00009046 /* Setting this will prevent free() calls. That avoids calling free()
9047 * recursively when free() was invoked with a bad pointer. */
9048 really_exiting = TRUE;
9049
Bram Moolenaar071d4272004-06-13 20:20:40 +00009050 out_str(IObuff);
9051 screen_start(); /* don't know where cursor is now */
9052 out_flush();
9053
9054 ml_close_notmod(); /* close all not-modified buffers */
9055
9056 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
9057 {
9058 if (buf->b_ml.ml_mfp != NULL && buf->b_ml.ml_mfp->mf_fname != NULL)
9059 {
9060 OUT_STR(_("Vim: preserving files...\n"));
9061 screen_start(); /* don't know where cursor is now */
9062 out_flush();
9063 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
9064 break;
9065 }
9066 }
9067
9068 ml_close_all(FALSE); /* close all memfiles, without deleting */
9069
9070 OUT_STR(_("Vim: Finished.\n"));
9071
9072 getout(1);
9073}
9074
9075/*
9076 * return TRUE if "fname" exists.
9077 */
9078 int
9079vim_fexists(fname)
9080 char_u *fname;
9081{
9082 struct stat st;
9083
9084 if (mch_stat((char *)fname, &st))
9085 return FALSE;
9086 return TRUE;
9087}
9088
9089/*
9090 * Check for CTRL-C pressed, but only once in a while.
9091 * Should be used instead of ui_breakcheck() for functions that check for
9092 * each line in the file. Calling ui_breakcheck() each time takes too much
9093 * time, because it can be a system call.
9094 */
9095
9096#ifndef BREAKCHECK_SKIP
9097# ifdef FEAT_GUI /* assume the GUI only runs on fast computers */
9098# define BREAKCHECK_SKIP 200
9099# else
9100# define BREAKCHECK_SKIP 32
9101# endif
9102#endif
9103
9104static int breakcheck_count = 0;
9105
9106 void
9107line_breakcheck()
9108{
9109 if (++breakcheck_count >= BREAKCHECK_SKIP)
9110 {
9111 breakcheck_count = 0;
9112 ui_breakcheck();
9113 }
9114}
9115
9116/*
9117 * Like line_breakcheck() but check 10 times less often.
9118 */
9119 void
9120fast_breakcheck()
9121{
9122 if (++breakcheck_count >= BREAKCHECK_SKIP * 10)
9123 {
9124 breakcheck_count = 0;
9125 ui_breakcheck();
9126 }
9127}
9128
9129/*
Bram Moolenaard7834d32009-12-02 16:14:36 +00009130 * Invoke expand_wildcards() for one pattern.
9131 * Expand items like "%:h" before the expansion.
9132 * Returns OK or FAIL.
9133 */
9134 int
9135expand_wildcards_eval(pat, num_file, file, flags)
9136 char_u **pat; /* pointer to input pattern */
9137 int *num_file; /* resulting number of files */
9138 char_u ***file; /* array of resulting files */
9139 int flags; /* EW_DIR, etc. */
9140{
9141 int ret = FAIL;
9142 char_u *eval_pat = NULL;
9143 char_u *exp_pat = *pat;
9144 char_u *ignored_msg;
9145 int usedlen;
9146
9147 if (*exp_pat == '%' || *exp_pat == '#' || *exp_pat == '<')
9148 {
9149 ++emsg_off;
9150 eval_pat = eval_vars(exp_pat, exp_pat, &usedlen,
9151 NULL, &ignored_msg, NULL);
9152 --emsg_off;
9153 if (eval_pat != NULL)
9154 exp_pat = concat_str(eval_pat, exp_pat + usedlen);
9155 }
9156
9157 if (exp_pat != NULL)
9158 ret = expand_wildcards(1, &exp_pat, num_file, file, flags);
9159
9160 if (eval_pat != NULL)
9161 {
9162 vim_free(exp_pat);
9163 vim_free(eval_pat);
9164 }
9165
9166 return ret;
9167}
9168
9169/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00009170 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching
9171 * 'wildignore'.
Bram Moolenaar9e193ac2010-07-19 23:11:27 +02009172 * Returns OK or FAIL. When FAIL then "num_file" won't be set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009173 */
9174 int
9175expand_wildcards(num_pat, pat, num_file, file, flags)
9176 int num_pat; /* number of input patterns */
9177 char_u **pat; /* array of input patterns */
9178 int *num_file; /* resulting number of files */
9179 char_u ***file; /* array of resulting files */
9180 int flags; /* EW_DIR, etc. */
9181{
9182 int retval;
9183 int i, j;
9184 char_u *p;
9185 int non_suf_match; /* number without matching suffix */
9186
9187 retval = gen_expand_wildcards(num_pat, pat, num_file, file, flags);
9188
9189 /* When keeping all matches, return here */
Bram Moolenaar9e193ac2010-07-19 23:11:27 +02009190 if ((flags & EW_KEEPALL) || retval == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009191 return retval;
9192
9193#ifdef FEAT_WILDIGN
9194 /*
9195 * Remove names that match 'wildignore'.
9196 */
9197 if (*p_wig)
9198 {
9199 char_u *ffname;
9200
9201 /* check all files in (*file)[] */
9202 for (i = 0; i < *num_file; ++i)
9203 {
9204 ffname = FullName_save((*file)[i], FALSE);
9205 if (ffname == NULL) /* out of memory */
9206 break;
9207# ifdef VMS
9208 vms_remove_version(ffname);
9209# endif
9210 if (match_file_list(p_wig, (*file)[i], ffname))
9211 {
9212 /* remove this matching file from the list */
9213 vim_free((*file)[i]);
9214 for (j = i; j + 1 < *num_file; ++j)
9215 (*file)[j] = (*file)[j + 1];
9216 --*num_file;
9217 --i;
9218 }
9219 vim_free(ffname);
9220 }
9221 }
9222#endif
9223
9224 /*
9225 * Move the names where 'suffixes' match to the end.
9226 */
9227 if (*num_file > 1)
9228 {
9229 non_suf_match = 0;
9230 for (i = 0; i < *num_file; ++i)
9231 {
9232 if (!match_suffix((*file)[i]))
9233 {
9234 /*
9235 * Move the name without matching suffix to the front
9236 * of the list.
9237 */
9238 p = (*file)[i];
9239 for (j = i; j > non_suf_match; --j)
9240 (*file)[j] = (*file)[j - 1];
9241 (*file)[non_suf_match++] = p;
9242 }
9243 }
9244 }
9245
9246 return retval;
9247}
9248
9249/*
9250 * Return TRUE if "fname" matches with an entry in 'suffixes'.
9251 */
9252 int
9253match_suffix(fname)
9254 char_u *fname;
9255{
9256 int fnamelen, setsuflen;
9257 char_u *setsuf;
9258#define MAXSUFLEN 30 /* maximum length of a file suffix */
9259 char_u suf_buf[MAXSUFLEN];
9260
9261 fnamelen = (int)STRLEN(fname);
9262 setsuflen = 0;
9263 for (setsuf = p_su; *setsuf; )
9264 {
9265 setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
Bram Moolenaar055a2ba2009-07-14 19:40:21 +00009266 if (setsuflen == 0)
9267 {
9268 char_u *tail = gettail(fname);
9269
9270 /* empty entry: match name without a '.' */
9271 if (vim_strchr(tail, '.') == NULL)
9272 {
9273 setsuflen = 1;
9274 break;
9275 }
9276 }
9277 else
9278 {
9279 if (fnamelen >= setsuflen
9280 && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
9281 (size_t)setsuflen) == 0)
9282 break;
9283 setsuflen = 0;
9284 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009285 }
9286 return (setsuflen != 0);
9287}
9288
9289#if !defined(NO_EXPANDPATH) || defined(PROTO)
9290
9291# ifdef VIM_BACKTICK
9292static int vim_backtick __ARGS((char_u *p));
9293static int expand_backtick __ARGS((garray_T *gap, char_u *pat, int flags));
9294# endif
9295
9296# if defined(MSDOS) || defined(FEAT_GUI_W16) || defined(WIN3264)
9297/*
9298 * File name expansion code for MS-DOS, Win16 and Win32. It's here because
9299 * it's shared between these systems.
9300 */
9301# if defined(DJGPP) || defined(PROTO)
9302# define _cdecl /* DJGPP doesn't have this */
9303# else
9304# ifdef __BORLANDC__
9305# define _cdecl _RTLENTRYF
9306# endif
9307# endif
9308
9309/*
9310 * comparison function for qsort in dos_expandpath()
9311 */
9312 static int _cdecl
9313pstrcmp(const void *a, const void *b)
9314{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00009315 return (pathcmp(*(char **)a, *(char **)b, -1));
Bram Moolenaar071d4272004-06-13 20:20:40 +00009316}
9317
9318# ifndef WIN3264
9319 static void
9320namelowcpy(
9321 char_u *d,
9322 char_u *s)
9323{
9324# ifdef DJGPP
9325 if (USE_LONG_FNAME) /* don't lower case on Windows 95/NT systems */
9326 while (*s)
9327 *d++ = *s++;
9328 else
9329# endif
9330 while (*s)
9331 *d++ = TOLOWER_LOC(*s++);
9332 *d = NUL;
9333}
9334# endif
9335
9336/*
Bram Moolenaar231334e2005-07-25 20:46:57 +00009337 * Recursively expand one path component into all matching files and/or
9338 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009339 * Return the number of matches found.
9340 * "path" has backslashes before chars that are not to be expanded, starting
9341 * at "path[wildoff]".
Bram Moolenaar231334e2005-07-25 20:46:57 +00009342 * Return the number of matches found.
9343 * NOTE: much of this is identical to unix_expandpath(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00009344 */
9345 static int
9346dos_expandpath(
9347 garray_T *gap,
9348 char_u *path,
9349 int wildoff,
Bram Moolenaar231334e2005-07-25 20:46:57 +00009350 int flags, /* EW_* flags */
Bram Moolenaar25394022007-05-10 19:06:20 +00009351 int didstar) /* expanded "**" once already */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009352{
Bram Moolenaar231334e2005-07-25 20:46:57 +00009353 char_u *buf;
9354 char_u *path_end;
9355 char_u *p, *s, *e;
9356 int start_len = gap->ga_len;
9357 char_u *pat;
9358 regmatch_T regmatch;
9359 int starts_with_dot;
9360 int matches;
9361 int len;
9362 int starstar = FALSE;
9363 static int stardepth = 0; /* depth for "**" expansion */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009364#ifdef WIN3264
9365 WIN32_FIND_DATA fb;
9366 HANDLE hFind = (HANDLE)0;
9367# ifdef FEAT_MBYTE
9368 WIN32_FIND_DATAW wfb;
9369 WCHAR *wn = NULL; /* UCS-2 name, NULL when not used. */
9370# endif
9371#else
9372 struct ffblk fb;
9373#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009374 char_u *matchname;
Bram Moolenaar231334e2005-07-25 20:46:57 +00009375 int ok;
9376
9377 /* Expanding "**" may take a long time, check for CTRL-C. */
9378 if (stardepth > 0)
9379 {
9380 ui_breakcheck();
9381 if (got_int)
9382 return 0;
9383 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009384
9385 /* make room for file name */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009386 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009387 if (buf == NULL)
9388 return 0;
9389
9390 /*
9391 * Find the first part in the path name that contains a wildcard or a ~1.
9392 * Copy it into buf, including the preceding characters.
9393 */
9394 p = buf;
9395 s = buf;
9396 e = NULL;
9397 path_end = path;
9398 while (*path_end != NUL)
9399 {
9400 /* May ignore a wildcard that has a backslash before it; it will
9401 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
9402 if (path_end >= path + wildoff && rem_backslash(path_end))
9403 *p++ = *path_end++;
9404 else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
9405 {
9406 if (e != NULL)
9407 break;
9408 s = p + 1;
9409 }
9410 else if (path_end >= path + wildoff
9411 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
9412 e = p;
9413#ifdef FEAT_MBYTE
9414 if (has_mbyte)
9415 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00009416 len = (*mb_ptr2len)(path_end);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009417 STRNCPY(p, path_end, len);
9418 p += len;
9419 path_end += len;
9420 }
9421 else
9422#endif
9423 *p++ = *path_end++;
9424 }
9425 e = p;
9426 *e = NUL;
9427
9428 /* now we have one wildcard component between s and e */
9429 /* Remove backslashes between "wildoff" and the start of the wildcard
9430 * component. */
9431 for (p = buf + wildoff; p < s; ++p)
9432 if (rem_backslash(p))
9433 {
Bram Moolenaar8c8de832008-06-24 22:58:06 +00009434 STRMOVE(p, p + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009435 --e;
9436 --s;
9437 }
9438
Bram Moolenaar231334e2005-07-25 20:46:57 +00009439 /* Check for "**" between "s" and "e". */
9440 for (p = s; p < e; ++p)
9441 if (p[0] == '*' && p[1] == '*')
9442 starstar = TRUE;
9443
Bram Moolenaar071d4272004-06-13 20:20:40 +00009444 starts_with_dot = (*s == '.');
9445 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
9446 if (pat == NULL)
9447 {
9448 vim_free(buf);
9449 return 0;
9450 }
9451
9452 /* compile the regexp into a program */
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009453 if (flags & (EW_NOERROR | EW_NOTWILD))
Bram Moolenaarb5609832011-07-20 15:04:58 +02009454 ++emsg_silent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009455 regmatch.rm_ic = TRUE; /* Always ignore case */
9456 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009457 if (flags & (EW_NOERROR | EW_NOTWILD))
Bram Moolenaarb5609832011-07-20 15:04:58 +02009458 --emsg_silent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009459 vim_free(pat);
9460
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009461 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009462 {
9463 vim_free(buf);
9464 return 0;
9465 }
9466
9467 /* remember the pattern or file name being looked for */
9468 matchname = vim_strsave(s);
9469
Bram Moolenaar231334e2005-07-25 20:46:57 +00009470 /* If "**" is by itself, this is the first time we encounter it and more
9471 * is following then find matches without any directory. */
9472 if (!didstar && stardepth < 100 && starstar && e - s == 2
9473 && *path_end == '/')
9474 {
9475 STRCPY(s, path_end + 1);
9476 ++stardepth;
9477 (void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
9478 --stardepth;
9479 }
9480
Bram Moolenaar071d4272004-06-13 20:20:40 +00009481 /* Scan all files in the directory with "dir/ *.*" */
9482 STRCPY(s, "*.*");
9483#ifdef WIN3264
9484# ifdef FEAT_MBYTE
9485 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
9486 {
9487 /* The active codepage differs from 'encoding'. Attempt using the
9488 * wide function. If it fails because it is not implemented fall back
9489 * to the non-wide version (for Windows 98) */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009490 wn = enc_to_utf16(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009491 if (wn != NULL)
9492 {
9493 hFind = FindFirstFileW(wn, &wfb);
9494 if (hFind == INVALID_HANDLE_VALUE
9495 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
9496 {
9497 vim_free(wn);
9498 wn = NULL;
9499 }
9500 }
9501 }
9502
9503 if (wn == NULL)
9504# endif
9505 hFind = FindFirstFile(buf, &fb);
9506 ok = (hFind != INVALID_HANDLE_VALUE);
9507#else
9508 /* If we are expanding wildcards we try both files and directories */
9509 ok = (findfirst((char *)buf, &fb,
9510 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
9511#endif
9512
9513 while (ok)
9514 {
9515#ifdef WIN3264
9516# ifdef FEAT_MBYTE
9517 if (wn != NULL)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009518 p = utf16_to_enc(wfb.cFileName, NULL); /* p is allocated here */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009519 else
9520# endif
9521 p = (char_u *)fb.cFileName;
9522#else
9523 p = (char_u *)fb.ff_name;
9524#endif
9525 /* Ignore entries starting with a dot, unless when asked for. Accept
9526 * all entries found with "matchname". */
9527 if ((p[0] != '.' || starts_with_dot)
9528 && (matchname == NULL
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009529 || (regmatch.regprog != NULL
9530 && vim_regexec(&regmatch, p, (colnr_T)0))
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009531 || ((flags & EW_NOTWILD)
9532 && fnamencmp(path + (s - buf), p, e - s) == 0)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009533 {
9534#ifdef WIN3264
9535 STRCPY(s, p);
9536#else
9537 namelowcpy(s, p);
9538#endif
9539 len = (int)STRLEN(buf);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009540
9541 if (starstar && stardepth < 100)
9542 {
9543 /* For "**" in the pattern first go deeper in the tree to
9544 * find matches. */
9545 STRCPY(buf + len, "/**");
9546 STRCPY(buf + len + 3, path_end);
9547 ++stardepth;
9548 (void)dos_expandpath(gap, buf, len + 1, flags, TRUE);
9549 --stardepth;
9550 }
9551
Bram Moolenaar071d4272004-06-13 20:20:40 +00009552 STRCPY(buf + len, path_end);
9553 if (mch_has_exp_wildcard(path_end))
9554 {
9555 /* need to expand another component of the path */
9556 /* remove backslashes for the remaining components only */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009557 (void)dos_expandpath(gap, buf, len + 1, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009558 }
9559 else
9560 {
9561 /* no more wildcards, check if there is a match */
9562 /* remove backslashes for the remaining components only */
9563 if (*path_end != 0)
9564 backslash_halve(buf + len + 1);
9565 if (mch_getperm(buf) >= 0) /* add existing file */
9566 addfile(gap, buf, flags);
9567 }
9568 }
9569
9570#ifdef WIN3264
9571# ifdef FEAT_MBYTE
9572 if (wn != NULL)
9573 {
9574 vim_free(p);
9575 ok = FindNextFileW(hFind, &wfb);
9576 }
9577 else
9578# endif
9579 ok = FindNextFile(hFind, &fb);
9580#else
9581 ok = (findnext(&fb) == 0);
9582#endif
9583
9584 /* If no more matches and no match was used, try expanding the name
9585 * itself. Finds the long name of a short filename. */
9586 if (!ok && matchname != NULL && gap->ga_len == start_len)
9587 {
9588 STRCPY(s, matchname);
9589#ifdef WIN3264
9590 FindClose(hFind);
9591# ifdef FEAT_MBYTE
9592 if (wn != NULL)
9593 {
9594 vim_free(wn);
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009595 wn = enc_to_utf16(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009596 if (wn != NULL)
9597 hFind = FindFirstFileW(wn, &wfb);
9598 }
9599 if (wn == NULL)
9600# endif
9601 hFind = FindFirstFile(buf, &fb);
9602 ok = (hFind != INVALID_HANDLE_VALUE);
9603#else
9604 ok = (findfirst((char *)buf, &fb,
9605 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
9606#endif
9607 vim_free(matchname);
9608 matchname = NULL;
9609 }
9610 }
9611
9612#ifdef WIN3264
9613 FindClose(hFind);
9614# ifdef FEAT_MBYTE
9615 vim_free(wn);
9616# endif
9617#endif
9618 vim_free(buf);
9619 vim_free(regmatch.regprog);
9620 vim_free(matchname);
9621
9622 matches = gap->ga_len - start_len;
9623 if (matches > 0)
9624 qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
9625 sizeof(char_u *), pstrcmp);
9626 return matches;
9627}
9628
9629 int
9630mch_expandpath(
9631 garray_T *gap,
9632 char_u *path,
9633 int flags) /* EW_* flags */
9634{
Bram Moolenaar231334e2005-07-25 20:46:57 +00009635 return dos_expandpath(gap, path, 0, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009636}
9637# endif /* MSDOS || FEAT_GUI_W16 || WIN3264 */
9638
Bram Moolenaar231334e2005-07-25 20:46:57 +00009639#if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
9640 || defined(PROTO)
9641/*
9642 * Unix style wildcard expansion code.
9643 * It's here because it's used both for Unix and Mac.
9644 */
9645static int pstrcmp __ARGS((const void *, const void *));
9646
9647 static int
9648pstrcmp(a, b)
9649 const void *a, *b;
9650{
9651 return (pathcmp(*(char **)a, *(char **)b, -1));
9652}
9653
9654/*
9655 * Recursively expand one path component into all matching files and/or
9656 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
9657 * "path" has backslashes before chars that are not to be expanded, starting
9658 * at "path + wildoff".
9659 * Return the number of matches found.
9660 * NOTE: much of this is identical to dos_expandpath(), keep in sync!
9661 */
9662 int
9663unix_expandpath(gap, path, wildoff, flags, didstar)
9664 garray_T *gap;
9665 char_u *path;
9666 int wildoff;
9667 int flags; /* EW_* flags */
9668 int didstar; /* expanded "**" once already */
9669{
9670 char_u *buf;
9671 char_u *path_end;
9672 char_u *p, *s, *e;
9673 int start_len = gap->ga_len;
9674 char_u *pat;
9675 regmatch_T regmatch;
9676 int starts_with_dot;
9677 int matches;
9678 int len;
9679 int starstar = FALSE;
9680 static int stardepth = 0; /* depth for "**" expansion */
9681
9682 DIR *dirp;
9683 struct dirent *dp;
9684
9685 /* Expanding "**" may take a long time, check for CTRL-C. */
9686 if (stardepth > 0)
9687 {
9688 ui_breakcheck();
9689 if (got_int)
9690 return 0;
9691 }
9692
9693 /* make room for file name */
9694 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
9695 if (buf == NULL)
9696 return 0;
9697
9698 /*
9699 * Find the first part in the path name that contains a wildcard.
Bram Moolenaar2d0b92f2012-04-30 21:09:43 +02009700 * When EW_ICASE is set every letter is considered to be a wildcard.
Bram Moolenaar231334e2005-07-25 20:46:57 +00009701 * Copy it into "buf", including the preceding characters.
9702 */
9703 p = buf;
9704 s = buf;
9705 e = NULL;
9706 path_end = path;
9707 while (*path_end != NUL)
9708 {
9709 /* May ignore a wildcard that has a backslash before it; it will
9710 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
9711 if (path_end >= path + wildoff && rem_backslash(path_end))
9712 *p++ = *path_end++;
9713 else if (*path_end == '/')
9714 {
9715 if (e != NULL)
9716 break;
9717 s = p + 1;
9718 }
9719 else if (path_end >= path + wildoff
Bram Moolenaar2d0b92f2012-04-30 21:09:43 +02009720 && (vim_strchr((char_u *)"*?[{~$", *path_end) != NULL
9721#ifndef CASE_INSENSITIVE_FILENAME
9722 || ((flags & EW_ICASE)
9723 && isalpha(PTR2CHAR(path_end)))
9724#endif
9725 ))
Bram Moolenaar231334e2005-07-25 20:46:57 +00009726 e = p;
9727#ifdef FEAT_MBYTE
9728 if (has_mbyte)
9729 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00009730 len = (*mb_ptr2len)(path_end);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009731 STRNCPY(p, path_end, len);
9732 p += len;
9733 path_end += len;
9734 }
9735 else
9736#endif
9737 *p++ = *path_end++;
9738 }
9739 e = p;
9740 *e = NUL;
9741
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009742 /* Now we have one wildcard component between "s" and "e". */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009743 /* Remove backslashes between "wildoff" and the start of the wildcard
9744 * component. */
9745 for (p = buf + wildoff; p < s; ++p)
9746 if (rem_backslash(p))
9747 {
Bram Moolenaar8c8de832008-06-24 22:58:06 +00009748 STRMOVE(p, p + 1);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009749 --e;
9750 --s;
9751 }
9752
9753 /* Check for "**" between "s" and "e". */
9754 for (p = s; p < e; ++p)
9755 if (p[0] == '*' && p[1] == '*')
9756 starstar = TRUE;
9757
9758 /* convert the file pattern to a regexp pattern */
9759 starts_with_dot = (*s == '.');
9760 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
9761 if (pat == NULL)
9762 {
9763 vim_free(buf);
9764 return 0;
9765 }
9766
9767 /* compile the regexp into a program */
Bram Moolenaarcc016f52005-12-10 20:23:46 +00009768#ifdef CASE_INSENSITIVE_FILENAME
Bram Moolenaar231334e2005-07-25 20:46:57 +00009769 regmatch.rm_ic = TRUE; /* Behave like Terminal.app */
9770#else
Bram Moolenaar94950a92010-12-02 16:01:29 +01009771 if (flags & EW_ICASE)
9772 regmatch.rm_ic = TRUE; /* 'wildignorecase' set */
9773 else
9774 regmatch.rm_ic = FALSE; /* Don't ignore case */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009775#endif
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009776 if (flags & (EW_NOERROR | EW_NOTWILD))
9777 ++emsg_silent;
Bram Moolenaar231334e2005-07-25 20:46:57 +00009778 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009779 if (flags & (EW_NOERROR | EW_NOTWILD))
9780 --emsg_silent;
Bram Moolenaar231334e2005-07-25 20:46:57 +00009781 vim_free(pat);
9782
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009783 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
Bram Moolenaar231334e2005-07-25 20:46:57 +00009784 {
9785 vim_free(buf);
9786 return 0;
9787 }
9788
9789 /* If "**" is by itself, this is the first time we encounter it and more
9790 * is following then find matches without any directory. */
9791 if (!didstar && stardepth < 100 && starstar && e - s == 2
9792 && *path_end == '/')
9793 {
9794 STRCPY(s, path_end + 1);
9795 ++stardepth;
9796 (void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
9797 --stardepth;
9798 }
9799
9800 /* open the directory for scanning */
9801 *s = NUL;
9802 dirp = opendir(*buf == NUL ? "." : (char *)buf);
9803
9804 /* Find all matching entries */
9805 if (dirp != NULL)
9806 {
9807 for (;;)
9808 {
9809 dp = readdir(dirp);
9810 if (dp == NULL)
9811 break;
9812 if ((dp->d_name[0] != '.' || starts_with_dot)
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009813 && ((regmatch.regprog != NULL && vim_regexec(&regmatch,
9814 (char_u *)dp->d_name, (colnr_T)0))
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009815 || ((flags & EW_NOTWILD)
9816 && fnamencmp(path + (s - buf), dp->d_name, e - s) == 0)))
Bram Moolenaar231334e2005-07-25 20:46:57 +00009817 {
9818 STRCPY(s, dp->d_name);
9819 len = STRLEN(buf);
9820
9821 if (starstar && stardepth < 100)
9822 {
9823 /* For "**" in the pattern first go deeper in the tree to
9824 * find matches. */
9825 STRCPY(buf + len, "/**");
9826 STRCPY(buf + len + 3, path_end);
9827 ++stardepth;
9828 (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
9829 --stardepth;
9830 }
9831
9832 STRCPY(buf + len, path_end);
9833 if (mch_has_exp_wildcard(path_end)) /* handle more wildcards */
9834 {
9835 /* need to expand another component of the path */
9836 /* remove backslashes for the remaining components only */
9837 (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
9838 }
9839 else
9840 {
9841 /* no more wildcards, check if there is a match */
9842 /* remove backslashes for the remaining components only */
9843 if (*path_end != NUL)
9844 backslash_halve(buf + len + 1);
9845 if (mch_getperm(buf) >= 0) /* add existing file */
9846 {
Bram Moolenaar95e9b492006-03-15 23:04:43 +00009847#ifdef MACOS_CONVERT
Bram Moolenaar231334e2005-07-25 20:46:57 +00009848 size_t precomp_len = STRLEN(buf)+1;
9849 char_u *precomp_buf =
9850 mac_precompose_path(buf, precomp_len, &precomp_len);
Bram Moolenaar95e9b492006-03-15 23:04:43 +00009851
Bram Moolenaar231334e2005-07-25 20:46:57 +00009852 if (precomp_buf)
9853 {
9854 mch_memmove(buf, precomp_buf, precomp_len);
9855 vim_free(precomp_buf);
9856 }
9857#endif
9858 addfile(gap, buf, flags);
9859 }
9860 }
9861 }
9862 }
9863
9864 closedir(dirp);
9865 }
9866
9867 vim_free(buf);
9868 vim_free(regmatch.regprog);
9869
9870 matches = gap->ga_len - start_len;
9871 if (matches > 0)
9872 qsort(((char_u **)gap->ga_data) + start_len, matches,
9873 sizeof(char_u *), pstrcmp);
9874 return matches;
9875}
9876#endif
9877
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009878#if defined(FEAT_SEARCHPATH)
9879static int find_previous_pathsep __ARGS((char_u *path, char_u **psep));
9880static int is_unique __ARGS((char_u *maybe_unique, garray_T *gap, int i));
Bram Moolenaar162bd912010-07-28 22:29:10 +02009881static void expand_path_option __ARGS((char_u *curdir, garray_T *gap));
9882static char_u *get_path_cutoff __ARGS((char_u *fname, garray_T *gap));
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009883static void uniquefy_paths __ARGS((garray_T *gap, char_u *pattern));
9884static int expand_in_path __ARGS((garray_T *gap, char_u *pattern, int flags));
9885
9886/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009887 * Moves "*psep" back to the previous path separator in "path".
9888 * Returns FAIL is "*psep" ends up at the beginning of "path".
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009889 */
9890 static int
9891find_previous_pathsep(path, psep)
9892 char_u *path;
9893 char_u **psep;
9894{
9895 /* skip the current separator */
9896 if (*psep > path && vim_ispathsep(**psep))
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009897 --*psep;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009898
9899 /* find the previous separator */
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009900 while (*psep > path)
9901 {
9902 if (vim_ispathsep(**psep))
9903 return OK;
9904 mb_ptr_back(path, *psep);
9905 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009906
9907 return FAIL;
9908}
9909
9910/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009911 * Returns TRUE if "maybe_unique" is unique wrt other_paths in "gap".
9912 * "maybe_unique" is the end portion of "((char_u **)gap->ga_data)[i]".
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009913 */
9914 static int
9915is_unique(maybe_unique, gap, i)
9916 char_u *maybe_unique;
9917 garray_T *gap;
9918 int i;
9919{
9920 int j;
9921 int candidate_len;
9922 int other_path_len;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009923 char_u **other_paths = (char_u **)gap->ga_data;
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009924 char_u *rival;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009925
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009926 for (j = 0; j < gap->ga_len; j++)
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009927 {
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009928 if (j == i)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009929 continue; /* don't compare it with itself */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009930
Bram Moolenaar624c7aa2010-07-16 20:38:52 +02009931 candidate_len = (int)STRLEN(maybe_unique);
9932 other_path_len = (int)STRLEN(other_paths[j]);
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009933 if (other_path_len < candidate_len)
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009934 continue; /* it's different when it's shorter */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009935
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009936 rival = other_paths[j] + other_path_len - candidate_len;
Bram Moolenaarda9836c2010-08-16 21:53:27 +02009937 if (fnamecmp(maybe_unique, rival) == 0
9938 && (rival == other_paths[j] || vim_ispathsep(*(rival - 1))))
Bram Moolenaar162bd912010-07-28 22:29:10 +02009939 return FALSE; /* match */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009940 }
9941
Bram Moolenaar162bd912010-07-28 22:29:10 +02009942 return TRUE; /* no match found */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009943}
9944
9945/*
Bram Moolenaar1a509df2010-08-01 17:59:57 +02009946 * Split the 'path' option into an array of strings in garray_T. Relative
Bram Moolenaar162bd912010-07-28 22:29:10 +02009947 * paths are expanded to their equivalent fullpath. This includes the "."
9948 * (relative to current buffer directory) and empty path (relative to current
9949 * directory) notations.
9950 *
9951 * TODO: handle upward search (;) and path limiter (**N) notations by
9952 * expanding each into their equivalent path(s).
9953 */
9954 static void
9955expand_path_option(curdir, gap)
9956 char_u *curdir;
9957 garray_T *gap;
9958{
9959 char_u *path_option = *curbuf->b_p_path == NUL
9960 ? p_path : curbuf->b_p_path;
9961 char_u *buf;
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009962 char_u *p;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009963 int len;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009964
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +02009965 if ((buf = alloc((int)MAXPATHL)) == NULL)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009966 return;
9967
9968 while (*path_option != NUL)
9969 {
9970 copy_option_part(&path_option, buf, MAXPATHL, " ,");
9971
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009972 if (buf[0] == '.' && (buf[1] == NUL || vim_ispathsep(buf[1])))
Bram Moolenaar162bd912010-07-28 22:29:10 +02009973 {
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009974 /* Relative to current buffer:
9975 * "/path/file" + "." -> "/path/"
9976 * "/path/file" + "./subdir" -> "/path/subdir" */
Bram Moolenaar162bd912010-07-28 22:29:10 +02009977 if (curbuf->b_ffname == NULL)
9978 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009979 p = gettail(curbuf->b_ffname);
9980 len = (int)(p - curbuf->b_ffname);
9981 if (len + (int)STRLEN(buf) >= MAXPATHL)
9982 continue;
9983 if (buf[1] == NUL)
9984 buf[len] = NUL;
9985 else
9986 STRMOVE(buf + len, buf + 2);
9987 mch_memmove(buf, curbuf->b_ffname, len);
9988 simplify_filename(buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009989 }
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009990 else if (buf[0] == NUL)
9991 /* relative to current directory */
Bram Moolenaar162bd912010-07-28 22:29:10 +02009992 STRCPY(buf, curdir);
Bram Moolenaar84f888a2010-08-05 21:40:16 +02009993 else if (path_with_url(buf))
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009994 /* URL can't be used here */
Bram Moolenaar84f888a2010-08-05 21:40:16 +02009995 continue;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009996 else if (!mch_isFullName(buf))
9997 {
9998 /* Expand relative path to their full path equivalent */
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009999 len = (int)STRLEN(curdir);
10000 if (len + (int)STRLEN(buf) + 3 > MAXPATHL)
Bram Moolenaar162bd912010-07-28 22:29:10 +020010001 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010002 STRMOVE(buf + len + 1, buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010003 STRCPY(buf, curdir);
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010004 buf[len] = PATHSEP;
Bram Moolenaar57adda12010-08-03 22:11:29 +020010005 simplify_filename(buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010006 }
10007
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010008 if (ga_grow(gap, 1) == FAIL)
10009 break;
10010 p = vim_strsave(buf);
10011 if (p == NULL)
10012 break;
10013 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010014 }
10015
10016 vim_free(buf);
10017}
10018
10019/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010020 * Returns a pointer to the file or directory name in "fname" that matches the
10021 * longest path in "ga"p, or NULL if there is no match. For example:
Bram Moolenaar162bd912010-07-28 22:29:10 +020010022 *
10023 * path: /foo/bar/baz
10024 * fname: /foo/bar/baz/quux.txt
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010025 * returns: ^this
Bram Moolenaar162bd912010-07-28 22:29:10 +020010026 */
10027 static char_u *
10028get_path_cutoff(fname, gap)
10029 char_u *fname;
10030 garray_T *gap;
10031{
10032 int i;
10033 int maxlen = 0;
10034 char_u **path_part = (char_u **)gap->ga_data;
10035 char_u *cutoff = NULL;
10036
10037 for (i = 0; i < gap->ga_len; i++)
10038 {
10039 int j = 0;
10040
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010041 while ((fname[j] == path_part[i][j]
Bram Moolenaar2d7c47d2010-08-10 19:50:26 +020010042# if defined(MSWIN) || defined(MSDOS)
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010043 || (vim_ispathsep(fname[j]) && vim_ispathsep(path_part[i][j]))
10044#endif
10045 ) && fname[j] != NUL && path_part[i][j] != NUL)
Bram Moolenaar162bd912010-07-28 22:29:10 +020010046 j++;
10047 if (j > maxlen)
10048 {
10049 maxlen = j;
10050 cutoff = &fname[j];
10051 }
10052 }
10053
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010054 /* skip to the file or directory name */
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010055 if (cutoff != NULL)
Bram Moolenaar31710262010-08-13 13:36:15 +020010056 while (vim_ispathsep(*cutoff))
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010057 mb_ptr_adv(cutoff);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010058
10059 return cutoff;
10060}
10061
10062/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010063 * Sorts, removes duplicates and modifies all the fullpath names in "gap" so
10064 * that they are unique with respect to each other while conserving the part
10065 * that matches the pattern. Beware, this is at least O(n^2) wrt "gap->ga_len".
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010066 */
10067 static void
10068uniquefy_paths(gap, pattern)
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +020010069 garray_T *gap;
10070 char_u *pattern;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010071{
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +020010072 int i;
10073 int len;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010074 char_u **fnames = (char_u **)gap->ga_data;
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010075 int sort_again = FALSE;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010076 char_u *pat;
10077 char_u *file_pattern;
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010078 char_u *curdir;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010079 regmatch_T regmatch;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010080 garray_T path_ga;
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010081 char_u **in_curdir = NULL;
10082 char_u *short_name;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010083
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +020010084 remove_duplicates(gap);
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010085 ga_init2(&path_ga, (int)sizeof(char_u *), 1);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010086
10087 /*
10088 * We need to prepend a '*' at the beginning of file_pattern so that the
10089 * regex matches anywhere in the path. FIXME: is this valid for all
Bram Moolenaarb31e4382010-07-24 16:01:56 +020010090 * possible patterns?
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010091 */
Bram Moolenaar624c7aa2010-07-16 20:38:52 +020010092 len = (int)STRLEN(pattern);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010093 file_pattern = alloc(len + 2);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010094 if (file_pattern == NULL)
10095 return;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010096 file_pattern[0] = '*';
Bram Moolenaar162bd912010-07-28 22:29:10 +020010097 file_pattern[1] = NUL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010098 STRCAT(file_pattern, pattern);
10099 pat = file_pat_to_reg_pat(file_pattern, NULL, NULL, TRUE);
10100 vim_free(file_pattern);
Bram Moolenaarb31e4382010-07-24 16:01:56 +020010101 if (pat == NULL)
10102 return;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010103
Bram Moolenaarb31e4382010-07-24 16:01:56 +020010104 regmatch.rm_ic = TRUE; /* always ignore case */
10105 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
10106 vim_free(pat);
10107 if (regmatch.regprog == NULL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010108 return;
10109
Bram Moolenaar162bd912010-07-28 22:29:10 +020010110 if ((curdir = alloc((int)(MAXPATHL))) == NULL)
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010111 goto theend;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010112 mch_dirname(curdir, MAXPATHL);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010113 expand_path_option(curdir, &path_ga);
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010114
10115 in_curdir = (char_u **)alloc_clear(gap->ga_len * sizeof(char_u *));
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010116 if (in_curdir == NULL)
10117 goto theend;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010118
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010119 for (i = 0; i < gap->ga_len && !got_int; i++)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010120 {
Bram Moolenaar162bd912010-07-28 22:29:10 +020010121 char_u *path = fnames[i];
10122 int is_in_curdir;
Bram Moolenaar31710262010-08-13 13:36:15 +020010123 char_u *dir_end = gettail_dir(path);
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010124 char_u *pathsep_p;
10125 char_u *path_cutoff;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010126
Bram Moolenaar624c7aa2010-07-16 20:38:52 +020010127 len = (int)STRLEN(path);
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010128 is_in_curdir = fnamencmp(curdir, path, dir_end - path) == 0
Bram Moolenaar162bd912010-07-28 22:29:10 +020010129 && curdir[dir_end - path] == NUL;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010130 if (is_in_curdir)
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010131 in_curdir[i] = vim_strsave(path);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010132
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010133 /* Shorten the filename while maintaining its uniqueness */
10134 path_cutoff = get_path_cutoff(path, &path_ga);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010135
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010136 /* we start at the end of the path */
10137 pathsep_p = path + len - 1;
10138
10139 while (find_previous_pathsep(path, &pathsep_p))
10140 if (vim_regexec(&regmatch, pathsep_p + 1, (colnr_T)0)
10141 && is_unique(pathsep_p + 1, gap, i)
10142 && path_cutoff != NULL && pathsep_p + 1 >= path_cutoff)
10143 {
10144 sort_again = TRUE;
10145 mch_memmove(path, pathsep_p + 1, STRLEN(pathsep_p));
10146 break;
10147 }
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010148
10149 if (mch_isFullName(path))
10150 {
10151 /*
10152 * Last resort: shorten relative to curdir if possible.
10153 * 'possible' means:
10154 * 1. It is under the current directory.
10155 * 2. The result is actually shorter than the original.
10156 *
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010157 * Before curdir After
10158 * /foo/bar/file.txt /foo/bar ./file.txt
10159 * c:\foo\bar\file.txt c:\foo\bar .\file.txt
10160 * /file.txt / /file.txt
10161 * c:\file.txt c:\ .\file.txt
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010162 */
10163 short_name = shorten_fname(path, curdir);
Bram Moolenaar31710262010-08-13 13:36:15 +020010164 if (short_name != NULL && short_name > path + 1
10165#if defined(MSWIN) || defined(MSDOS)
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010166 /* On windows,
Bram Moolenaar31710262010-08-13 13:36:15 +020010167 * shorten_fname("c:\a\a.txt", "c:\a\b")
Bram Moolenaar31710262010-08-13 13:36:15 +020010168 * returns "\a\a.txt", which is not really the short
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010169 * name, hence: */
Bram Moolenaar31710262010-08-13 13:36:15 +020010170 && !vim_ispathsep(*short_name)
10171#endif
10172 )
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010173 {
10174 STRCPY(path, ".");
10175 add_pathsep(path);
Bram Moolenaarcda000e2010-08-14 13:34:39 +020010176 STRMOVE(path + STRLEN(path), short_name);
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010177 }
10178 }
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010179 ui_breakcheck();
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010180 }
10181
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010182 /* Shorten filenames in /in/current/directory/{filename} */
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010183 for (i = 0; i < gap->ga_len && !got_int; i++)
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010184 {
10185 char_u *rel_path;
10186 char_u *path = in_curdir[i];
10187
10188 if (path == NULL)
10189 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010190
10191 /* If the {filename} is not unique, change it to ./{filename}.
10192 * Else reduce it to {filename} */
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010193 short_name = shorten_fname(path, curdir);
10194 if (short_name == NULL)
10195 short_name = path;
10196 if (is_unique(short_name, gap, i))
10197 {
10198 STRCPY(fnames[i], short_name);
10199 continue;
10200 }
10201
10202 rel_path = alloc((int)(STRLEN(short_name) + STRLEN(PATHSEPSTR) + 2));
10203 if (rel_path == NULL)
10204 goto theend;
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010205 STRCPY(rel_path, ".");
10206 add_pathsep(rel_path);
10207 STRCAT(rel_path, short_name);
10208
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010209 vim_free(fnames[i]);
10210 fnames[i] = rel_path;
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010211 sort_again = TRUE;
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010212 ui_breakcheck();
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010213 }
10214
Bram Moolenaar162bd912010-07-28 22:29:10 +020010215theend:
10216 vim_free(curdir);
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010217 if (in_curdir != NULL)
10218 {
10219 for (i = 0; i < gap->ga_len; i++)
10220 vim_free(in_curdir[i]);
10221 vim_free(in_curdir);
10222 }
Bram Moolenaar162bd912010-07-28 22:29:10 +020010223 ga_clear_strings(&path_ga);
Bram Moolenaarb31e4382010-07-24 16:01:56 +020010224 vim_free(regmatch.regprog);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010225
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010226 if (sort_again)
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +020010227 remove_duplicates(gap);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010228}
10229
10230/*
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010231 * Calls globpath() with 'path' values for the given pattern and stores the
10232 * result in "gap".
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010233 * Returns the total number of matches.
10234 */
10235 static int
10236expand_in_path(gap, pattern, flags)
10237 garray_T *gap;
10238 char_u *pattern;
10239 int flags; /* EW_* flags */
10240{
Bram Moolenaar162bd912010-07-28 22:29:10 +020010241 char_u *curdir;
10242 garray_T path_ga;
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010243 char_u *files = NULL;
10244 char_u *s; /* start */
10245 char_u *e; /* end */
10246 char_u *paths = NULL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010247
Bram Moolenaar7f0f6212010-08-03 22:21:00 +020010248 if ((curdir = alloc((unsigned)MAXPATHL)) == NULL)
Bram Moolenaar162bd912010-07-28 22:29:10 +020010249 return 0;
10250 mch_dirname(curdir, MAXPATHL);
10251
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010252 ga_init2(&path_ga, (int)sizeof(char_u *), 1);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010253 expand_path_option(curdir, &path_ga);
10254 vim_free(curdir);
Bram Moolenaar006d2b02010-08-04 12:39:44 +020010255 if (path_ga.ga_len == 0)
10256 return 0;
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010257
10258 paths = ga_concat_strings(&path_ga);
10259 ga_clear_strings(&path_ga);
10260 if (paths == NULL)
Bram Moolenaar7f0f6212010-08-03 22:21:00 +020010261 return 0;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010262
Bram Moolenaar94950a92010-12-02 16:01:29 +010010263 files = globpath(paths, pattern, (flags & EW_ICASE) ? WILD_ICASE : 0);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010264 vim_free(paths);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010265 if (files == NULL)
10266 return 0;
10267
10268 /* Copy each path in files into gap */
10269 s = e = files;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010270 while (*s != NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010271 {
Bram Moolenaar162bd912010-07-28 22:29:10 +020010272 while (*e != '\n' && *e != NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010273 e++;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010274 if (*e == NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010275 {
10276 addfile(gap, s, flags);
10277 break;
10278 }
10279 else
10280 {
10281 /* *e is '\n' */
Bram Moolenaar162bd912010-07-28 22:29:10 +020010282 *e = NUL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010283 addfile(gap, s, flags);
10284 e++;
10285 s = e;
10286 }
10287 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010288 vim_free(files);
10289
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010290 return gap->ga_len;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010291}
10292#endif
10293
Bram Moolenaar1587a1e2010-07-29 20:59:59 +020010294#if defined(FEAT_SEARCHPATH) || defined(FEAT_CMDL_COMPL) || defined(PROTO)
10295/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010296 * Sort "gap" and remove duplicate entries. "gap" is expected to contain a
10297 * list of file names in allocated memory.
Bram Moolenaar1587a1e2010-07-29 20:59:59 +020010298 */
10299 void
10300remove_duplicates(gap)
10301 garray_T *gap;
10302{
10303 int i;
10304 int j;
10305 char_u **fnames = (char_u **)gap->ga_data;
10306
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010307 sort_strings(fnames, gap->ga_len);
Bram Moolenaar1587a1e2010-07-29 20:59:59 +020010308 for (i = gap->ga_len - 1; i > 0; --i)
10309 if (fnamecmp(fnames[i - 1], fnames[i]) == 0)
10310 {
10311 vim_free(fnames[i]);
10312 for (j = i + 1; j < gap->ga_len; ++j)
10313 fnames[j - 1] = fnames[j];
10314 --gap->ga_len;
10315 }
10316}
10317#endif
10318
Bram Moolenaar071d4272004-06-13 20:20:40 +000010319/*
10320 * Generic wildcard expansion code.
10321 *
10322 * Characters in "pat" that should not be expanded must be preceded with a
10323 * backslash. E.g., "/path\ with\ spaces/my\*star*"
10324 *
10325 * Return FAIL when no single file was found. In this case "num_file" is not
10326 * set, and "file" may contain an error message.
10327 * Return OK when some files found. "num_file" is set to the number of
10328 * matches, "file" to the array of matches. Call FreeWild() later.
10329 */
10330 int
10331gen_expand_wildcards(num_pat, pat, num_file, file, flags)
10332 int num_pat; /* number of input patterns */
10333 char_u **pat; /* array of input patterns */
10334 int *num_file; /* resulting number of files */
10335 char_u ***file; /* array of resulting files */
10336 int flags; /* EW_* flags */
10337{
10338 int i;
10339 garray_T ga;
10340 char_u *p;
10341 static int recursive = FALSE;
10342 int add_pat;
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010343#if defined(FEAT_SEARCHPATH)
10344 int did_expand_in_path = FALSE;
10345#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000010346
10347 /*
10348 * expand_env() is called to expand things like "~user". If this fails,
10349 * it calls ExpandOne(), which brings us back here. In this case, always
10350 * call the machine specific expansion function, if possible. Otherwise,
10351 * return FAIL.
10352 */
10353 if (recursive)
10354#ifdef SPECIAL_WILDCHAR
10355 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
10356#else
10357 return FAIL;
10358#endif
10359
10360#ifdef SPECIAL_WILDCHAR
10361 /*
10362 * If there are any special wildcard characters which we cannot handle
10363 * here, call machine specific function for all the expansion. This
10364 * avoids starting the shell for each argument separately.
10365 * For `=expr` do use the internal function.
10366 */
10367 for (i = 0; i < num_pat; i++)
10368 {
10369 if (vim_strpbrk(pat[i], (char_u *)SPECIAL_WILDCHAR) != NULL
10370# ifdef VIM_BACKTICK
10371 && !(vim_backtick(pat[i]) && pat[i][1] == '=')
10372# endif
10373 )
10374 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
10375 }
10376#endif
10377
10378 recursive = TRUE;
10379
10380 /*
10381 * The matching file names are stored in a growarray. Init it empty.
10382 */
10383 ga_init2(&ga, (int)sizeof(char_u *), 30);
10384
10385 for (i = 0; i < num_pat; ++i)
10386 {
10387 add_pat = -1;
10388 p = pat[i];
10389
10390#ifdef VIM_BACKTICK
10391 if (vim_backtick(p))
10392 add_pat = expand_backtick(&ga, p, flags);
10393 else
10394#endif
10395 {
10396 /*
10397 * First expand environment variables, "~/" and "~user/".
10398 */
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010399 if (vim_strchr(p, '$') != NULL || *p == '~')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010400 {
Bram Moolenaar9f0545d2007-09-26 20:36:32 +000010401 p = expand_env_save_opt(p, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010402 if (p == NULL)
10403 p = pat[i];
10404#ifdef UNIX
10405 /*
10406 * On Unix, if expand_env() can't expand an environment
10407 * variable, use the shell to do that. Discard previously
10408 * found file names and start all over again.
10409 */
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010410 else if (vim_strchr(p, '$') != NULL || *p == '~')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010411 {
10412 vim_free(p);
Bram Moolenaar782027e2009-06-24 14:25:49 +000010413 ga_clear_strings(&ga);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010414 i = mch_expand_wildcards(num_pat, pat, num_file, file,
10415 flags);
10416 recursive = FALSE;
10417 return i;
10418 }
10419#endif
10420 }
10421
10422 /*
10423 * If there are wildcards: Expand file names and add each match to
10424 * the list. If there is no match, and EW_NOTFOUND is given, add
10425 * the pattern.
10426 * If there are no wildcards: Add the file name if it exists or
10427 * when EW_NOTFOUND is given.
10428 */
10429 if (mch_has_exp_wildcard(p))
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010430 {
10431#if defined(FEAT_SEARCHPATH)
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010432 if ((flags & EW_PATH)
10433 && !mch_isFullName(p)
10434 && !(p[0] == '.'
10435 && (vim_ispathsep(p[1])
10436 || (p[1] == '.' && vim_ispathsep(p[2]))))
10437 )
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010438 {
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010439 /* :find completion where 'path' is used.
10440 * Recursiveness is OK here. */
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010441 recursive = FALSE;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010442 add_pat = expand_in_path(&ga, p, flags);
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010443 recursive = TRUE;
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010444 did_expand_in_path = TRUE;
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010445 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010446 else
10447#endif
10448 add_pat = mch_expandpath(&ga, p, flags);
10449 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010450 }
10451
10452 if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
10453 {
10454 char_u *t = backslash_halve_save(p);
10455
10456#if defined(MACOS_CLASSIC)
10457 slash_to_colon(t);
10458#endif
10459 /* When EW_NOTFOUND is used, always add files and dirs. Makes
10460 * "vim c:/" work. */
10461 if (flags & EW_NOTFOUND)
10462 addfile(&ga, t, flags | EW_DIR | EW_FILE);
10463 else if (mch_getperm(t) >= 0)
10464 addfile(&ga, t, flags);
10465 vim_free(t);
10466 }
10467
Bram Moolenaarb28ebbc2010-07-14 16:59:57 +020010468#if defined(FEAT_SEARCHPATH)
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010469 if (did_expand_in_path && ga.ga_len > 0 && (flags & EW_PATH))
Bram Moolenaarb28ebbc2010-07-14 16:59:57 +020010470 uniquefy_paths(&ga, p);
10471#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000010472 if (p != pat[i])
10473 vim_free(p);
10474 }
10475
10476 *num_file = ga.ga_len;
10477 *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data : (char_u **)"";
10478
10479 recursive = FALSE;
10480
10481 return (ga.ga_data != NULL) ? OK : FAIL;
10482}
10483
10484# ifdef VIM_BACKTICK
10485
10486/*
10487 * Return TRUE if we can expand this backtick thing here.
10488 */
10489 static int
10490vim_backtick(p)
10491 char_u *p;
10492{
10493 return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
10494}
10495
10496/*
10497 * Expand an item in `backticks` by executing it as a command.
10498 * Currently only works when pat[] starts and ends with a `.
10499 * Returns number of file names found.
10500 */
10501 static int
10502expand_backtick(gap, pat, flags)
10503 garray_T *gap;
10504 char_u *pat;
10505 int flags; /* EW_* flags */
10506{
10507 char_u *p;
10508 char_u *cmd;
10509 char_u *buffer;
10510 int cnt = 0;
10511 int i;
10512
10513 /* Create the command: lop off the backticks. */
10514 cmd = vim_strnsave(pat + 1, (int)STRLEN(pat) - 2);
10515 if (cmd == NULL)
10516 return 0;
10517
10518#ifdef FEAT_EVAL
10519 if (*cmd == '=') /* `={expr}`: Expand expression */
Bram Moolenaar362e1a32006-03-06 23:29:24 +000010520 buffer = eval_to_string(cmd + 1, &p, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010521 else
10522#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010523 buffer = get_cmd_output(cmd, NULL,
10524 (flags & EW_SILENT) ? SHELL_SILENT : 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010525 vim_free(cmd);
10526 if (buffer == NULL)
10527 return 0;
10528
10529 cmd = buffer;
10530 while (*cmd != NUL)
10531 {
10532 cmd = skipwhite(cmd); /* skip over white space */
10533 p = cmd;
10534 while (*p != NUL && *p != '\r' && *p != '\n') /* skip over entry */
10535 ++p;
10536 /* add an entry if it is not empty */
10537 if (p > cmd)
10538 {
10539 i = *p;
10540 *p = NUL;
10541 addfile(gap, cmd, flags);
10542 *p = i;
10543 ++cnt;
10544 }
10545 cmd = p;
10546 while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
10547 ++cmd;
10548 }
10549
10550 vim_free(buffer);
10551 return cnt;
10552}
10553# endif /* VIM_BACKTICK */
10554
10555/*
10556 * Add a file to a file list. Accepted flags:
10557 * EW_DIR add directories
10558 * EW_FILE add files
Bram Moolenaar1f35bf92006-03-07 22:38:47 +000010559 * EW_EXEC add executable files
Bram Moolenaar071d4272004-06-13 20:20:40 +000010560 * EW_NOTFOUND add even when it doesn't exist
10561 * EW_ADDSLASH add slash after directory name
10562 */
10563 void
10564addfile(gap, f, flags)
10565 garray_T *gap;
10566 char_u *f; /* filename */
10567 int flags;
10568{
10569 char_u *p;
10570 int isdir;
10571
10572 /* if the file/dir doesn't exist, may not add it */
10573 if (!(flags & EW_NOTFOUND) && mch_getperm(f) < 0)
10574 return;
10575
10576#ifdef FNAME_ILLEGAL
10577 /* if the file/dir contains illegal characters, don't add it */
10578 if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
10579 return;
10580#endif
10581
10582 isdir = mch_isdir(f);
10583 if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
10584 return;
10585
Bram Moolenaar1f35bf92006-03-07 22:38:47 +000010586 /* If the file isn't executable, may not add it. Do accept directories. */
10587 if (!isdir && (flags & EW_EXEC) && !mch_can_exe(f))
10588 return;
10589
Bram Moolenaar071d4272004-06-13 20:20:40 +000010590 /* Make room for another item in the file list. */
10591 if (ga_grow(gap, 1) == FAIL)
10592 return;
10593
10594 p = alloc((unsigned)(STRLEN(f) + 1 + isdir));
10595 if (p == NULL)
10596 return;
10597
10598 STRCPY(p, f);
10599#ifdef BACKSLASH_IN_FILENAME
10600 slash_adjust(p);
10601#endif
10602 /*
10603 * Append a slash or backslash after directory names if none is present.
10604 */
10605#ifndef DONT_ADD_PATHSEP_TO_DIR
10606 if (isdir && (flags & EW_ADDSLASH))
10607 add_pathsep(p);
10608#endif
10609 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010610}
10611#endif /* !NO_EXPANDPATH */
10612
10613#if defined(VIM_BACKTICK) || defined(FEAT_EVAL) || defined(PROTO)
10614
10615#ifndef SEEK_SET
10616# define SEEK_SET 0
10617#endif
10618#ifndef SEEK_END
10619# define SEEK_END 2
10620#endif
10621
10622/*
10623 * Get the stdout of an external command.
10624 * Returns an allocated string, or NULL for error.
10625 */
10626 char_u *
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010627get_cmd_output(cmd, infile, flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010628 char_u *cmd;
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010629 char_u *infile; /* optional input file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010630 int flags; /* can be SHELL_SILENT */
10631{
10632 char_u *tempname;
10633 char_u *command;
10634 char_u *buffer = NULL;
10635 int len;
10636 int i = 0;
10637 FILE *fd;
10638
10639 if (check_restricted() || check_secure())
10640 return NULL;
10641
10642 /* get a name for the temp file */
10643 if ((tempname = vim_tempname('o')) == NULL)
10644 {
10645 EMSG(_(e_notmp));
10646 return NULL;
10647 }
10648
10649 /* Add the redirection stuff */
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010650 command = make_filter_cmd(cmd, infile, tempname);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010651 if (command == NULL)
10652 goto done;
10653
10654 /*
10655 * Call the shell to execute the command (errors are ignored).
10656 * Don't check timestamps here.
10657 */
10658 ++no_check_timestamps;
10659 call_shell(command, SHELL_DOOUT | SHELL_EXPAND | flags);
10660 --no_check_timestamps;
10661
10662 vim_free(command);
10663
10664 /*
10665 * read the names from the file into memory
10666 */
10667# ifdef VMS
Bram Moolenaar25394022007-05-10 19:06:20 +000010668 /* created temporary file is not always readable as binary */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010669 fd = mch_fopen((char *)tempname, "r");
10670# else
10671 fd = mch_fopen((char *)tempname, READBIN);
10672# endif
10673
10674 if (fd == NULL)
10675 {
10676 EMSG2(_(e_notopen), tempname);
10677 goto done;
10678 }
10679
10680 fseek(fd, 0L, SEEK_END);
10681 len = ftell(fd); /* get size of temp file */
10682 fseek(fd, 0L, SEEK_SET);
10683
10684 buffer = alloc(len + 1);
10685 if (buffer != NULL)
10686 i = (int)fread((char *)buffer, (size_t)1, (size_t)len, fd);
10687 fclose(fd);
10688 mch_remove(tempname);
10689 if (buffer == NULL)
10690 goto done;
10691#ifdef VMS
10692 len = i; /* VMS doesn't give us what we asked for... */
10693#endif
10694 if (i != len)
10695 {
10696 EMSG2(_(e_notread), tempname);
10697 vim_free(buffer);
10698 buffer = NULL;
10699 }
10700 else
Bram Moolenaar162bd912010-07-28 22:29:10 +020010701 buffer[len] = NUL; /* make sure the buffer is terminated */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010702
10703done:
10704 vim_free(tempname);
10705 return buffer;
10706}
10707#endif
10708
10709/*
10710 * Free the list of files returned by expand_wildcards() or other expansion
10711 * functions.
10712 */
10713 void
10714FreeWild(count, files)
10715 int count;
10716 char_u **files;
10717{
Bram Moolenaarfc1421e2006-04-20 22:17:20 +000010718 if (count <= 0 || files == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010719 return;
10720#if defined(__EMX__) && defined(__ALWAYS_HAS_TRAILING_NULL_POINTER) /* XXX */
10721 /*
10722 * Is this still OK for when other functions than expand_wildcards() have
10723 * been used???
10724 */
10725 _fnexplodefree((char **)files);
10726#else
10727 while (count--)
10728 vim_free(files[count]);
10729 vim_free(files);
10730#endif
10731}
10732
10733/*
Bram Moolenaara9dc3752010-07-11 20:46:53 +020010734 * Return TRUE when need to go to Insert mode because of 'insertmode'.
Bram Moolenaar071d4272004-06-13 20:20:40 +000010735 * Don't do this when still processing a command or a mapping.
10736 * Don't do this when inside a ":normal" command.
10737 */
10738 int
10739goto_im()
10740{
10741 return (p_im && stuff_empty() && typebuf_typed());
10742}