blob: 1519e97b3166c121cfa1c28b4794f26414172308 [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
463 * regmatch_T code above, in which case, these two seperate sections
464 * 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 {
1056 /* allocate buffer (may concatenate p_exta later) */
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +02001057 leader = alloc(lead_len + lead_repl_len + extra_space + extra_len
1058 + (second_line_indent > 0 ? second_line_indent : 0));
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 {
3345 /* Need some more space. This migth happen when receiving a long
3346 * 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;
4502 char_u *homedir_env;
4503 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
4528 homedir_env = mch_getenv((char_u *)"SYS$LOGIN");
4529#else
4530 homedir_env = mch_getenv((char_u *)"HOME");
4531#endif
4532
4533 if (homedir_env != NULL && *homedir_env == NUL)
4534 homedir_env = NULL;
4535 if (homedir_env != NULL)
4536 envlen = STRLEN(homedir_env);
4537
4538 if (!one)
4539 src = skipwhite(src);
4540 while (*src && dstlen > 0)
4541 {
4542 /*
4543 * Here we are at the beginning of a file name.
4544 * First, check to see if the beginning of the file name matches
4545 * $HOME or the "real" home directory. Check that there is a '/'
4546 * after the match (so that if e.g. the file is "/home/pieter/bla",
4547 * and the home directory is "/home/piet", the file does not end up
4548 * as "~er/bla" (which would seem to indicate the file "bla" in user
4549 * er's home directory)).
4550 */
4551 p = homedir;
4552 len = dirlen;
4553 for (;;)
4554 {
4555 if ( len
4556 && fnamencmp(src, p, len) == 0
4557 && (vim_ispathsep(src[len])
4558 || (!one && (src[len] == ',' || src[len] == ' '))
4559 || src[len] == NUL))
4560 {
4561 src += len;
4562 if (--dstlen > 0)
4563 *dst++ = '~';
4564
4565 /*
4566 * If it's just the home directory, add "/".
4567 */
4568 if (!vim_ispathsep(src[0]) && --dstlen > 0)
4569 *dst++ = '/';
4570 break;
4571 }
4572 if (p == homedir_env)
4573 break;
4574 p = homedir_env;
4575 len = envlen;
4576 }
4577
4578 /* if (!one) skip to separator: space or comma */
4579 while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
4580 *dst++ = *src++;
4581 /* skip separator */
4582 while ((*src == ' ' || *src == ',') && --dstlen > 0)
4583 *dst++ = *src++;
4584 }
4585 /* if (dstlen == 0) out of space, what to do??? */
4586
4587 *dst = NUL;
4588}
4589
4590/*
4591 * Like home_replace, store the replaced string in allocated memory.
4592 * When something fails, NULL is returned.
4593 */
4594 char_u *
4595home_replace_save(buf, src)
4596 buf_T *buf; /* when not NULL, check for help files */
4597 char_u *src; /* input file name */
4598{
4599 char_u *dst;
4600 unsigned len;
4601
4602 len = 3; /* space for "~/" and trailing NUL */
4603 if (src != NULL) /* just in case */
4604 len += (unsigned)STRLEN(src);
4605 dst = alloc(len);
4606 if (dst != NULL)
4607 home_replace(buf, src, dst, len, TRUE);
4608 return dst;
4609}
4610
4611/*
4612 * Compare two file names and return:
4613 * FPC_SAME if they both exist and are the same file.
4614 * FPC_SAMEX if they both don't exist and have the same file name.
4615 * FPC_DIFF if they both exist and are different files.
4616 * FPC_NOTX if they both don't exist.
4617 * FPC_DIFFX if one of them doesn't exist.
4618 * For the first name environment variables are expanded
4619 */
4620 int
4621fullpathcmp(s1, s2, checkname)
4622 char_u *s1, *s2;
4623 int checkname; /* when both don't exist, check file names */
4624{
4625#ifdef UNIX
4626 char_u exp1[MAXPATHL];
4627 char_u full1[MAXPATHL];
4628 char_u full2[MAXPATHL];
4629 struct stat st1, st2;
4630 int r1, r2;
4631
4632 expand_env(s1, exp1, MAXPATHL);
4633 r1 = mch_stat((char *)exp1, &st1);
4634 r2 = mch_stat((char *)s2, &st2);
4635 if (r1 != 0 && r2 != 0)
4636 {
4637 /* if mch_stat() doesn't work, may compare the names */
4638 if (checkname)
4639 {
4640 if (fnamecmp(exp1, s2) == 0)
4641 return FPC_SAMEX;
4642 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4643 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4644 if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
4645 return FPC_SAMEX;
4646 }
4647 return FPC_NOTX;
4648 }
4649 if (r1 != 0 || r2 != 0)
4650 return FPC_DIFFX;
4651 if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
4652 return FPC_SAME;
4653 return FPC_DIFF;
4654#else
4655 char_u *exp1; /* expanded s1 */
4656 char_u *full1; /* full path of s1 */
4657 char_u *full2; /* full path of s2 */
4658 int retval = FPC_DIFF;
4659 int r1, r2;
4660
4661 /* allocate one buffer to store three paths (alloc()/free() is slow!) */
4662 if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
4663 {
4664 full1 = exp1 + MAXPATHL;
4665 full2 = full1 + MAXPATHL;
4666
4667 expand_env(s1, exp1, MAXPATHL);
4668 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4669 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4670
4671 /* If vim_FullName() fails, the file probably doesn't exist. */
4672 if (r1 != OK && r2 != OK)
4673 {
4674 if (checkname && fnamecmp(exp1, s2) == 0)
4675 retval = FPC_SAMEX;
4676 else
4677 retval = FPC_NOTX;
4678 }
4679 else if (r1 != OK || r2 != OK)
4680 retval = FPC_DIFFX;
4681 else if (fnamecmp(full1, full2))
4682 retval = FPC_DIFF;
4683 else
4684 retval = FPC_SAME;
4685 vim_free(exp1);
4686 }
4687 return retval;
4688#endif
4689}
4690
4691/*
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004692 * Get the tail of a path: the file name.
Bram Moolenaar31710262010-08-13 13:36:15 +02004693 * When the path ends in a path separator the tail is the NUL after it.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004694 * Fail safe: never returns NULL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004695 */
4696 char_u *
4697gettail(fname)
4698 char_u *fname;
4699{
4700 char_u *p1, *p2;
4701
4702 if (fname == NULL)
4703 return (char_u *)"";
4704 for (p1 = p2 = fname; *p2; ) /* find last part of path */
4705 {
4706 if (vim_ispathsep(*p2))
4707 p1 = p2 + 1;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004708 mb_ptr_adv(p2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004709 }
4710 return p1;
4711}
4712
Bram Moolenaar31710262010-08-13 13:36:15 +02004713#if defined(FEAT_SEARCHPATH)
4714static char_u *gettail_dir __ARGS((char_u *fname));
4715
4716/*
4717 * Return the end of the directory name, on the first path
4718 * separator:
4719 * "/path/file", "/path/dir/", "/path//dir", "/file"
4720 * ^ ^ ^ ^
4721 */
4722 static char_u *
4723gettail_dir(fname)
4724 char_u *fname;
4725{
4726 char_u *dir_end = fname;
4727 char_u *next_dir_end = fname;
4728 int look_for_sep = TRUE;
4729 char_u *p;
4730
4731 for (p = fname; *p != NUL; )
4732 {
4733 if (vim_ispathsep(*p))
4734 {
4735 if (look_for_sep)
4736 {
4737 next_dir_end = p;
4738 look_for_sep = FALSE;
4739 }
4740 }
4741 else
4742 {
4743 if (!look_for_sep)
4744 dir_end = next_dir_end;
4745 look_for_sep = TRUE;
4746 }
4747 mb_ptr_adv(p);
4748 }
4749 return dir_end;
4750}
4751#endif
4752
Bram Moolenaar071d4272004-06-13 20:20:40 +00004753/*
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004754 * Get pointer to tail of "fname", including path separators. Putting a NUL
4755 * here leaves the directory name. Takes care of "c:/" and "//".
4756 * Always returns a valid pointer.
4757 */
4758 char_u *
4759gettail_sep(fname)
4760 char_u *fname;
4761{
4762 char_u *p;
4763 char_u *t;
4764
4765 p = get_past_head(fname); /* don't remove the '/' from "c:/file" */
4766 t = gettail(fname);
4767 while (t > p && after_pathsep(fname, t))
4768 --t;
4769#ifdef VMS
4770 /* path separator is part of the path */
4771 ++t;
4772#endif
4773 return t;
4774}
4775
4776/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004777 * get the next path component (just after the next path separator).
4778 */
4779 char_u *
4780getnextcomp(fname)
4781 char_u *fname;
4782{
4783 while (*fname && !vim_ispathsep(*fname))
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004784 mb_ptr_adv(fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004785 if (*fname)
4786 ++fname;
4787 return fname;
4788}
4789
Bram Moolenaar071d4272004-06-13 20:20:40 +00004790/*
4791 * Get a pointer to one character past the head of a path name.
4792 * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
4793 * If there is no head, path is returned.
4794 */
4795 char_u *
4796get_past_head(path)
4797 char_u *path;
4798{
4799 char_u *retval;
4800
4801#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
4802 /* may skip "c:" */
4803 if (isalpha(path[0]) && path[1] == ':')
4804 retval = path + 2;
4805 else
4806 retval = path;
4807#else
4808# if defined(AMIGA)
4809 /* may skip "label:" */
4810 retval = vim_strchr(path, ':');
4811 if (retval == NULL)
4812 retval = path;
4813# else /* Unix */
4814 retval = path;
4815# endif
4816#endif
4817
4818 while (vim_ispathsep(*retval))
4819 ++retval;
4820
4821 return retval;
4822}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004823
4824/*
4825 * return TRUE if 'c' is a path separator.
4826 */
4827 int
4828vim_ispathsep(c)
4829 int c;
4830{
Bram Moolenaare60acc12011-05-10 16:41:25 +02004831#ifdef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00004832 return (c == '/'); /* UNIX has ':' inside file names */
Bram Moolenaare60acc12011-05-10 16:41:25 +02004833#else
4834# ifdef BACKSLASH_IN_FILENAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00004835 return (c == ':' || c == '/' || c == '\\');
Bram Moolenaare60acc12011-05-10 16:41:25 +02004836# else
4837# ifdef VMS
Bram Moolenaar071d4272004-06-13 20:20:40 +00004838 /* server"user passwd"::device:[full.path.name]fname.extension;version" */
4839 return (c == ':' || c == '[' || c == ']' || c == '/'
4840 || c == '<' || c == '>' || c == '"' );
Bram Moolenaare60acc12011-05-10 16:41:25 +02004841# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004842 return (c == ':' || c == '/');
Bram Moolenaare60acc12011-05-10 16:41:25 +02004843# endif /* VMS */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004844# endif
Bram Moolenaare60acc12011-05-10 16:41:25 +02004845#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004846}
4847
4848#if defined(FEAT_SEARCHPATH) || defined(PROTO)
4849/*
4850 * return TRUE if 'c' is a path list separator.
4851 */
4852 int
4853vim_ispathlistsep(c)
4854 int c;
4855{
4856#ifdef UNIX
4857 return (c == ':');
4858#else
Bram Moolenaar25394022007-05-10 19:06:20 +00004859 return (c == ';'); /* might not be right for every system... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004860#endif
4861}
4862#endif
4863
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004864#if defined(FEAT_GUI_TABLINE) || defined(FEAT_WINDOWS) \
4865 || defined(FEAT_EVAL) || defined(PROTO)
4866/*
4867 * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
4868 * It's done in-place.
4869 */
4870 void
4871shorten_dir(str)
4872 char_u *str;
4873{
4874 char_u *tail, *s, *d;
4875 int skip = FALSE;
4876
4877 tail = gettail(str);
4878 d = str;
4879 for (s = str; ; ++s)
4880 {
4881 if (s >= tail) /* copy the whole tail */
4882 {
4883 *d++ = *s;
4884 if (*s == NUL)
4885 break;
4886 }
4887 else if (vim_ispathsep(*s)) /* copy '/' and next char */
4888 {
4889 *d++ = *s;
4890 skip = FALSE;
4891 }
4892 else if (!skip)
4893 {
4894 *d++ = *s; /* copy next char */
4895 if (*s != '~' && *s != '.') /* and leading "~" and "." */
4896 skip = TRUE;
4897# ifdef FEAT_MBYTE
4898 if (has_mbyte)
4899 {
4900 int l = mb_ptr2len(s);
4901
4902 while (--l > 0)
Bram Moolenaarb6baca52006-08-15 20:24:14 +00004903 *d++ = *++s;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004904 }
4905# endif
4906 }
4907 }
4908}
4909#endif
4910
Bram Moolenaar900b4d72005-12-12 22:05:50 +00004911/*
4912 * Return TRUE if the directory of "fname" exists, FALSE otherwise.
4913 * Also returns TRUE if there is no directory name.
4914 * "fname" must be writable!.
4915 */
4916 int
4917dir_of_file_exists(fname)
4918 char_u *fname;
4919{
4920 char_u *p;
4921 int c;
4922 int retval;
4923
4924 p = gettail_sep(fname);
4925 if (p == fname)
4926 return TRUE;
4927 c = *p;
4928 *p = NUL;
4929 retval = mch_isdir(fname);
4930 *p = c;
4931 return retval;
4932}
4933
Bram Moolenaar071d4272004-06-13 20:20:40 +00004934#if (defined(CASE_INSENSITIVE_FILENAME) && defined(BACKSLASH_IN_FILENAME)) \
4935 || defined(PROTO)
4936/*
4937 * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally.
4938 */
4939 int
4940vim_fnamecmp(x, y)
4941 char_u *x, *y;
4942{
4943 return vim_fnamencmp(x, y, MAXPATHL);
4944}
4945
4946 int
4947vim_fnamencmp(x, y, len)
4948 char_u *x, *y;
4949 size_t len;
4950{
4951 while (len > 0 && *x && *y)
4952 {
4953 if (TOLOWER_LOC(*x) != TOLOWER_LOC(*y)
4954 && !(*x == '/' && *y == '\\')
4955 && !(*x == '\\' && *y == '/'))
4956 break;
4957 ++x;
4958 ++y;
4959 --len;
4960 }
4961 if (len == 0)
4962 return 0;
4963 return (*x - *y);
4964}
4965#endif
4966
4967/*
4968 * Concatenate file names fname1 and fname2 into allocated memory.
Bram Moolenaar25394022007-05-10 19:06:20 +00004969 * Only add a '/' or '\\' when 'sep' is TRUE and it is necessary.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004970 */
4971 char_u *
4972concat_fnames(fname1, fname2, sep)
4973 char_u *fname1;
4974 char_u *fname2;
4975 int sep;
4976{
4977 char_u *dest;
4978
4979 dest = alloc((unsigned)(STRLEN(fname1) + STRLEN(fname2) + 3));
4980 if (dest != NULL)
4981 {
4982 STRCPY(dest, fname1);
4983 if (sep)
4984 add_pathsep(dest);
4985 STRCAT(dest, fname2);
4986 }
4987 return dest;
4988}
4989
Bram Moolenaard6754642005-01-17 22:18:45 +00004990/*
4991 * Concatenate two strings and return the result in allocated memory.
4992 * Returns NULL when out of memory.
4993 */
4994 char_u *
4995concat_str(str1, str2)
4996 char_u *str1;
4997 char_u *str2;
4998{
4999 char_u *dest;
5000 size_t l = STRLEN(str1);
5001
5002 dest = alloc((unsigned)(l + STRLEN(str2) + 1L));
5003 if (dest != NULL)
5004 {
5005 STRCPY(dest, str1);
5006 STRCPY(dest + l, str2);
5007 }
5008 return dest;
5009}
Bram Moolenaard6754642005-01-17 22:18:45 +00005010
Bram Moolenaar071d4272004-06-13 20:20:40 +00005011/*
5012 * Add a path separator to a file name, unless it already ends in a path
5013 * separator.
5014 */
5015 void
5016add_pathsep(p)
5017 char_u *p;
5018{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005019 if (*p != NUL && !after_pathsep(p, p + STRLEN(p)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005020 STRCAT(p, PATHSEPSTR);
5021}
5022
5023/*
5024 * FullName_save - Make an allocated copy of a full file name.
5025 * Returns NULL when out of memory.
5026 */
5027 char_u *
5028FullName_save(fname, force)
5029 char_u *fname;
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +02005030 int force; /* force expansion, even when it already looks
5031 * like a full path name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005032{
5033 char_u *buf;
5034 char_u *new_fname = NULL;
5035
5036 if (fname == NULL)
5037 return NULL;
5038
5039 buf = alloc((unsigned)MAXPATHL);
5040 if (buf != NULL)
5041 {
5042 if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
5043 new_fname = vim_strsave(buf);
5044 else
5045 new_fname = vim_strsave(fname);
5046 vim_free(buf);
5047 }
5048 return new_fname;
5049}
5050
5051#if defined(FEAT_CINDENT) || defined(FEAT_SYN_HL)
5052
5053static char_u *skip_string __ARGS((char_u *p));
5054
5055/*
5056 * Find the start of a comment, not knowing if we are in a comment right now.
5057 * Search starts at w_cursor.lnum and goes backwards.
5058 */
5059 pos_T *
5060find_start_comment(ind_maxcomment) /* XXX */
5061 int ind_maxcomment;
5062{
5063 pos_T *pos;
5064 char_u *line;
5065 char_u *p;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005066 int cur_maxcomment = ind_maxcomment;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005067
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005068 for (;;)
5069 {
5070 pos = findmatchlimit(NULL, '*', FM_BACKWARD, cur_maxcomment);
5071 if (pos == NULL)
5072 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005073
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005074 /*
5075 * Check if the comment start we found is inside a string.
5076 * If it is then restrict the search to below this line and try again.
5077 */
5078 line = ml_get(pos->lnum);
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00005079 for (p = line; *p && (colnr_T)(p - line) < pos->col; ++p)
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005080 p = skip_string(p);
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00005081 if ((colnr_T)(p - line) <= pos->col)
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005082 break;
5083 cur_maxcomment = curwin->w_cursor.lnum - pos->lnum - 1;
5084 if (cur_maxcomment <= 0)
5085 {
5086 pos = NULL;
5087 break;
5088 }
5089 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005090 return pos;
5091}
5092
5093/*
5094 * Skip to the end of a "string" and a 'c' character.
5095 * If there is no string or character, return argument unmodified.
5096 */
5097 static char_u *
5098skip_string(p)
5099 char_u *p;
5100{
5101 int i;
5102
5103 /*
5104 * We loop, because strings may be concatenated: "date""time".
5105 */
5106 for ( ; ; ++p)
5107 {
5108 if (p[0] == '\'') /* 'c' or '\n' or '\000' */
5109 {
5110 if (!p[1]) /* ' at end of line */
5111 break;
5112 i = 2;
5113 if (p[1] == '\\') /* '\n' or '\000' */
5114 {
5115 ++i;
5116 while (vim_isdigit(p[i - 1])) /* '\000' */
5117 ++i;
5118 }
5119 if (p[i] == '\'') /* check for trailing ' */
5120 {
5121 p += i;
5122 continue;
5123 }
5124 }
5125 else if (p[0] == '"') /* start of string */
5126 {
5127 for (++p; p[0]; ++p)
5128 {
5129 if (p[0] == '\\' && p[1] != NUL)
5130 ++p;
5131 else if (p[0] == '"') /* end of string */
5132 break;
5133 }
5134 if (p[0] == '"')
5135 continue;
5136 }
5137 break; /* no string found */
5138 }
5139 if (!*p)
5140 --p; /* backup from NUL */
5141 return p;
5142}
5143#endif /* FEAT_CINDENT || FEAT_SYN_HL */
5144
5145#if defined(FEAT_CINDENT) || defined(PROTO)
5146
5147/*
5148 * Do C or expression indenting on the current line.
5149 */
5150 void
5151do_c_expr_indent()
5152{
5153# ifdef FEAT_EVAL
5154 if (*curbuf->b_p_inde != NUL)
5155 fixthisline(get_expr_indent);
5156 else
5157# endif
5158 fixthisline(get_c_indent);
5159}
5160
5161/*
5162 * Functions for C-indenting.
5163 * Most of this originally comes from Eric Fischer.
5164 */
5165/*
5166 * Below "XXX" means that this function may unlock the current line.
5167 */
5168
5169static char_u *cin_skipcomment __ARGS((char_u *));
5170static int cin_nocode __ARGS((char_u *));
5171static pos_T *find_line_comment __ARGS((void));
5172static int cin_islabel_skip __ARGS((char_u **));
5173static int cin_isdefault __ARGS((char_u *));
5174static char_u *after_label __ARGS((char_u *l));
5175static int get_indent_nolabel __ARGS((linenr_T lnum));
5176static int skip_label __ARGS((linenr_T, char_u **pp, int ind_maxcomment));
5177static int cin_first_id_amount __ARGS((void));
5178static int cin_get_equal_amount __ARGS((linenr_T lnum));
5179static int cin_ispreproc __ARGS((char_u *));
5180static int cin_ispreproc_cont __ARGS((char_u **pp, linenr_T *lnump));
5181static int cin_iscomment __ARGS((char_u *));
5182static int cin_islinecomment __ARGS((char_u *));
5183static int cin_isterminated __ARGS((char_u *, int, int));
5184static int cin_isinit __ARGS((void));
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005185static int cin_isfuncdecl __ARGS((char_u **, linenr_T, linenr_T, int, int));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005186static int cin_isif __ARGS((char_u *));
5187static int cin_iselse __ARGS((char_u *));
5188static int cin_isdo __ARGS((char_u *));
5189static int cin_iswhileofdo __ARGS((char_u *, linenr_T, int));
Bram Moolenaarb345d492012-04-09 20:42:26 +02005190static int cin_is_if_for_while_before_offset __ARGS((char_u *line, int *poffset));
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005191static int cin_iswhileofdo_end __ARGS((int terminated, int ind_maxparen, int ind_maxcomment));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005192static int cin_isbreak __ARGS((char_u *));
Bram Moolenaare7c56862007-08-04 10:14:52 +00005193static int cin_is_cpp_baseclass __ARGS((colnr_T *col));
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005194static int get_baseclass_amount __ARGS((int col, int ind_maxparen, int ind_maxcomment, int ind_cpp_baseclass));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005195static int cin_ends_in __ARGS((char_u *, char_u *, char_u *));
5196static int cin_skip2pos __ARGS((pos_T *trypos));
5197static pos_T *find_start_brace __ARGS((int));
5198static pos_T *find_match_paren __ARGS((int, int));
5199static int corr_ind_maxparen __ARGS((int ind_maxparen, pos_T *startpos));
5200static int find_last_paren __ARGS((char_u *l, int start, int end));
5201static int find_match __ARGS((int lookfor, linenr_T ourscope, int ind_maxparen, int ind_maxcomment));
Bram Moolenaared38b0a2011-05-25 15:16:18 +02005202static int cin_is_cpp_namespace __ARGS((char_u *));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005203
Bram Moolenaar39353fd2007-03-27 09:02:11 +00005204static int ind_hash_comment = 0; /* # starts a comment */
5205
Bram Moolenaar071d4272004-06-13 20:20:40 +00005206/*
5207 * Skip over white space and C comments within the line.
Bram Moolenaar39353fd2007-03-27 09:02:11 +00005208 * Also skip over Perl/shell comments if desired.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005209 */
5210 static char_u *
5211cin_skipcomment(s)
5212 char_u *s;
5213{
5214 while (*s)
5215 {
Bram Moolenaar39353fd2007-03-27 09:02:11 +00005216 char_u *prev_s = s;
5217
Bram Moolenaar071d4272004-06-13 20:20:40 +00005218 s = skipwhite(s);
Bram Moolenaar39353fd2007-03-27 09:02:11 +00005219
5220 /* Perl/shell # comment comment continues until eol. Require a space
5221 * before # to avoid recognizing $#array. */
5222 if (ind_hash_comment != 0 && s != prev_s && *s == '#')
5223 {
5224 s += STRLEN(s);
5225 break;
5226 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005227 if (*s != '/')
5228 break;
5229 ++s;
5230 if (*s == '/') /* slash-slash comment continues till eol */
5231 {
5232 s += STRLEN(s);
5233 break;
5234 }
5235 if (*s != '*')
5236 break;
5237 for (++s; *s; ++s) /* skip slash-star comment */
5238 if (s[0] == '*' && s[1] == '/')
5239 {
5240 s += 2;
5241 break;
5242 }
5243 }
5244 return s;
5245}
5246
5247/*
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005248 * Return TRUE if there is no code at *s. White space and comments are
Bram Moolenaar071d4272004-06-13 20:20:40 +00005249 * not considered code.
5250 */
5251 static int
5252cin_nocode(s)
5253 char_u *s;
5254{
5255 return *cin_skipcomment(s) == NUL;
5256}
5257
5258/*
5259 * Check previous lines for a "//" line comment, skipping over blank lines.
5260 */
5261 static pos_T *
5262find_line_comment() /* XXX */
5263{
5264 static pos_T pos;
5265 char_u *line;
5266 char_u *p;
5267
5268 pos = curwin->w_cursor;
5269 while (--pos.lnum > 0)
5270 {
5271 line = ml_get(pos.lnum);
5272 p = skipwhite(line);
5273 if (cin_islinecomment(p))
5274 {
5275 pos.col = (int)(p - line);
5276 return &pos;
5277 }
5278 if (*p != NUL)
5279 break;
5280 }
5281 return NULL;
5282}
5283
5284/*
5285 * Check if string matches "label:"; move to character after ':' if true.
5286 */
5287 static int
5288cin_islabel_skip(s)
5289 char_u **s;
5290{
5291 if (!vim_isIDc(**s)) /* need at least one ID character */
5292 return FALSE;
5293
5294 while (vim_isIDc(**s))
5295 (*s)++;
5296
5297 *s = cin_skipcomment(*s);
5298
5299 /* "::" is not a label, it's C++ */
5300 return (**s == ':' && *++*s != ':');
5301}
5302
5303/*
5304 * Recognize a label: "label:".
5305 * Note: curwin->w_cursor must be where we are looking for the label.
5306 */
5307 int
5308cin_islabel(ind_maxcomment) /* XXX */
5309 int ind_maxcomment;
5310{
5311 char_u *s;
5312
5313 s = cin_skipcomment(ml_get_curline());
5314
5315 /*
5316 * Exclude "default" from labels, since it should be indented
5317 * like a switch label. Same for C++ scope declarations.
5318 */
5319 if (cin_isdefault(s))
5320 return FALSE;
5321 if (cin_isscopedecl(s))
5322 return FALSE;
5323
5324 if (cin_islabel_skip(&s))
5325 {
5326 /*
5327 * Only accept a label if the previous line is terminated or is a case
5328 * label.
5329 */
5330 pos_T cursor_save;
5331 pos_T *trypos;
5332 char_u *line;
5333
5334 cursor_save = curwin->w_cursor;
5335 while (curwin->w_cursor.lnum > 1)
5336 {
5337 --curwin->w_cursor.lnum;
5338
5339 /*
5340 * If we're in a comment now, skip to the start of the comment.
5341 */
5342 curwin->w_cursor.col = 0;
5343 if ((trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
5344 curwin->w_cursor = *trypos;
5345
5346 line = ml_get_curline();
5347 if (cin_ispreproc(line)) /* ignore #defines, #if, etc. */
5348 continue;
5349 if (*(line = cin_skipcomment(line)) == NUL)
5350 continue;
5351
5352 curwin->w_cursor = cursor_save;
5353 if (cin_isterminated(line, TRUE, FALSE)
5354 || cin_isscopedecl(line)
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005355 || cin_iscase(line, TRUE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005356 || (cin_islabel_skip(&line) && cin_nocode(line)))
5357 return TRUE;
5358 return FALSE;
5359 }
5360 curwin->w_cursor = cursor_save;
5361 return TRUE; /* label at start of file??? */
5362 }
5363 return FALSE;
5364}
5365
5366/*
5367 * Recognize structure initialization and enumerations.
5368 * Q&D-Implementation:
5369 * check for "=" at end or "[typedef] enum" at beginning of line.
5370 */
5371 static int
5372cin_isinit(void)
5373{
5374 char_u *s;
5375
5376 s = cin_skipcomment(ml_get_curline());
5377
5378 if (STRNCMP(s, "typedef", 7) == 0 && !vim_isIDc(s[7]))
5379 s = cin_skipcomment(s + 7);
5380
Bram Moolenaara5285652011-12-14 20:05:21 +01005381 if (STRNCMP(s, "static", 6) == 0 && !vim_isIDc(s[6]))
5382 s = cin_skipcomment(s + 6);
5383
Bram Moolenaar071d4272004-06-13 20:20:40 +00005384 if (STRNCMP(s, "enum", 4) == 0 && !vim_isIDc(s[4]))
5385 return TRUE;
5386
5387 if (cin_ends_in(s, (char_u *)"=", (char_u *)"{"))
5388 return TRUE;
5389
5390 return FALSE;
5391}
5392
5393/*
5394 * Recognize a switch label: "case .*:" or "default:".
5395 */
5396 int
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005397cin_iscase(s, strict)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005398 char_u *s;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005399 int strict; /* Allow relaxed check of case statement for JS */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005400{
5401 s = cin_skipcomment(s);
5402 if (STRNCMP(s, "case", 4) == 0 && !vim_isIDc(s[4]))
5403 {
5404 for (s += 4; *s; ++s)
5405 {
5406 s = cin_skipcomment(s);
5407 if (*s == ':')
5408 {
5409 if (s[1] == ':') /* skip over "::" for C++ */
5410 ++s;
5411 else
5412 return TRUE;
5413 }
5414 if (*s == '\'' && s[1] && s[2] == '\'')
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005415 s += 2; /* skip over ':' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005416 else if (*s == '/' && (s[1] == '*' || s[1] == '/'))
5417 return FALSE; /* stop at comment */
5418 else if (*s == '"')
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005419 {
5420 /* JS etc. */
5421 if (strict)
5422 return FALSE; /* stop at string */
5423 else
5424 return TRUE;
5425 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005426 }
5427 return FALSE;
5428 }
5429
5430 if (cin_isdefault(s))
5431 return TRUE;
5432 return FALSE;
5433}
5434
5435/*
5436 * Recognize a "default" switch label.
5437 */
5438 static int
5439cin_isdefault(s)
5440 char_u *s;
5441{
5442 return (STRNCMP(s, "default", 7) == 0
5443 && *(s = cin_skipcomment(s + 7)) == ':'
5444 && s[1] != ':');
5445}
5446
5447/*
Bram Moolenaar1a509df2010-08-01 17:59:57 +02005448 * Recognize a "public/private/protected" scope declaration label.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005449 */
5450 int
5451cin_isscopedecl(s)
5452 char_u *s;
5453{
5454 int i;
5455
5456 s = cin_skipcomment(s);
5457 if (STRNCMP(s, "public", 6) == 0)
5458 i = 6;
5459 else if (STRNCMP(s, "protected", 9) == 0)
5460 i = 9;
5461 else if (STRNCMP(s, "private", 7) == 0)
5462 i = 7;
5463 else
5464 return FALSE;
5465 return (*(s = cin_skipcomment(s + i)) == ':' && s[1] != ':');
5466}
5467
Bram Moolenaared38b0a2011-05-25 15:16:18 +02005468/* Maximum number of lines to search back for a "namespace" line. */
5469#define FIND_NAMESPACE_LIM 20
5470
5471/*
5472 * Recognize a "namespace" scope declaration.
5473 */
5474 static int
5475cin_is_cpp_namespace(s)
5476 char_u *s;
5477{
5478 char_u *p;
5479 int has_name = FALSE;
5480
5481 s = cin_skipcomment(s);
5482 if (STRNCMP(s, "namespace", 9) == 0 && (s[9] == NUL || !vim_iswordc(s[9])))
5483 {
5484 p = cin_skipcomment(skipwhite(s + 9));
5485 while (*p != NUL)
5486 {
5487 if (vim_iswhite(*p))
5488 {
5489 has_name = TRUE; /* found end of a name */
5490 p = cin_skipcomment(skipwhite(p));
5491 }
5492 else if (*p == '{')
5493 {
5494 break;
5495 }
5496 else if (vim_iswordc(*p))
5497 {
5498 if (has_name)
5499 return FALSE; /* word character after skipping past name */
5500 ++p;
5501 }
5502 else
5503 {
5504 return FALSE;
5505 }
5506 }
5507 return TRUE;
5508 }
5509 return FALSE;
5510}
5511
Bram Moolenaar071d4272004-06-13 20:20:40 +00005512/*
5513 * Return a pointer to the first non-empty non-comment character after a ':'.
5514 * Return NULL if not found.
5515 * case 234: a = b;
5516 * ^
5517 */
5518 static char_u *
5519after_label(l)
5520 char_u *l;
5521{
5522 for ( ; *l; ++l)
5523 {
5524 if (*l == ':')
5525 {
5526 if (l[1] == ':') /* skip over "::" for C++ */
5527 ++l;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005528 else if (!cin_iscase(l + 1, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005529 break;
5530 }
5531 else if (*l == '\'' && l[1] && l[2] == '\'')
5532 l += 2; /* skip over 'x' */
5533 }
5534 if (*l == NUL)
5535 return NULL;
5536 l = cin_skipcomment(l + 1);
5537 if (*l == NUL)
5538 return NULL;
5539 return l;
5540}
5541
5542/*
5543 * Get indent of line "lnum", skipping a label.
5544 * Return 0 if there is nothing after the label.
5545 */
5546 static int
5547get_indent_nolabel(lnum) /* XXX */
5548 linenr_T lnum;
5549{
5550 char_u *l;
5551 pos_T fp;
5552 colnr_T col;
5553 char_u *p;
5554
5555 l = ml_get(lnum);
5556 p = after_label(l);
5557 if (p == NULL)
5558 return 0;
5559
5560 fp.col = (colnr_T)(p - l);
5561 fp.lnum = lnum;
5562 getvcol(curwin, &fp, &col, NULL, NULL);
5563 return (int)col;
5564}
5565
5566/*
5567 * Find indent for line "lnum", ignoring any case or jump label.
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005568 * Also return a pointer to the text (after the label) in "pp".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005569 * label: if (asdf && asdfasdf)
5570 * ^
5571 */
5572 static int
5573skip_label(lnum, pp, ind_maxcomment)
5574 linenr_T lnum;
5575 char_u **pp;
5576 int ind_maxcomment;
5577{
5578 char_u *l;
5579 int amount;
5580 pos_T cursor_save;
5581
5582 cursor_save = curwin->w_cursor;
5583 curwin->w_cursor.lnum = lnum;
5584 l = ml_get_curline();
5585 /* XXX */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005586 if (cin_iscase(l, FALSE) || cin_isscopedecl(l)
5587 || cin_islabel(ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005588 {
5589 amount = get_indent_nolabel(lnum);
5590 l = after_label(ml_get_curline());
5591 if (l == NULL) /* just in case */
5592 l = ml_get_curline();
5593 }
5594 else
5595 {
5596 amount = get_indent();
5597 l = ml_get_curline();
5598 }
5599 *pp = l;
5600
5601 curwin->w_cursor = cursor_save;
5602 return amount;
5603}
5604
5605/*
5606 * Return the indent of the first variable name after a type in a declaration.
5607 * int a, indent of "a"
5608 * static struct foo b, indent of "b"
5609 * enum bla c, indent of "c"
5610 * Returns zero when it doesn't look like a declaration.
5611 */
5612 static int
5613cin_first_id_amount()
5614{
5615 char_u *line, *p, *s;
5616 int len;
5617 pos_T fp;
5618 colnr_T col;
5619
5620 line = ml_get_curline();
5621 p = skipwhite(line);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005622 len = (int)(skiptowhite(p) - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005623 if (len == 6 && STRNCMP(p, "static", 6) == 0)
5624 {
5625 p = skipwhite(p + 6);
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00005626 len = (int)(skiptowhite(p) - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005627 }
5628 if (len == 6 && STRNCMP(p, "struct", 6) == 0)
5629 p = skipwhite(p + 6);
5630 else if (len == 4 && STRNCMP(p, "enum", 4) == 0)
5631 p = skipwhite(p + 4);
5632 else if ((len == 8 && STRNCMP(p, "unsigned", 8) == 0)
5633 || (len == 6 && STRNCMP(p, "signed", 6) == 0))
5634 {
5635 s = skipwhite(p + len);
5636 if ((STRNCMP(s, "int", 3) == 0 && vim_iswhite(s[3]))
5637 || (STRNCMP(s, "long", 4) == 0 && vim_iswhite(s[4]))
5638 || (STRNCMP(s, "short", 5) == 0 && vim_iswhite(s[5]))
5639 || (STRNCMP(s, "char", 4) == 0 && vim_iswhite(s[4])))
5640 p = s;
5641 }
5642 for (len = 0; vim_isIDc(p[len]); ++len)
5643 ;
5644 if (len == 0 || !vim_iswhite(p[len]) || cin_nocode(p))
5645 return 0;
5646
5647 p = skipwhite(p + len);
5648 fp.lnum = curwin->w_cursor.lnum;
5649 fp.col = (colnr_T)(p - line);
5650 getvcol(curwin, &fp, &col, NULL, NULL);
5651 return (int)col;
5652}
5653
5654/*
5655 * Return the indent of the first non-blank after an equal sign.
5656 * char *foo = "here";
5657 * Return zero if no (useful) equal sign found.
5658 * Return -1 if the line above "lnum" ends in a backslash.
5659 * foo = "asdf\
5660 * asdf\
5661 * here";
5662 */
5663 static int
5664cin_get_equal_amount(lnum)
5665 linenr_T lnum;
5666{
5667 char_u *line;
5668 char_u *s;
5669 colnr_T col;
5670 pos_T fp;
5671
5672 if (lnum > 1)
5673 {
5674 line = ml_get(lnum - 1);
5675 if (*line != NUL && line[STRLEN(line) - 1] == '\\')
5676 return -1;
5677 }
5678
5679 line = s = ml_get(lnum);
5680 while (*s != NUL && vim_strchr((char_u *)"=;{}\"'", *s) == NULL)
5681 {
5682 if (cin_iscomment(s)) /* ignore comments */
5683 s = cin_skipcomment(s);
5684 else
5685 ++s;
5686 }
5687 if (*s != '=')
5688 return 0;
5689
5690 s = skipwhite(s + 1);
5691 if (cin_nocode(s))
5692 return 0;
5693
5694 if (*s == '"') /* nice alignment for continued strings */
5695 ++s;
5696
5697 fp.lnum = lnum;
5698 fp.col = (colnr_T)(s - line);
5699 getvcol(curwin, &fp, &col, NULL, NULL);
5700 return (int)col;
5701}
5702
5703/*
5704 * Recognize a preprocessor statement: Any line that starts with '#'.
5705 */
5706 static int
5707cin_ispreproc(s)
5708 char_u *s;
5709{
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005710 if (*skipwhite(s) == '#')
Bram Moolenaar071d4272004-06-13 20:20:40 +00005711 return TRUE;
5712 return FALSE;
5713}
5714
5715/*
5716 * Return TRUE if line "*pp" at "*lnump" is a preprocessor statement or a
5717 * continuation line of a preprocessor statement. Decrease "*lnump" to the
5718 * start and return the line in "*pp".
5719 */
5720 static int
5721cin_ispreproc_cont(pp, lnump)
5722 char_u **pp;
5723 linenr_T *lnump;
5724{
5725 char_u *line = *pp;
5726 linenr_T lnum = *lnump;
5727 int retval = FALSE;
5728
Bram Moolenaard8e9bb22005-07-09 21:14:46 +00005729 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005730 {
5731 if (cin_ispreproc(line))
5732 {
5733 retval = TRUE;
5734 *lnump = lnum;
5735 break;
5736 }
5737 if (lnum == 1)
5738 break;
5739 line = ml_get(--lnum);
5740 if (*line == NUL || line[STRLEN(line) - 1] != '\\')
5741 break;
5742 }
5743
5744 if (lnum != *lnump)
5745 *pp = ml_get(*lnump);
5746 return retval;
5747}
5748
5749/*
5750 * Recognize the start of a C or C++ comment.
5751 */
5752 static int
5753cin_iscomment(p)
5754 char_u *p;
5755{
5756 return (p[0] == '/' && (p[1] == '*' || p[1] == '/'));
5757}
5758
5759/*
5760 * Recognize the start of a "//" comment.
5761 */
5762 static int
5763cin_islinecomment(p)
5764 char_u *p;
5765{
5766 return (p[0] == '/' && p[1] == '/');
5767}
5768
5769/*
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005770 * Recognize a line that starts with '{' or '}', or ends with ';', ',', '{' or
5771 * '}'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005772 * Don't consider "} else" a terminated line.
Bram Moolenaar496f9512011-05-19 16:35:09 +02005773 * If a line begins with an "else", only consider it terminated if no unmatched
5774 * opening braces follow (handle "else { foo();" correctly).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005775 * Return the character terminating the line (ending char's have precedence if
5776 * both apply in order to determine initializations).
5777 */
5778 static int
5779cin_isterminated(s, incl_open, incl_comma)
5780 char_u *s;
5781 int incl_open; /* include '{' at the end as terminator */
5782 int incl_comma; /* recognize a trailing comma */
5783{
Bram Moolenaar496f9512011-05-19 16:35:09 +02005784 char_u found_start = 0;
5785 unsigned n_open = 0;
5786 int is_else = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005787
5788 s = cin_skipcomment(s);
5789
5790 if (*s == '{' || (*s == '}' && !cin_iselse(s)))
5791 found_start = *s;
5792
Bram Moolenaar496f9512011-05-19 16:35:09 +02005793 if (!found_start)
5794 is_else = cin_iselse(s);
5795
Bram Moolenaar071d4272004-06-13 20:20:40 +00005796 while (*s)
5797 {
5798 /* skip over comments, "" strings and 'c'haracters */
5799 s = skip_string(cin_skipcomment(s));
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005800 if (*s == '}' && n_open > 0)
5801 --n_open;
Bram Moolenaar496f9512011-05-19 16:35:09 +02005802 if ((!is_else || n_open == 0)
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005803 && (*s == ';' || *s == '}' || (incl_comma && *s == ','))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005804 && cin_nocode(s + 1))
5805 return *s;
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005806 else if (*s == '{')
5807 {
5808 if (incl_open && cin_nocode(s + 1))
5809 return *s;
5810 else
5811 ++n_open;
5812 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005813
5814 if (*s)
5815 s++;
5816 }
5817 return found_start;
5818}
5819
5820/*
5821 * Recognize the basic picture of a function declaration -- it needs to
5822 * have an open paren somewhere and a close paren at the end of the line and
5823 * no semicolons anywhere.
5824 * When a line ends in a comma we continue looking in the next line.
5825 * "sp" points to a string with the line. When looking at other lines it must
5826 * be restored to the line. When it's NULL fetch lines here.
5827 * "lnum" is where we start looking.
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005828 * "min_lnum" is the line before which we will not be looking.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005829 */
5830 static int
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005831cin_isfuncdecl(sp, first_lnum, min_lnum, ind_maxparen, ind_maxcomment)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005832 char_u **sp;
5833 linenr_T first_lnum;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005834 linenr_T min_lnum;
5835 int ind_maxparen;
5836 int ind_maxcomment;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005837{
5838 char_u *s;
5839 linenr_T lnum = first_lnum;
5840 int retval = FALSE;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005841 pos_T *trypos;
5842 int just_started = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005843
5844 if (sp == NULL)
5845 s = ml_get(lnum);
5846 else
5847 s = *sp;
5848
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005849 if (find_last_paren(s, '(', ')')
5850 && (trypos = find_match_paren(ind_maxparen, ind_maxcomment)) != NULL)
5851 {
5852 lnum = trypos->lnum;
5853 if (lnum < min_lnum)
5854 return FALSE;
5855
5856 s = ml_get(lnum);
5857 }
5858
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005859 /* Ignore line starting with #. */
5860 if (cin_ispreproc(s))
5861 return FALSE;
5862
Bram Moolenaar071d4272004-06-13 20:20:40 +00005863 while (*s && *s != '(' && *s != ';' && *s != '\'' && *s != '"')
5864 {
5865 if (cin_iscomment(s)) /* ignore comments */
5866 s = cin_skipcomment(s);
5867 else
5868 ++s;
5869 }
5870 if (*s != '(')
5871 return FALSE; /* ';', ' or " before any () or no '(' */
5872
5873 while (*s && *s != ';' && *s != '\'' && *s != '"')
5874 {
5875 if (*s == ')' && cin_nocode(s + 1))
5876 {
5877 /* ')' at the end: may have found a match
5878 * Check for he previous line not to end in a backslash:
5879 * #if defined(x) && \
5880 * defined(y)
5881 */
5882 lnum = first_lnum - 1;
5883 s = ml_get(lnum);
5884 if (*s == NUL || s[STRLEN(s) - 1] != '\\')
5885 retval = TRUE;
5886 goto done;
5887 }
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005888 if ((*s == ',' && cin_nocode(s + 1)) || s[1] == NUL || cin_nocode(s))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005889 {
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005890 int comma = (*s == ',');
5891
5892 /* ',' at the end: continue looking in the next line.
5893 * At the end: check for ',' in the next line, for this style:
5894 * func(arg1
5895 * , arg2) */
5896 for (;;)
5897 {
5898 if (lnum >= curbuf->b_ml.ml_line_count)
5899 break;
5900 s = ml_get(++lnum);
5901 if (!cin_ispreproc(s))
5902 break;
5903 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005904 if (lnum >= curbuf->b_ml.ml_line_count)
5905 break;
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005906 /* Require a comma at end of the line or a comma or ')' at the
5907 * start of next line. */
5908 s = skipwhite(s);
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005909 if (!just_started && (!comma && *s != ',' && *s != ')'))
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005910 break;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005911 just_started = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005912 }
5913 else if (cin_iscomment(s)) /* ignore comments */
5914 s = cin_skipcomment(s);
5915 else
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005916 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005917 ++s;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005918 just_started = FALSE;
5919 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005920 }
5921
5922done:
5923 if (lnum != first_lnum && sp != NULL)
5924 *sp = ml_get(first_lnum);
5925
5926 return retval;
5927}
5928
5929 static int
5930cin_isif(p)
5931 char_u *p;
5932{
5933 return (STRNCMP(p, "if", 2) == 0 && !vim_isIDc(p[2]));
5934}
5935
5936 static int
5937cin_iselse(p)
5938 char_u *p;
5939{
5940 if (*p == '}') /* accept "} else" */
5941 p = cin_skipcomment(p + 1);
5942 return (STRNCMP(p, "else", 4) == 0 && !vim_isIDc(p[4]));
5943}
5944
5945 static int
5946cin_isdo(p)
5947 char_u *p;
5948{
5949 return (STRNCMP(p, "do", 2) == 0 && !vim_isIDc(p[2]));
5950}
5951
5952/*
5953 * Check if this is a "while" that should have a matching "do".
5954 * We only accept a "while (condition) ;", with only white space between the
5955 * ')' and ';'. The condition may be spread over several lines.
5956 */
5957 static int
5958cin_iswhileofdo(p, lnum, ind_maxparen) /* XXX */
5959 char_u *p;
5960 linenr_T lnum;
5961 int ind_maxparen;
5962{
5963 pos_T cursor_save;
5964 pos_T *trypos;
5965 int retval = FALSE;
5966
5967 p = cin_skipcomment(p);
5968 if (*p == '}') /* accept "} while (cond);" */
5969 p = cin_skipcomment(p + 1);
5970 if (STRNCMP(p, "while", 5) == 0 && !vim_isIDc(p[5]))
5971 {
5972 cursor_save = curwin->w_cursor;
5973 curwin->w_cursor.lnum = lnum;
5974 curwin->w_cursor.col = 0;
5975 p = ml_get_curline();
5976 while (*p && *p != 'w') /* skip any '}', until the 'w' of the "while" */
5977 {
5978 ++p;
5979 ++curwin->w_cursor.col;
5980 }
5981 if ((trypos = findmatchlimit(NULL, 0, 0, ind_maxparen)) != NULL
5982 && *cin_skipcomment(ml_get_pos(trypos) + 1) == ';')
5983 retval = TRUE;
5984 curwin->w_cursor = cursor_save;
5985 }
5986 return retval;
5987}
5988
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005989/*
Bram Moolenaarb345d492012-04-09 20:42:26 +02005990 * Check whether in "p" there is an "if", "for" or "while" before "*poffset".
Bram Moolenaar3675fa02012-04-05 17:17:42 +02005991 * Return 0 if there is none.
5992 * Otherwise return !0 and update "*poffset" to point to the place where the
5993 * string was found.
5994 */
5995 static int
Bram Moolenaarb345d492012-04-09 20:42:26 +02005996cin_is_if_for_while_before_offset(line, poffset)
Bram Moolenaar3675fa02012-04-05 17:17:42 +02005997 char_u *line;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02005998 int *poffset;
5999{
Bram Moolenaarb345d492012-04-09 20:42:26 +02006000 int offset = *poffset;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006001
6002 if (offset-- < 2)
6003 return 0;
6004 while (offset > 2 && vim_iswhite(line[offset]))
6005 --offset;
6006
6007 offset -= 1;
6008 if (!STRNCMP(line + offset, "if", 2))
6009 goto probablyFound;
6010
6011 if (offset >= 1)
6012 {
6013 offset -= 1;
6014 if (!STRNCMP(line + offset, "for", 3))
6015 goto probablyFound;
6016
6017 if (offset >= 2)
6018 {
6019 offset -= 2;
6020 if (!STRNCMP(line + offset, "while", 5))
6021 goto probablyFound;
6022 }
6023 }
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006024 return 0;
Bram Moolenaarb345d492012-04-09 20:42:26 +02006025
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006026probablyFound:
6027 if (!offset || !vim_isIDc(line[offset - 1]))
6028 {
6029 *poffset = offset;
6030 return 1;
6031 }
6032 return 0;
6033}
6034
6035/*
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006036 * Return TRUE if we are at the end of a do-while.
6037 * do
6038 * nothing;
6039 * while (foo
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00006040 * && bar); <-- here
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006041 * Adjust the cursor to the line with "while".
6042 */
6043 static int
6044cin_iswhileofdo_end(terminated, ind_maxparen, ind_maxcomment)
6045 int terminated;
6046 int ind_maxparen;
6047 int ind_maxcomment;
6048{
6049 char_u *line;
6050 char_u *p;
6051 char_u *s;
6052 pos_T *trypos;
6053 int i;
6054
6055 if (terminated != ';') /* there must be a ';' at the end */
6056 return FALSE;
6057
6058 p = line = ml_get_curline();
6059 while (*p != NUL)
6060 {
6061 p = cin_skipcomment(p);
6062 if (*p == ')')
6063 {
6064 s = skipwhite(p + 1);
6065 if (*s == ';' && cin_nocode(s + 1))
6066 {
6067 /* Found ");" at end of the line, now check there is "while"
6068 * before the matching '('. XXX */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006069 i = (int)(p - line);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006070 curwin->w_cursor.col = i;
6071 trypos = find_match_paren(ind_maxparen, ind_maxcomment);
6072 if (trypos != NULL)
6073 {
6074 s = cin_skipcomment(ml_get(trypos->lnum));
6075 if (*s == '}') /* accept "} while (cond);" */
6076 s = cin_skipcomment(s + 1);
6077 if (STRNCMP(s, "while", 5) == 0 && !vim_isIDc(s[5]))
6078 {
6079 curwin->w_cursor.lnum = trypos->lnum;
6080 return TRUE;
6081 }
6082 }
6083
6084 /* Searching may have made "line" invalid, get it again. */
6085 line = ml_get_curline();
6086 p = line + i;
6087 }
6088 }
6089 if (*p != NUL)
6090 ++p;
6091 }
6092 return FALSE;
6093}
6094
Bram Moolenaar071d4272004-06-13 20:20:40 +00006095 static int
6096cin_isbreak(p)
6097 char_u *p;
6098{
6099 return (STRNCMP(p, "break", 5) == 0 && !vim_isIDc(p[5]));
6100}
6101
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006102/*
6103 * Find the position of a C++ base-class declaration or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006104 * constructor-initialization. eg:
6105 *
6106 * class MyClass :
6107 * baseClass <-- here
6108 * class MyClass : public baseClass,
6109 * anotherBaseClass <-- here (should probably lineup ??)
6110 * MyClass::MyClass(...) :
6111 * baseClass(...) <-- here (constructor-initialization)
Bram Moolenaar18144c82006-04-12 21:52:12 +00006112 *
6113 * This is a lot of guessing. Watch out for "cond ? func() : foo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00006114 */
6115 static int
Bram Moolenaare7c56862007-08-04 10:14:52 +00006116cin_is_cpp_baseclass(col)
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006117 colnr_T *col; /* return: column to align with */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006118{
6119 char_u *s;
6120 int class_or_struct, lookfor_ctor_init, cpp_base_class;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006121 linenr_T lnum = curwin->w_cursor.lnum;
Bram Moolenaare7c56862007-08-04 10:14:52 +00006122 char_u *line = ml_get_curline();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006123
6124 *col = 0;
6125
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006126 s = skipwhite(line);
6127 if (*s == '#') /* skip #define FOO x ? (x) : x */
6128 return FALSE;
6129 s = cin_skipcomment(s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006130 if (*s == NUL)
6131 return FALSE;
6132
6133 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
6134
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006135 /* Search for a line starting with '#', empty, ending in ';' or containing
6136 * '{' or '}' and start below it. This handles the following situations:
6137 * a = cond ?
6138 * func() :
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00006139 * asdf;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006140 * func::foo()
6141 * : something
6142 * {}
6143 * Foo::Foo (int one, int two)
6144 * : something(4),
6145 * somethingelse(3)
6146 * {}
6147 */
6148 while (lnum > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006149 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00006150 line = ml_get(lnum - 1);
6151 s = skipwhite(line);
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006152 if (*s == '#' || *s == NUL)
6153 break;
6154 while (*s != NUL)
6155 {
6156 s = cin_skipcomment(s);
6157 if (*s == '{' || *s == '}'
6158 || (*s == ';' && cin_nocode(s + 1)))
6159 break;
6160 if (*s != NUL)
6161 ++s;
6162 }
6163 if (*s != NUL)
6164 break;
6165 --lnum;
6166 }
6167
Bram Moolenaare7c56862007-08-04 10:14:52 +00006168 line = ml_get(lnum);
6169 s = cin_skipcomment(line);
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006170 for (;;)
6171 {
6172 if (*s == NUL)
6173 {
6174 if (lnum == curwin->w_cursor.lnum)
6175 break;
6176 /* Continue in the cursor line. */
Bram Moolenaare7c56862007-08-04 10:14:52 +00006177 line = ml_get(++lnum);
6178 s = cin_skipcomment(line);
6179 if (*s == NUL)
6180 continue;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006181 }
6182
Bram Moolenaaraede6ce2011-05-10 11:56:30 +02006183 if (s[0] == '"')
6184 s = skip_string(s) + 1;
6185 else if (s[0] == ':')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006186 {
6187 if (s[1] == ':')
6188 {
6189 /* skip double colon. It can't be a constructor
6190 * initialization any more */
6191 lookfor_ctor_init = FALSE;
6192 s = cin_skipcomment(s + 2);
6193 }
6194 else if (lookfor_ctor_init || class_or_struct)
6195 {
6196 /* we have something found, that looks like the start of
Bram Moolenaare21877a2008-02-13 09:58:14 +00006197 * cpp-base-class-declaration or constructor-initialization */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006198 cpp_base_class = TRUE;
6199 lookfor_ctor_init = class_or_struct = FALSE;
6200 *col = 0;
6201 s = cin_skipcomment(s + 1);
6202 }
6203 else
6204 s = cin_skipcomment(s + 1);
6205 }
6206 else if ((STRNCMP(s, "class", 5) == 0 && !vim_isIDc(s[5]))
6207 || (STRNCMP(s, "struct", 6) == 0 && !vim_isIDc(s[6])))
6208 {
6209 class_or_struct = TRUE;
6210 lookfor_ctor_init = FALSE;
6211
6212 if (*s == 'c')
6213 s = cin_skipcomment(s + 5);
6214 else
6215 s = cin_skipcomment(s + 6);
6216 }
6217 else
6218 {
6219 if (s[0] == '{' || s[0] == '}' || s[0] == ';')
6220 {
6221 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
6222 }
6223 else if (s[0] == ')')
6224 {
6225 /* Constructor-initialization is assumed if we come across
6226 * something like "):" */
6227 class_or_struct = FALSE;
6228 lookfor_ctor_init = TRUE;
6229 }
Bram Moolenaar18144c82006-04-12 21:52:12 +00006230 else if (s[0] == '?')
6231 {
6232 /* Avoid seeing '() :' after '?' as constructor init. */
6233 return FALSE;
6234 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006235 else if (!vim_isIDc(s[0]))
6236 {
6237 /* if it is not an identifier, we are wrong */
6238 class_or_struct = FALSE;
6239 lookfor_ctor_init = FALSE;
6240 }
6241 else if (*col == 0)
6242 {
6243 /* it can't be a constructor-initialization any more */
6244 lookfor_ctor_init = FALSE;
6245
6246 /* the first statement starts here: lineup with this one... */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006247 if (cpp_base_class)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006248 *col = (colnr_T)(s - line);
6249 }
6250
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006251 /* When the line ends in a comma don't align with it. */
6252 if (lnum == curwin->w_cursor.lnum && *s == ',' && cin_nocode(s + 1))
6253 *col = 0;
6254
Bram Moolenaar071d4272004-06-13 20:20:40 +00006255 s = cin_skipcomment(s + 1);
6256 }
6257 }
6258
6259 return cpp_base_class;
6260}
6261
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006262 static int
6263get_baseclass_amount(col, ind_maxparen, ind_maxcomment, ind_cpp_baseclass)
6264 int col;
6265 int ind_maxparen;
6266 int ind_maxcomment;
6267 int ind_cpp_baseclass;
6268{
6269 int amount;
6270 colnr_T vcol;
6271 pos_T *trypos;
6272
6273 if (col == 0)
6274 {
6275 amount = get_indent();
6276 if (find_last_paren(ml_get_curline(), '(', ')')
6277 && (trypos = find_match_paren(ind_maxparen,
6278 ind_maxcomment)) != NULL)
6279 amount = get_indent_lnum(trypos->lnum); /* XXX */
6280 if (!cin_ends_in(ml_get_curline(), (char_u *)",", NULL))
6281 amount += ind_cpp_baseclass;
6282 }
6283 else
6284 {
6285 curwin->w_cursor.col = col;
6286 getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
6287 amount = (int)vcol;
6288 }
6289 if (amount < ind_cpp_baseclass)
6290 amount = ind_cpp_baseclass;
6291 return amount;
6292}
6293
Bram Moolenaar071d4272004-06-13 20:20:40 +00006294/*
6295 * Return TRUE if string "s" ends with the string "find", possibly followed by
6296 * white space and comments. Skip strings and comments.
6297 * Ignore "ignore" after "find" if it's not NULL.
6298 */
6299 static int
6300cin_ends_in(s, find, ignore)
6301 char_u *s;
6302 char_u *find;
6303 char_u *ignore;
6304{
6305 char_u *p = s;
6306 char_u *r;
6307 int len = (int)STRLEN(find);
6308
6309 while (*p != NUL)
6310 {
6311 p = cin_skipcomment(p);
6312 if (STRNCMP(p, find, len) == 0)
6313 {
6314 r = skipwhite(p + len);
6315 if (ignore != NULL && STRNCMP(r, ignore, STRLEN(ignore)) == 0)
6316 r = skipwhite(r + STRLEN(ignore));
6317 if (cin_nocode(r))
6318 return TRUE;
6319 }
6320 if (*p != NUL)
6321 ++p;
6322 }
6323 return FALSE;
6324}
6325
6326/*
6327 * Skip strings, chars and comments until at or past "trypos".
6328 * Return the column found.
6329 */
6330 static int
6331cin_skip2pos(trypos)
6332 pos_T *trypos;
6333{
6334 char_u *line;
6335 char_u *p;
6336
6337 p = line = ml_get(trypos->lnum);
6338 while (*p && (colnr_T)(p - line) < trypos->col)
6339 {
6340 if (cin_iscomment(p))
6341 p = cin_skipcomment(p);
6342 else
6343 {
6344 p = skip_string(p);
6345 ++p;
6346 }
6347 }
6348 return (int)(p - line);
6349}
6350
6351/*
6352 * Find the '{' at the start of the block we are in.
6353 * Return NULL if no match found.
6354 * Ignore a '{' that is in a comment, makes indenting the next three lines
6355 * work. */
6356/* foo() */
6357/* { */
6358/* } */
6359
6360 static pos_T *
6361find_start_brace(ind_maxcomment) /* XXX */
6362 int ind_maxcomment;
6363{
6364 pos_T cursor_save;
6365 pos_T *trypos;
6366 pos_T *pos;
6367 static pos_T pos_copy;
6368
6369 cursor_save = curwin->w_cursor;
6370 while ((trypos = findmatchlimit(NULL, '{', FM_BLOCKSTOP, 0)) != NULL)
6371 {
6372 pos_copy = *trypos; /* copy pos_T, next findmatch will change it */
6373 trypos = &pos_copy;
6374 curwin->w_cursor = *trypos;
6375 pos = NULL;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006376 /* ignore the { if it's in a // or / * * / comment */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006377 if ((colnr_T)cin_skip2pos(trypos) == trypos->col
6378 && (pos = find_start_comment(ind_maxcomment)) == NULL) /* XXX */
6379 break;
6380 if (pos != NULL)
6381 curwin->w_cursor.lnum = pos->lnum;
6382 }
6383 curwin->w_cursor = cursor_save;
6384 return trypos;
6385}
6386
6387/*
6388 * Find the matching '(', failing if it is in a comment.
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006389 * Return NULL if no match found.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006390 */
6391 static pos_T *
6392find_match_paren(ind_maxparen, ind_maxcomment) /* XXX */
6393 int ind_maxparen;
6394 int ind_maxcomment;
6395{
6396 pos_T cursor_save;
6397 pos_T *trypos;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006398 static pos_T pos_copy;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006399
6400 cursor_save = curwin->w_cursor;
6401 if ((trypos = findmatchlimit(NULL, '(', 0, ind_maxparen)) != NULL)
6402 {
6403 /* check if the ( is in a // comment */
6404 if ((colnr_T)cin_skip2pos(trypos) > trypos->col)
6405 trypos = NULL;
6406 else
6407 {
6408 pos_copy = *trypos; /* copy trypos, findmatch will change it */
6409 trypos = &pos_copy;
6410 curwin->w_cursor = *trypos;
6411 if (find_start_comment(ind_maxcomment) != NULL) /* XXX */
6412 trypos = NULL;
6413 }
6414 }
6415 curwin->w_cursor = cursor_save;
6416 return trypos;
6417}
6418
6419/*
6420 * Return ind_maxparen corrected for the difference in line number between the
6421 * cursor position and "startpos". This makes sure that searching for a
6422 * matching paren above the cursor line doesn't find a match because of
6423 * looking a few lines further.
6424 */
6425 static int
6426corr_ind_maxparen(ind_maxparen, startpos)
6427 int ind_maxparen;
6428 pos_T *startpos;
6429{
6430 long n = (long)startpos->lnum - (long)curwin->w_cursor.lnum;
6431
6432 if (n > 0 && n < ind_maxparen / 2)
6433 return ind_maxparen - (int)n;
6434 return ind_maxparen;
6435}
6436
6437/*
6438 * Set w_cursor.col to the column number of the last unmatched ')' or '{' in
Bram Moolenaar6d8f9c62011-11-30 13:03:28 +01006439 * line "l". "l" must point to the start of the line.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006440 */
6441 static int
6442find_last_paren(l, start, end)
6443 char_u *l;
6444 int start, end;
6445{
6446 int i;
6447 int retval = FALSE;
6448 int open_count = 0;
6449
6450 curwin->w_cursor.col = 0; /* default is start of line */
6451
Bram Moolenaar6d8f9c62011-11-30 13:03:28 +01006452 for (i = 0; l[i] != NUL; i++)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006453 {
6454 i = (int)(cin_skipcomment(l + i) - l); /* ignore parens in comments */
6455 i = (int)(skip_string(l + i) - l); /* ignore parens in quotes */
6456 if (l[i] == start)
6457 ++open_count;
6458 else if (l[i] == end)
6459 {
6460 if (open_count > 0)
6461 --open_count;
6462 else
6463 {
6464 curwin->w_cursor.col = i;
6465 retval = TRUE;
6466 }
6467 }
6468 }
6469 return retval;
6470}
6471
6472 int
6473get_c_indent()
6474{
6475 /*
6476 * spaces from a block's opening brace the prevailing indent for that
6477 * block should be
6478 */
6479 int ind_level = curbuf->b_p_sw;
6480
6481 /*
6482 * spaces from the edge of the line an open brace that's at the end of a
6483 * line is imagined to be.
6484 */
6485 int ind_open_imag = 0;
6486
6487 /*
Bram Moolenaar1a509df2010-08-01 17:59:57 +02006488 * spaces from the prevailing indent for a line that is not preceded by
Bram Moolenaar071d4272004-06-13 20:20:40 +00006489 * an opening brace.
6490 */
6491 int ind_no_brace = 0;
6492
6493 /*
6494 * column where the first { of a function should be located }
6495 */
6496 int ind_first_open = 0;
6497
6498 /*
6499 * spaces from the prevailing indent a leftmost open brace should be
6500 * located
6501 */
6502 int ind_open_extra = 0;
6503
6504 /*
6505 * spaces from the matching open brace (real location for one at the left
6506 * edge; imaginary location from one that ends a line) the matching close
6507 * brace should be located
6508 */
6509 int ind_close_extra = 0;
6510
6511 /*
6512 * spaces from the edge of the line an open brace sitting in the leftmost
6513 * column is imagined to be
6514 */
6515 int ind_open_left_imag = 0;
6516
6517 /*
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006518 * Spaces jump labels should be shifted to the left if N is non-negative,
6519 * otherwise the jump label will be put to column 1.
6520 */
6521 int ind_jump_label = -1;
6522
6523 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006524 * spaces from the switch() indent a "case xx" label should be located
6525 */
6526 int ind_case = curbuf->b_p_sw;
6527
6528 /*
6529 * spaces from the "case xx:" code after a switch() should be located
6530 */
6531 int ind_case_code = curbuf->b_p_sw;
6532
6533 /*
6534 * lineup break at end of case in switch() with case label
6535 */
6536 int ind_case_break = 0;
6537
6538 /*
6539 * spaces from the class declaration indent a scope declaration label
6540 * should be located
6541 */
6542 int ind_scopedecl = curbuf->b_p_sw;
6543
6544 /*
6545 * spaces from the scope declaration label code should be located
6546 */
6547 int ind_scopedecl_code = curbuf->b_p_sw;
6548
6549 /*
6550 * amount K&R-style parameters should be indented
6551 */
6552 int ind_param = curbuf->b_p_sw;
6553
6554 /*
6555 * amount a function type spec should be indented
6556 */
6557 int ind_func_type = curbuf->b_p_sw;
6558
6559 /*
6560 * amount a cpp base class declaration or constructor initialization
6561 * should be indented
6562 */
6563 int ind_cpp_baseclass = curbuf->b_p_sw;
6564
6565 /*
6566 * additional spaces beyond the prevailing indent a continuation line
6567 * should be located
6568 */
6569 int ind_continuation = curbuf->b_p_sw;
6570
6571 /*
6572 * spaces from the indent of the line with an unclosed parentheses
6573 */
6574 int ind_unclosed = curbuf->b_p_sw * 2;
6575
6576 /*
6577 * spaces from the indent of the line with an unclosed parentheses, which
6578 * itself is also unclosed
6579 */
6580 int ind_unclosed2 = curbuf->b_p_sw;
6581
6582 /*
6583 * suppress ignoring spaces from the indent of a line starting with an
6584 * unclosed parentheses.
6585 */
6586 int ind_unclosed_noignore = 0;
6587
6588 /*
6589 * If the opening paren is the last nonwhite character on the line, and
6590 * ind_unclosed_wrapped is nonzero, use this indent relative to the outer
6591 * context (for very long lines).
6592 */
6593 int ind_unclosed_wrapped = 0;
6594
6595 /*
6596 * suppress ignoring white space when lining up with the character after
6597 * an unclosed parentheses.
6598 */
6599 int ind_unclosed_whiteok = 0;
6600
6601 /*
6602 * indent a closing parentheses under the line start of the matching
6603 * opening parentheses.
6604 */
6605 int ind_matching_paren = 0;
6606
6607 /*
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006608 * indent a closing parentheses under the previous line.
6609 */
6610 int ind_paren_prev = 0;
6611
6612 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006613 * Extra indent for comments.
6614 */
6615 int ind_comment = 0;
6616
6617 /*
6618 * spaces from the comment opener when there is nothing after it.
6619 */
6620 int ind_in_comment = 3;
6621
6622 /*
6623 * boolean: if non-zero, use ind_in_comment even if there is something
6624 * after the comment opener.
6625 */
6626 int ind_in_comment2 = 0;
6627
6628 /*
6629 * max lines to search for an open paren
6630 */
6631 int ind_maxparen = 20;
6632
6633 /*
6634 * max lines to search for an open comment
6635 */
6636 int ind_maxcomment = 70;
6637
6638 /*
6639 * handle braces for java code
6640 */
6641 int ind_java = 0;
6642
6643 /*
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006644 * not to confuse JS object properties with labels
6645 */
6646 int ind_js = 0;
6647
6648 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006649 * handle blocked cases correctly
6650 */
6651 int ind_keep_case_label = 0;
6652
Bram Moolenaared38b0a2011-05-25 15:16:18 +02006653 /*
6654 * handle C++ namespace
6655 */
6656 int ind_cpp_namespace = 0;
6657
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006658 /*
6659 * handle continuation lines containing conditions of if(), for() and
6660 * while()
6661 */
6662 int ind_if_for_while = 0;
6663
Bram Moolenaar071d4272004-06-13 20:20:40 +00006664 pos_T cur_curpos;
6665 int amount;
6666 int scope_amount;
Bram Moolenaarb21e5842006-04-16 18:30:08 +00006667 int cur_amount = MAXCOL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006668 colnr_T col;
6669 char_u *theline;
6670 char_u *linecopy;
6671 pos_T *trypos;
6672 pos_T *tryposBrace = NULL;
6673 pos_T our_paren_pos;
6674 char_u *start;
6675 int start_brace;
Bram Moolenaare21877a2008-02-13 09:58:14 +00006676#define BRACE_IN_COL0 1 /* '{' is in column 0 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006677#define BRACE_AT_START 2 /* '{' is at start of line */
6678#define BRACE_AT_END 3 /* '{' is at end of line */
6679 linenr_T ourscope;
6680 char_u *l;
6681 char_u *look;
6682 char_u terminated;
6683 int lookfor;
6684#define LOOKFOR_INITIAL 0
6685#define LOOKFOR_IF 1
6686#define LOOKFOR_DO 2
6687#define LOOKFOR_CASE 3
6688#define LOOKFOR_ANY 4
6689#define LOOKFOR_TERM 5
6690#define LOOKFOR_UNTERM 6
6691#define LOOKFOR_SCOPEDECL 7
6692#define LOOKFOR_NOBREAK 8
6693#define LOOKFOR_CPP_BASECLASS 9
6694#define LOOKFOR_ENUM_OR_INIT 10
6695
6696 int whilelevel;
6697 linenr_T lnum;
6698 char_u *options;
Bram Moolenaar48d27922012-06-13 13:40:48 +02006699 char_u *digits;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006700 int fraction = 0; /* init for GCC */
6701 int divider;
6702 int n;
6703 int iscase;
6704 int lookfor_break;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02006705 int lookfor_cpp_namespace = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006706 int cont_amount = 0; /* amount for continuation line */
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006707 int original_line_islabel;
Bram Moolenaare79d1532011-10-04 18:03:47 +02006708 int added_to_amount = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006709
6710 for (options = curbuf->b_p_cino; *options; )
6711 {
6712 l = options++;
6713 if (*options == '-')
6714 ++options;
Bram Moolenaar48d27922012-06-13 13:40:48 +02006715 digits = options; /* remember where the digits start */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006716 n = getdigits(&options);
6717 divider = 0;
6718 if (*options == '.') /* ".5s" means a fraction */
6719 {
6720 fraction = atol((char *)++options);
6721 while (VIM_ISDIGIT(*options))
6722 {
6723 ++options;
6724 if (divider)
6725 divider *= 10;
6726 else
6727 divider = 10;
6728 }
6729 }
6730 if (*options == 's') /* "2s" means two times 'shiftwidth' */
6731 {
Bram Moolenaar48d27922012-06-13 13:40:48 +02006732 if (options == digits)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006733 n = curbuf->b_p_sw; /* just "s" is one 'shiftwidth' */
6734 else
6735 {
6736 n *= curbuf->b_p_sw;
6737 if (divider)
6738 n += (curbuf->b_p_sw * fraction + divider / 2) / divider;
6739 }
6740 ++options;
6741 }
6742 if (l[1] == '-')
6743 n = -n;
6744 /* When adding an entry here, also update the default 'cinoptions' in
Bram Moolenaar39353fd2007-03-27 09:02:11 +00006745 * doc/indent.txt, and add explanation for it! */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006746 switch (*l)
6747 {
6748 case '>': ind_level = n; break;
6749 case 'e': ind_open_imag = n; break;
6750 case 'n': ind_no_brace = n; break;
6751 case 'f': ind_first_open = n; break;
6752 case '{': ind_open_extra = n; break;
6753 case '}': ind_close_extra = n; break;
6754 case '^': ind_open_left_imag = n; break;
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006755 case 'L': ind_jump_label = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006756 case ':': ind_case = n; break;
6757 case '=': ind_case_code = n; break;
6758 case 'b': ind_case_break = n; break;
6759 case 'p': ind_param = n; break;
6760 case 't': ind_func_type = n; break;
6761 case '/': ind_comment = n; break;
6762 case 'c': ind_in_comment = n; break;
6763 case 'C': ind_in_comment2 = n; break;
6764 case 'i': ind_cpp_baseclass = n; break;
6765 case '+': ind_continuation = n; break;
6766 case '(': ind_unclosed = n; break;
6767 case 'u': ind_unclosed2 = n; break;
6768 case 'U': ind_unclosed_noignore = n; break;
6769 case 'W': ind_unclosed_wrapped = n; break;
6770 case 'w': ind_unclosed_whiteok = n; break;
6771 case 'm': ind_matching_paren = n; break;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006772 case 'M': ind_paren_prev = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006773 case ')': ind_maxparen = n; break;
6774 case '*': ind_maxcomment = n; break;
6775 case 'g': ind_scopedecl = n; break;
6776 case 'h': ind_scopedecl_code = n; break;
6777 case 'j': ind_java = n; break;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006778 case 'J': ind_js = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006779 case 'l': ind_keep_case_label = n; break;
Bram Moolenaar39353fd2007-03-27 09:02:11 +00006780 case '#': ind_hash_comment = n; break;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02006781 case 'N': ind_cpp_namespace = n; break;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006782 case 'k': ind_if_for_while = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006783 }
Bram Moolenaardfdf3c42010-03-23 18:22:46 +01006784 if (*options == ',')
6785 ++options;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006786 }
6787
6788 /* remember where the cursor was when we started */
6789 cur_curpos = curwin->w_cursor;
6790
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006791 /* if we are at line 1 0 is fine, right? */
6792 if (cur_curpos.lnum == 1)
6793 return 0;
6794
Bram Moolenaar071d4272004-06-13 20:20:40 +00006795 /* Get a copy of the current contents of the line.
6796 * This is required, because only the most recent line obtained with
6797 * ml_get is valid! */
6798 linecopy = vim_strsave(ml_get(cur_curpos.lnum));
6799 if (linecopy == NULL)
6800 return 0;
6801
6802 /*
6803 * In insert mode and the cursor is on a ')' truncate the line at the
6804 * cursor position. We don't want to line up with the matching '(' when
6805 * inserting new stuff.
6806 * For unknown reasons the cursor might be past the end of the line, thus
6807 * check for that.
6808 */
6809 if ((State & INSERT)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006810 && curwin->w_cursor.col < (colnr_T)STRLEN(linecopy)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006811 && linecopy[curwin->w_cursor.col] == ')')
6812 linecopy[curwin->w_cursor.col] = NUL;
6813
6814 theline = skipwhite(linecopy);
6815
6816 /* move the cursor to the start of the line */
6817
6818 curwin->w_cursor.col = 0;
6819
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006820 original_line_islabel = cin_islabel(ind_maxcomment); /* XXX */
6821
Bram Moolenaar071d4272004-06-13 20:20:40 +00006822 /*
6823 * #defines and so on always go at the left when included in 'cinkeys'.
6824 */
6825 if (*theline == '#' && (*linecopy == '#' || in_cinkeys('#', ' ', TRUE)))
6826 {
6827 amount = 0;
6828 }
6829
6830 /*
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006831 * Is it a non-case label? Then that goes at the left margin too unless:
6832 * - JS flag is set.
6833 * - 'L' item has a positive value.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006834 */
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006835 else if (original_line_islabel && !ind_js && ind_jump_label < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006836 {
6837 amount = 0;
6838 }
6839
6840 /*
6841 * If we're inside a "//" comment and there is a "//" comment in a
6842 * previous line, lineup with that one.
6843 */
6844 else if (cin_islinecomment(theline)
6845 && (trypos = find_line_comment()) != NULL) /* XXX */
6846 {
6847 /* find how indented the line beginning the comment is */
6848 getvcol(curwin, trypos, &col, NULL, NULL);
6849 amount = col;
6850 }
6851
6852 /*
6853 * If we're inside a comment and not looking at the start of the
6854 * comment, try using the 'comments' option.
6855 */
6856 else if (!cin_iscomment(theline)
6857 && (trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
6858 {
6859 int lead_start_len = 2;
6860 int lead_middle_len = 1;
6861 char_u lead_start[COM_MAX_LEN]; /* start-comment string */
6862 char_u lead_middle[COM_MAX_LEN]; /* middle-comment string */
6863 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
6864 char_u *p;
6865 int start_align = 0;
6866 int start_off = 0;
6867 int done = FALSE;
6868
6869 /* find how indented the line beginning the comment is */
6870 getvcol(curwin, trypos, &col, NULL, NULL);
6871 amount = col;
Bram Moolenaar4aa97422011-04-11 14:27:38 +02006872 *lead_start = NUL;
6873 *lead_middle = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006874
6875 p = curbuf->b_p_com;
6876 while (*p != NUL)
6877 {
6878 int align = 0;
6879 int off = 0;
6880 int what = 0;
6881
6882 while (*p != NUL && *p != ':')
6883 {
6884 if (*p == COM_START || *p == COM_END || *p == COM_MIDDLE)
6885 what = *p++;
6886 else if (*p == COM_LEFT || *p == COM_RIGHT)
6887 align = *p++;
6888 else if (VIM_ISDIGIT(*p) || *p == '-')
6889 off = getdigits(&p);
6890 else
6891 ++p;
6892 }
6893
6894 if (*p == ':')
6895 ++p;
6896 (void)copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
6897 if (what == COM_START)
6898 {
6899 STRCPY(lead_start, lead_end);
6900 lead_start_len = (int)STRLEN(lead_start);
6901 start_off = off;
6902 start_align = align;
6903 }
6904 else if (what == COM_MIDDLE)
6905 {
6906 STRCPY(lead_middle, lead_end);
6907 lead_middle_len = (int)STRLEN(lead_middle);
6908 }
6909 else if (what == COM_END)
6910 {
6911 /* If our line starts with the middle comment string, line it
6912 * up with the comment opener per the 'comments' option. */
6913 if (STRNCMP(theline, lead_middle, lead_middle_len) == 0
6914 && STRNCMP(theline, lead_end, STRLEN(lead_end)) != 0)
6915 {
6916 done = TRUE;
6917 if (curwin->w_cursor.lnum > 1)
6918 {
6919 /* If the start comment string matches in the previous
Bram Moolenaare21877a2008-02-13 09:58:14 +00006920 * line, use the indent of that line plus offset. If
Bram Moolenaar071d4272004-06-13 20:20:40 +00006921 * the middle comment string matches in the previous
6922 * line, use the indent of that line. XXX */
6923 look = skipwhite(ml_get(curwin->w_cursor.lnum - 1));
6924 if (STRNCMP(look, lead_start, lead_start_len) == 0)
6925 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6926 else if (STRNCMP(look, lead_middle,
6927 lead_middle_len) == 0)
6928 {
6929 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6930 break;
6931 }
6932 /* If the start comment string doesn't match with the
6933 * start of the comment, skip this entry. XXX */
6934 else if (STRNCMP(ml_get(trypos->lnum) + trypos->col,
6935 lead_start, lead_start_len) != 0)
6936 continue;
6937 }
6938 if (start_off != 0)
6939 amount += start_off;
6940 else if (start_align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006941 amount += vim_strsize(lead_start)
6942 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006943 break;
6944 }
6945
6946 /* If our line starts with the end comment string, line it up
6947 * with the middle comment */
6948 if (STRNCMP(theline, lead_middle, lead_middle_len) != 0
6949 && STRNCMP(theline, lead_end, STRLEN(lead_end)) == 0)
6950 {
6951 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6952 /* XXX */
6953 if (off != 0)
6954 amount += off;
6955 else if (align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006956 amount += vim_strsize(lead_start)
6957 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006958 done = TRUE;
6959 break;
6960 }
6961 }
6962 }
6963
6964 /* If our line starts with an asterisk, line up with the
6965 * asterisk in the comment opener; otherwise, line up
6966 * with the first character of the comment text.
6967 */
6968 if (done)
6969 ;
6970 else if (theline[0] == '*')
6971 amount += 1;
6972 else
6973 {
6974 /*
6975 * If we are more than one line away from the comment opener, take
6976 * the indent of the previous non-empty line. If 'cino' has "CO"
6977 * and we are just below the comment opener and there are any
6978 * white characters after it line up with the text after it;
6979 * otherwise, add the amount specified by "c" in 'cino'
6980 */
6981 amount = -1;
6982 for (lnum = cur_curpos.lnum - 1; lnum > trypos->lnum; --lnum)
6983 {
6984 if (linewhite(lnum)) /* skip blank lines */
6985 continue;
6986 amount = get_indent_lnum(lnum); /* XXX */
6987 break;
6988 }
6989 if (amount == -1) /* use the comment opener */
6990 {
6991 if (!ind_in_comment2)
6992 {
6993 start = ml_get(trypos->lnum);
6994 look = start + trypos->col + 2; /* skip / and * */
6995 if (*look != NUL) /* if something after it */
6996 trypos->col = (colnr_T)(skipwhite(look) - start);
6997 }
6998 getvcol(curwin, trypos, &col, NULL, NULL);
6999 amount = col;
7000 if (ind_in_comment2 || *look == NUL)
7001 amount += ind_in_comment;
7002 }
7003 }
7004 }
7005
7006 /*
7007 * Are we inside parentheses or braces?
7008 */ /* XXX */
7009 else if (((trypos = find_match_paren(ind_maxparen, ind_maxcomment)) != NULL
7010 && ind_java == 0)
7011 || (tryposBrace = find_start_brace(ind_maxcomment)) != NULL
7012 || trypos != NULL)
7013 {
7014 if (trypos != NULL && tryposBrace != NULL)
7015 {
7016 /* Both an unmatched '(' and '{' is found. Use the one which is
7017 * closer to the current cursor position, set the other to NULL. */
7018 if (trypos->lnum != tryposBrace->lnum
7019 ? trypos->lnum < tryposBrace->lnum
7020 : trypos->col < tryposBrace->col)
7021 trypos = NULL;
7022 else
7023 tryposBrace = NULL;
7024 }
7025
7026 if (trypos != NULL)
7027 {
7028 /*
7029 * If the matching paren is more than one line away, use the indent of
7030 * a previous non-empty line that matches the same paren.
7031 */
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007032 if (theline[0] == ')' && ind_paren_prev)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007033 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007034 /* Line up with the start of the matching paren line. */
7035 amount = get_indent_lnum(curwin->w_cursor.lnum - 1); /* XXX */
7036 }
7037 else
7038 {
7039 amount = -1;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007040 our_paren_pos = *trypos;
7041 for (lnum = cur_curpos.lnum - 1; lnum > our_paren_pos.lnum; --lnum)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007042 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007043 l = skipwhite(ml_get(lnum));
7044 if (cin_nocode(l)) /* skip comment lines */
7045 continue;
7046 if (cin_ispreproc_cont(&l, &lnum))
7047 continue; /* ignore #define, #if, etc. */
7048 curwin->w_cursor.lnum = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007049
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007050 /* Skip a comment. XXX */
7051 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
7052 {
7053 lnum = trypos->lnum + 1;
7054 continue;
7055 }
7056
7057 /* XXX */
7058 if ((trypos = find_match_paren(
7059 corr_ind_maxparen(ind_maxparen, &cur_curpos),
Bram Moolenaar071d4272004-06-13 20:20:40 +00007060 ind_maxcomment)) != NULL
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007061 && trypos->lnum == our_paren_pos.lnum
7062 && trypos->col == our_paren_pos.col)
7063 {
7064 amount = get_indent_lnum(lnum); /* XXX */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007065
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007066 if (theline[0] == ')')
7067 {
7068 if (our_paren_pos.lnum != lnum
7069 && cur_amount > amount)
7070 cur_amount = amount;
7071 amount = -1;
7072 }
7073 break;
7074 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007075 }
7076 }
7077
7078 /*
7079 * Line up with line where the matching paren is. XXX
7080 * If the line starts with a '(' or the indent for unclosed
7081 * parentheses is zero, line up with the unclosed parentheses.
7082 */
7083 if (amount == -1)
7084 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007085 int ignore_paren_col = 0;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007086 int is_if_for_while = 0;
7087
7088 if (ind_if_for_while)
7089 {
7090 /* Look for the outermost opening parenthesis on this line
7091 * and check whether it belongs to an "if", "for" or "while". */
7092
7093 pos_T cursor_save = curwin->w_cursor;
7094 pos_T outermost;
7095 char_u *line;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007096
7097 trypos = &our_paren_pos;
7098 do {
7099 outermost = *trypos;
7100 curwin->w_cursor.lnum = outermost.lnum;
7101 curwin->w_cursor.col = outermost.col;
7102
7103 trypos = find_match_paren(ind_maxparen, ind_maxcomment);
7104 } while (trypos && trypos->lnum == outermost.lnum);
7105
7106 curwin->w_cursor = cursor_save;
7107
7108 line = ml_get(outermost.lnum);
7109
7110 is_if_for_while =
Bram Moolenaarb345d492012-04-09 20:42:26 +02007111 cin_is_if_for_while_before_offset(line, &outermost.col);
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007112 }
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007113
Bram Moolenaar071d4272004-06-13 20:20:40 +00007114 amount = skip_label(our_paren_pos.lnum, &look, ind_maxcomment);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007115 look = skipwhite(look);
7116 if (*look == '(')
7117 {
7118 linenr_T save_lnum = curwin->w_cursor.lnum;
7119 char_u *line;
7120 int look_col;
7121
7122 /* Ignore a '(' in front of the line that has a match before
7123 * our matching '('. */
7124 curwin->w_cursor.lnum = our_paren_pos.lnum;
7125 line = ml_get_curline();
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007126 look_col = (int)(look - line);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007127 curwin->w_cursor.col = look_col + 1;
7128 if ((trypos = findmatchlimit(NULL, ')', 0, ind_maxparen))
7129 != NULL
7130 && trypos->lnum == our_paren_pos.lnum
7131 && trypos->col < our_paren_pos.col)
7132 ignore_paren_col = trypos->col + 1;
7133
7134 curwin->w_cursor.lnum = save_lnum;
7135 look = ml_get(our_paren_pos.lnum) + look_col;
7136 }
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007137 if (theline[0] == ')' || (ind_unclosed == 0 && is_if_for_while == 0)
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007138 || (!ind_unclosed_noignore && *look == '('
7139 && ignore_paren_col == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007140 {
7141 /*
7142 * If we're looking at a close paren, line up right there;
7143 * otherwise, line up with the next (non-white) character.
7144 * When ind_unclosed_wrapped is set and the matching paren is
7145 * the last nonwhite character of the line, use either the
7146 * indent of the current line or the indentation of the next
7147 * outer paren and add ind_unclosed_wrapped (for very long
7148 * lines).
7149 */
7150 if (theline[0] != ')')
7151 {
7152 cur_amount = MAXCOL;
7153 l = ml_get(our_paren_pos.lnum);
7154 if (ind_unclosed_wrapped
7155 && cin_ends_in(l, (char_u *)"(", NULL))
7156 {
7157 /* look for opening unmatched paren, indent one level
7158 * for each additional level */
7159 n = 1;
7160 for (col = 0; col < our_paren_pos.col; ++col)
7161 {
7162 switch (l[col])
7163 {
7164 case '(':
7165 case '{': ++n;
7166 break;
7167
7168 case ')':
7169 case '}': if (n > 1)
7170 --n;
7171 break;
7172 }
7173 }
7174
7175 our_paren_pos.col = 0;
7176 amount += n * ind_unclosed_wrapped;
7177 }
7178 else if (ind_unclosed_whiteok)
7179 our_paren_pos.col++;
7180 else
7181 {
7182 col = our_paren_pos.col + 1;
7183 while (vim_iswhite(l[col]))
7184 col++;
7185 if (l[col] != NUL) /* In case of trailing space */
7186 our_paren_pos.col = col;
7187 else
7188 our_paren_pos.col++;
7189 }
7190 }
7191
7192 /*
7193 * Find how indented the paren is, or the character after it
7194 * if we did the above "if".
7195 */
7196 if (our_paren_pos.col > 0)
7197 {
7198 getvcol(curwin, &our_paren_pos, &col, NULL, NULL);
7199 if (cur_amount > (int)col)
7200 cur_amount = col;
7201 }
7202 }
7203
7204 if (theline[0] == ')' && ind_matching_paren)
7205 {
7206 /* Line up with the start of the matching paren line. */
7207 }
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007208 else if ((ind_unclosed == 0 && is_if_for_while == 0)
7209 || (!ind_unclosed_noignore
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007210 && *look == '(' && ignore_paren_col == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007211 {
7212 if (cur_amount != MAXCOL)
7213 amount = cur_amount;
7214 }
7215 else
7216 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007217 /* Add ind_unclosed2 for each '(' before our matching one, but
7218 * ignore (void) before the line (ignore_paren_col). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007219 col = our_paren_pos.col;
Bram Moolenaarb21e5842006-04-16 18:30:08 +00007220 while ((int)our_paren_pos.col > ignore_paren_col)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007221 {
7222 --our_paren_pos.col;
7223 switch (*ml_get_pos(&our_paren_pos))
7224 {
7225 case '(': amount += ind_unclosed2;
7226 col = our_paren_pos.col;
7227 break;
7228 case ')': amount -= ind_unclosed2;
7229 col = MAXCOL;
7230 break;
7231 }
7232 }
7233
7234 /* Use ind_unclosed once, when the first '(' is not inside
7235 * braces */
7236 if (col == MAXCOL)
7237 amount += ind_unclosed;
7238 else
7239 {
7240 curwin->w_cursor.lnum = our_paren_pos.lnum;
7241 curwin->w_cursor.col = col;
Bram Moolenaar367bec82011-04-11 14:26:19 +02007242 if (find_match_paren(ind_maxparen, ind_maxcomment) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007243 amount += ind_unclosed2;
7244 else
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007245 {
7246 if (is_if_for_while)
7247 amount += ind_if_for_while;
7248 else
7249 amount += ind_unclosed;
7250 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007251 }
7252 /*
7253 * For a line starting with ')' use the minimum of the two
7254 * positions, to avoid giving it more indent than the previous
7255 * lines:
7256 * func_long_name( if (x
7257 * arg && yy
7258 * ) ^ not here ) ^ not here
7259 */
7260 if (cur_amount < amount)
7261 amount = cur_amount;
7262 }
7263 }
7264
7265 /* add extra indent for a comment */
7266 if (cin_iscomment(theline))
7267 amount += ind_comment;
7268 }
7269
7270 /*
7271 * Are we at least inside braces, then?
7272 */
7273 else
7274 {
7275 trypos = tryposBrace;
7276
7277 ourscope = trypos->lnum;
7278 start = ml_get(ourscope);
7279
7280 /*
7281 * Now figure out how indented the line is in general.
7282 * If the brace was at the start of the line, we use that;
7283 * otherwise, check out the indentation of the line as
7284 * a whole and then add the "imaginary indent" to that.
7285 */
7286 look = skipwhite(start);
7287 if (*look == '{')
7288 {
7289 getvcol(curwin, trypos, &col, NULL, NULL);
7290 amount = col;
7291 if (*start == '{')
7292 start_brace = BRACE_IN_COL0;
7293 else
7294 start_brace = BRACE_AT_START;
7295 }
7296 else
7297 {
7298 /*
7299 * that opening brace might have been on a continuation
7300 * line. if so, find the start of the line.
7301 */
7302 curwin->w_cursor.lnum = ourscope;
7303
7304 /*
7305 * position the cursor over the rightmost paren, so that
7306 * matching it will take us back to the start of the line.
7307 */
7308 lnum = ourscope;
7309 if (find_last_paren(start, '(', ')')
7310 && (trypos = find_match_paren(ind_maxparen,
7311 ind_maxcomment)) != NULL)
7312 lnum = trypos->lnum;
7313
7314 /*
7315 * It could have been something like
7316 * case 1: if (asdf &&
7317 * ldfd) {
7318 * }
7319 */
Bram Moolenaar6ec154b2011-06-12 21:51:08 +02007320 if (ind_js || (ind_keep_case_label
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007321 && cin_iscase(skipwhite(ml_get_curline()), FALSE)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007322 amount = get_indent();
7323 else
7324 amount = skip_label(lnum, &l, ind_maxcomment);
7325
7326 start_brace = BRACE_AT_END;
7327 }
7328
7329 /*
7330 * if we're looking at a closing brace, that's where
7331 * we want to be. otherwise, add the amount of room
7332 * that an indent is supposed to be.
7333 */
7334 if (theline[0] == '}')
7335 {
7336 /*
7337 * they may want closing braces to line up with something
7338 * other than the open brace. indulge them, if so.
7339 */
7340 amount += ind_close_extra;
7341 }
7342 else
7343 {
7344 /*
7345 * If we're looking at an "else", try to find an "if"
7346 * to match it with.
7347 * If we're looking at a "while", try to find a "do"
7348 * to match it with.
7349 */
7350 lookfor = LOOKFOR_INITIAL;
7351 if (cin_iselse(theline))
7352 lookfor = LOOKFOR_IF;
7353 else if (cin_iswhileofdo(theline, cur_curpos.lnum, ind_maxparen))
7354 /* XXX */
7355 lookfor = LOOKFOR_DO;
7356 if (lookfor != LOOKFOR_INITIAL)
7357 {
7358 curwin->w_cursor.lnum = cur_curpos.lnum;
7359 if (find_match(lookfor, ourscope, ind_maxparen,
7360 ind_maxcomment) == OK)
7361 {
7362 amount = get_indent(); /* XXX */
7363 goto theend;
7364 }
7365 }
7366
7367 /*
7368 * We get here if we are not on an "while-of-do" or "else" (or
7369 * failed to find a matching "if").
7370 * Search backwards for something to line up with.
7371 * First set amount for when we don't find anything.
7372 */
7373
7374 /*
7375 * if the '{' is _really_ at the left margin, use the imaginary
7376 * location of a left-margin brace. Otherwise, correct the
7377 * location for ind_open_extra.
7378 */
7379
7380 if (start_brace == BRACE_IN_COL0) /* '{' is in column 0 */
7381 {
7382 amount = ind_open_left_imag;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007383 lookfor_cpp_namespace = TRUE;
7384 }
7385 else if (start_brace == BRACE_AT_START &&
7386 lookfor_cpp_namespace) /* '{' is at start */
7387 {
7388
7389 lookfor_cpp_namespace = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007390 }
7391 else
7392 {
7393 if (start_brace == BRACE_AT_END) /* '{' is at end of line */
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007394 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007395 amount += ind_open_imag;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007396
7397 l = skipwhite(ml_get_curline());
7398 if (cin_is_cpp_namespace(l))
7399 amount += ind_cpp_namespace;
7400 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007401 else
7402 {
7403 /* Compensate for adding ind_open_extra later. */
7404 amount -= ind_open_extra;
7405 if (amount < 0)
7406 amount = 0;
7407 }
7408 }
7409
7410 lookfor_break = FALSE;
7411
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007412 if (cin_iscase(theline, FALSE)) /* it's a switch() label */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007413 {
7414 lookfor = LOOKFOR_CASE; /* find a previous switch() label */
7415 amount += ind_case;
7416 }
7417 else if (cin_isscopedecl(theline)) /* private:, ... */
7418 {
7419 lookfor = LOOKFOR_SCOPEDECL; /* class decl is this block */
7420 amount += ind_scopedecl;
7421 }
7422 else
7423 {
7424 if (ind_case_break && cin_isbreak(theline)) /* break; ... */
7425 lookfor_break = TRUE;
7426
7427 lookfor = LOOKFOR_INITIAL;
7428 amount += ind_level; /* ind_level from start of block */
7429 }
7430 scope_amount = amount;
7431 whilelevel = 0;
7432
7433 /*
7434 * Search backwards. If we find something we recognize, line up
7435 * with that.
7436 *
7437 * if we're looking at an open brace, indent
7438 * the usual amount relative to the conditional
7439 * that opens the block.
7440 */
7441 curwin->w_cursor = cur_curpos;
7442 for (;;)
7443 {
7444 curwin->w_cursor.lnum--;
7445 curwin->w_cursor.col = 0;
7446
7447 /*
7448 * If we went all the way back to the start of our scope, line
7449 * up with it.
7450 */
7451 if (curwin->w_cursor.lnum <= ourscope)
7452 {
7453 /* we reached end of scope:
7454 * if looking for a enum or structure initialization
7455 * go further back:
7456 * if it is an initializer (enum xxx or xxx =), then
7457 * don't add ind_continuation, otherwise it is a variable
7458 * declaration:
7459 * int x,
7460 * here; <-- add ind_continuation
7461 */
7462 if (lookfor == LOOKFOR_ENUM_OR_INIT)
7463 {
7464 if (curwin->w_cursor.lnum == 0
7465 || curwin->w_cursor.lnum
7466 < ourscope - ind_maxparen)
7467 {
7468 /* nothing found (abuse ind_maxparen as limit)
7469 * assume terminated line (i.e. a variable
7470 * initialization) */
7471 if (cont_amount > 0)
7472 amount = cont_amount;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007473 else if (!ind_js)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007474 amount += ind_continuation;
7475 break;
7476 }
7477
7478 l = ml_get_curline();
7479
7480 /*
7481 * If we're in a comment now, skip to the start of the
7482 * comment.
7483 */
7484 trypos = find_start_comment(ind_maxcomment);
7485 if (trypos != NULL)
7486 {
7487 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007488 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007489 continue;
7490 }
7491
7492 /*
7493 * Skip preprocessor directives and blank lines.
7494 */
7495 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7496 continue;
7497
7498 if (cin_nocode(l))
7499 continue;
7500
7501 terminated = cin_isterminated(l, FALSE, TRUE);
7502
7503 /*
7504 * If we are at top level and the line looks like a
7505 * function declaration, we are done
7506 * (it's a variable declaration).
7507 */
7508 if (start_brace != BRACE_IN_COL0
Bram Moolenaarc367faa2011-12-14 20:21:35 +01007509 || !cin_isfuncdecl(&l, curwin->w_cursor.lnum,
7510 0, ind_maxparen, ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007511 {
7512 /* if the line is terminated with another ','
7513 * it is a continued variable initialization.
7514 * don't add extra indent.
7515 * TODO: does not work, if a function
7516 * declaration is split over multiple lines:
7517 * cin_isfuncdecl returns FALSE then.
7518 */
7519 if (terminated == ',')
7520 break;
7521
7522 /* if it es a enum declaration or an assignment,
7523 * we are done.
7524 */
7525 if (terminated != ';' && cin_isinit())
7526 break;
7527
7528 /* nothing useful found */
7529 if (terminated == 0 || terminated == '{')
7530 continue;
7531 }
7532
7533 if (terminated != ';')
7534 {
7535 /* Skip parens and braces. Position the cursor
7536 * over the rightmost paren, so that matching it
7537 * will take us back to the start of the line.
7538 */ /* XXX */
7539 trypos = NULL;
7540 if (find_last_paren(l, '(', ')'))
7541 trypos = find_match_paren(ind_maxparen,
7542 ind_maxcomment);
7543
7544 if (trypos == NULL && find_last_paren(l, '{', '}'))
7545 trypos = find_start_brace(ind_maxcomment);
7546
7547 if (trypos != NULL)
7548 {
7549 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007550 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007551 continue;
7552 }
7553 }
7554
7555 /* it's a variable declaration, add indentation
7556 * like in
7557 * int a,
7558 * b;
7559 */
7560 if (cont_amount > 0)
7561 amount = cont_amount;
7562 else
7563 amount += ind_continuation;
7564 }
7565 else if (lookfor == LOOKFOR_UNTERM)
7566 {
7567 if (cont_amount > 0)
7568 amount = cont_amount;
7569 else
7570 amount += ind_continuation;
7571 }
Bram Moolenaare79d1532011-10-04 18:03:47 +02007572 else
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007573 {
Bram Moolenaare79d1532011-10-04 18:03:47 +02007574 if (lookfor != LOOKFOR_TERM
Bram Moolenaar071d4272004-06-13 20:20:40 +00007575 && lookfor != LOOKFOR_CPP_BASECLASS)
Bram Moolenaare79d1532011-10-04 18:03:47 +02007576 {
7577 amount = scope_amount;
7578 if (theline[0] == '{')
7579 {
7580 amount += ind_open_extra;
7581 added_to_amount = ind_open_extra;
7582 }
7583 }
7584
7585 if (lookfor_cpp_namespace)
7586 {
7587 /*
7588 * Looking for C++ namespace, need to look further
7589 * back.
7590 */
7591 if (curwin->w_cursor.lnum == ourscope)
7592 continue;
7593
7594 if (curwin->w_cursor.lnum == 0
7595 || curwin->w_cursor.lnum
7596 < ourscope - FIND_NAMESPACE_LIM)
7597 break;
7598
7599 l = ml_get_curline();
7600
7601 /* If we're in a comment now, skip to the start of
7602 * the comment. */
7603 trypos = find_start_comment(ind_maxcomment);
7604 if (trypos != NULL)
7605 {
7606 curwin->w_cursor.lnum = trypos->lnum + 1;
7607 curwin->w_cursor.col = 0;
7608 continue;
7609 }
7610
7611 /* Skip preprocessor directives and blank lines. */
7612 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7613 continue;
7614
7615 /* Finally the actual check for "namespace". */
7616 if (cin_is_cpp_namespace(l))
7617 {
7618 amount += ind_cpp_namespace - added_to_amount;
7619 break;
7620 }
7621
7622 if (cin_nocode(l))
7623 continue;
7624 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007625 }
7626 break;
7627 }
7628
7629 /*
7630 * If we're in a comment now, skip to the start of the comment.
7631 */ /* XXX */
7632 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
7633 {
7634 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007635 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007636 continue;
7637 }
7638
7639 l = ml_get_curline();
7640
7641 /*
7642 * If this is a switch() label, may line up relative to that.
Bram Moolenaar18144c82006-04-12 21:52:12 +00007643 * If this is a C++ scope declaration, do the same.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007644 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007645 iscase = cin_iscase(l, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007646 if (iscase || cin_isscopedecl(l))
7647 {
7648 /* we are only looking for cpp base class
7649 * declaration/initialization any longer */
7650 if (lookfor == LOOKFOR_CPP_BASECLASS)
7651 break;
7652
7653 /* When looking for a "do" we are not interested in
7654 * labels. */
7655 if (whilelevel > 0)
7656 continue;
7657
7658 /*
7659 * case xx:
7660 * c = 99 + <- this indent plus continuation
7661 *-> here;
7662 */
7663 if (lookfor == LOOKFOR_UNTERM
7664 || lookfor == LOOKFOR_ENUM_OR_INIT)
7665 {
7666 if (cont_amount > 0)
7667 amount = cont_amount;
7668 else
7669 amount += ind_continuation;
7670 break;
7671 }
7672
7673 /*
7674 * case xx: <- line up with this case
7675 * x = 333;
7676 * case yy:
7677 */
7678 if ( (iscase && lookfor == LOOKFOR_CASE)
7679 || (iscase && lookfor_break)
7680 || (!iscase && lookfor == LOOKFOR_SCOPEDECL))
7681 {
7682 /*
7683 * Check that this case label is not for another
7684 * switch()
7685 */ /* XXX */
7686 if ((trypos = find_start_brace(ind_maxcomment)) ==
7687 NULL || trypos->lnum == ourscope)
7688 {
7689 amount = get_indent(); /* XXX */
7690 break;
7691 }
7692 continue;
7693 }
7694
7695 n = get_indent_nolabel(curwin->w_cursor.lnum); /* XXX */
7696
7697 /*
7698 * case xx: if (cond) <- line up with this if
7699 * y = y + 1;
7700 * -> s = 99;
7701 *
7702 * case xx:
7703 * if (cond) <- line up with this line
7704 * y = y + 1;
7705 * -> s = 99;
7706 */
7707 if (lookfor == LOOKFOR_TERM)
7708 {
7709 if (n)
7710 amount = n;
7711
7712 if (!lookfor_break)
7713 break;
7714 }
7715
7716 /*
7717 * case xx: x = x + 1; <- line up with this x
7718 * -> y = y + 1;
7719 *
7720 * case xx: if (cond) <- line up with this if
7721 * -> y = y + 1;
7722 */
7723 if (n)
7724 {
7725 amount = n;
7726 l = after_label(ml_get_curline());
7727 if (l != NULL && cin_is_cinword(l))
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007728 {
7729 if (theline[0] == '{')
7730 amount += ind_open_extra;
7731 else
7732 amount += ind_level + ind_no_brace;
7733 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007734 break;
7735 }
7736
7737 /*
7738 * Try to get the indent of a statement before the switch
7739 * label. If nothing is found, line up relative to the
7740 * switch label.
7741 * break; <- may line up with this line
7742 * case xx:
7743 * -> y = 1;
7744 */
7745 scope_amount = get_indent() + (iscase /* XXX */
7746 ? ind_case_code : ind_scopedecl_code);
7747 lookfor = ind_case_break ? LOOKFOR_NOBREAK : LOOKFOR_ANY;
7748 continue;
7749 }
7750
7751 /*
7752 * Looking for a switch() label or C++ scope declaration,
7753 * ignore other lines, skip {}-blocks.
7754 */
7755 if (lookfor == LOOKFOR_CASE || lookfor == LOOKFOR_SCOPEDECL)
7756 {
7757 if (find_last_paren(l, '{', '}') && (trypos =
7758 find_start_brace(ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007759 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007760 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007761 curwin->w_cursor.col = 0;
7762 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007763 continue;
7764 }
7765
7766 /*
7767 * Ignore jump labels with nothing after them.
7768 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007769 if (!ind_js && cin_islabel(ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007770 {
7771 l = after_label(ml_get_curline());
7772 if (l == NULL || cin_nocode(l))
7773 continue;
7774 }
7775
7776 /*
7777 * Ignore #defines, #if, etc.
7778 * Ignore comment and empty lines.
7779 * (need to get the line again, cin_islabel() may have
7780 * unlocked it)
7781 */
7782 l = ml_get_curline();
7783 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum)
7784 || cin_nocode(l))
7785 continue;
7786
7787 /*
7788 * Are we at the start of a cpp base class declaration or
7789 * constructor initialization?
7790 */ /* XXX */
Bram Moolenaar18144c82006-04-12 21:52:12 +00007791 n = FALSE;
7792 if (lookfor != LOOKFOR_TERM && ind_cpp_baseclass > 0)
7793 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00007794 n = cin_is_cpp_baseclass(&col);
Bram Moolenaar18144c82006-04-12 21:52:12 +00007795 l = ml_get_curline();
7796 }
7797 if (n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007798 {
7799 if (lookfor == LOOKFOR_UNTERM)
7800 {
7801 if (cont_amount > 0)
7802 amount = cont_amount;
7803 else
7804 amount += ind_continuation;
7805 }
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007806 else if (theline[0] == '{')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007807 {
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007808 /* Need to find start of the declaration. */
7809 lookfor = LOOKFOR_UNTERM;
7810 ind_continuation = 0;
7811 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007812 }
7813 else
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007814 /* XXX */
7815 amount = get_baseclass_amount(col, ind_maxparen,
7816 ind_maxcomment, ind_cpp_baseclass);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007817 break;
7818 }
7819 else if (lookfor == LOOKFOR_CPP_BASECLASS)
7820 {
7821 /* only look, whether there is a cpp base class
Bram Moolenaar18144c82006-04-12 21:52:12 +00007822 * declaration or initialization before the opening brace.
7823 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007824 if (cin_isterminated(l, TRUE, FALSE))
7825 break;
7826 else
7827 continue;
7828 }
7829
7830 /*
7831 * What happens next depends on the line being terminated.
7832 * If terminated with a ',' only consider it terminating if
Bram Moolenaar25394022007-05-10 19:06:20 +00007833 * there is another unterminated statement behind, eg:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007834 * 123,
7835 * sizeof
7836 * here
7837 * Otherwise check whether it is a enumeration or structure
7838 * initialisation (not indented) or a variable declaration
7839 * (indented).
7840 */
7841 terminated = cin_isterminated(l, FALSE, TRUE);
7842
7843 if (terminated == 0 || (lookfor != LOOKFOR_UNTERM
7844 && terminated == ','))
7845 {
7846 /*
7847 * if we're in the middle of a paren thing,
7848 * go back to the line that starts it so
7849 * we can get the right prevailing indent
7850 * if ( foo &&
7851 * bar )
7852 */
7853 /*
7854 * position the cursor over the rightmost paren, so that
7855 * matching it will take us back to the start of the line.
7856 */
7857 (void)find_last_paren(l, '(', ')');
7858 trypos = find_match_paren(
7859 corr_ind_maxparen(ind_maxparen, &cur_curpos),
7860 ind_maxcomment);
7861
7862 /*
7863 * If we are looking for ',', we also look for matching
7864 * braces.
7865 */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007866 if (trypos == NULL && terminated == ','
7867 && find_last_paren(l, '{', '}'))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007868 trypos = find_start_brace(ind_maxcomment);
7869
7870 if (trypos != NULL)
7871 {
7872 /*
7873 * Check if we are on a case label now. This is
7874 * handled above.
7875 * case xx: if ( asdf &&
7876 * asdf)
7877 */
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007878 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007879 l = ml_get_curline();
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007880 if (cin_iscase(l, FALSE) || cin_isscopedecl(l))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007881 {
7882 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007883 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007884 continue;
7885 }
7886 }
7887
7888 /*
7889 * Skip over continuation lines to find the one to get the
7890 * indent from
7891 * char *usethis = "bla\
7892 * bla",
7893 * here;
7894 */
7895 if (terminated == ',')
7896 {
7897 while (curwin->w_cursor.lnum > 1)
7898 {
7899 l = ml_get(curwin->w_cursor.lnum - 1);
7900 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
7901 break;
7902 --curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007903 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007904 }
7905 }
7906
7907 /*
7908 * Get indent and pointer to text for current line,
7909 * ignoring any jump label. XXX
7910 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007911 if (!ind_js)
7912 cur_amount = skip_label(curwin->w_cursor.lnum,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007913 &l, ind_maxcomment);
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007914 else
7915 cur_amount = get_indent();
Bram Moolenaar071d4272004-06-13 20:20:40 +00007916 /*
7917 * If this is just above the line we are indenting, and it
7918 * starts with a '{', line it up with this line.
7919 * while (not)
7920 * -> {
7921 * }
7922 */
7923 if (terminated != ',' && lookfor != LOOKFOR_TERM
7924 && theline[0] == '{')
7925 {
7926 amount = cur_amount;
7927 /*
7928 * Only add ind_open_extra when the current line
7929 * doesn't start with a '{', which must have a match
7930 * in the same line (scope is the same). Probably:
7931 * { 1, 2 },
7932 * -> { 3, 4 }
7933 */
7934 if (*skipwhite(l) != '{')
7935 amount += ind_open_extra;
7936
7937 if (ind_cpp_baseclass)
7938 {
7939 /* have to look back, whether it is a cpp base
7940 * class declaration or initialization */
7941 lookfor = LOOKFOR_CPP_BASECLASS;
7942 continue;
7943 }
7944 break;
7945 }
7946
7947 /*
7948 * Check if we are after an "if", "while", etc.
7949 * Also allow " } else".
7950 */
7951 if (cin_is_cinword(l) || cin_iselse(skipwhite(l)))
7952 {
7953 /*
7954 * Found an unterminated line after an if (), line up
7955 * with the last one.
7956 * if (cond)
7957 * 100 +
7958 * -> here;
7959 */
7960 if (lookfor == LOOKFOR_UNTERM
7961 || lookfor == LOOKFOR_ENUM_OR_INIT)
7962 {
7963 if (cont_amount > 0)
7964 amount = cont_amount;
7965 else
7966 amount += ind_continuation;
7967 break;
7968 }
7969
7970 /*
7971 * If this is just above the line we are indenting, we
7972 * are finished.
7973 * while (not)
7974 * -> here;
7975 * Otherwise this indent can be used when the line
7976 * before this is terminated.
7977 * yyy;
7978 * if (stat)
7979 * while (not)
7980 * xxx;
7981 * -> here;
7982 */
7983 amount = cur_amount;
7984 if (theline[0] == '{')
7985 amount += ind_open_extra;
7986 if (lookfor != LOOKFOR_TERM)
7987 {
7988 amount += ind_level + ind_no_brace;
7989 break;
7990 }
7991
7992 /*
7993 * Special trick: when expecting the while () after a
7994 * do, line up with the while()
7995 * do
7996 * x = 1;
7997 * -> here
7998 */
7999 l = skipwhite(ml_get_curline());
8000 if (cin_isdo(l))
8001 {
8002 if (whilelevel == 0)
8003 break;
8004 --whilelevel;
8005 }
8006
8007 /*
8008 * When searching for a terminated line, don't use the
Bram Moolenaar334adf02011-05-25 13:34:04 +02008009 * one between the "if" and the matching "else".
Bram Moolenaar071d4272004-06-13 20:20:40 +00008010 * Need to use the scope of this "else". XXX
8011 * If whilelevel != 0 continue looking for a "do {".
8012 */
Bram Moolenaar334adf02011-05-25 13:34:04 +02008013 if (cin_iselse(l) && whilelevel == 0)
8014 {
8015 /* If we're looking at "} else", let's make sure we
8016 * find the opening brace of the enclosing scope,
8017 * not the one from "if () {". */
8018 if (*l == '}')
8019 curwin->w_cursor.col =
Bram Moolenaar9b83c2f2011-05-25 17:29:44 +02008020 (colnr_T)(l - ml_get_curline()) + 1;
Bram Moolenaar334adf02011-05-25 13:34:04 +02008021
8022 if ((trypos = find_start_brace(ind_maxcomment))
8023 == NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00008024 || find_match(LOOKFOR_IF, trypos->lnum,
Bram Moolenaar334adf02011-05-25 13:34:04 +02008025 ind_maxparen, ind_maxcomment) == FAIL)
8026 break;
8027 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008028 }
8029
8030 /*
8031 * If we're below an unterminated line that is not an
8032 * "if" or something, we may line up with this line or
Bram Moolenaar25394022007-05-10 19:06:20 +00008033 * add something for a continuation line, depending on
Bram Moolenaar071d4272004-06-13 20:20:40 +00008034 * the line before this one.
8035 */
8036 else
8037 {
8038 /*
8039 * Found two unterminated lines on a row, line up with
8040 * the last one.
8041 * c = 99 +
8042 * 100 +
8043 * -> here;
8044 */
8045 if (lookfor == LOOKFOR_UNTERM)
8046 {
8047 /* When line ends in a comma add extra indent */
8048 if (terminated == ',')
8049 amount += ind_continuation;
8050 break;
8051 }
8052
8053 if (lookfor == LOOKFOR_ENUM_OR_INIT)
8054 {
8055 /* Found two lines ending in ',', lineup with the
8056 * lowest one, but check for cpp base class
8057 * declaration/initialization, if it is an
8058 * opening brace or we are looking just for
8059 * enumerations/initializations. */
8060 if (terminated == ',')
8061 {
8062 if (ind_cpp_baseclass == 0)
8063 break;
8064
8065 lookfor = LOOKFOR_CPP_BASECLASS;
8066 continue;
8067 }
8068
8069 /* Ignore unterminated lines in between, but
8070 * reduce indent. */
8071 if (amount > cur_amount)
8072 amount = cur_amount;
8073 }
8074 else
8075 {
8076 /*
8077 * Found first unterminated line on a row, may
8078 * line up with this line, remember its indent
8079 * 100 +
8080 * -> here;
8081 */
8082 amount = cur_amount;
8083
8084 /*
8085 * If previous line ends in ',', check whether we
8086 * are in an initialization or enum
8087 * struct xxx =
8088 * {
8089 * sizeof a,
8090 * 124 };
8091 * or a normal possible continuation line.
8092 * but only, of no other statement has been found
8093 * yet.
8094 */
8095 if (lookfor == LOOKFOR_INITIAL && terminated == ',')
8096 {
8097 lookfor = LOOKFOR_ENUM_OR_INIT;
8098 cont_amount = cin_first_id_amount();
8099 }
8100 else
8101 {
8102 if (lookfor == LOOKFOR_INITIAL
8103 && *l != NUL
8104 && l[STRLEN(l) - 1] == '\\')
8105 /* XXX */
8106 cont_amount = cin_get_equal_amount(
8107 curwin->w_cursor.lnum);
8108 if (lookfor != LOOKFOR_TERM)
8109 lookfor = LOOKFOR_UNTERM;
8110 }
8111 }
8112 }
8113 }
8114
8115 /*
8116 * Check if we are after a while (cond);
8117 * If so: Ignore until the matching "do".
8118 */
8119 /* XXX */
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00008120 else if (cin_iswhileofdo_end(terminated, ind_maxparen,
8121 ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008122 {
8123 /*
8124 * Found an unterminated line after a while ();, line up
8125 * with the last one.
8126 * while (cond);
8127 * 100 + <- line up with this one
8128 * -> here;
8129 */
8130 if (lookfor == LOOKFOR_UNTERM
8131 || lookfor == LOOKFOR_ENUM_OR_INIT)
8132 {
8133 if (cont_amount > 0)
8134 amount = cont_amount;
8135 else
8136 amount += ind_continuation;
8137 break;
8138 }
8139
8140 if (whilelevel == 0)
8141 {
8142 lookfor = LOOKFOR_TERM;
8143 amount = get_indent(); /* XXX */
8144 if (theline[0] == '{')
8145 amount += ind_open_extra;
8146 }
8147 ++whilelevel;
8148 }
8149
8150 /*
8151 * We are after a "normal" statement.
8152 * If we had another statement we can stop now and use the
8153 * indent of that other statement.
8154 * Otherwise the indent of the current statement may be used,
8155 * search backwards for the next "normal" statement.
8156 */
8157 else
8158 {
8159 /*
8160 * Skip single break line, if before a switch label. It
8161 * may be lined up with the case label.
8162 */
8163 if (lookfor == LOOKFOR_NOBREAK
8164 && cin_isbreak(skipwhite(ml_get_curline())))
8165 {
8166 lookfor = LOOKFOR_ANY;
8167 continue;
8168 }
8169
8170 /*
8171 * Handle "do {" line.
8172 */
8173 if (whilelevel > 0)
8174 {
8175 l = cin_skipcomment(ml_get_curline());
8176 if (cin_isdo(l))
8177 {
8178 amount = get_indent(); /* XXX */
8179 --whilelevel;
8180 continue;
8181 }
8182 }
8183
8184 /*
8185 * Found a terminated line above an unterminated line. Add
8186 * the amount for a continuation line.
8187 * x = 1;
8188 * y = foo +
8189 * -> here;
8190 * or
8191 * int x = 1;
8192 * int foo,
8193 * -> here;
8194 */
8195 if (lookfor == LOOKFOR_UNTERM
8196 || lookfor == LOOKFOR_ENUM_OR_INIT)
8197 {
8198 if (cont_amount > 0)
8199 amount = cont_amount;
8200 else
8201 amount += ind_continuation;
8202 break;
8203 }
8204
8205 /*
8206 * Found a terminated line above a terminated line or "if"
8207 * etc. line. Use the amount of the line below us.
8208 * x = 1; x = 1;
8209 * if (asdf) y = 2;
8210 * while (asdf) ->here;
8211 * here;
8212 * ->foo;
8213 */
8214 if (lookfor == LOOKFOR_TERM)
8215 {
8216 if (!lookfor_break && whilelevel == 0)
8217 break;
8218 }
8219
8220 /*
8221 * First line above the one we're indenting is terminated.
8222 * To know what needs to be done look further backward for
8223 * a terminated line.
8224 */
8225 else
8226 {
8227 /*
8228 * position the cursor over the rightmost paren, so
8229 * that matching it will take us back to the start of
8230 * the line. Helps for:
8231 * func(asdr,
8232 * asdfasdf);
8233 * here;
8234 */
8235term_again:
8236 l = ml_get_curline();
8237 if (find_last_paren(l, '(', ')')
8238 && (trypos = find_match_paren(ind_maxparen,
8239 ind_maxcomment)) != NULL)
8240 {
8241 /*
8242 * Check if we are on a case label now. This is
8243 * handled above.
8244 * case xx: if ( asdf &&
8245 * asdf)
8246 */
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008247 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008248 l = ml_get_curline();
Bram Moolenaar3acfc302010-07-11 17:23:02 +02008249 if (cin_iscase(l, FALSE) || cin_isscopedecl(l))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008250 {
8251 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008252 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008253 continue;
8254 }
8255 }
8256
8257 /* When aligning with the case statement, don't align
8258 * with a statement after it.
8259 * case 1: { <-- don't use this { position
8260 * stat;
8261 * }
8262 * case 2:
8263 * stat;
8264 * }
8265 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02008266 iscase = (ind_keep_case_label && cin_iscase(l, FALSE));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008267
8268 /*
8269 * Get indent and pointer to text for current line,
8270 * ignoring any jump label.
8271 */
8272 amount = skip_label(curwin->w_cursor.lnum,
8273 &l, ind_maxcomment);
8274
8275 if (theline[0] == '{')
8276 amount += ind_open_extra;
8277 /* See remark above: "Only add ind_open_extra.." */
Bram Moolenaar18144c82006-04-12 21:52:12 +00008278 l = skipwhite(l);
8279 if (*l == '{')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008280 amount -= ind_open_extra;
8281 lookfor = iscase ? LOOKFOR_ANY : LOOKFOR_TERM;
8282
8283 /*
Bram Moolenaar18144c82006-04-12 21:52:12 +00008284 * When a terminated line starts with "else" skip to
8285 * the matching "if":
8286 * else 3;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008287 * indent this;
Bram Moolenaar18144c82006-04-12 21:52:12 +00008288 * Need to use the scope of this "else". XXX
8289 * If whilelevel != 0 continue looking for a "do {".
8290 */
8291 if (lookfor == LOOKFOR_TERM
8292 && *l != '}'
8293 && cin_iselse(l)
8294 && whilelevel == 0)
8295 {
8296 if ((trypos = find_start_brace(ind_maxcomment))
8297 == NULL
8298 || find_match(LOOKFOR_IF, trypos->lnum,
8299 ind_maxparen, ind_maxcomment) == FAIL)
8300 break;
8301 continue;
8302 }
8303
8304 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008305 * If we're at the end of a block, skip to the start of
8306 * that block.
8307 */
Bram Moolenaar6d8f9c62011-11-30 13:03:28 +01008308 l = ml_get_curline();
Bram Moolenaar50f42ca2011-07-15 14:12:30 +02008309 if (find_last_paren(l, '{', '}')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008310 && (trypos = find_start_brace(ind_maxcomment))
8311 != NULL) /* XXX */
8312 {
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008313 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008314 /* if not "else {" check for terminated again */
8315 /* but skip block for "} else {" */
8316 l = cin_skipcomment(ml_get_curline());
8317 if (*l == '}' || !cin_iselse(l))
8318 goto term_again;
8319 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008320 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008321 }
8322 }
8323 }
8324 }
8325 }
8326 }
8327
8328 /* add extra indent for a comment */
8329 if (cin_iscomment(theline))
8330 amount += ind_comment;
Bram Moolenaar02c707a2010-07-17 17:12:06 +02008331
8332 /* subtract extra left-shift for jump labels */
8333 if (ind_jump_label > 0 && original_line_islabel)
8334 amount -= ind_jump_label;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008335 }
8336
8337 /*
8338 * ok -- we're not inside any sort of structure at all!
8339 *
8340 * this means we're at the top level, and everything should
8341 * basically just match where the previous line is, except
8342 * for the lines immediately following a function declaration,
8343 * which are K&R-style parameters and need to be indented.
8344 */
8345 else
8346 {
8347 /*
8348 * if our line starts with an open brace, forget about any
8349 * prevailing indent and make sure it looks like the start
8350 * of a function
8351 */
8352
8353 if (theline[0] == '{')
8354 {
8355 amount = ind_first_open;
8356 }
8357
8358 /*
8359 * If the NEXT line is a function declaration, the current
8360 * line needs to be indented as a function type spec.
Bram Moolenaar1a89bbe2010-03-02 12:38:22 +01008361 * Don't do this if the current line looks like a comment or if the
8362 * current line is terminated, ie. ends in ';', or if the current line
8363 * contains { or }: "void f() {\n if (1)"
Bram Moolenaar071d4272004-06-13 20:20:40 +00008364 */
8365 else if (cur_curpos.lnum < curbuf->b_ml.ml_line_count
8366 && !cin_nocode(theline)
Bram Moolenaar1a89bbe2010-03-02 12:38:22 +01008367 && vim_strchr(theline, '{') == NULL
8368 && vim_strchr(theline, '}') == NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00008369 && !cin_ends_in(theline, (char_u *)":", NULL)
8370 && !cin_ends_in(theline, (char_u *)",", NULL)
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008371 && cin_isfuncdecl(NULL, cur_curpos.lnum + 1,
8372 cur_curpos.lnum + 1,
8373 ind_maxparen, ind_maxcomment)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008374 && !cin_isterminated(theline, FALSE, TRUE))
8375 {
8376 amount = ind_func_type;
8377 }
8378 else
8379 {
8380 amount = 0;
8381 curwin->w_cursor = cur_curpos;
8382
8383 /* search backwards until we find something we recognize */
8384
8385 while (curwin->w_cursor.lnum > 1)
8386 {
8387 curwin->w_cursor.lnum--;
8388 curwin->w_cursor.col = 0;
8389
8390 l = ml_get_curline();
8391
8392 /*
8393 * If we're in a comment now, skip to the start of the comment.
8394 */ /* XXX */
8395 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
8396 {
8397 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008398 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008399 continue;
8400 }
8401
8402 /*
Bram Moolenaar18144c82006-04-12 21:52:12 +00008403 * Are we at the start of a cpp base class declaration or
8404 * constructor initialization?
Bram Moolenaar071d4272004-06-13 20:20:40 +00008405 */ /* XXX */
Bram Moolenaar18144c82006-04-12 21:52:12 +00008406 n = FALSE;
8407 if (ind_cpp_baseclass != 0 && theline[0] != '{')
8408 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00008409 n = cin_is_cpp_baseclass(&col);
Bram Moolenaar18144c82006-04-12 21:52:12 +00008410 l = ml_get_curline();
8411 }
8412 if (n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008413 {
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00008414 /* XXX */
8415 amount = get_baseclass_amount(col, ind_maxparen,
8416 ind_maxcomment, ind_cpp_baseclass);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008417 break;
8418 }
8419
8420 /*
8421 * Skip preprocessor directives and blank lines.
8422 */
8423 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
8424 continue;
8425
8426 if (cin_nocode(l))
8427 continue;
8428
8429 /*
8430 * If the previous line ends in ',', use one level of
8431 * indentation:
8432 * int foo,
8433 * bar;
8434 * do this before checking for '}' in case of eg.
8435 * enum foobar
8436 * {
8437 * ...
8438 * } foo,
8439 * bar;
8440 */
8441 n = 0;
8442 if (cin_ends_in(l, (char_u *)",", NULL)
8443 || (*l != NUL && (n = l[STRLEN(l) - 1]) == '\\'))
8444 {
8445 /* take us back to opening paren */
8446 if (find_last_paren(l, '(', ')')
8447 && (trypos = find_match_paren(ind_maxparen,
8448 ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008449 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008450
8451 /* For a line ending in ',' that is a continuation line go
8452 * back to the first line with a backslash:
8453 * char *foo = "bla\
8454 * bla",
8455 * here;
8456 */
8457 while (n == 0 && curwin->w_cursor.lnum > 1)
8458 {
8459 l = ml_get(curwin->w_cursor.lnum - 1);
8460 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
8461 break;
8462 --curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008463 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008464 }
8465
8466 amount = get_indent(); /* XXX */
8467
8468 if (amount == 0)
8469 amount = cin_first_id_amount();
8470 if (amount == 0)
8471 amount = ind_continuation;
8472 break;
8473 }
8474
8475 /*
8476 * If the line looks like a function declaration, and we're
8477 * not in a comment, put it the left margin.
8478 */
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008479 if (cin_isfuncdecl(NULL, cur_curpos.lnum, 0,
8480 ind_maxparen, ind_maxcomment)) /* XXX */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008481 break;
8482 l = ml_get_curline();
8483
8484 /*
8485 * Finding the closing '}' of a previous function. Put
8486 * current line at the left margin. For when 'cino' has "fs".
8487 */
8488 if (*skipwhite(l) == '}')
8489 break;
8490
8491 /* (matching {)
8492 * If the previous line ends on '};' (maybe followed by
8493 * comments) align at column 0. For example:
8494 * char *string_array[] = { "foo",
8495 * / * x * / "b};ar" }; / * foobar * /
8496 */
8497 if (cin_ends_in(l, (char_u *)"};", NULL))
8498 break;
8499
8500 /*
Bram Moolenaar3388bb42011-11-30 17:20:23 +01008501 * Find a line only has a semicolon that belongs to a previous
8502 * line ending in '}', e.g. before an #endif. Don't increase
8503 * indent then.
8504 */
8505 if (*(look = skipwhite(l)) == ';' && cin_nocode(look + 1))
8506 {
8507 pos_T curpos_save = curwin->w_cursor;
8508
8509 while (curwin->w_cursor.lnum > 1)
8510 {
8511 look = ml_get(--curwin->w_cursor.lnum);
8512 if (!(cin_nocode(look) || cin_ispreproc_cont(
8513 &look, &curwin->w_cursor.lnum)))
8514 break;
8515 }
8516 if (curwin->w_cursor.lnum > 0
8517 && cin_ends_in(look, (char_u *)"}", NULL))
8518 break;
8519
8520 curwin->w_cursor = curpos_save;
8521 }
8522
8523 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008524 * If the PREVIOUS line is a function declaration, the current
8525 * line (and the ones that follow) needs to be indented as
8526 * parameters.
8527 */
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008528 if (cin_isfuncdecl(&l, curwin->w_cursor.lnum, 0,
8529 ind_maxparen, ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008530 {
8531 amount = ind_param;
8532 break;
8533 }
8534
8535 /*
8536 * If the previous line ends in ';' and the line before the
8537 * previous line ends in ',' or '\', ident to column zero:
8538 * int foo,
8539 * bar;
8540 * indent_to_0 here;
8541 */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00008542 if (cin_ends_in(l, (char_u *)";", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008543 {
8544 l = ml_get(curwin->w_cursor.lnum - 1);
8545 if (cin_ends_in(l, (char_u *)",", NULL)
8546 || (*l != NUL && l[STRLEN(l) - 1] == '\\'))
8547 break;
8548 l = ml_get_curline();
8549 }
8550
8551 /*
8552 * Doesn't look like anything interesting -- so just
8553 * use the indent of this line.
8554 *
8555 * Position the cursor over the rightmost paren, so that
8556 * matching it will take us back to the start of the line.
8557 */
8558 find_last_paren(l, '(', ')');
8559
8560 if ((trypos = find_match_paren(ind_maxparen,
8561 ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008562 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008563 amount = get_indent(); /* XXX */
8564 break;
8565 }
8566
8567 /* add extra indent for a comment */
8568 if (cin_iscomment(theline))
8569 amount += ind_comment;
8570
8571 /* add extra indent if the previous line ended in a backslash:
8572 * "asdfasdf\
8573 * here";
8574 * char *foo = "asdf\
8575 * here";
8576 */
8577 if (cur_curpos.lnum > 1)
8578 {
8579 l = ml_get(cur_curpos.lnum - 1);
8580 if (*l != NUL && l[STRLEN(l) - 1] == '\\')
8581 {
8582 cur_amount = cin_get_equal_amount(cur_curpos.lnum - 1);
8583 if (cur_amount > 0)
8584 amount = cur_amount;
8585 else if (cur_amount == 0)
8586 amount += ind_continuation;
8587 }
8588 }
8589 }
8590 }
8591
8592theend:
8593 /* put the cursor back where it belongs */
8594 curwin->w_cursor = cur_curpos;
8595
8596 vim_free(linecopy);
8597
8598 if (amount < 0)
8599 return 0;
8600 return amount;
8601}
8602
8603 static int
8604find_match(lookfor, ourscope, ind_maxparen, ind_maxcomment)
8605 int lookfor;
8606 linenr_T ourscope;
8607 int ind_maxparen;
8608 int ind_maxcomment;
8609{
8610 char_u *look;
8611 pos_T *theirscope;
8612 char_u *mightbeif;
8613 int elselevel;
8614 int whilelevel;
8615
8616 if (lookfor == LOOKFOR_IF)
8617 {
8618 elselevel = 1;
8619 whilelevel = 0;
8620 }
8621 else
8622 {
8623 elselevel = 0;
8624 whilelevel = 1;
8625 }
8626
8627 curwin->w_cursor.col = 0;
8628
8629 while (curwin->w_cursor.lnum > ourscope + 1)
8630 {
8631 curwin->w_cursor.lnum--;
8632 curwin->w_cursor.col = 0;
8633
8634 look = cin_skipcomment(ml_get_curline());
8635 if (cin_iselse(look)
8636 || cin_isif(look)
8637 || cin_isdo(look) /* XXX */
8638 || cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
8639 {
8640 /*
8641 * if we've gone outside the braces entirely,
8642 * we must be out of scope...
8643 */
8644 theirscope = find_start_brace(ind_maxcomment); /* XXX */
8645 if (theirscope == NULL)
8646 break;
8647
8648 /*
8649 * and if the brace enclosing this is further
8650 * back than the one enclosing the else, we're
8651 * out of luck too.
8652 */
8653 if (theirscope->lnum < ourscope)
8654 break;
8655
8656 /*
8657 * and if they're enclosed in a *deeper* brace,
8658 * then we can ignore it because it's in a
8659 * different scope...
8660 */
8661 if (theirscope->lnum > ourscope)
8662 continue;
8663
8664 /*
8665 * if it was an "else" (that's not an "else if")
8666 * then we need to go back to another if, so
8667 * increment elselevel
8668 */
8669 look = cin_skipcomment(ml_get_curline());
8670 if (cin_iselse(look))
8671 {
8672 mightbeif = cin_skipcomment(look + 4);
8673 if (!cin_isif(mightbeif))
8674 ++elselevel;
8675 continue;
8676 }
8677
8678 /*
8679 * if it was a "while" then we need to go back to
8680 * another "do", so increment whilelevel. XXX
8681 */
8682 if (cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
8683 {
8684 ++whilelevel;
8685 continue;
8686 }
8687
8688 /* If it's an "if" decrement elselevel */
8689 look = cin_skipcomment(ml_get_curline());
8690 if (cin_isif(look))
8691 {
8692 elselevel--;
8693 /*
8694 * When looking for an "if" ignore "while"s that
8695 * get in the way.
8696 */
8697 if (elselevel == 0 && lookfor == LOOKFOR_IF)
8698 whilelevel = 0;
8699 }
8700
8701 /* If it's a "do" decrement whilelevel */
8702 if (cin_isdo(look))
8703 whilelevel--;
8704
8705 /*
8706 * if we've used up all the elses, then
8707 * this must be the if that we want!
8708 * match the indent level of that if.
8709 */
8710 if (elselevel <= 0 && whilelevel <= 0)
8711 {
8712 return OK;
8713 }
8714 }
8715 }
8716 return FAIL;
8717}
8718
8719# if defined(FEAT_EVAL) || defined(PROTO)
8720/*
8721 * Get indent level from 'indentexpr'.
8722 */
8723 int
8724get_expr_indent()
8725{
8726 int indent;
8727 pos_T pos;
8728 int save_State;
Bram Moolenaard1f56e62006-02-22 21:25:37 +00008729 int use_sandbox = was_set_insecurely((char_u *)"indentexpr",
8730 OPT_LOCAL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008731
8732 pos = curwin->w_cursor;
8733 set_vim_var_nr(VV_LNUM, curwin->w_cursor.lnum);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00008734 if (use_sandbox)
8735 ++sandbox;
8736 ++textlock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008737 indent = eval_to_number(curbuf->b_p_inde);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00008738 if (use_sandbox)
8739 --sandbox;
8740 --textlock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008741
8742 /* Restore the cursor position so that 'indentexpr' doesn't need to.
8743 * Pretend to be in Insert mode, allow cursor past end of line for "o"
8744 * command. */
8745 save_State = State;
8746 State = INSERT;
8747 curwin->w_cursor = pos;
8748 check_cursor();
8749 State = save_State;
8750
8751 /* If there is an error, just keep the current indent. */
8752 if (indent < 0)
8753 indent = get_indent();
8754
8755 return indent;
8756}
8757# endif
8758
8759#endif /* FEAT_CINDENT */
8760
8761#if defined(FEAT_LISP) || defined(PROTO)
8762
8763static int lisp_match __ARGS((char_u *p));
8764
8765 static int
8766lisp_match(p)
8767 char_u *p;
8768{
8769 char_u buf[LSIZE];
8770 int len;
8771 char_u *word = p_lispwords;
8772
8773 while (*word != NUL)
8774 {
8775 (void)copy_option_part(&word, buf, LSIZE, ",");
8776 len = (int)STRLEN(buf);
8777 if (STRNCMP(buf, p, len) == 0 && p[len] == ' ')
8778 return TRUE;
8779 }
8780 return FALSE;
8781}
8782
8783/*
8784 * When 'p' is present in 'cpoptions, a Vi compatible method is used.
8785 * The incompatible newer method is quite a bit better at indenting
8786 * code in lisp-like languages than the traditional one; it's still
8787 * mostly heuristics however -- Dirk van Deun, dirk@rave.org
8788 *
8789 * TODO:
8790 * Findmatch() should be adapted for lisp, also to make showmatch
8791 * work correctly: now (v5.3) it seems all C/C++ oriented:
8792 * - it does not recognize the #\( and #\) notations as character literals
8793 * - it doesn't know about comments starting with a semicolon
8794 * - it incorrectly interprets '(' as a character literal
8795 * All this messes up get_lisp_indent in some rare cases.
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008796 * Update from Sergey Khorev:
8797 * I tried to fix the first two issues.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008798 */
8799 int
8800get_lisp_indent()
8801{
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008802 pos_T *pos, realpos, paren;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008803 int amount;
8804 char_u *that;
8805 colnr_T col;
8806 colnr_T firsttry;
8807 int parencount, quotecount;
8808 int vi_lisp;
8809
8810 /* Set vi_lisp to use the vi-compatible method */
8811 vi_lisp = (vim_strchr(p_cpo, CPO_LISP) != NULL);
8812
8813 realpos = curwin->w_cursor;
8814 curwin->w_cursor.col = 0;
8815
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008816 if ((pos = findmatch(NULL, '(')) == NULL)
8817 pos = findmatch(NULL, '[');
8818 else
8819 {
8820 paren = *pos;
8821 pos = findmatch(NULL, '[');
8822 if (pos == NULL || ltp(pos, &paren))
8823 pos = &paren;
8824 }
8825 if (pos != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008826 {
8827 /* Extra trick: Take the indent of the first previous non-white
8828 * line that is at the same () level. */
8829 amount = -1;
8830 parencount = 0;
8831
8832 while (--curwin->w_cursor.lnum >= pos->lnum)
8833 {
8834 if (linewhite(curwin->w_cursor.lnum))
8835 continue;
8836 for (that = ml_get_curline(); *that != NUL; ++that)
8837 {
8838 if (*that == ';')
8839 {
8840 while (*(that + 1) != NUL)
8841 ++that;
8842 continue;
8843 }
8844 if (*that == '\\')
8845 {
8846 if (*(that + 1) != NUL)
8847 ++that;
8848 continue;
8849 }
8850 if (*that == '"' && *(that + 1) != NUL)
8851 {
Bram Moolenaar15ff6c12006-09-15 18:18:09 +00008852 while (*++that && *that != '"')
8853 {
8854 /* skipping escaped characters in the string */
8855 if (*that == '\\')
8856 {
8857 if (*++that == NUL)
8858 break;
8859 if (that[1] == NUL)
8860 {
8861 ++that;
8862 break;
8863 }
8864 }
8865 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008866 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008867 if (*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008868 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008869 else if (*that == ')' || *that == ']')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008870 --parencount;
8871 }
8872 if (parencount == 0)
8873 {
8874 amount = get_indent();
8875 break;
8876 }
8877 }
8878
8879 if (amount == -1)
8880 {
8881 curwin->w_cursor.lnum = pos->lnum;
8882 curwin->w_cursor.col = pos->col;
8883 col = pos->col;
8884
8885 that = ml_get_curline();
8886
8887 if (vi_lisp && get_indent() == 0)
8888 amount = 2;
8889 else
8890 {
8891 amount = 0;
8892 while (*that && col)
8893 {
8894 amount += lbr_chartabsize_adv(&that, (colnr_T)amount);
8895 col--;
8896 }
8897
8898 /*
8899 * Some keywords require "body" indenting rules (the
8900 * non-standard-lisp ones are Scheme special forms):
8901 *
8902 * (let ((a 1)) instead (let ((a 1))
8903 * (...)) of (...))
8904 */
8905
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008906 if (!vi_lisp && (*that == '(' || *that == '[')
8907 && lisp_match(that + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008908 amount += 2;
8909 else
8910 {
8911 that++;
8912 amount++;
8913 firsttry = amount;
8914
8915 while (vim_iswhite(*that))
8916 {
8917 amount += lbr_chartabsize(that, (colnr_T)amount);
8918 ++that;
8919 }
8920
8921 if (*that && *that != ';') /* not a comment line */
8922 {
Bram Moolenaare21877a2008-02-13 09:58:14 +00008923 /* test *that != '(' to accommodate first let/do
Bram Moolenaar071d4272004-06-13 20:20:40 +00008924 * argument if it is more than one line */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008925 if (!vi_lisp && *that != '(' && *that != '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008926 firsttry++;
8927
8928 parencount = 0;
8929 quotecount = 0;
8930
8931 if (vi_lisp
8932 || (*that != '"'
8933 && *that != '\''
8934 && *that != '#'
8935 && (*that < '0' || *that > '9')))
8936 {
8937 while (*that
8938 && (!vim_iswhite(*that)
8939 || quotecount
8940 || parencount)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008941 && (!((*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008942 && !quotecount
8943 && !parencount
8944 && vi_lisp)))
8945 {
8946 if (*that == '"')
8947 quotecount = !quotecount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008948 if ((*that == '(' || *that == '[')
8949 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008950 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008951 if ((*that == ')' || *that == ']')
8952 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008953 --parencount;
8954 if (*that == '\\' && *(that+1) != NUL)
8955 amount += lbr_chartabsize_adv(&that,
8956 (colnr_T)amount);
8957 amount += lbr_chartabsize_adv(&that,
8958 (colnr_T)amount);
8959 }
8960 }
8961 while (vim_iswhite(*that))
8962 {
8963 amount += lbr_chartabsize(that, (colnr_T)amount);
8964 that++;
8965 }
8966 if (!*that || *that == ';')
8967 amount = firsttry;
8968 }
8969 }
8970 }
8971 }
8972 }
8973 else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008974 amount = 0; /* no matching '(' or '[' found, use zero indent */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008975
8976 curwin->w_cursor = realpos;
8977
8978 return amount;
8979}
8980#endif /* FEAT_LISP */
8981
8982 void
8983prepare_to_exit()
8984{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00008985#if defined(SIGHUP) && defined(SIG_IGN)
8986 /* Ignore SIGHUP, because a dropped connection causes a read error, which
8987 * makes Vim exit and then handling SIGHUP causes various reentrance
8988 * problems. */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00008989 signal(SIGHUP, SIG_IGN);
8990#endif
8991
Bram Moolenaar071d4272004-06-13 20:20:40 +00008992#ifdef FEAT_GUI
8993 if (gui.in_use)
8994 {
8995 gui.dying = TRUE;
8996 out_trash(); /* trash any pending output */
8997 }
8998 else
8999#endif
9000 {
9001 windgoto((int)Rows - 1, 0);
9002
9003 /*
9004 * Switch terminal mode back now, so messages end up on the "normal"
9005 * screen (if there are two screens).
9006 */
9007 settmode(TMODE_COOK);
9008#ifdef WIN3264
9009 if (can_end_termcap_mode(FALSE) == TRUE)
9010#endif
9011 stoptermcap();
9012 out_flush();
9013 }
9014}
9015
9016/*
9017 * Preserve files and exit.
9018 * When called IObuff must contain a message.
9019 */
9020 void
9021preserve_exit()
9022{
9023 buf_T *buf;
9024
9025 prepare_to_exit();
9026
Bram Moolenaar4770d092006-01-12 23:22:24 +00009027 /* Setting this will prevent free() calls. That avoids calling free()
9028 * recursively when free() was invoked with a bad pointer. */
9029 really_exiting = TRUE;
9030
Bram Moolenaar071d4272004-06-13 20:20:40 +00009031 out_str(IObuff);
9032 screen_start(); /* don't know where cursor is now */
9033 out_flush();
9034
9035 ml_close_notmod(); /* close all not-modified buffers */
9036
9037 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
9038 {
9039 if (buf->b_ml.ml_mfp != NULL && buf->b_ml.ml_mfp->mf_fname != NULL)
9040 {
9041 OUT_STR(_("Vim: preserving files...\n"));
9042 screen_start(); /* don't know where cursor is now */
9043 out_flush();
9044 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
9045 break;
9046 }
9047 }
9048
9049 ml_close_all(FALSE); /* close all memfiles, without deleting */
9050
9051 OUT_STR(_("Vim: Finished.\n"));
9052
9053 getout(1);
9054}
9055
9056/*
9057 * return TRUE if "fname" exists.
9058 */
9059 int
9060vim_fexists(fname)
9061 char_u *fname;
9062{
9063 struct stat st;
9064
9065 if (mch_stat((char *)fname, &st))
9066 return FALSE;
9067 return TRUE;
9068}
9069
9070/*
9071 * Check for CTRL-C pressed, but only once in a while.
9072 * Should be used instead of ui_breakcheck() for functions that check for
9073 * each line in the file. Calling ui_breakcheck() each time takes too much
9074 * time, because it can be a system call.
9075 */
9076
9077#ifndef BREAKCHECK_SKIP
9078# ifdef FEAT_GUI /* assume the GUI only runs on fast computers */
9079# define BREAKCHECK_SKIP 200
9080# else
9081# define BREAKCHECK_SKIP 32
9082# endif
9083#endif
9084
9085static int breakcheck_count = 0;
9086
9087 void
9088line_breakcheck()
9089{
9090 if (++breakcheck_count >= BREAKCHECK_SKIP)
9091 {
9092 breakcheck_count = 0;
9093 ui_breakcheck();
9094 }
9095}
9096
9097/*
9098 * Like line_breakcheck() but check 10 times less often.
9099 */
9100 void
9101fast_breakcheck()
9102{
9103 if (++breakcheck_count >= BREAKCHECK_SKIP * 10)
9104 {
9105 breakcheck_count = 0;
9106 ui_breakcheck();
9107 }
9108}
9109
9110/*
Bram Moolenaard7834d32009-12-02 16:14:36 +00009111 * Invoke expand_wildcards() for one pattern.
9112 * Expand items like "%:h" before the expansion.
9113 * Returns OK or FAIL.
9114 */
9115 int
9116expand_wildcards_eval(pat, num_file, file, flags)
9117 char_u **pat; /* pointer to input pattern */
9118 int *num_file; /* resulting number of files */
9119 char_u ***file; /* array of resulting files */
9120 int flags; /* EW_DIR, etc. */
9121{
9122 int ret = FAIL;
9123 char_u *eval_pat = NULL;
9124 char_u *exp_pat = *pat;
9125 char_u *ignored_msg;
9126 int usedlen;
9127
9128 if (*exp_pat == '%' || *exp_pat == '#' || *exp_pat == '<')
9129 {
9130 ++emsg_off;
9131 eval_pat = eval_vars(exp_pat, exp_pat, &usedlen,
9132 NULL, &ignored_msg, NULL);
9133 --emsg_off;
9134 if (eval_pat != NULL)
9135 exp_pat = concat_str(eval_pat, exp_pat + usedlen);
9136 }
9137
9138 if (exp_pat != NULL)
9139 ret = expand_wildcards(1, &exp_pat, num_file, file, flags);
9140
9141 if (eval_pat != NULL)
9142 {
9143 vim_free(exp_pat);
9144 vim_free(eval_pat);
9145 }
9146
9147 return ret;
9148}
9149
9150/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00009151 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching
9152 * 'wildignore'.
Bram Moolenaar9e193ac2010-07-19 23:11:27 +02009153 * Returns OK or FAIL. When FAIL then "num_file" won't be set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009154 */
9155 int
9156expand_wildcards(num_pat, pat, num_file, file, flags)
9157 int num_pat; /* number of input patterns */
9158 char_u **pat; /* array of input patterns */
9159 int *num_file; /* resulting number of files */
9160 char_u ***file; /* array of resulting files */
9161 int flags; /* EW_DIR, etc. */
9162{
9163 int retval;
9164 int i, j;
9165 char_u *p;
9166 int non_suf_match; /* number without matching suffix */
9167
9168 retval = gen_expand_wildcards(num_pat, pat, num_file, file, flags);
9169
9170 /* When keeping all matches, return here */
Bram Moolenaar9e193ac2010-07-19 23:11:27 +02009171 if ((flags & EW_KEEPALL) || retval == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009172 return retval;
9173
9174#ifdef FEAT_WILDIGN
9175 /*
9176 * Remove names that match 'wildignore'.
9177 */
9178 if (*p_wig)
9179 {
9180 char_u *ffname;
9181
9182 /* check all files in (*file)[] */
9183 for (i = 0; i < *num_file; ++i)
9184 {
9185 ffname = FullName_save((*file)[i], FALSE);
9186 if (ffname == NULL) /* out of memory */
9187 break;
9188# ifdef VMS
9189 vms_remove_version(ffname);
9190# endif
9191 if (match_file_list(p_wig, (*file)[i], ffname))
9192 {
9193 /* remove this matching file from the list */
9194 vim_free((*file)[i]);
9195 for (j = i; j + 1 < *num_file; ++j)
9196 (*file)[j] = (*file)[j + 1];
9197 --*num_file;
9198 --i;
9199 }
9200 vim_free(ffname);
9201 }
9202 }
9203#endif
9204
9205 /*
9206 * Move the names where 'suffixes' match to the end.
9207 */
9208 if (*num_file > 1)
9209 {
9210 non_suf_match = 0;
9211 for (i = 0; i < *num_file; ++i)
9212 {
9213 if (!match_suffix((*file)[i]))
9214 {
9215 /*
9216 * Move the name without matching suffix to the front
9217 * of the list.
9218 */
9219 p = (*file)[i];
9220 for (j = i; j > non_suf_match; --j)
9221 (*file)[j] = (*file)[j - 1];
9222 (*file)[non_suf_match++] = p;
9223 }
9224 }
9225 }
9226
9227 return retval;
9228}
9229
9230/*
9231 * Return TRUE if "fname" matches with an entry in 'suffixes'.
9232 */
9233 int
9234match_suffix(fname)
9235 char_u *fname;
9236{
9237 int fnamelen, setsuflen;
9238 char_u *setsuf;
9239#define MAXSUFLEN 30 /* maximum length of a file suffix */
9240 char_u suf_buf[MAXSUFLEN];
9241
9242 fnamelen = (int)STRLEN(fname);
9243 setsuflen = 0;
9244 for (setsuf = p_su; *setsuf; )
9245 {
9246 setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
Bram Moolenaar055a2ba2009-07-14 19:40:21 +00009247 if (setsuflen == 0)
9248 {
9249 char_u *tail = gettail(fname);
9250
9251 /* empty entry: match name without a '.' */
9252 if (vim_strchr(tail, '.') == NULL)
9253 {
9254 setsuflen = 1;
9255 break;
9256 }
9257 }
9258 else
9259 {
9260 if (fnamelen >= setsuflen
9261 && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
9262 (size_t)setsuflen) == 0)
9263 break;
9264 setsuflen = 0;
9265 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009266 }
9267 return (setsuflen != 0);
9268}
9269
9270#if !defined(NO_EXPANDPATH) || defined(PROTO)
9271
9272# ifdef VIM_BACKTICK
9273static int vim_backtick __ARGS((char_u *p));
9274static int expand_backtick __ARGS((garray_T *gap, char_u *pat, int flags));
9275# endif
9276
9277# if defined(MSDOS) || defined(FEAT_GUI_W16) || defined(WIN3264)
9278/*
9279 * File name expansion code for MS-DOS, Win16 and Win32. It's here because
9280 * it's shared between these systems.
9281 */
9282# if defined(DJGPP) || defined(PROTO)
9283# define _cdecl /* DJGPP doesn't have this */
9284# else
9285# ifdef __BORLANDC__
9286# define _cdecl _RTLENTRYF
9287# endif
9288# endif
9289
9290/*
9291 * comparison function for qsort in dos_expandpath()
9292 */
9293 static int _cdecl
9294pstrcmp(const void *a, const void *b)
9295{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00009296 return (pathcmp(*(char **)a, *(char **)b, -1));
Bram Moolenaar071d4272004-06-13 20:20:40 +00009297}
9298
9299# ifndef WIN3264
9300 static void
9301namelowcpy(
9302 char_u *d,
9303 char_u *s)
9304{
9305# ifdef DJGPP
9306 if (USE_LONG_FNAME) /* don't lower case on Windows 95/NT systems */
9307 while (*s)
9308 *d++ = *s++;
9309 else
9310# endif
9311 while (*s)
9312 *d++ = TOLOWER_LOC(*s++);
9313 *d = NUL;
9314}
9315# endif
9316
9317/*
Bram Moolenaar231334e2005-07-25 20:46:57 +00009318 * Recursively expand one path component into all matching files and/or
9319 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009320 * Return the number of matches found.
9321 * "path" has backslashes before chars that are not to be expanded, starting
9322 * at "path[wildoff]".
Bram Moolenaar231334e2005-07-25 20:46:57 +00009323 * Return the number of matches found.
9324 * NOTE: much of this is identical to unix_expandpath(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00009325 */
9326 static int
9327dos_expandpath(
9328 garray_T *gap,
9329 char_u *path,
9330 int wildoff,
Bram Moolenaar231334e2005-07-25 20:46:57 +00009331 int flags, /* EW_* flags */
Bram Moolenaar25394022007-05-10 19:06:20 +00009332 int didstar) /* expanded "**" once already */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009333{
Bram Moolenaar231334e2005-07-25 20:46:57 +00009334 char_u *buf;
9335 char_u *path_end;
9336 char_u *p, *s, *e;
9337 int start_len = gap->ga_len;
9338 char_u *pat;
9339 regmatch_T regmatch;
9340 int starts_with_dot;
9341 int matches;
9342 int len;
9343 int starstar = FALSE;
9344 static int stardepth = 0; /* depth for "**" expansion */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009345#ifdef WIN3264
9346 WIN32_FIND_DATA fb;
9347 HANDLE hFind = (HANDLE)0;
9348# ifdef FEAT_MBYTE
9349 WIN32_FIND_DATAW wfb;
9350 WCHAR *wn = NULL; /* UCS-2 name, NULL when not used. */
9351# endif
9352#else
9353 struct ffblk fb;
9354#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009355 char_u *matchname;
Bram Moolenaar231334e2005-07-25 20:46:57 +00009356 int ok;
9357
9358 /* Expanding "**" may take a long time, check for CTRL-C. */
9359 if (stardepth > 0)
9360 {
9361 ui_breakcheck();
9362 if (got_int)
9363 return 0;
9364 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009365
9366 /* make room for file name */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009367 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009368 if (buf == NULL)
9369 return 0;
9370
9371 /*
9372 * Find the first part in the path name that contains a wildcard or a ~1.
9373 * Copy it into buf, including the preceding characters.
9374 */
9375 p = buf;
9376 s = buf;
9377 e = NULL;
9378 path_end = path;
9379 while (*path_end != NUL)
9380 {
9381 /* May ignore a wildcard that has a backslash before it; it will
9382 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
9383 if (path_end >= path + wildoff && rem_backslash(path_end))
9384 *p++ = *path_end++;
9385 else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
9386 {
9387 if (e != NULL)
9388 break;
9389 s = p + 1;
9390 }
9391 else if (path_end >= path + wildoff
9392 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
9393 e = p;
9394#ifdef FEAT_MBYTE
9395 if (has_mbyte)
9396 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00009397 len = (*mb_ptr2len)(path_end);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009398 STRNCPY(p, path_end, len);
9399 p += len;
9400 path_end += len;
9401 }
9402 else
9403#endif
9404 *p++ = *path_end++;
9405 }
9406 e = p;
9407 *e = NUL;
9408
9409 /* now we have one wildcard component between s and e */
9410 /* Remove backslashes between "wildoff" and the start of the wildcard
9411 * component. */
9412 for (p = buf + wildoff; p < s; ++p)
9413 if (rem_backslash(p))
9414 {
Bram Moolenaar8c8de832008-06-24 22:58:06 +00009415 STRMOVE(p, p + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009416 --e;
9417 --s;
9418 }
9419
Bram Moolenaar231334e2005-07-25 20:46:57 +00009420 /* Check for "**" between "s" and "e". */
9421 for (p = s; p < e; ++p)
9422 if (p[0] == '*' && p[1] == '*')
9423 starstar = TRUE;
9424
Bram Moolenaar071d4272004-06-13 20:20:40 +00009425 starts_with_dot = (*s == '.');
9426 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
9427 if (pat == NULL)
9428 {
9429 vim_free(buf);
9430 return 0;
9431 }
9432
9433 /* compile the regexp into a program */
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009434 if (flags & (EW_NOERROR | EW_NOTWILD))
Bram Moolenaarb5609832011-07-20 15:04:58 +02009435 ++emsg_silent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009436 regmatch.rm_ic = TRUE; /* Always ignore case */
9437 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009438 if (flags & (EW_NOERROR | EW_NOTWILD))
Bram Moolenaarb5609832011-07-20 15:04:58 +02009439 --emsg_silent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009440 vim_free(pat);
9441
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009442 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009443 {
9444 vim_free(buf);
9445 return 0;
9446 }
9447
9448 /* remember the pattern or file name being looked for */
9449 matchname = vim_strsave(s);
9450
Bram Moolenaar231334e2005-07-25 20:46:57 +00009451 /* If "**" is by itself, this is the first time we encounter it and more
9452 * is following then find matches without any directory. */
9453 if (!didstar && stardepth < 100 && starstar && e - s == 2
9454 && *path_end == '/')
9455 {
9456 STRCPY(s, path_end + 1);
9457 ++stardepth;
9458 (void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
9459 --stardepth;
9460 }
9461
Bram Moolenaar071d4272004-06-13 20:20:40 +00009462 /* Scan all files in the directory with "dir/ *.*" */
9463 STRCPY(s, "*.*");
9464#ifdef WIN3264
9465# ifdef FEAT_MBYTE
9466 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
9467 {
9468 /* The active codepage differs from 'encoding'. Attempt using the
9469 * wide function. If it fails because it is not implemented fall back
9470 * to the non-wide version (for Windows 98) */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009471 wn = enc_to_utf16(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009472 if (wn != NULL)
9473 {
9474 hFind = FindFirstFileW(wn, &wfb);
9475 if (hFind == INVALID_HANDLE_VALUE
9476 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
9477 {
9478 vim_free(wn);
9479 wn = NULL;
9480 }
9481 }
9482 }
9483
9484 if (wn == NULL)
9485# endif
9486 hFind = FindFirstFile(buf, &fb);
9487 ok = (hFind != INVALID_HANDLE_VALUE);
9488#else
9489 /* If we are expanding wildcards we try both files and directories */
9490 ok = (findfirst((char *)buf, &fb,
9491 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
9492#endif
9493
9494 while (ok)
9495 {
9496#ifdef WIN3264
9497# ifdef FEAT_MBYTE
9498 if (wn != NULL)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009499 p = utf16_to_enc(wfb.cFileName, NULL); /* p is allocated here */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009500 else
9501# endif
9502 p = (char_u *)fb.cFileName;
9503#else
9504 p = (char_u *)fb.ff_name;
9505#endif
9506 /* Ignore entries starting with a dot, unless when asked for. Accept
9507 * all entries found with "matchname". */
9508 if ((p[0] != '.' || starts_with_dot)
9509 && (matchname == NULL
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009510 || (regmatch.regprog != NULL
9511 && vim_regexec(&regmatch, p, (colnr_T)0))
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009512 || ((flags & EW_NOTWILD)
9513 && fnamencmp(path + (s - buf), p, e - s) == 0)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009514 {
9515#ifdef WIN3264
9516 STRCPY(s, p);
9517#else
9518 namelowcpy(s, p);
9519#endif
9520 len = (int)STRLEN(buf);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009521
9522 if (starstar && stardepth < 100)
9523 {
9524 /* For "**" in the pattern first go deeper in the tree to
9525 * find matches. */
9526 STRCPY(buf + len, "/**");
9527 STRCPY(buf + len + 3, path_end);
9528 ++stardepth;
9529 (void)dos_expandpath(gap, buf, len + 1, flags, TRUE);
9530 --stardepth;
9531 }
9532
Bram Moolenaar071d4272004-06-13 20:20:40 +00009533 STRCPY(buf + len, path_end);
9534 if (mch_has_exp_wildcard(path_end))
9535 {
9536 /* need to expand another component of the path */
9537 /* remove backslashes for the remaining components only */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009538 (void)dos_expandpath(gap, buf, len + 1, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009539 }
9540 else
9541 {
9542 /* no more wildcards, check if there is a match */
9543 /* remove backslashes for the remaining components only */
9544 if (*path_end != 0)
9545 backslash_halve(buf + len + 1);
9546 if (mch_getperm(buf) >= 0) /* add existing file */
9547 addfile(gap, buf, flags);
9548 }
9549 }
9550
9551#ifdef WIN3264
9552# ifdef FEAT_MBYTE
9553 if (wn != NULL)
9554 {
9555 vim_free(p);
9556 ok = FindNextFileW(hFind, &wfb);
9557 }
9558 else
9559# endif
9560 ok = FindNextFile(hFind, &fb);
9561#else
9562 ok = (findnext(&fb) == 0);
9563#endif
9564
9565 /* If no more matches and no match was used, try expanding the name
9566 * itself. Finds the long name of a short filename. */
9567 if (!ok && matchname != NULL && gap->ga_len == start_len)
9568 {
9569 STRCPY(s, matchname);
9570#ifdef WIN3264
9571 FindClose(hFind);
9572# ifdef FEAT_MBYTE
9573 if (wn != NULL)
9574 {
9575 vim_free(wn);
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009576 wn = enc_to_utf16(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009577 if (wn != NULL)
9578 hFind = FindFirstFileW(wn, &wfb);
9579 }
9580 if (wn == NULL)
9581# endif
9582 hFind = FindFirstFile(buf, &fb);
9583 ok = (hFind != INVALID_HANDLE_VALUE);
9584#else
9585 ok = (findfirst((char *)buf, &fb,
9586 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
9587#endif
9588 vim_free(matchname);
9589 matchname = NULL;
9590 }
9591 }
9592
9593#ifdef WIN3264
9594 FindClose(hFind);
9595# ifdef FEAT_MBYTE
9596 vim_free(wn);
9597# endif
9598#endif
9599 vim_free(buf);
9600 vim_free(regmatch.regprog);
9601 vim_free(matchname);
9602
9603 matches = gap->ga_len - start_len;
9604 if (matches > 0)
9605 qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
9606 sizeof(char_u *), pstrcmp);
9607 return matches;
9608}
9609
9610 int
9611mch_expandpath(
9612 garray_T *gap,
9613 char_u *path,
9614 int flags) /* EW_* flags */
9615{
Bram Moolenaar231334e2005-07-25 20:46:57 +00009616 return dos_expandpath(gap, path, 0, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009617}
9618# endif /* MSDOS || FEAT_GUI_W16 || WIN3264 */
9619
Bram Moolenaar231334e2005-07-25 20:46:57 +00009620#if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
9621 || defined(PROTO)
9622/*
9623 * Unix style wildcard expansion code.
9624 * It's here because it's used both for Unix and Mac.
9625 */
9626static int pstrcmp __ARGS((const void *, const void *));
9627
9628 static int
9629pstrcmp(a, b)
9630 const void *a, *b;
9631{
9632 return (pathcmp(*(char **)a, *(char **)b, -1));
9633}
9634
9635/*
9636 * Recursively expand one path component into all matching files and/or
9637 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
9638 * "path" has backslashes before chars that are not to be expanded, starting
9639 * at "path + wildoff".
9640 * Return the number of matches found.
9641 * NOTE: much of this is identical to dos_expandpath(), keep in sync!
9642 */
9643 int
9644unix_expandpath(gap, path, wildoff, flags, didstar)
9645 garray_T *gap;
9646 char_u *path;
9647 int wildoff;
9648 int flags; /* EW_* flags */
9649 int didstar; /* expanded "**" once already */
9650{
9651 char_u *buf;
9652 char_u *path_end;
9653 char_u *p, *s, *e;
9654 int start_len = gap->ga_len;
9655 char_u *pat;
9656 regmatch_T regmatch;
9657 int starts_with_dot;
9658 int matches;
9659 int len;
9660 int starstar = FALSE;
9661 static int stardepth = 0; /* depth for "**" expansion */
9662
9663 DIR *dirp;
9664 struct dirent *dp;
9665
9666 /* Expanding "**" may take a long time, check for CTRL-C. */
9667 if (stardepth > 0)
9668 {
9669 ui_breakcheck();
9670 if (got_int)
9671 return 0;
9672 }
9673
9674 /* make room for file name */
9675 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
9676 if (buf == NULL)
9677 return 0;
9678
9679 /*
9680 * Find the first part in the path name that contains a wildcard.
Bram Moolenaar2d0b92f2012-04-30 21:09:43 +02009681 * When EW_ICASE is set every letter is considered to be a wildcard.
Bram Moolenaar231334e2005-07-25 20:46:57 +00009682 * Copy it into "buf", including the preceding characters.
9683 */
9684 p = buf;
9685 s = buf;
9686 e = NULL;
9687 path_end = path;
9688 while (*path_end != NUL)
9689 {
9690 /* May ignore a wildcard that has a backslash before it; it will
9691 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
9692 if (path_end >= path + wildoff && rem_backslash(path_end))
9693 *p++ = *path_end++;
9694 else if (*path_end == '/')
9695 {
9696 if (e != NULL)
9697 break;
9698 s = p + 1;
9699 }
9700 else if (path_end >= path + wildoff
Bram Moolenaar2d0b92f2012-04-30 21:09:43 +02009701 && (vim_strchr((char_u *)"*?[{~$", *path_end) != NULL
9702#ifndef CASE_INSENSITIVE_FILENAME
9703 || ((flags & EW_ICASE)
9704 && isalpha(PTR2CHAR(path_end)))
9705#endif
9706 ))
Bram Moolenaar231334e2005-07-25 20:46:57 +00009707 e = p;
9708#ifdef FEAT_MBYTE
9709 if (has_mbyte)
9710 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00009711 len = (*mb_ptr2len)(path_end);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009712 STRNCPY(p, path_end, len);
9713 p += len;
9714 path_end += len;
9715 }
9716 else
9717#endif
9718 *p++ = *path_end++;
9719 }
9720 e = p;
9721 *e = NUL;
9722
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009723 /* Now we have one wildcard component between "s" and "e". */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009724 /* Remove backslashes between "wildoff" and the start of the wildcard
9725 * component. */
9726 for (p = buf + wildoff; p < s; ++p)
9727 if (rem_backslash(p))
9728 {
Bram Moolenaar8c8de832008-06-24 22:58:06 +00009729 STRMOVE(p, p + 1);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009730 --e;
9731 --s;
9732 }
9733
9734 /* Check for "**" between "s" and "e". */
9735 for (p = s; p < e; ++p)
9736 if (p[0] == '*' && p[1] == '*')
9737 starstar = TRUE;
9738
9739 /* convert the file pattern to a regexp pattern */
9740 starts_with_dot = (*s == '.');
9741 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
9742 if (pat == NULL)
9743 {
9744 vim_free(buf);
9745 return 0;
9746 }
9747
9748 /* compile the regexp into a program */
Bram Moolenaarcc016f52005-12-10 20:23:46 +00009749#ifdef CASE_INSENSITIVE_FILENAME
Bram Moolenaar231334e2005-07-25 20:46:57 +00009750 regmatch.rm_ic = TRUE; /* Behave like Terminal.app */
9751#else
Bram Moolenaar94950a92010-12-02 16:01:29 +01009752 if (flags & EW_ICASE)
9753 regmatch.rm_ic = TRUE; /* 'wildignorecase' set */
9754 else
9755 regmatch.rm_ic = FALSE; /* Don't ignore case */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009756#endif
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009757 if (flags & (EW_NOERROR | EW_NOTWILD))
9758 ++emsg_silent;
Bram Moolenaar231334e2005-07-25 20:46:57 +00009759 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009760 if (flags & (EW_NOERROR | EW_NOTWILD))
9761 --emsg_silent;
Bram Moolenaar231334e2005-07-25 20:46:57 +00009762 vim_free(pat);
9763
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009764 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
Bram Moolenaar231334e2005-07-25 20:46:57 +00009765 {
9766 vim_free(buf);
9767 return 0;
9768 }
9769
9770 /* If "**" is by itself, this is the first time we encounter it and more
9771 * is following then find matches without any directory. */
9772 if (!didstar && stardepth < 100 && starstar && e - s == 2
9773 && *path_end == '/')
9774 {
9775 STRCPY(s, path_end + 1);
9776 ++stardepth;
9777 (void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
9778 --stardepth;
9779 }
9780
9781 /* open the directory for scanning */
9782 *s = NUL;
9783 dirp = opendir(*buf == NUL ? "." : (char *)buf);
9784
9785 /* Find all matching entries */
9786 if (dirp != NULL)
9787 {
9788 for (;;)
9789 {
9790 dp = readdir(dirp);
9791 if (dp == NULL)
9792 break;
9793 if ((dp->d_name[0] != '.' || starts_with_dot)
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009794 && ((regmatch.regprog != NULL && vim_regexec(&regmatch,
9795 (char_u *)dp->d_name, (colnr_T)0))
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009796 || ((flags & EW_NOTWILD)
9797 && fnamencmp(path + (s - buf), dp->d_name, e - s) == 0)))
Bram Moolenaar231334e2005-07-25 20:46:57 +00009798 {
9799 STRCPY(s, dp->d_name);
9800 len = STRLEN(buf);
9801
9802 if (starstar && stardepth < 100)
9803 {
9804 /* For "**" in the pattern first go deeper in the tree to
9805 * find matches. */
9806 STRCPY(buf + len, "/**");
9807 STRCPY(buf + len + 3, path_end);
9808 ++stardepth;
9809 (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
9810 --stardepth;
9811 }
9812
9813 STRCPY(buf + len, path_end);
9814 if (mch_has_exp_wildcard(path_end)) /* handle more wildcards */
9815 {
9816 /* need to expand another component of the path */
9817 /* remove backslashes for the remaining components only */
9818 (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
9819 }
9820 else
9821 {
9822 /* no more wildcards, check if there is a match */
9823 /* remove backslashes for the remaining components only */
9824 if (*path_end != NUL)
9825 backslash_halve(buf + len + 1);
9826 if (mch_getperm(buf) >= 0) /* add existing file */
9827 {
Bram Moolenaar95e9b492006-03-15 23:04:43 +00009828#ifdef MACOS_CONVERT
Bram Moolenaar231334e2005-07-25 20:46:57 +00009829 size_t precomp_len = STRLEN(buf)+1;
9830 char_u *precomp_buf =
9831 mac_precompose_path(buf, precomp_len, &precomp_len);
Bram Moolenaar95e9b492006-03-15 23:04:43 +00009832
Bram Moolenaar231334e2005-07-25 20:46:57 +00009833 if (precomp_buf)
9834 {
9835 mch_memmove(buf, precomp_buf, precomp_len);
9836 vim_free(precomp_buf);
9837 }
9838#endif
9839 addfile(gap, buf, flags);
9840 }
9841 }
9842 }
9843 }
9844
9845 closedir(dirp);
9846 }
9847
9848 vim_free(buf);
9849 vim_free(regmatch.regprog);
9850
9851 matches = gap->ga_len - start_len;
9852 if (matches > 0)
9853 qsort(((char_u **)gap->ga_data) + start_len, matches,
9854 sizeof(char_u *), pstrcmp);
9855 return matches;
9856}
9857#endif
9858
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009859#if defined(FEAT_SEARCHPATH)
9860static int find_previous_pathsep __ARGS((char_u *path, char_u **psep));
9861static int is_unique __ARGS((char_u *maybe_unique, garray_T *gap, int i));
Bram Moolenaar162bd912010-07-28 22:29:10 +02009862static void expand_path_option __ARGS((char_u *curdir, garray_T *gap));
9863static char_u *get_path_cutoff __ARGS((char_u *fname, garray_T *gap));
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009864static void uniquefy_paths __ARGS((garray_T *gap, char_u *pattern));
9865static int expand_in_path __ARGS((garray_T *gap, char_u *pattern, int flags));
9866
9867/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009868 * Moves "*psep" back to the previous path separator in "path".
9869 * Returns FAIL is "*psep" ends up at the beginning of "path".
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009870 */
9871 static int
9872find_previous_pathsep(path, psep)
9873 char_u *path;
9874 char_u **psep;
9875{
9876 /* skip the current separator */
9877 if (*psep > path && vim_ispathsep(**psep))
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009878 --*psep;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009879
9880 /* find the previous separator */
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009881 while (*psep > path)
9882 {
9883 if (vim_ispathsep(**psep))
9884 return OK;
9885 mb_ptr_back(path, *psep);
9886 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009887
9888 return FAIL;
9889}
9890
9891/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009892 * Returns TRUE if "maybe_unique" is unique wrt other_paths in "gap".
9893 * "maybe_unique" is the end portion of "((char_u **)gap->ga_data)[i]".
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009894 */
9895 static int
9896is_unique(maybe_unique, gap, i)
9897 char_u *maybe_unique;
9898 garray_T *gap;
9899 int i;
9900{
9901 int j;
9902 int candidate_len;
9903 int other_path_len;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009904 char_u **other_paths = (char_u **)gap->ga_data;
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009905 char_u *rival;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009906
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009907 for (j = 0; j < gap->ga_len; j++)
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009908 {
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009909 if (j == i)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009910 continue; /* don't compare it with itself */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009911
Bram Moolenaar624c7aa2010-07-16 20:38:52 +02009912 candidate_len = (int)STRLEN(maybe_unique);
9913 other_path_len = (int)STRLEN(other_paths[j]);
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009914 if (other_path_len < candidate_len)
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009915 continue; /* it's different when it's shorter */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009916
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009917 rival = other_paths[j] + other_path_len - candidate_len;
Bram Moolenaarda9836c2010-08-16 21:53:27 +02009918 if (fnamecmp(maybe_unique, rival) == 0
9919 && (rival == other_paths[j] || vim_ispathsep(*(rival - 1))))
Bram Moolenaar162bd912010-07-28 22:29:10 +02009920 return FALSE; /* match */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009921 }
9922
Bram Moolenaar162bd912010-07-28 22:29:10 +02009923 return TRUE; /* no match found */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009924}
9925
9926/*
Bram Moolenaar1a509df2010-08-01 17:59:57 +02009927 * Split the 'path' option into an array of strings in garray_T. Relative
Bram Moolenaar162bd912010-07-28 22:29:10 +02009928 * paths are expanded to their equivalent fullpath. This includes the "."
9929 * (relative to current buffer directory) and empty path (relative to current
9930 * directory) notations.
9931 *
9932 * TODO: handle upward search (;) and path limiter (**N) notations by
9933 * expanding each into their equivalent path(s).
9934 */
9935 static void
9936expand_path_option(curdir, gap)
9937 char_u *curdir;
9938 garray_T *gap;
9939{
9940 char_u *path_option = *curbuf->b_p_path == NUL
9941 ? p_path : curbuf->b_p_path;
9942 char_u *buf;
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009943 char_u *p;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009944 int len;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009945
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +02009946 if ((buf = alloc((int)MAXPATHL)) == NULL)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009947 return;
9948
9949 while (*path_option != NUL)
9950 {
9951 copy_option_part(&path_option, buf, MAXPATHL, " ,");
9952
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009953 if (buf[0] == '.' && (buf[1] == NUL || vim_ispathsep(buf[1])))
Bram Moolenaar162bd912010-07-28 22:29:10 +02009954 {
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009955 /* Relative to current buffer:
9956 * "/path/file" + "." -> "/path/"
9957 * "/path/file" + "./subdir" -> "/path/subdir" */
Bram Moolenaar162bd912010-07-28 22:29:10 +02009958 if (curbuf->b_ffname == NULL)
9959 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009960 p = gettail(curbuf->b_ffname);
9961 len = (int)(p - curbuf->b_ffname);
9962 if (len + (int)STRLEN(buf) >= MAXPATHL)
9963 continue;
9964 if (buf[1] == NUL)
9965 buf[len] = NUL;
9966 else
9967 STRMOVE(buf + len, buf + 2);
9968 mch_memmove(buf, curbuf->b_ffname, len);
9969 simplify_filename(buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009970 }
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009971 else if (buf[0] == NUL)
9972 /* relative to current directory */
Bram Moolenaar162bd912010-07-28 22:29:10 +02009973 STRCPY(buf, curdir);
Bram Moolenaar84f888a2010-08-05 21:40:16 +02009974 else if (path_with_url(buf))
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009975 /* URL can't be used here */
Bram Moolenaar84f888a2010-08-05 21:40:16 +02009976 continue;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009977 else if (!mch_isFullName(buf))
9978 {
9979 /* Expand relative path to their full path equivalent */
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009980 len = (int)STRLEN(curdir);
9981 if (len + (int)STRLEN(buf) + 3 > MAXPATHL)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009982 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009983 STRMOVE(buf + len + 1, buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009984 STRCPY(buf, curdir);
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009985 buf[len] = PATHSEP;
Bram Moolenaar57adda12010-08-03 22:11:29 +02009986 simplify_filename(buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009987 }
9988
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009989 if (ga_grow(gap, 1) == FAIL)
9990 break;
9991 p = vim_strsave(buf);
9992 if (p == NULL)
9993 break;
9994 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009995 }
9996
9997 vim_free(buf);
9998}
9999
10000/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010001 * Returns a pointer to the file or directory name in "fname" that matches the
10002 * longest path in "ga"p, or NULL if there is no match. For example:
Bram Moolenaar162bd912010-07-28 22:29:10 +020010003 *
10004 * path: /foo/bar/baz
10005 * fname: /foo/bar/baz/quux.txt
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010006 * returns: ^this
Bram Moolenaar162bd912010-07-28 22:29:10 +020010007 */
10008 static char_u *
10009get_path_cutoff(fname, gap)
10010 char_u *fname;
10011 garray_T *gap;
10012{
10013 int i;
10014 int maxlen = 0;
10015 char_u **path_part = (char_u **)gap->ga_data;
10016 char_u *cutoff = NULL;
10017
10018 for (i = 0; i < gap->ga_len; i++)
10019 {
10020 int j = 0;
10021
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010022 while ((fname[j] == path_part[i][j]
Bram Moolenaar2d7c47d2010-08-10 19:50:26 +020010023# if defined(MSWIN) || defined(MSDOS)
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010024 || (vim_ispathsep(fname[j]) && vim_ispathsep(path_part[i][j]))
10025#endif
10026 ) && fname[j] != NUL && path_part[i][j] != NUL)
Bram Moolenaar162bd912010-07-28 22:29:10 +020010027 j++;
10028 if (j > maxlen)
10029 {
10030 maxlen = j;
10031 cutoff = &fname[j];
10032 }
10033 }
10034
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010035 /* skip to the file or directory name */
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010036 if (cutoff != NULL)
Bram Moolenaar31710262010-08-13 13:36:15 +020010037 while (vim_ispathsep(*cutoff))
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010038 mb_ptr_adv(cutoff);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010039
10040 return cutoff;
10041}
10042
10043/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010044 * Sorts, removes duplicates and modifies all the fullpath names in "gap" so
10045 * that they are unique with respect to each other while conserving the part
10046 * that matches the pattern. Beware, this is at least O(n^2) wrt "gap->ga_len".
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010047 */
10048 static void
10049uniquefy_paths(gap, pattern)
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +020010050 garray_T *gap;
10051 char_u *pattern;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010052{
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +020010053 int i;
10054 int len;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010055 char_u **fnames = (char_u **)gap->ga_data;
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010056 int sort_again = FALSE;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010057 char_u *pat;
10058 char_u *file_pattern;
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010059 char_u *curdir;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010060 regmatch_T regmatch;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010061 garray_T path_ga;
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010062 char_u **in_curdir = NULL;
10063 char_u *short_name;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010064
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +020010065 remove_duplicates(gap);
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010066 ga_init2(&path_ga, (int)sizeof(char_u *), 1);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010067
10068 /*
10069 * We need to prepend a '*' at the beginning of file_pattern so that the
10070 * regex matches anywhere in the path. FIXME: is this valid for all
Bram Moolenaarb31e4382010-07-24 16:01:56 +020010071 * possible patterns?
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010072 */
Bram Moolenaar624c7aa2010-07-16 20:38:52 +020010073 len = (int)STRLEN(pattern);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010074 file_pattern = alloc(len + 2);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010075 if (file_pattern == NULL)
10076 return;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010077 file_pattern[0] = '*';
Bram Moolenaar162bd912010-07-28 22:29:10 +020010078 file_pattern[1] = NUL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010079 STRCAT(file_pattern, pattern);
10080 pat = file_pat_to_reg_pat(file_pattern, NULL, NULL, TRUE);
10081 vim_free(file_pattern);
Bram Moolenaarb31e4382010-07-24 16:01:56 +020010082 if (pat == NULL)
10083 return;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010084
Bram Moolenaarb31e4382010-07-24 16:01:56 +020010085 regmatch.rm_ic = TRUE; /* always ignore case */
10086 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
10087 vim_free(pat);
10088 if (regmatch.regprog == NULL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010089 return;
10090
Bram Moolenaar162bd912010-07-28 22:29:10 +020010091 if ((curdir = alloc((int)(MAXPATHL))) == NULL)
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010092 goto theend;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010093 mch_dirname(curdir, MAXPATHL);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010094 expand_path_option(curdir, &path_ga);
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010095
10096 in_curdir = (char_u **)alloc_clear(gap->ga_len * sizeof(char_u *));
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010097 if (in_curdir == NULL)
10098 goto theend;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010099
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010100 for (i = 0; i < gap->ga_len && !got_int; i++)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010101 {
Bram Moolenaar162bd912010-07-28 22:29:10 +020010102 char_u *path = fnames[i];
10103 int is_in_curdir;
Bram Moolenaar31710262010-08-13 13:36:15 +020010104 char_u *dir_end = gettail_dir(path);
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010105 char_u *pathsep_p;
10106 char_u *path_cutoff;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010107
Bram Moolenaar624c7aa2010-07-16 20:38:52 +020010108 len = (int)STRLEN(path);
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010109 is_in_curdir = fnamencmp(curdir, path, dir_end - path) == 0
Bram Moolenaar162bd912010-07-28 22:29:10 +020010110 && curdir[dir_end - path] == NUL;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010111 if (is_in_curdir)
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010112 in_curdir[i] = vim_strsave(path);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010113
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010114 /* Shorten the filename while maintaining its uniqueness */
10115 path_cutoff = get_path_cutoff(path, &path_ga);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010116
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010117 /* we start at the end of the path */
10118 pathsep_p = path + len - 1;
10119
10120 while (find_previous_pathsep(path, &pathsep_p))
10121 if (vim_regexec(&regmatch, pathsep_p + 1, (colnr_T)0)
10122 && is_unique(pathsep_p + 1, gap, i)
10123 && path_cutoff != NULL && pathsep_p + 1 >= path_cutoff)
10124 {
10125 sort_again = TRUE;
10126 mch_memmove(path, pathsep_p + 1, STRLEN(pathsep_p));
10127 break;
10128 }
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010129
10130 if (mch_isFullName(path))
10131 {
10132 /*
10133 * Last resort: shorten relative to curdir if possible.
10134 * 'possible' means:
10135 * 1. It is under the current directory.
10136 * 2. The result is actually shorter than the original.
10137 *
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010138 * Before curdir After
10139 * /foo/bar/file.txt /foo/bar ./file.txt
10140 * c:\foo\bar\file.txt c:\foo\bar .\file.txt
10141 * /file.txt / /file.txt
10142 * c:\file.txt c:\ .\file.txt
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010143 */
10144 short_name = shorten_fname(path, curdir);
Bram Moolenaar31710262010-08-13 13:36:15 +020010145 if (short_name != NULL && short_name > path + 1
10146#if defined(MSWIN) || defined(MSDOS)
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010147 /* On windows,
Bram Moolenaar31710262010-08-13 13:36:15 +020010148 * shorten_fname("c:\a\a.txt", "c:\a\b")
Bram Moolenaar31710262010-08-13 13:36:15 +020010149 * returns "\a\a.txt", which is not really the short
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010150 * name, hence: */
Bram Moolenaar31710262010-08-13 13:36:15 +020010151 && !vim_ispathsep(*short_name)
10152#endif
10153 )
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010154 {
10155 STRCPY(path, ".");
10156 add_pathsep(path);
Bram Moolenaarcda000e2010-08-14 13:34:39 +020010157 STRMOVE(path + STRLEN(path), short_name);
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010158 }
10159 }
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010160 ui_breakcheck();
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010161 }
10162
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010163 /* Shorten filenames in /in/current/directory/{filename} */
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010164 for (i = 0; i < gap->ga_len && !got_int; i++)
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010165 {
10166 char_u *rel_path;
10167 char_u *path = in_curdir[i];
10168
10169 if (path == NULL)
10170 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010171
10172 /* If the {filename} is not unique, change it to ./{filename}.
10173 * Else reduce it to {filename} */
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010174 short_name = shorten_fname(path, curdir);
10175 if (short_name == NULL)
10176 short_name = path;
10177 if (is_unique(short_name, gap, i))
10178 {
10179 STRCPY(fnames[i], short_name);
10180 continue;
10181 }
10182
10183 rel_path = alloc((int)(STRLEN(short_name) + STRLEN(PATHSEPSTR) + 2));
10184 if (rel_path == NULL)
10185 goto theend;
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010186 STRCPY(rel_path, ".");
10187 add_pathsep(rel_path);
10188 STRCAT(rel_path, short_name);
10189
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010190 vim_free(fnames[i]);
10191 fnames[i] = rel_path;
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010192 sort_again = TRUE;
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010193 ui_breakcheck();
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010194 }
10195
Bram Moolenaar162bd912010-07-28 22:29:10 +020010196theend:
10197 vim_free(curdir);
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010198 if (in_curdir != NULL)
10199 {
10200 for (i = 0; i < gap->ga_len; i++)
10201 vim_free(in_curdir[i]);
10202 vim_free(in_curdir);
10203 }
Bram Moolenaar162bd912010-07-28 22:29:10 +020010204 ga_clear_strings(&path_ga);
Bram Moolenaarb31e4382010-07-24 16:01:56 +020010205 vim_free(regmatch.regprog);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010206
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010207 if (sort_again)
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +020010208 remove_duplicates(gap);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010209}
10210
10211/*
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010212 * Calls globpath() with 'path' values for the given pattern and stores the
10213 * result in "gap".
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010214 * Returns the total number of matches.
10215 */
10216 static int
10217expand_in_path(gap, pattern, flags)
10218 garray_T *gap;
10219 char_u *pattern;
10220 int flags; /* EW_* flags */
10221{
Bram Moolenaar162bd912010-07-28 22:29:10 +020010222 char_u *curdir;
10223 garray_T path_ga;
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010224 char_u *files = NULL;
10225 char_u *s; /* start */
10226 char_u *e; /* end */
10227 char_u *paths = NULL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010228
Bram Moolenaar7f0f6212010-08-03 22:21:00 +020010229 if ((curdir = alloc((unsigned)MAXPATHL)) == NULL)
Bram Moolenaar162bd912010-07-28 22:29:10 +020010230 return 0;
10231 mch_dirname(curdir, MAXPATHL);
10232
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010233 ga_init2(&path_ga, (int)sizeof(char_u *), 1);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010234 expand_path_option(curdir, &path_ga);
10235 vim_free(curdir);
Bram Moolenaar006d2b02010-08-04 12:39:44 +020010236 if (path_ga.ga_len == 0)
10237 return 0;
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010238
10239 paths = ga_concat_strings(&path_ga);
10240 ga_clear_strings(&path_ga);
10241 if (paths == NULL)
Bram Moolenaar7f0f6212010-08-03 22:21:00 +020010242 return 0;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010243
Bram Moolenaar94950a92010-12-02 16:01:29 +010010244 files = globpath(paths, pattern, (flags & EW_ICASE) ? WILD_ICASE : 0);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010245 vim_free(paths);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010246 if (files == NULL)
10247 return 0;
10248
10249 /* Copy each path in files into gap */
10250 s = e = files;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010251 while (*s != NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010252 {
Bram Moolenaar162bd912010-07-28 22:29:10 +020010253 while (*e != '\n' && *e != NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010254 e++;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010255 if (*e == NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010256 {
10257 addfile(gap, s, flags);
10258 break;
10259 }
10260 else
10261 {
10262 /* *e is '\n' */
Bram Moolenaar162bd912010-07-28 22:29:10 +020010263 *e = NUL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010264 addfile(gap, s, flags);
10265 e++;
10266 s = e;
10267 }
10268 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010269 vim_free(files);
10270
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010271 return gap->ga_len;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010272}
10273#endif
10274
Bram Moolenaar1587a1e2010-07-29 20:59:59 +020010275#if defined(FEAT_SEARCHPATH) || defined(FEAT_CMDL_COMPL) || defined(PROTO)
10276/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010277 * Sort "gap" and remove duplicate entries. "gap" is expected to contain a
10278 * list of file names in allocated memory.
Bram Moolenaar1587a1e2010-07-29 20:59:59 +020010279 */
10280 void
10281remove_duplicates(gap)
10282 garray_T *gap;
10283{
10284 int i;
10285 int j;
10286 char_u **fnames = (char_u **)gap->ga_data;
10287
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010288 sort_strings(fnames, gap->ga_len);
Bram Moolenaar1587a1e2010-07-29 20:59:59 +020010289 for (i = gap->ga_len - 1; i > 0; --i)
10290 if (fnamecmp(fnames[i - 1], fnames[i]) == 0)
10291 {
10292 vim_free(fnames[i]);
10293 for (j = i + 1; j < gap->ga_len; ++j)
10294 fnames[j - 1] = fnames[j];
10295 --gap->ga_len;
10296 }
10297}
10298#endif
10299
Bram Moolenaar071d4272004-06-13 20:20:40 +000010300/*
10301 * Generic wildcard expansion code.
10302 *
10303 * Characters in "pat" that should not be expanded must be preceded with a
10304 * backslash. E.g., "/path\ with\ spaces/my\*star*"
10305 *
10306 * Return FAIL when no single file was found. In this case "num_file" is not
10307 * set, and "file" may contain an error message.
10308 * Return OK when some files found. "num_file" is set to the number of
10309 * matches, "file" to the array of matches. Call FreeWild() later.
10310 */
10311 int
10312gen_expand_wildcards(num_pat, pat, num_file, file, flags)
10313 int num_pat; /* number of input patterns */
10314 char_u **pat; /* array of input patterns */
10315 int *num_file; /* resulting number of files */
10316 char_u ***file; /* array of resulting files */
10317 int flags; /* EW_* flags */
10318{
10319 int i;
10320 garray_T ga;
10321 char_u *p;
10322 static int recursive = FALSE;
10323 int add_pat;
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010324#if defined(FEAT_SEARCHPATH)
10325 int did_expand_in_path = FALSE;
10326#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000010327
10328 /*
10329 * expand_env() is called to expand things like "~user". If this fails,
10330 * it calls ExpandOne(), which brings us back here. In this case, always
10331 * call the machine specific expansion function, if possible. Otherwise,
10332 * return FAIL.
10333 */
10334 if (recursive)
10335#ifdef SPECIAL_WILDCHAR
10336 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
10337#else
10338 return FAIL;
10339#endif
10340
10341#ifdef SPECIAL_WILDCHAR
10342 /*
10343 * If there are any special wildcard characters which we cannot handle
10344 * here, call machine specific function for all the expansion. This
10345 * avoids starting the shell for each argument separately.
10346 * For `=expr` do use the internal function.
10347 */
10348 for (i = 0; i < num_pat; i++)
10349 {
10350 if (vim_strpbrk(pat[i], (char_u *)SPECIAL_WILDCHAR) != NULL
10351# ifdef VIM_BACKTICK
10352 && !(vim_backtick(pat[i]) && pat[i][1] == '=')
10353# endif
10354 )
10355 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
10356 }
10357#endif
10358
10359 recursive = TRUE;
10360
10361 /*
10362 * The matching file names are stored in a growarray. Init it empty.
10363 */
10364 ga_init2(&ga, (int)sizeof(char_u *), 30);
10365
10366 for (i = 0; i < num_pat; ++i)
10367 {
10368 add_pat = -1;
10369 p = pat[i];
10370
10371#ifdef VIM_BACKTICK
10372 if (vim_backtick(p))
10373 add_pat = expand_backtick(&ga, p, flags);
10374 else
10375#endif
10376 {
10377 /*
10378 * First expand environment variables, "~/" and "~user/".
10379 */
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010380 if (vim_strchr(p, '$') != NULL || *p == '~')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010381 {
Bram Moolenaar9f0545d2007-09-26 20:36:32 +000010382 p = expand_env_save_opt(p, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010383 if (p == NULL)
10384 p = pat[i];
10385#ifdef UNIX
10386 /*
10387 * On Unix, if expand_env() can't expand an environment
10388 * variable, use the shell to do that. Discard previously
10389 * found file names and start all over again.
10390 */
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010391 else if (vim_strchr(p, '$') != NULL || *p == '~')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010392 {
10393 vim_free(p);
Bram Moolenaar782027e2009-06-24 14:25:49 +000010394 ga_clear_strings(&ga);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010395 i = mch_expand_wildcards(num_pat, pat, num_file, file,
10396 flags);
10397 recursive = FALSE;
10398 return i;
10399 }
10400#endif
10401 }
10402
10403 /*
10404 * If there are wildcards: Expand file names and add each match to
10405 * the list. If there is no match, and EW_NOTFOUND is given, add
10406 * the pattern.
10407 * If there are no wildcards: Add the file name if it exists or
10408 * when EW_NOTFOUND is given.
10409 */
10410 if (mch_has_exp_wildcard(p))
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010411 {
10412#if defined(FEAT_SEARCHPATH)
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010413 if ((flags & EW_PATH)
10414 && !mch_isFullName(p)
10415 && !(p[0] == '.'
10416 && (vim_ispathsep(p[1])
10417 || (p[1] == '.' && vim_ispathsep(p[2]))))
10418 )
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010419 {
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010420 /* :find completion where 'path' is used.
10421 * Recursiveness is OK here. */
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010422 recursive = FALSE;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010423 add_pat = expand_in_path(&ga, p, flags);
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010424 recursive = TRUE;
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010425 did_expand_in_path = TRUE;
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010426 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010427 else
10428#endif
10429 add_pat = mch_expandpath(&ga, p, flags);
10430 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010431 }
10432
10433 if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
10434 {
10435 char_u *t = backslash_halve_save(p);
10436
10437#if defined(MACOS_CLASSIC)
10438 slash_to_colon(t);
10439#endif
10440 /* When EW_NOTFOUND is used, always add files and dirs. Makes
10441 * "vim c:/" work. */
10442 if (flags & EW_NOTFOUND)
10443 addfile(&ga, t, flags | EW_DIR | EW_FILE);
10444 else if (mch_getperm(t) >= 0)
10445 addfile(&ga, t, flags);
10446 vim_free(t);
10447 }
10448
Bram Moolenaarb28ebbc2010-07-14 16:59:57 +020010449#if defined(FEAT_SEARCHPATH)
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010450 if (did_expand_in_path && ga.ga_len > 0 && (flags & EW_PATH))
Bram Moolenaarb28ebbc2010-07-14 16:59:57 +020010451 uniquefy_paths(&ga, p);
10452#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000010453 if (p != pat[i])
10454 vim_free(p);
10455 }
10456
10457 *num_file = ga.ga_len;
10458 *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data : (char_u **)"";
10459
10460 recursive = FALSE;
10461
10462 return (ga.ga_data != NULL) ? OK : FAIL;
10463}
10464
10465# ifdef VIM_BACKTICK
10466
10467/*
10468 * Return TRUE if we can expand this backtick thing here.
10469 */
10470 static int
10471vim_backtick(p)
10472 char_u *p;
10473{
10474 return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
10475}
10476
10477/*
10478 * Expand an item in `backticks` by executing it as a command.
10479 * Currently only works when pat[] starts and ends with a `.
10480 * Returns number of file names found.
10481 */
10482 static int
10483expand_backtick(gap, pat, flags)
10484 garray_T *gap;
10485 char_u *pat;
10486 int flags; /* EW_* flags */
10487{
10488 char_u *p;
10489 char_u *cmd;
10490 char_u *buffer;
10491 int cnt = 0;
10492 int i;
10493
10494 /* Create the command: lop off the backticks. */
10495 cmd = vim_strnsave(pat + 1, (int)STRLEN(pat) - 2);
10496 if (cmd == NULL)
10497 return 0;
10498
10499#ifdef FEAT_EVAL
10500 if (*cmd == '=') /* `={expr}`: Expand expression */
Bram Moolenaar362e1a32006-03-06 23:29:24 +000010501 buffer = eval_to_string(cmd + 1, &p, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010502 else
10503#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010504 buffer = get_cmd_output(cmd, NULL,
10505 (flags & EW_SILENT) ? SHELL_SILENT : 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010506 vim_free(cmd);
10507 if (buffer == NULL)
10508 return 0;
10509
10510 cmd = buffer;
10511 while (*cmd != NUL)
10512 {
10513 cmd = skipwhite(cmd); /* skip over white space */
10514 p = cmd;
10515 while (*p != NUL && *p != '\r' && *p != '\n') /* skip over entry */
10516 ++p;
10517 /* add an entry if it is not empty */
10518 if (p > cmd)
10519 {
10520 i = *p;
10521 *p = NUL;
10522 addfile(gap, cmd, flags);
10523 *p = i;
10524 ++cnt;
10525 }
10526 cmd = p;
10527 while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
10528 ++cmd;
10529 }
10530
10531 vim_free(buffer);
10532 return cnt;
10533}
10534# endif /* VIM_BACKTICK */
10535
10536/*
10537 * Add a file to a file list. Accepted flags:
10538 * EW_DIR add directories
10539 * EW_FILE add files
Bram Moolenaar1f35bf92006-03-07 22:38:47 +000010540 * EW_EXEC add executable files
Bram Moolenaar071d4272004-06-13 20:20:40 +000010541 * EW_NOTFOUND add even when it doesn't exist
10542 * EW_ADDSLASH add slash after directory name
10543 */
10544 void
10545addfile(gap, f, flags)
10546 garray_T *gap;
10547 char_u *f; /* filename */
10548 int flags;
10549{
10550 char_u *p;
10551 int isdir;
10552
10553 /* if the file/dir doesn't exist, may not add it */
10554 if (!(flags & EW_NOTFOUND) && mch_getperm(f) < 0)
10555 return;
10556
10557#ifdef FNAME_ILLEGAL
10558 /* if the file/dir contains illegal characters, don't add it */
10559 if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
10560 return;
10561#endif
10562
10563 isdir = mch_isdir(f);
10564 if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
10565 return;
10566
Bram Moolenaar1f35bf92006-03-07 22:38:47 +000010567 /* If the file isn't executable, may not add it. Do accept directories. */
10568 if (!isdir && (flags & EW_EXEC) && !mch_can_exe(f))
10569 return;
10570
Bram Moolenaar071d4272004-06-13 20:20:40 +000010571 /* Make room for another item in the file list. */
10572 if (ga_grow(gap, 1) == FAIL)
10573 return;
10574
10575 p = alloc((unsigned)(STRLEN(f) + 1 + isdir));
10576 if (p == NULL)
10577 return;
10578
10579 STRCPY(p, f);
10580#ifdef BACKSLASH_IN_FILENAME
10581 slash_adjust(p);
10582#endif
10583 /*
10584 * Append a slash or backslash after directory names if none is present.
10585 */
10586#ifndef DONT_ADD_PATHSEP_TO_DIR
10587 if (isdir && (flags & EW_ADDSLASH))
10588 add_pathsep(p);
10589#endif
10590 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010591}
10592#endif /* !NO_EXPANDPATH */
10593
10594#if defined(VIM_BACKTICK) || defined(FEAT_EVAL) || defined(PROTO)
10595
10596#ifndef SEEK_SET
10597# define SEEK_SET 0
10598#endif
10599#ifndef SEEK_END
10600# define SEEK_END 2
10601#endif
10602
10603/*
10604 * Get the stdout of an external command.
10605 * Returns an allocated string, or NULL for error.
10606 */
10607 char_u *
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010608get_cmd_output(cmd, infile, flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010609 char_u *cmd;
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010610 char_u *infile; /* optional input file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010611 int flags; /* can be SHELL_SILENT */
10612{
10613 char_u *tempname;
10614 char_u *command;
10615 char_u *buffer = NULL;
10616 int len;
10617 int i = 0;
10618 FILE *fd;
10619
10620 if (check_restricted() || check_secure())
10621 return NULL;
10622
10623 /* get a name for the temp file */
10624 if ((tempname = vim_tempname('o')) == NULL)
10625 {
10626 EMSG(_(e_notmp));
10627 return NULL;
10628 }
10629
10630 /* Add the redirection stuff */
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010631 command = make_filter_cmd(cmd, infile, tempname);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010632 if (command == NULL)
10633 goto done;
10634
10635 /*
10636 * Call the shell to execute the command (errors are ignored).
10637 * Don't check timestamps here.
10638 */
10639 ++no_check_timestamps;
10640 call_shell(command, SHELL_DOOUT | SHELL_EXPAND | flags);
10641 --no_check_timestamps;
10642
10643 vim_free(command);
10644
10645 /*
10646 * read the names from the file into memory
10647 */
10648# ifdef VMS
Bram Moolenaar25394022007-05-10 19:06:20 +000010649 /* created temporary file is not always readable as binary */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010650 fd = mch_fopen((char *)tempname, "r");
10651# else
10652 fd = mch_fopen((char *)tempname, READBIN);
10653# endif
10654
10655 if (fd == NULL)
10656 {
10657 EMSG2(_(e_notopen), tempname);
10658 goto done;
10659 }
10660
10661 fseek(fd, 0L, SEEK_END);
10662 len = ftell(fd); /* get size of temp file */
10663 fseek(fd, 0L, SEEK_SET);
10664
10665 buffer = alloc(len + 1);
10666 if (buffer != NULL)
10667 i = (int)fread((char *)buffer, (size_t)1, (size_t)len, fd);
10668 fclose(fd);
10669 mch_remove(tempname);
10670 if (buffer == NULL)
10671 goto done;
10672#ifdef VMS
10673 len = i; /* VMS doesn't give us what we asked for... */
10674#endif
10675 if (i != len)
10676 {
10677 EMSG2(_(e_notread), tempname);
10678 vim_free(buffer);
10679 buffer = NULL;
10680 }
10681 else
Bram Moolenaar162bd912010-07-28 22:29:10 +020010682 buffer[len] = NUL; /* make sure the buffer is terminated */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010683
10684done:
10685 vim_free(tempname);
10686 return buffer;
10687}
10688#endif
10689
10690/*
10691 * Free the list of files returned by expand_wildcards() or other expansion
10692 * functions.
10693 */
10694 void
10695FreeWild(count, files)
10696 int count;
10697 char_u **files;
10698{
Bram Moolenaarfc1421e2006-04-20 22:17:20 +000010699 if (count <= 0 || files == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010700 return;
10701#if defined(__EMX__) && defined(__ALWAYS_HAS_TRAILING_NULL_POINTER) /* XXX */
10702 /*
10703 * Is this still OK for when other functions than expand_wildcards() have
10704 * been used???
10705 */
10706 _fnexplodefree((char **)files);
10707#else
10708 while (count--)
10709 vim_free(files[count]);
10710 vim_free(files);
10711#endif
10712}
10713
10714/*
Bram Moolenaara9dc3752010-07-11 20:46:53 +020010715 * Return TRUE when need to go to Insert mode because of 'insertmode'.
Bram Moolenaar071d4272004-06-13 20:20:40 +000010716 * Don't do this when still processing a command or a mapping.
10717 * Don't do this when inside a ":normal" command.
10718 */
10719 int
10720goto_im()
10721{
10722 return (p_im && stuff_empty() && typebuf_typed());
10723}