blob: e11e10e0cfa536458d37e854fcc06f4aecd0e607 [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
Bram Moolenaar96b7ca52012-06-29 15:04:49 +0200427 regmatch_T regmatch;
428 int lead_len = 0; /* length of comment leader */
429
Bram Moolenaar071d4272004-06-13 20:20:40 +0000430 if (lnum > curbuf->b_ml.ml_line_count)
431 return -1;
Bram Moolenaar86b68352004-12-27 21:59:20 +0000432 pos.lnum = 0;
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200433
434#ifdef FEAT_COMMENTS
Bram Moolenaar96b7ca52012-06-29 15:04:49 +0200435 /* In format_lines() (i.e. not insert mode), fo+=q is needed too... */
436 if ((State & INSERT) || has_format_option(FO_Q_COMS))
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200437 lead_len = get_leader_len(ml_get(lnum), NULL, FALSE, TRUE);
Bram Moolenaar86b68352004-12-27 21:59:20 +0000438#endif
Bram Moolenaar96b7ca52012-06-29 15:04:49 +0200439 regmatch.regprog = vim_regcomp(curbuf->b_p_flp, RE_MAGIC);
440 if (regmatch.regprog != NULL)
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200441 {
Bram Moolenaar96b7ca52012-06-29 15:04:49 +0200442 regmatch.rm_ic = FALSE;
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200443
Bram Moolenaar96b7ca52012-06-29 15:04:49 +0200444 /* vim_regexec() expects a pointer to a line. This lets us
445 * start matching for the flp beyond any comment leader... */
446 if (vim_regexec(&regmatch, ml_get(lnum) + lead_len, (colnr_T)0))
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200447 {
Bram Moolenaar96b7ca52012-06-29 15:04:49 +0200448 pos.lnum = lnum;
449 pos.col = (colnr_T)(*regmatch.endp - ml_get(lnum));
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200450#ifdef FEAT_VIRTUALEDIT
Bram Moolenaar96b7ca52012-06-29 15:04:49 +0200451 pos.coladd = 0;
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200452#endif
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200453 }
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200454 }
Bram Moolenaar96b7ca52012-06-29 15:04:49 +0200455 vim_free(regmatch.regprog);
Bram Moolenaar86b68352004-12-27 21:59:20 +0000456
457 if (pos.lnum == 0 || *ml_get_pos(&pos) == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000458 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000459 getvcol(curwin, &pos, &col, NULL, NULL);
460 return (int)col;
461}
462
463#if defined(FEAT_CINDENT) || defined(FEAT_SMARTINDENT)
464
465static int cin_is_cinword __ARGS((char_u *line));
466
467/*
468 * Return TRUE if the string "line" starts with a word from 'cinwords'.
469 */
470 static int
471cin_is_cinword(line)
472 char_u *line;
473{
474 char_u *cinw;
475 char_u *cinw_buf;
476 int cinw_len;
477 int retval = FALSE;
478 int len;
479
480 cinw_len = (int)STRLEN(curbuf->b_p_cinw) + 1;
481 cinw_buf = alloc((unsigned)cinw_len);
482 if (cinw_buf != NULL)
483 {
484 line = skipwhite(line);
485 for (cinw = curbuf->b_p_cinw; *cinw; )
486 {
487 len = copy_option_part(&cinw, cinw_buf, cinw_len, ",");
488 if (STRNCMP(line, cinw_buf, len) == 0
489 && (!vim_iswordc(line[len]) || !vim_iswordc(line[len - 1])))
490 {
491 retval = TRUE;
492 break;
493 }
494 }
495 vim_free(cinw_buf);
496 }
497 return retval;
498}
499#endif
500
501/*
502 * open_line: Add a new line below or above the current line.
503 *
504 * For VREPLACE mode, we only add a new line when we get to the end of the
505 * file, otherwise we just start replacing the next line.
506 *
507 * Caller must take care of undo. Since VREPLACE may affect any number of
508 * lines however, it may call u_save_cursor() again when starting to change a
509 * new line.
510 * "flags": OPENLINE_DELSPACES delete spaces after cursor
511 * OPENLINE_DO_COM format comments
512 * OPENLINE_KEEPTRAIL keep trailing spaces
513 * OPENLINE_MARKFIX adjust mark positions after the line break
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200514 * OPENLINE_COM_LIST format comments with list or 2nd line indent
515 *
516 * "second_line_indent": indent for after ^^D in Insert mode or if flag
517 * OPENLINE_COM_LIST
Bram Moolenaar071d4272004-06-13 20:20:40 +0000518 *
519 * Return TRUE for success, FALSE for failure
520 */
521 int
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200522open_line(dir, flags, second_line_indent)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000523 int dir; /* FORWARD or BACKWARD */
524 int flags;
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200525 int second_line_indent;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000526{
527 char_u *saved_line; /* copy of the original line */
528 char_u *next_line = NULL; /* copy of the next line */
529 char_u *p_extra = NULL; /* what goes to next line */
530 int less_cols = 0; /* less columns for mark in new line */
531 int less_cols_off = 0; /* columns to skip for mark adjust */
532 pos_T old_cursor; /* old cursor position */
533 int newcol = 0; /* new cursor column */
534 int newindent = 0; /* auto-indent of the new line */
535 int n;
536 int trunc_line = FALSE; /* truncate current line afterwards */
537 int retval = FALSE; /* return value, default is FAIL */
538#ifdef FEAT_COMMENTS
539 int extra_len = 0; /* length of p_extra string */
540 int lead_len; /* length of comment leader */
541 char_u *lead_flags; /* position in 'comments' for comment leader */
542 char_u *leader = NULL; /* copy of comment leader */
543#endif
544 char_u *allocated = NULL; /* allocated memory */
545#if defined(FEAT_SMARTINDENT) || defined(FEAT_VREPLACE) || defined(FEAT_LISP) \
546 || defined(FEAT_CINDENT) || defined(FEAT_COMMENTS)
547 char_u *p;
548#endif
549 int saved_char = NUL; /* init for GCC */
550#if defined(FEAT_SMARTINDENT) || defined(FEAT_COMMENTS)
551 pos_T *pos;
552#endif
553#ifdef FEAT_SMARTINDENT
554 int do_si = (!p_paste && curbuf->b_p_si
555# ifdef FEAT_CINDENT
556 && !curbuf->b_p_cin
557# endif
558 );
559 int no_si = FALSE; /* reset did_si afterwards */
560 int first_char = NUL; /* init for GCC */
561#endif
562#if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
563 int vreplace_mode;
564#endif
565 int did_append; /* appended a new line */
566 int saved_pi = curbuf->b_p_pi; /* copy of preserveindent setting */
567
568 /*
569 * make a copy of the current line so we can mess with it
570 */
571 saved_line = vim_strsave(ml_get_curline());
572 if (saved_line == NULL) /* out of memory! */
573 return FALSE;
574
575#ifdef FEAT_VREPLACE
576 if (State & VREPLACE_FLAG)
577 {
578 /*
579 * With VREPLACE we make a copy of the next line, which we will be
580 * starting to replace. First make the new line empty and let vim play
581 * with the indenting and comment leader to its heart's content. Then
582 * we grab what it ended up putting on the new line, put back the
583 * original line, and call ins_char() to put each new character onto
584 * the line, replacing what was there before and pushing the right
585 * stuff onto the replace stack. -- webb.
586 */
587 if (curwin->w_cursor.lnum < orig_line_count)
588 next_line = vim_strsave(ml_get(curwin->w_cursor.lnum + 1));
589 else
590 next_line = vim_strsave((char_u *)"");
591 if (next_line == NULL) /* out of memory! */
592 goto theend;
593
594 /*
595 * In VREPLACE mode, a NL replaces the rest of the line, and starts
596 * replacing the next line, so push all of the characters left on the
597 * line onto the replace stack. We'll push any other characters that
598 * might be replaced at the start of the next line (due to autoindent
599 * etc) a bit later.
600 */
601 replace_push(NUL); /* Call twice because BS over NL expects it */
602 replace_push(NUL);
603 p = saved_line + curwin->w_cursor.col;
604 while (*p != NUL)
Bram Moolenaar2c994e82008-01-02 16:49:36 +0000605 {
606#ifdef FEAT_MBYTE
607 if (has_mbyte)
608 p += replace_push_mb(p);
609 else
610#endif
611 replace_push(*p++);
612 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000613 saved_line[curwin->w_cursor.col] = NUL;
614 }
615#endif
616
617 if ((State & INSERT)
618#ifdef FEAT_VREPLACE
619 && !(State & VREPLACE_FLAG)
620#endif
621 )
622 {
623 p_extra = saved_line + curwin->w_cursor.col;
624#ifdef FEAT_SMARTINDENT
625 if (do_si) /* need first char after new line break */
626 {
627 p = skipwhite(p_extra);
628 first_char = *p;
629 }
630#endif
631#ifdef FEAT_COMMENTS
632 extra_len = (int)STRLEN(p_extra);
633#endif
634 saved_char = *p_extra;
635 *p_extra = NUL;
636 }
637
638 u_clearline(); /* cannot do "U" command when adding lines */
639#ifdef FEAT_SMARTINDENT
640 did_si = FALSE;
641#endif
642 ai_col = 0;
643
644 /*
645 * If we just did an auto-indent, then we didn't type anything on
646 * the prior line, and it should be truncated. Do this even if 'ai' is not
647 * set because automatically inserting a comment leader also sets did_ai.
648 */
649 if (dir == FORWARD && did_ai)
650 trunc_line = TRUE;
651
652 /*
653 * If 'autoindent' and/or 'smartindent' is set, try to figure out what
654 * indent to use for the new line.
655 */
656 if (curbuf->b_p_ai
657#ifdef FEAT_SMARTINDENT
658 || do_si
659#endif
660 )
661 {
662 /*
663 * count white space on current line
664 */
665 newindent = get_indent_str(saved_line, (int)curbuf->b_p_ts);
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200666 if (newindent == 0 && !(flags & OPENLINE_COM_LIST))
667 newindent = second_line_indent; /* for ^^D command in insert mode */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000668
669#ifdef FEAT_SMARTINDENT
670 /*
671 * Do smart indenting.
672 * In insert/replace mode (only when dir == FORWARD)
673 * we may move some text to the next line. If it starts with '{'
674 * don't add an indent. Fixes inserting a NL before '{' in line
675 * "if (condition) {"
676 */
677 if (!trunc_line && do_si && *saved_line != NUL
678 && (p_extra == NULL || first_char != '{'))
679 {
680 char_u *ptr;
681 char_u last_char;
682
683 old_cursor = curwin->w_cursor;
684 ptr = saved_line;
685# ifdef FEAT_COMMENTS
686 if (flags & OPENLINE_DO_COM)
Bram Moolenaar81340392012-06-06 16:12:59 +0200687 lead_len = get_leader_len(ptr, NULL, FALSE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000688 else
689 lead_len = 0;
690# endif
691 if (dir == FORWARD)
692 {
693 /*
694 * Skip preprocessor directives, unless they are
695 * recognised as comments.
696 */
697 if (
698# ifdef FEAT_COMMENTS
699 lead_len == 0 &&
700# endif
701 ptr[0] == '#')
702 {
703 while (ptr[0] == '#' && curwin->w_cursor.lnum > 1)
704 ptr = ml_get(--curwin->w_cursor.lnum);
705 newindent = get_indent();
706 }
707# ifdef FEAT_COMMENTS
708 if (flags & OPENLINE_DO_COM)
Bram Moolenaar81340392012-06-06 16:12:59 +0200709 lead_len = get_leader_len(ptr, NULL, FALSE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000710 else
711 lead_len = 0;
712 if (lead_len > 0)
713 {
714 /*
715 * This case gets the following right:
716 * \*
717 * * A comment (read '\' as '/').
718 * *\
719 * #define IN_THE_WAY
720 * This should line up here;
721 */
722 p = skipwhite(ptr);
723 if (p[0] == '/' && p[1] == '*')
724 p++;
725 if (p[0] == '*')
726 {
727 for (p++; *p; p++)
728 {
729 if (p[0] == '/' && p[-1] == '*')
730 {
731 /*
732 * End of C comment, indent should line up
733 * with the line containing the start of
734 * the comment
735 */
736 curwin->w_cursor.col = (colnr_T)(p - ptr);
737 if ((pos = findmatch(NULL, NUL)) != NULL)
738 {
739 curwin->w_cursor.lnum = pos->lnum;
740 newindent = get_indent();
741 }
742 }
743 }
744 }
745 }
746 else /* Not a comment line */
747# endif
748 {
749 /* Find last non-blank in line */
750 p = ptr + STRLEN(ptr) - 1;
751 while (p > ptr && vim_iswhite(*p))
752 --p;
753 last_char = *p;
754
755 /*
756 * find the character just before the '{' or ';'
757 */
758 if (last_char == '{' || last_char == ';')
759 {
760 if (p > ptr)
761 --p;
762 while (p > ptr && vim_iswhite(*p))
763 --p;
764 }
765 /*
766 * Try to catch lines that are split over multiple
767 * lines. eg:
768 * if (condition &&
769 * condition) {
770 * Should line up here!
771 * }
772 */
773 if (*p == ')')
774 {
775 curwin->w_cursor.col = (colnr_T)(p - ptr);
776 if ((pos = findmatch(NULL, '(')) != NULL)
777 {
778 curwin->w_cursor.lnum = pos->lnum;
779 newindent = get_indent();
780 ptr = ml_get_curline();
781 }
782 }
783 /*
784 * If last character is '{' do indent, without
785 * checking for "if" and the like.
786 */
787 if (last_char == '{')
788 {
789 did_si = TRUE; /* do indent */
790 no_si = TRUE; /* don't delete it when '{' typed */
791 }
792 /*
793 * Look for "if" and the like, use 'cinwords'.
794 * Don't do this if the previous line ended in ';' or
795 * '}'.
796 */
797 else if (last_char != ';' && last_char != '}'
798 && cin_is_cinword(ptr))
799 did_si = TRUE;
800 }
801 }
802 else /* dir == BACKWARD */
803 {
804 /*
805 * Skip preprocessor directives, unless they are
806 * recognised as comments.
807 */
808 if (
809# ifdef FEAT_COMMENTS
810 lead_len == 0 &&
811# endif
812 ptr[0] == '#')
813 {
814 int was_backslashed = FALSE;
815
816 while ((ptr[0] == '#' || was_backslashed) &&
817 curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
818 {
819 if (*ptr && ptr[STRLEN(ptr) - 1] == '\\')
820 was_backslashed = TRUE;
821 else
822 was_backslashed = FALSE;
823 ptr = ml_get(++curwin->w_cursor.lnum);
824 }
825 if (was_backslashed)
826 newindent = 0; /* Got to end of file */
827 else
828 newindent = get_indent();
829 }
830 p = skipwhite(ptr);
831 if (*p == '}') /* if line starts with '}': do indent */
832 did_si = TRUE;
833 else /* can delete indent when '{' typed */
834 can_si_back = TRUE;
835 }
836 curwin->w_cursor = old_cursor;
837 }
838 if (do_si)
839 can_si = TRUE;
840#endif /* FEAT_SMARTINDENT */
841
842 did_ai = TRUE;
843 }
844
845#ifdef FEAT_COMMENTS
846 /*
847 * Find out if the current line starts with a comment leader.
848 * This may then be inserted in front of the new line.
849 */
850 end_comment_pending = NUL;
851 if (flags & OPENLINE_DO_COM)
Bram Moolenaar81340392012-06-06 16:12:59 +0200852 lead_len = get_leader_len(saved_line, &lead_flags, dir == BACKWARD, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000853 else
854 lead_len = 0;
855 if (lead_len > 0)
856 {
857 char_u *lead_repl = NULL; /* replaces comment leader */
858 int lead_repl_len = 0; /* length of *lead_repl */
859 char_u lead_middle[COM_MAX_LEN]; /* middle-comment string */
860 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
861 char_u *comment_end = NULL; /* where lead_end has been found */
862 int extra_space = FALSE; /* append extra space */
863 int current_flag;
864 int require_blank = FALSE; /* requires blank after middle */
865 char_u *p2;
866
867 /*
868 * If the comment leader has the start, middle or end flag, it may not
869 * be used or may be replaced with the middle leader.
870 */
871 for (p = lead_flags; *p && *p != ':'; ++p)
872 {
873 if (*p == COM_BLANK)
874 {
875 require_blank = TRUE;
876 continue;
877 }
878 if (*p == COM_START || *p == COM_MIDDLE)
879 {
880 current_flag = *p;
881 if (*p == COM_START)
882 {
883 /*
884 * Doing "O" on a start of comment does not insert leader.
885 */
886 if (dir == BACKWARD)
887 {
888 lead_len = 0;
889 break;
890 }
891
892 /* find start of middle part */
893 (void)copy_option_part(&p, lead_middle, COM_MAX_LEN, ",");
894 require_blank = FALSE;
895 }
896
897 /*
898 * Isolate the strings of the middle and end leader.
899 */
900 while (*p && p[-1] != ':') /* find end of middle flags */
901 {
902 if (*p == COM_BLANK)
903 require_blank = TRUE;
904 ++p;
905 }
906 (void)copy_option_part(&p, lead_middle, COM_MAX_LEN, ",");
907
908 while (*p && p[-1] != ':') /* find end of end flags */
909 {
910 /* Check whether we allow automatic ending of comments */
911 if (*p == COM_AUTO_END)
912 end_comment_pending = -1; /* means we want to set it */
913 ++p;
914 }
915 n = copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
916
917 if (end_comment_pending == -1) /* we can set it now */
918 end_comment_pending = lead_end[n - 1];
919
920 /*
921 * If the end of the comment is in the same line, don't use
922 * the comment leader.
923 */
924 if (dir == FORWARD)
925 {
926 for (p = saved_line + lead_len; *p; ++p)
927 if (STRNCMP(p, lead_end, n) == 0)
928 {
929 comment_end = p;
930 lead_len = 0;
931 break;
932 }
933 }
934
935 /*
936 * Doing "o" on a start of comment inserts the middle leader.
937 */
938 if (lead_len > 0)
939 {
940 if (current_flag == COM_START)
941 {
942 lead_repl = lead_middle;
943 lead_repl_len = (int)STRLEN(lead_middle);
944 }
945
946 /*
947 * If we have hit RETURN immediately after the start
948 * comment leader, then put a space after the middle
949 * comment leader on the next line.
950 */
951 if (!vim_iswhite(saved_line[lead_len - 1])
952 && ((p_extra != NULL
953 && (int)curwin->w_cursor.col == lead_len)
954 || (p_extra == NULL
955 && saved_line[lead_len] == NUL)
956 || require_blank))
957 extra_space = TRUE;
958 }
959 break;
960 }
961 if (*p == COM_END)
962 {
963 /*
964 * Doing "o" on the end of a comment does not insert leader.
965 * Remember where the end is, might want to use it to find the
966 * start (for C-comments).
967 */
968 if (dir == FORWARD)
969 {
970 comment_end = skipwhite(saved_line);
971 lead_len = 0;
972 break;
973 }
974
975 /*
976 * Doing "O" on the end of a comment inserts the middle leader.
977 * Find the string for the middle leader, searching backwards.
978 */
979 while (p > curbuf->b_p_com && *p != ',')
980 --p;
981 for (lead_repl = p; lead_repl > curbuf->b_p_com
982 && lead_repl[-1] != ':'; --lead_repl)
983 ;
984 lead_repl_len = (int)(p - lead_repl);
985
986 /* We can probably always add an extra space when doing "O" on
987 * the comment-end */
988 extra_space = TRUE;
989
990 /* Check whether we allow automatic ending of comments */
991 for (p2 = p; *p2 && *p2 != ':'; p2++)
992 {
993 if (*p2 == COM_AUTO_END)
994 end_comment_pending = -1; /* means we want to set it */
995 }
996 if (end_comment_pending == -1)
997 {
998 /* Find last character in end-comment string */
999 while (*p2 && *p2 != ',')
1000 p2++;
1001 end_comment_pending = p2[-1];
1002 }
1003 break;
1004 }
1005 if (*p == COM_FIRST)
1006 {
1007 /*
1008 * Comment leader for first line only: Don't repeat leader
1009 * when using "O", blank out leader when using "o".
1010 */
1011 if (dir == BACKWARD)
1012 lead_len = 0;
1013 else
1014 {
1015 lead_repl = (char_u *)"";
1016 lead_repl_len = 0;
1017 }
1018 break;
1019 }
1020 }
1021 if (lead_len)
1022 {
Bram Moolenaardc7e85e2012-06-20 12:40:08 +02001023 /* allocate buffer (may concatenate p_extra later) */
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +02001024 leader = alloc(lead_len + lead_repl_len + extra_space + extra_len
Bram Moolenaardc7e85e2012-06-20 12:40:08 +02001025 + (second_line_indent > 0 ? second_line_indent : 0) + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001026 allocated = leader; /* remember to free it later */
1027
1028 if (leader == NULL)
1029 lead_len = 0;
1030 else
1031 {
Bram Moolenaarce0842a2005-07-18 21:58:11 +00001032 vim_strncpy(leader, saved_line, lead_len);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001033
1034 /*
1035 * Replace leader with lead_repl, right or left adjusted
1036 */
1037 if (lead_repl != NULL)
1038 {
1039 int c = 0;
1040 int off = 0;
1041
Bram Moolenaard7d5b472009-11-11 16:30:08 +00001042 for (p = lead_flags; *p != NUL && *p != ':'; )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001043 {
1044 if (*p == COM_RIGHT || *p == COM_LEFT)
Bram Moolenaard7d5b472009-11-11 16:30:08 +00001045 c = *p++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001046 else if (VIM_ISDIGIT(*p) || *p == '-')
1047 off = getdigits(&p);
Bram Moolenaard7d5b472009-11-11 16:30:08 +00001048 else
1049 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001050 }
1051 if (c == COM_RIGHT) /* right adjusted leader */
1052 {
1053 /* find last non-white in the leader to line up with */
1054 for (p = leader + lead_len - 1; p > leader
1055 && vim_iswhite(*p); --p)
1056 ;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001057 ++p;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001058
1059#ifdef FEAT_MBYTE
1060 /* Compute the length of the replaced characters in
1061 * screen characters, not bytes. */
1062 {
1063 int repl_size = vim_strnsize(lead_repl,
1064 lead_repl_len);
1065 int old_size = 0;
1066 char_u *endp = p;
1067 int l;
1068
1069 while (old_size < repl_size && p > leader)
1070 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001071 mb_ptr_back(leader, p);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001072 old_size += ptr2cells(p);
1073 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001074 l = lead_repl_len - (int)(endp - p);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001075 if (l != 0)
1076 mch_memmove(endp + l, endp,
1077 (size_t)((leader + lead_len) - endp));
1078 lead_len += l;
1079 }
1080#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001081 if (p < leader + lead_repl_len)
1082 p = leader;
1083 else
1084 p -= lead_repl_len;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001085#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001086 mch_memmove(p, lead_repl, (size_t)lead_repl_len);
1087 if (p + lead_repl_len > leader + lead_len)
1088 p[lead_repl_len] = NUL;
1089
1090 /* blank-out any other chars from the old leader. */
1091 while (--p >= leader)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001092 {
1093#ifdef FEAT_MBYTE
1094 int l = mb_head_off(leader, p);
1095
1096 if (l > 1)
1097 {
1098 p -= l;
1099 if (ptr2cells(p) > 1)
1100 {
1101 p[1] = ' ';
1102 --l;
1103 }
1104 mch_memmove(p + 1, p + l + 1,
1105 (size_t)((leader + lead_len) - (p + l + 1)));
1106 lead_len -= l;
1107 *p = ' ';
1108 }
1109 else
1110#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001111 if (!vim_iswhite(*p))
1112 *p = ' ';
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001113 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001114 }
1115 else /* left adjusted leader */
1116 {
1117 p = skipwhite(leader);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001118#ifdef FEAT_MBYTE
1119 /* Compute the length of the replaced characters in
1120 * screen characters, not bytes. Move the part that is
1121 * not to be overwritten. */
1122 {
1123 int repl_size = vim_strnsize(lead_repl,
1124 lead_repl_len);
1125 int i;
1126 int l;
1127
1128 for (i = 0; p[i] != NUL && i < lead_len; i += l)
1129 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00001130 l = (*mb_ptr2len)(p + i);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001131 if (vim_strnsize(p, i + l) > repl_size)
1132 break;
1133 }
1134 if (i != lead_repl_len)
1135 {
1136 mch_memmove(p + lead_repl_len, p + i,
Bram Moolenaar2d7ff052009-11-17 15:08:26 +00001137 (size_t)(lead_len - i - (p - leader)));
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001138 lead_len += lead_repl_len - i;
1139 }
1140 }
1141#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001142 mch_memmove(p, lead_repl, (size_t)lead_repl_len);
1143
1144 /* Replace any remaining non-white chars in the old
1145 * leader by spaces. Keep Tabs, the indent must
1146 * remain the same. */
1147 for (p += lead_repl_len; p < leader + lead_len; ++p)
1148 if (!vim_iswhite(*p))
1149 {
1150 /* Don't put a space before a TAB. */
1151 if (p + 1 < leader + lead_len && p[1] == TAB)
1152 {
1153 --lead_len;
1154 mch_memmove(p, p + 1,
1155 (leader + lead_len) - p);
1156 }
1157 else
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001158 {
1159#ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00001160 int l = (*mb_ptr2len)(p);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001161
1162 if (l > 1)
1163 {
1164 if (ptr2cells(p) > 1)
1165 {
1166 /* Replace a double-wide char with
1167 * two spaces */
1168 --l;
1169 *p++ = ' ';
1170 }
1171 mch_memmove(p + 1, p + l,
1172 (leader + lead_len) - p);
1173 lead_len -= l - 1;
1174 }
1175#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001176 *p = ' ';
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001177 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001178 }
1179 *p = NUL;
1180 }
1181
1182 /* Recompute the indent, it may have changed. */
1183 if (curbuf->b_p_ai
1184#ifdef FEAT_SMARTINDENT
1185 || do_si
1186#endif
1187 )
1188 newindent = get_indent_str(leader, (int)curbuf->b_p_ts);
1189
1190 /* Add the indent offset */
1191 if (newindent + off < 0)
1192 {
1193 off = -newindent;
1194 newindent = 0;
1195 }
1196 else
1197 newindent += off;
1198
1199 /* Correct trailing spaces for the shift, so that
1200 * alignment remains equal. */
1201 while (off > 0 && lead_len > 0
1202 && leader[lead_len - 1] == ' ')
1203 {
1204 /* Don't do it when there is a tab before the space */
1205 if (vim_strchr(skipwhite(leader), '\t') != NULL)
1206 break;
1207 --lead_len;
1208 --off;
1209 }
1210
1211 /* If the leader ends in white space, don't add an
1212 * extra space */
1213 if (lead_len > 0 && vim_iswhite(leader[lead_len - 1]))
1214 extra_space = FALSE;
1215 leader[lead_len] = NUL;
1216 }
1217
1218 if (extra_space)
1219 {
1220 leader[lead_len++] = ' ';
1221 leader[lead_len] = NUL;
1222 }
1223
1224 newcol = lead_len;
1225
1226 /*
1227 * if a new indent will be set below, remove the indent that
1228 * is in the comment leader
1229 */
1230 if (newindent
1231#ifdef FEAT_SMARTINDENT
1232 || did_si
1233#endif
1234 )
1235 {
1236 while (lead_len && vim_iswhite(*leader))
1237 {
1238 --lead_len;
1239 --newcol;
1240 ++leader;
1241 }
1242 }
1243
1244 }
1245#ifdef FEAT_SMARTINDENT
1246 did_si = can_si = FALSE;
1247#endif
1248 }
1249 else if (comment_end != NULL)
1250 {
1251 /*
1252 * We have finished a comment, so we don't use the leader.
1253 * If this was a C-comment and 'ai' or 'si' is set do a normal
1254 * indent to align with the line containing the start of the
1255 * comment.
1256 */
1257 if (comment_end[0] == '*' && comment_end[1] == '/' &&
1258 (curbuf->b_p_ai
1259#ifdef FEAT_SMARTINDENT
1260 || do_si
1261#endif
1262 ))
1263 {
1264 old_cursor = curwin->w_cursor;
1265 curwin->w_cursor.col = (colnr_T)(comment_end - saved_line);
1266 if ((pos = findmatch(NULL, NUL)) != NULL)
1267 {
1268 curwin->w_cursor.lnum = pos->lnum;
1269 newindent = get_indent();
1270 }
1271 curwin->w_cursor = old_cursor;
1272 }
1273 }
1274 }
1275#endif
1276
1277 /* (State == INSERT || State == REPLACE), only when dir == FORWARD */
1278 if (p_extra != NULL)
1279 {
1280 *p_extra = saved_char; /* restore char that NUL replaced */
1281
1282 /*
1283 * When 'ai' set or "flags" has OPENLINE_DELSPACES, skip to the first
1284 * non-blank.
1285 *
1286 * When in REPLACE mode, put the deleted blanks on the replace stack,
1287 * preceded by a NUL, so they can be put back when a BS is entered.
1288 */
1289 if (REPLACE_NORMAL(State))
1290 replace_push(NUL); /* end of extra blanks */
1291 if (curbuf->b_p_ai || (flags & OPENLINE_DELSPACES))
1292 {
1293 while ((*p_extra == ' ' || *p_extra == '\t')
1294#ifdef FEAT_MBYTE
1295 && (!enc_utf8
1296 || !utf_iscomposing(utf_ptr2char(p_extra + 1)))
1297#endif
1298 )
1299 {
1300 if (REPLACE_NORMAL(State))
1301 replace_push(*p_extra);
1302 ++p_extra;
1303 ++less_cols_off;
1304 }
1305 }
1306 if (*p_extra != NUL)
1307 did_ai = FALSE; /* append some text, don't truncate now */
1308
1309 /* columns for marks adjusted for removed columns */
1310 less_cols = (int)(p_extra - saved_line);
1311 }
1312
1313 if (p_extra == NULL)
1314 p_extra = (char_u *)""; /* append empty line */
1315
1316#ifdef FEAT_COMMENTS
1317 /* concatenate leader and p_extra, if there is a leader */
1318 if (lead_len)
1319 {
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +02001320 if (flags & OPENLINE_COM_LIST && second_line_indent > 0)
1321 {
1322 int i;
Bram Moolenaar36105782012-06-14 20:59:25 +02001323 int padding = second_line_indent
1324 - (newindent + (int)STRLEN(leader));
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +02001325
1326 /* Here whitespace is inserted after the comment char.
1327 * Below, set_indent(newindent, SIN_INSERT) will insert the
1328 * whitespace needed before the comment char. */
1329 for (i = 0; i < padding; i++)
1330 {
1331 STRCAT(leader, " ");
Bram Moolenaar5fb9ec52012-07-25 16:10:03 +02001332 less_cols--;
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +02001333 newcol++;
1334 }
1335 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001336 STRCAT(leader, p_extra);
1337 p_extra = leader;
1338 did_ai = TRUE; /* So truncating blanks works with comments */
1339 less_cols -= lead_len;
1340 }
1341 else
1342 end_comment_pending = NUL; /* turns out there was no leader */
1343#endif
1344
1345 old_cursor = curwin->w_cursor;
1346 if (dir == BACKWARD)
1347 --curwin->w_cursor.lnum;
1348#ifdef FEAT_VREPLACE
1349 if (!(State & VREPLACE_FLAG) || old_cursor.lnum >= orig_line_count)
1350#endif
1351 {
1352 if (ml_append(curwin->w_cursor.lnum, p_extra, (colnr_T)0, FALSE)
1353 == FAIL)
1354 goto theend;
1355 /* Postpone calling changed_lines(), because it would mess up folding
1356 * with markers. */
1357 mark_adjust(curwin->w_cursor.lnum + 1, (linenr_T)MAXLNUM, 1L, 0L);
1358 did_append = TRUE;
1359 }
1360#ifdef FEAT_VREPLACE
1361 else
1362 {
1363 /*
1364 * In VREPLACE mode we are starting to replace the next line.
1365 */
1366 curwin->w_cursor.lnum++;
1367 if (curwin->w_cursor.lnum >= Insstart.lnum + vr_lines_changed)
1368 {
1369 /* In case we NL to a new line, BS to the previous one, and NL
1370 * again, we don't want to save the new line for undo twice.
1371 */
1372 (void)u_save_cursor(); /* errors are ignored! */
1373 vr_lines_changed++;
1374 }
1375 ml_replace(curwin->w_cursor.lnum, p_extra, TRUE);
1376 changed_bytes(curwin->w_cursor.lnum, 0);
1377 curwin->w_cursor.lnum--;
1378 did_append = FALSE;
1379 }
1380#endif
1381
1382 if (newindent
1383#ifdef FEAT_SMARTINDENT
1384 || did_si
1385#endif
1386 )
1387 {
1388 ++curwin->w_cursor.lnum;
1389#ifdef FEAT_SMARTINDENT
1390 if (did_si)
1391 {
Bram Moolenaar14f24742012-08-08 18:01:05 +02001392 int sw = (int)get_sw_value();
1393
Bram Moolenaar071d4272004-06-13 20:20:40 +00001394 if (p_sr)
Bram Moolenaar14f24742012-08-08 18:01:05 +02001395 newindent -= newindent % sw;
1396 newindent += sw;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001397 }
1398#endif
Bram Moolenaar5002c292007-07-24 13:26:15 +00001399 /* Copy the indent */
1400 if (curbuf->b_p_ci)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001401 {
1402 (void)copy_indent(newindent, saved_line);
1403
1404 /*
1405 * Set the 'preserveindent' option so that any further screwing
1406 * with the line doesn't entirely destroy our efforts to preserve
1407 * it. It gets restored at the function end.
1408 */
1409 curbuf->b_p_pi = TRUE;
1410 }
1411 else
1412 (void)set_indent(newindent, SIN_INSERT);
1413 less_cols -= curwin->w_cursor.col;
1414
1415 ai_col = curwin->w_cursor.col;
1416
1417 /*
1418 * In REPLACE mode, for each character in the new indent, there must
1419 * be a NUL on the replace stack, for when it is deleted with BS
1420 */
1421 if (REPLACE_NORMAL(State))
1422 for (n = 0; n < (int)curwin->w_cursor.col; ++n)
1423 replace_push(NUL);
1424 newcol += curwin->w_cursor.col;
1425#ifdef FEAT_SMARTINDENT
1426 if (no_si)
1427 did_si = FALSE;
1428#endif
1429 }
1430
1431#ifdef FEAT_COMMENTS
1432 /*
1433 * In REPLACE mode, for each character in the extra leader, there must be
1434 * a NUL on the replace stack, for when it is deleted with BS.
1435 */
1436 if (REPLACE_NORMAL(State))
1437 while (lead_len-- > 0)
1438 replace_push(NUL);
1439#endif
1440
1441 curwin->w_cursor = old_cursor;
1442
1443 if (dir == FORWARD)
1444 {
1445 if (trunc_line || (State & INSERT))
1446 {
1447 /* truncate current line at cursor */
1448 saved_line[curwin->w_cursor.col] = NUL;
1449 /* Remove trailing white space, unless OPENLINE_KEEPTRAIL used. */
1450 if (trunc_line && !(flags & OPENLINE_KEEPTRAIL))
1451 truncate_spaces(saved_line);
1452 ml_replace(curwin->w_cursor.lnum, saved_line, FALSE);
1453 saved_line = NULL;
1454 if (did_append)
1455 {
1456 changed_lines(curwin->w_cursor.lnum, curwin->w_cursor.col,
1457 curwin->w_cursor.lnum + 1, 1L);
1458 did_append = FALSE;
1459
1460 /* Move marks after the line break to the new line. */
1461 if (flags & OPENLINE_MARKFIX)
1462 mark_col_adjust(curwin->w_cursor.lnum,
1463 curwin->w_cursor.col + less_cols_off,
1464 1L, (long)-less_cols);
1465 }
1466 else
1467 changed_bytes(curwin->w_cursor.lnum, curwin->w_cursor.col);
1468 }
1469
1470 /*
1471 * Put the cursor on the new line. Careful: the scrollup() above may
1472 * have moved w_cursor, we must use old_cursor.
1473 */
1474 curwin->w_cursor.lnum = old_cursor.lnum + 1;
1475 }
1476 if (did_append)
1477 changed_lines(curwin->w_cursor.lnum, 0, curwin->w_cursor.lnum, 1L);
1478
1479 curwin->w_cursor.col = newcol;
1480#ifdef FEAT_VIRTUALEDIT
1481 curwin->w_cursor.coladd = 0;
1482#endif
1483
1484#if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
1485 /*
1486 * In VREPLACE mode, we are handling the replace stack ourselves, so stop
1487 * fixthisline() from doing it (via change_indent()) by telling it we're in
1488 * normal INSERT mode.
1489 */
1490 if (State & VREPLACE_FLAG)
1491 {
1492 vreplace_mode = State; /* So we know to put things right later */
1493 State = INSERT;
1494 }
1495 else
1496 vreplace_mode = 0;
1497#endif
1498#ifdef FEAT_LISP
1499 /*
1500 * May do lisp indenting.
1501 */
1502 if (!p_paste
1503# ifdef FEAT_COMMENTS
1504 && leader == NULL
1505# endif
1506 && curbuf->b_p_lisp
1507 && curbuf->b_p_ai)
1508 {
1509 fixthisline(get_lisp_indent);
1510 p = ml_get_curline();
1511 ai_col = (colnr_T)(skipwhite(p) - p);
1512 }
1513#endif
1514#ifdef FEAT_CINDENT
1515 /*
1516 * May do indenting after opening a new line.
1517 */
1518 if (!p_paste
1519 && (curbuf->b_p_cin
1520# ifdef FEAT_EVAL
1521 || *curbuf->b_p_inde != NUL
1522# endif
1523 )
1524 && in_cinkeys(dir == FORWARD
1525 ? KEY_OPEN_FORW
1526 : KEY_OPEN_BACK, ' ', linewhite(curwin->w_cursor.lnum)))
1527 {
1528 do_c_expr_indent();
1529 p = ml_get_curline();
1530 ai_col = (colnr_T)(skipwhite(p) - p);
1531 }
1532#endif
1533#if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
1534 if (vreplace_mode != 0)
1535 State = vreplace_mode;
1536#endif
1537
1538#ifdef FEAT_VREPLACE
1539 /*
1540 * Finally, VREPLACE gets the stuff on the new line, then puts back the
1541 * original line, and inserts the new stuff char by char, pushing old stuff
1542 * onto the replace stack (via ins_char()).
1543 */
1544 if (State & VREPLACE_FLAG)
1545 {
1546 /* Put new line in p_extra */
1547 p_extra = vim_strsave(ml_get_curline());
1548 if (p_extra == NULL)
1549 goto theend;
1550
1551 /* Put back original line */
1552 ml_replace(curwin->w_cursor.lnum, next_line, FALSE);
1553
1554 /* Insert new stuff into line again */
1555 curwin->w_cursor.col = 0;
1556#ifdef FEAT_VIRTUALEDIT
1557 curwin->w_cursor.coladd = 0;
1558#endif
1559 ins_bytes(p_extra); /* will call changed_bytes() */
1560 vim_free(p_extra);
1561 next_line = NULL;
1562 }
1563#endif
1564
1565 retval = TRUE; /* success! */
1566theend:
1567 curbuf->b_p_pi = saved_pi;
1568 vim_free(saved_line);
1569 vim_free(next_line);
1570 vim_free(allocated);
1571 return retval;
1572}
1573
1574#if defined(FEAT_COMMENTS) || defined(PROTO)
1575/*
1576 * get_leader_len() returns the length of the prefix of the given string
1577 * which introduces a comment. If this string is not a comment then 0 is
1578 * returned.
1579 * When "flags" is not NULL, it is set to point to the flags of the recognized
1580 * comment leader.
1581 * "backward" must be true for the "O" command.
Bram Moolenaar81340392012-06-06 16:12:59 +02001582 * If "include_space" is set, include trailing whitespace while calculating the
1583 * length.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001584 */
1585 int
Bram Moolenaar81340392012-06-06 16:12:59 +02001586get_leader_len(line, flags, backward, include_space)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001587 char_u *line;
1588 char_u **flags;
1589 int backward;
Bram Moolenaar81340392012-06-06 16:12:59 +02001590 int include_space;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001591{
1592 int i, j;
Bram Moolenaar81340392012-06-06 16:12:59 +02001593 int result;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001594 int got_com = FALSE;
1595 int found_one;
1596 char_u part_buf[COM_MAX_LEN]; /* buffer for one option part */
1597 char_u *string; /* pointer to comment string */
1598 char_u *list;
Bram Moolenaara4271d52011-05-10 13:38:27 +02001599 int middle_match_len = 0;
1600 char_u *prev_list;
Bram Moolenaar05da4282011-05-10 14:44:11 +02001601 char_u *saved_flags = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001602
Bram Moolenaar81340392012-06-06 16:12:59 +02001603 result = i = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001604 while (vim_iswhite(line[i])) /* leading white space is ignored */
1605 ++i;
1606
1607 /*
1608 * Repeat to match several nested comment strings.
1609 */
Bram Moolenaara4271d52011-05-10 13:38:27 +02001610 while (line[i] != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001611 {
1612 /*
1613 * scan through the 'comments' option for a match
1614 */
1615 found_one = FALSE;
1616 for (list = curbuf->b_p_com; *list; )
1617 {
Bram Moolenaara4271d52011-05-10 13:38:27 +02001618 /* Get one option part into part_buf[]. Advance "list" to next
1619 * one. Put "string" at start of string. */
1620 if (!got_com && flags != NULL)
1621 *flags = list; /* remember where flags started */
1622 prev_list = list;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001623 (void)copy_option_part(&list, part_buf, COM_MAX_LEN, ",");
1624 string = vim_strchr(part_buf, ':');
1625 if (string == NULL) /* missing ':', ignore this part */
1626 continue;
1627 *string++ = NUL; /* isolate flags from string */
1628
Bram Moolenaara4271d52011-05-10 13:38:27 +02001629 /* If we found a middle match previously, use that match when this
1630 * is not a middle or end. */
1631 if (middle_match_len != 0
1632 && vim_strchr(part_buf, COM_MIDDLE) == NULL
1633 && vim_strchr(part_buf, COM_END) == NULL)
1634 break;
1635
1636 /* When we already found a nested comment, only accept further
1637 * nested comments. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001638 if (got_com && vim_strchr(part_buf, COM_NEST) == NULL)
1639 continue;
1640
Bram Moolenaara4271d52011-05-10 13:38:27 +02001641 /* When 'O' flag present and using "O" command skip this one. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001642 if (backward && vim_strchr(part_buf, COM_NOBACK) != NULL)
1643 continue;
1644
Bram Moolenaara4271d52011-05-10 13:38:27 +02001645 /* Line contents and string must match.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001646 * When string starts with white space, must have some white space
1647 * (but the amount does not need to match, there might be a mix of
Bram Moolenaara4271d52011-05-10 13:38:27 +02001648 * TABs and spaces). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001649 if (vim_iswhite(string[0]))
1650 {
1651 if (i == 0 || !vim_iswhite(line[i - 1]))
Bram Moolenaara4271d52011-05-10 13:38:27 +02001652 continue; /* missing shite space */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001653 while (vim_iswhite(string[0]))
1654 ++string;
1655 }
1656 for (j = 0; string[j] != NUL && string[j] == line[i + j]; ++j)
1657 ;
1658 if (string[j] != NUL)
Bram Moolenaara4271d52011-05-10 13:38:27 +02001659 continue; /* string doesn't match */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001660
Bram Moolenaara4271d52011-05-10 13:38:27 +02001661 /* When 'b' flag used, there must be white space or an
1662 * end-of-line after the string in the line. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001663 if (vim_strchr(part_buf, COM_BLANK) != NULL
1664 && !vim_iswhite(line[i + j]) && line[i + j] != NUL)
1665 continue;
1666
Bram Moolenaara4271d52011-05-10 13:38:27 +02001667 /* We have found a match, stop searching unless this is a middle
1668 * comment. The middle comment can be a substring of the end
1669 * comment in which case it's better to return the length of the
1670 * end comment and its flags. Thus we keep searching with middle
1671 * and end matches and use an end match if it matches better. */
1672 if (vim_strchr(part_buf, COM_MIDDLE) != NULL)
1673 {
1674 if (middle_match_len == 0)
1675 {
1676 middle_match_len = j;
1677 saved_flags = prev_list;
1678 }
1679 continue;
1680 }
1681 if (middle_match_len != 0 && j > middle_match_len)
1682 /* Use this match instead of the middle match, since it's a
1683 * longer thus better match. */
1684 middle_match_len = 0;
1685
1686 if (middle_match_len == 0)
1687 i += j;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001688 found_one = TRUE;
1689 break;
1690 }
1691
Bram Moolenaara4271d52011-05-10 13:38:27 +02001692 if (middle_match_len != 0)
1693 {
1694 /* Use the previously found middle match after failing to find a
1695 * match with an end. */
1696 if (!got_com && flags != NULL)
1697 *flags = saved_flags;
1698 i += middle_match_len;
1699 found_one = TRUE;
1700 }
1701
1702 /* No match found, stop scanning. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001703 if (!found_one)
1704 break;
1705
Bram Moolenaar81340392012-06-06 16:12:59 +02001706 result = i;
1707
Bram Moolenaara4271d52011-05-10 13:38:27 +02001708 /* Include any trailing white space. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001709 while (vim_iswhite(line[i]))
1710 ++i;
1711
Bram Moolenaar81340392012-06-06 16:12:59 +02001712 if (include_space)
1713 result = i;
1714
Bram Moolenaara4271d52011-05-10 13:38:27 +02001715 /* If this comment doesn't nest, stop here. */
1716 got_com = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001717 if (vim_strchr(part_buf, COM_NEST) == NULL)
1718 break;
1719 }
Bram Moolenaar81340392012-06-06 16:12:59 +02001720 return result;
1721}
Bram Moolenaara4271d52011-05-10 13:38:27 +02001722
Bram Moolenaar81340392012-06-06 16:12:59 +02001723/*
1724 * Return the offset at which the last comment in line starts. If there is no
1725 * comment in the whole line, -1 is returned.
1726 *
1727 * When "flags" is not null, it is set to point to the flags describing the
1728 * recognized comment leader.
1729 */
1730 int
1731get_last_leader_offset(line, flags)
1732 char_u *line;
1733 char_u **flags;
1734{
1735 int result = -1;
1736 int i, j;
1737 int lower_check_bound = 0;
1738 char_u *string;
1739 char_u *com_leader;
1740 char_u *com_flags;
1741 char_u *list;
1742 int found_one;
1743 char_u part_buf[COM_MAX_LEN]; /* buffer for one option part */
1744
1745 /*
1746 * Repeat to match several nested comment strings.
1747 */
1748 i = (int)STRLEN(line);
1749 while (--i >= lower_check_bound)
1750 {
1751 /*
1752 * scan through the 'comments' option for a match
1753 */
1754 found_one = FALSE;
1755 for (list = curbuf->b_p_com; *list; )
1756 {
1757 char_u *flags_save = list;
1758
1759 /*
1760 * Get one option part into part_buf[]. Advance list to next one.
1761 * put string at start of string.
1762 */
1763 (void)copy_option_part(&list, part_buf, COM_MAX_LEN, ",");
1764 string = vim_strchr(part_buf, ':');
1765 if (string == NULL) /* If everything is fine, this cannot actually
1766 * happen. */
1767 {
1768 continue;
1769 }
1770 *string++ = NUL; /* Isolate flags from string. */
1771 com_leader = string;
1772
1773 /*
1774 * Line contents and string must match.
1775 * When string starts with white space, must have some white space
1776 * (but the amount does not need to match, there might be a mix of
1777 * TABs and spaces).
1778 */
1779 if (vim_iswhite(string[0]))
1780 {
1781 if (i == 0 || !vim_iswhite(line[i - 1]))
1782 continue;
1783 while (vim_iswhite(string[0]))
1784 ++string;
1785 }
1786 for (j = 0; string[j] != NUL && string[j] == line[i + j]; ++j)
1787 /* do nothing */;
1788 if (string[j] != NUL)
1789 continue;
1790
1791 /*
1792 * When 'b' flag used, there must be white space or an
1793 * end-of-line after the string in the line.
1794 */
1795 if (vim_strchr(part_buf, COM_BLANK) != NULL
1796 && !vim_iswhite(line[i + j]) && line[i + j] != NUL)
1797 {
1798 continue;
1799 }
1800
1801 /*
1802 * We have found a match, stop searching.
1803 */
1804 found_one = TRUE;
1805
1806 if (flags)
1807 *flags = flags_save;
1808 com_flags = flags_save;
1809
1810 break;
1811 }
1812
1813 if (found_one)
1814 {
1815 char_u part_buf2[COM_MAX_LEN]; /* buffer for one option part */
1816 int len1, len2, off;
1817
1818 result = i;
1819 /*
1820 * If this comment nests, continue searching.
1821 */
1822 if (vim_strchr(part_buf, COM_NEST) != NULL)
1823 continue;
1824
1825 lower_check_bound = i;
1826
1827 /* Let's verify whether the comment leader found is a substring
1828 * of other comment leaders. If it is, let's adjust the
1829 * lower_check_bound so that we make sure that we have determined
1830 * the comment leader correctly.
1831 */
1832
1833 while (vim_iswhite(*com_leader))
1834 ++com_leader;
1835 len1 = (int)STRLEN(com_leader);
1836
1837 for (list = curbuf->b_p_com; *list; )
1838 {
1839 char_u *flags_save = list;
1840
1841 (void)copy_option_part(&list, part_buf2, COM_MAX_LEN, ",");
1842 if (flags_save == com_flags)
1843 continue;
1844 string = vim_strchr(part_buf2, ':');
1845 ++string;
1846 while (vim_iswhite(*string))
1847 ++string;
1848 len2 = (int)STRLEN(string);
1849 if (len2 == 0)
1850 continue;
1851
1852 /* Now we have to verify whether string ends with a substring
1853 * beginning the com_leader. */
1854 for (off = (len2 > i ? i : len2); off > 0 && off + len1 > len2;)
1855 {
1856 --off;
1857 if (!STRNCMP(string + off, com_leader, len2 - off))
1858 {
1859 if (i - off < lower_check_bound)
1860 lower_check_bound = i - off;
1861 }
1862 }
1863 }
1864 }
1865 }
1866 return result;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001867}
1868#endif
1869
1870/*
1871 * Return the number of window lines occupied by buffer line "lnum".
1872 */
1873 int
1874plines(lnum)
1875 linenr_T lnum;
1876{
1877 return plines_win(curwin, lnum, TRUE);
1878}
1879
1880 int
1881plines_win(wp, lnum, winheight)
1882 win_T *wp;
1883 linenr_T lnum;
1884 int winheight; /* when TRUE limit to window height */
1885{
1886#if defined(FEAT_DIFF) || defined(PROTO)
1887 /* Check for filler lines above this buffer line. When folded the result
1888 * is one line anyway. */
1889 return plines_win_nofill(wp, lnum, winheight) + diff_check_fill(wp, lnum);
1890}
1891
1892 int
1893plines_nofill(lnum)
1894 linenr_T lnum;
1895{
1896 return plines_win_nofill(curwin, lnum, TRUE);
1897}
1898
1899 int
1900plines_win_nofill(wp, lnum, winheight)
1901 win_T *wp;
1902 linenr_T lnum;
1903 int winheight; /* when TRUE limit to window height */
1904{
1905#endif
1906 int lines;
1907
1908 if (!wp->w_p_wrap)
1909 return 1;
1910
1911#ifdef FEAT_VERTSPLIT
1912 if (wp->w_width == 0)
1913 return 1;
1914#endif
1915
1916#ifdef FEAT_FOLDING
1917 /* A folded lines is handled just like an empty line. */
1918 /* NOTE: Caller must handle lines that are MAYBE folded. */
1919 if (lineFolded(wp, lnum) == TRUE)
1920 return 1;
1921#endif
1922
1923 lines = plines_win_nofold(wp, lnum);
1924 if (winheight > 0 && lines > wp->w_height)
1925 return (int)wp->w_height;
1926 return lines;
1927}
1928
1929/*
1930 * Return number of window lines physical line "lnum" will occupy in window
1931 * "wp". Does not care about folding, 'wrap' or 'diff'.
1932 */
1933 int
1934plines_win_nofold(wp, lnum)
1935 win_T *wp;
1936 linenr_T lnum;
1937{
1938 char_u *s;
1939 long col;
1940 int width;
1941
1942 s = ml_get_buf(wp->w_buffer, lnum, FALSE);
1943 if (*s == NUL) /* empty line */
1944 return 1;
1945 col = win_linetabsize(wp, s, (colnr_T)MAXCOL);
1946
1947 /*
1948 * If list mode is on, then the '$' at the end of the line may take up one
1949 * extra column.
1950 */
1951 if (wp->w_p_list && lcs_eol != NUL)
1952 col += 1;
1953
1954 /*
Bram Moolenaar64486672010-05-16 15:46:46 +02001955 * Add column offset for 'number', 'relativenumber' and 'foldcolumn'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001956 */
1957 width = W_WIDTH(wp) - win_col_off(wp);
1958 if (width <= 0)
1959 return 32000;
1960 if (col <= width)
1961 return 1;
1962 col -= width;
1963 width += win_col_off2(wp);
1964 return (col + (width - 1)) / width + 1;
1965}
1966
1967/*
1968 * Like plines_win(), but only reports the number of physical screen lines
1969 * used from the start of the line to the given column number.
1970 */
1971 int
1972plines_win_col(wp, lnum, column)
1973 win_T *wp;
1974 linenr_T lnum;
1975 long column;
1976{
1977 long col;
1978 char_u *s;
1979 int lines = 0;
1980 int width;
1981
1982#ifdef FEAT_DIFF
1983 /* Check for filler lines above this buffer line. When folded the result
1984 * is one line anyway. */
1985 lines = diff_check_fill(wp, lnum);
1986#endif
1987
1988 if (!wp->w_p_wrap)
1989 return lines + 1;
1990
1991#ifdef FEAT_VERTSPLIT
1992 if (wp->w_width == 0)
1993 return lines + 1;
1994#endif
1995
1996 s = ml_get_buf(wp->w_buffer, lnum, FALSE);
1997
1998 col = 0;
1999 while (*s != NUL && --column >= 0)
2000 {
2001 col += win_lbr_chartabsize(wp, s, (colnr_T)col, NULL);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002002 mb_ptr_adv(s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002003 }
2004
2005 /*
2006 * If *s is a TAB, and the TAB is not displayed as ^I, and we're not in
2007 * INSERT mode, then col must be adjusted so that it represents the last
2008 * screen position of the TAB. This only fixes an error when the TAB wraps
2009 * from one screen line to the next (when 'columns' is not a multiple of
2010 * 'ts') -- webb.
2011 */
2012 if (*s == TAB && (State & NORMAL) && (!wp->w_p_list || lcs_tab1))
2013 col += win_lbr_chartabsize(wp, s, (colnr_T)col, NULL) - 1;
2014
2015 /*
Bram Moolenaar64486672010-05-16 15:46:46 +02002016 * Add column offset for 'number', 'relativenumber', 'foldcolumn', etc.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002017 */
2018 width = W_WIDTH(wp) - win_col_off(wp);
Bram Moolenaar26470632006-10-24 19:12:40 +00002019 if (width <= 0)
2020 return 9999;
2021
2022 lines += 1;
2023 if (col > width)
2024 lines += (col - width) / (width + win_col_off2(wp)) + 1;
2025 return lines;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002026}
2027
2028 int
2029plines_m_win(wp, first, last)
2030 win_T *wp;
2031 linenr_T first, last;
2032{
2033 int count = 0;
2034
2035 while (first <= last)
2036 {
2037#ifdef FEAT_FOLDING
2038 int x;
2039
2040 /* Check if there are any really folded lines, but also included lines
2041 * that are maybe folded. */
2042 x = foldedCount(wp, first, NULL);
2043 if (x > 0)
2044 {
2045 ++count; /* count 1 for "+-- folded" line */
2046 first += x;
2047 }
2048 else
2049#endif
2050 {
2051#ifdef FEAT_DIFF
2052 if (first == wp->w_topline)
2053 count += plines_win_nofill(wp, first, TRUE) + wp->w_topfill;
2054 else
2055#endif
2056 count += plines_win(wp, first, TRUE);
2057 ++first;
2058 }
2059 }
2060 return (count);
2061}
2062
2063#if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) || defined(PROTO)
2064/*
2065 * Insert string "p" at the cursor position. Stops at a NUL byte.
2066 * Handles Replace mode and multi-byte characters.
2067 */
2068 void
2069ins_bytes(p)
2070 char_u *p;
2071{
2072 ins_bytes_len(p, (int)STRLEN(p));
2073}
2074#endif
2075
2076#if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) \
2077 || defined(FEAT_COMMENTS) || defined(FEAT_MBYTE) || defined(PROTO)
2078/*
2079 * Insert string "p" with length "len" at the cursor position.
2080 * Handles Replace mode and multi-byte characters.
2081 */
2082 void
2083ins_bytes_len(p, len)
2084 char_u *p;
2085 int len;
2086{
2087 int i;
2088# ifdef FEAT_MBYTE
2089 int n;
2090
Bram Moolenaar176dd1e2008-06-21 14:30:28 +00002091 if (has_mbyte)
2092 for (i = 0; i < len; i += n)
2093 {
2094 if (enc_utf8)
2095 /* avoid reading past p[len] */
2096 n = utfc_ptr2len_len(p + i, len - i);
2097 else
2098 n = (*mb_ptr2len)(p + i);
2099 ins_char_bytes(p + i, n);
2100 }
2101 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002102# endif
Bram Moolenaar176dd1e2008-06-21 14:30:28 +00002103 for (i = 0; i < len; ++i)
2104 ins_char(p[i]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002105}
2106#endif
2107
2108/*
2109 * Insert or replace a single character at the cursor position.
2110 * When in REPLACE or VREPLACE mode, replace any existing character.
2111 * Caller must have prepared for undo.
2112 * For multi-byte characters we get the whole character, the caller must
2113 * convert bytes to a character.
2114 */
2115 void
2116ins_char(c)
2117 int c;
2118{
2119#if defined(FEAT_MBYTE) || defined(PROTO)
Bram Moolenaar9a920d82012-06-01 15:21:02 +02002120 char_u buf[MB_MAXBYTES + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002121 int n;
2122
2123 n = (*mb_char2bytes)(c, buf);
2124
2125 /* When "c" is 0x100, 0x200, etc. we don't want to insert a NUL byte.
2126 * Happens for CTRL-Vu9900. */
2127 if (buf[0] == 0)
2128 buf[0] = '\n';
2129
2130 ins_char_bytes(buf, n);
2131}
2132
2133 void
2134ins_char_bytes(buf, charlen)
2135 char_u *buf;
2136 int charlen;
2137{
2138 int c = buf[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002139#endif
2140 int newlen; /* nr of bytes inserted */
2141 int oldlen; /* nr of bytes deleted (0 when not replacing) */
2142 char_u *p;
2143 char_u *newp;
2144 char_u *oldp;
2145 int linelen; /* length of old line including NUL */
2146 colnr_T col;
2147 linenr_T lnum = curwin->w_cursor.lnum;
2148 int i;
2149
2150#ifdef FEAT_VIRTUALEDIT
2151 /* Break tabs if needed. */
2152 if (virtual_active() && curwin->w_cursor.coladd > 0)
2153 coladvance_force(getviscol());
2154#endif
2155
2156 col = curwin->w_cursor.col;
2157 oldp = ml_get(lnum);
2158 linelen = (int)STRLEN(oldp) + 1;
2159
2160 /* The lengths default to the values for when not replacing. */
2161 oldlen = 0;
2162#ifdef FEAT_MBYTE
2163 newlen = charlen;
2164#else
2165 newlen = 1;
2166#endif
2167
2168 if (State & REPLACE_FLAG)
2169 {
2170#ifdef FEAT_VREPLACE
2171 if (State & VREPLACE_FLAG)
2172 {
2173 colnr_T new_vcol = 0; /* init for GCC */
2174 colnr_T vcol;
2175 int old_list;
2176#ifndef FEAT_MBYTE
2177 char_u buf[2];
2178#endif
2179
2180 /*
2181 * Disable 'list' temporarily, unless 'cpo' contains the 'L' flag.
2182 * Returns the old value of list, so when finished,
2183 * curwin->w_p_list should be set back to this.
2184 */
2185 old_list = curwin->w_p_list;
2186 if (old_list && vim_strchr(p_cpo, CPO_LISTWM) == NULL)
2187 curwin->w_p_list = FALSE;
2188
2189 /*
2190 * In virtual replace mode each character may replace one or more
2191 * characters (zero if it's a TAB). Count the number of bytes to
2192 * be deleted to make room for the new character, counting screen
2193 * cells. May result in adding spaces to fill a gap.
2194 */
2195 getvcol(curwin, &curwin->w_cursor, NULL, &vcol, NULL);
2196#ifndef FEAT_MBYTE
2197 buf[0] = c;
2198 buf[1] = NUL;
2199#endif
2200 new_vcol = vcol + chartabsize(buf, vcol);
2201 while (oldp[col + oldlen] != NUL && vcol < new_vcol)
2202 {
2203 vcol += chartabsize(oldp + col + oldlen, vcol);
2204 /* Don't need to remove a TAB that takes us to the right
2205 * position. */
2206 if (vcol > new_vcol && oldp[col + oldlen] == TAB)
2207 break;
2208#ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002209 oldlen += (*mb_ptr2len)(oldp + col + oldlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002210#else
2211 ++oldlen;
2212#endif
2213 /* Deleted a bit too much, insert spaces. */
2214 if (vcol > new_vcol)
2215 newlen += vcol - new_vcol;
2216 }
2217 curwin->w_p_list = old_list;
2218 }
2219 else
2220#endif
2221 if (oldp[col] != NUL)
2222 {
2223 /* normal replace */
2224#ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002225 oldlen = (*mb_ptr2len)(oldp + col);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002226#else
2227 oldlen = 1;
2228#endif
2229 }
2230
2231
2232 /* Push the replaced bytes onto the replace stack, so that they can be
2233 * put back when BS is used. The bytes of a multi-byte character are
2234 * done the other way around, so that the first byte is popped off
2235 * first (it tells the byte length of the character). */
2236 replace_push(NUL);
2237 for (i = 0; i < oldlen; ++i)
2238 {
2239#ifdef FEAT_MBYTE
Bram Moolenaar2c994e82008-01-02 16:49:36 +00002240 if (has_mbyte)
2241 i += replace_push_mb(oldp + col + i) - 1;
2242 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002243#endif
Bram Moolenaar2c994e82008-01-02 16:49:36 +00002244 replace_push(oldp[col + i]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002245 }
2246 }
2247
2248 newp = alloc_check((unsigned)(linelen + newlen - oldlen));
2249 if (newp == NULL)
2250 return;
2251
2252 /* Copy bytes before the cursor. */
2253 if (col > 0)
2254 mch_memmove(newp, oldp, (size_t)col);
2255
2256 /* Copy bytes after the changed character(s). */
2257 p = newp + col;
2258 mch_memmove(p + newlen, oldp + col + oldlen,
2259 (size_t)(linelen - col - oldlen));
2260
2261 /* Insert or overwrite the new character. */
2262#ifdef FEAT_MBYTE
2263 mch_memmove(p, buf, charlen);
2264 i = charlen;
2265#else
2266 *p = c;
2267 i = 1;
2268#endif
2269
2270 /* Fill with spaces when necessary. */
2271 while (i < newlen)
2272 p[i++] = ' ';
2273
2274 /* Replace the line in the buffer. */
2275 ml_replace(lnum, newp, FALSE);
2276
2277 /* mark the buffer as changed and prepare for displaying */
2278 changed_bytes(lnum, col);
2279
2280 /*
2281 * If we're in Insert or Replace mode and 'showmatch' is set, then briefly
2282 * show the match for right parens and braces.
2283 */
2284 if (p_sm && (State & INSERT)
2285 && msg_silent == 0
2286#ifdef FEAT_MBYTE
2287 && charlen == 1
2288#endif
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00002289#ifdef FEAT_INS_EXPAND
2290 && !ins_compl_active()
2291#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002292 )
2293 showmatch(c);
2294
2295#ifdef FEAT_RIGHTLEFT
2296 if (!p_ri || (State & REPLACE_FLAG))
2297#endif
2298 {
2299 /* Normal insert: move cursor right */
2300#ifdef FEAT_MBYTE
2301 curwin->w_cursor.col += charlen;
2302#else
2303 ++curwin->w_cursor.col;
2304#endif
2305 }
2306 /*
2307 * TODO: should try to update w_row here, to avoid recomputing it later.
2308 */
2309}
2310
2311/*
2312 * Insert a string at the cursor position.
2313 * Note: Does NOT handle Replace mode.
2314 * Caller must have prepared for undo.
2315 */
2316 void
2317ins_str(s)
2318 char_u *s;
2319{
2320 char_u *oldp, *newp;
2321 int newlen = (int)STRLEN(s);
2322 int oldlen;
2323 colnr_T col;
2324 linenr_T lnum = curwin->w_cursor.lnum;
2325
2326#ifdef FEAT_VIRTUALEDIT
2327 if (virtual_active() && curwin->w_cursor.coladd > 0)
2328 coladvance_force(getviscol());
2329#endif
2330
2331 col = curwin->w_cursor.col;
2332 oldp = ml_get(lnum);
2333 oldlen = (int)STRLEN(oldp);
2334
2335 newp = alloc_check((unsigned)(oldlen + newlen + 1));
2336 if (newp == NULL)
2337 return;
2338 if (col > 0)
2339 mch_memmove(newp, oldp, (size_t)col);
2340 mch_memmove(newp + col, s, (size_t)newlen);
2341 mch_memmove(newp + col + newlen, oldp + col, (size_t)(oldlen - col + 1));
2342 ml_replace(lnum, newp, FALSE);
2343 changed_bytes(lnum, col);
2344 curwin->w_cursor.col += newlen;
2345}
2346
2347/*
2348 * Delete one character under the cursor.
2349 * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
2350 * Caller must have prepared for undo.
2351 *
2352 * return FAIL for failure, OK otherwise
2353 */
2354 int
2355del_char(fixpos)
2356 int fixpos;
2357{
2358#ifdef FEAT_MBYTE
2359 if (has_mbyte)
2360 {
2361 /* Make sure the cursor is at the start of a character. */
2362 mb_adjust_cursor();
2363 if (*ml_get_cursor() == NUL)
2364 return FAIL;
2365 return del_chars(1L, fixpos);
2366 }
2367#endif
Bram Moolenaare3226be2005-12-18 22:10:00 +00002368 return del_bytes(1L, fixpos, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002369}
2370
2371#if defined(FEAT_MBYTE) || defined(PROTO)
2372/*
2373 * Like del_bytes(), but delete characters instead of bytes.
2374 */
2375 int
2376del_chars(count, fixpos)
2377 long count;
2378 int fixpos;
2379{
2380 long bytes = 0;
2381 long i;
2382 char_u *p;
2383 int l;
2384
2385 p = ml_get_cursor();
2386 for (i = 0; i < count && *p != NUL; ++i)
2387 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002388 l = (*mb_ptr2len)(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002389 bytes += l;
2390 p += l;
2391 }
Bram Moolenaare3226be2005-12-18 22:10:00 +00002392 return del_bytes(bytes, fixpos, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002393}
2394#endif
2395
2396/*
2397 * Delete "count" bytes under the cursor.
2398 * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
2399 * Caller must have prepared for undo.
2400 *
2401 * return FAIL for failure, OK otherwise
2402 */
2403 int
Bram Moolenaarca003e12006-03-17 23:19:38 +00002404del_bytes(count, fixpos_arg, use_delcombine)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002405 long count;
Bram Moolenaarca003e12006-03-17 23:19:38 +00002406 int fixpos_arg;
Bram Moolenaar78a15312009-05-15 19:33:18 +00002407 int use_delcombine UNUSED; /* 'delcombine' option applies */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002408{
2409 char_u *oldp, *newp;
2410 colnr_T oldlen;
2411 linenr_T lnum = curwin->w_cursor.lnum;
2412 colnr_T col = curwin->w_cursor.col;
2413 int was_alloced;
2414 long movelen;
Bram Moolenaarca003e12006-03-17 23:19:38 +00002415 int fixpos = fixpos_arg;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002416
2417 oldp = ml_get(lnum);
2418 oldlen = (int)STRLEN(oldp);
2419
2420 /*
2421 * Can't do anything when the cursor is on the NUL after the line.
2422 */
2423 if (col >= oldlen)
2424 return FAIL;
2425
2426#ifdef FEAT_MBYTE
2427 /* If 'delcombine' is set and deleting (less than) one character, only
2428 * delete the last combining character. */
Bram Moolenaare3226be2005-12-18 22:10:00 +00002429 if (p_deco && use_delcombine && enc_utf8
2430 && utfc_ptr2len(oldp + col) >= count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002431 {
Bram Moolenaar362e1a32006-03-06 23:29:24 +00002432 int cc[MAX_MCO];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002433 int n;
2434
Bram Moolenaar362e1a32006-03-06 23:29:24 +00002435 (void)utfc_ptr2char(oldp + col, cc);
2436 if (cc[0] != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002437 {
2438 /* Find the last composing char, there can be several. */
2439 n = col;
2440 do
2441 {
2442 col = n;
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002443 count = utf_ptr2len(oldp + n);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002444 n += count;
2445 } while (UTF_COMPOSINGLIKE(oldp + col, oldp + n));
2446 fixpos = 0;
2447 }
2448 }
2449#endif
2450
2451 /*
2452 * When count is too big, reduce it.
2453 */
2454 movelen = (long)oldlen - (long)col - count + 1; /* includes trailing NUL */
2455 if (movelen <= 1)
2456 {
2457 /*
2458 * If we just took off the last character of a non-blank line, and
Bram Moolenaarca003e12006-03-17 23:19:38 +00002459 * fixpos is TRUE, we don't want to end up positioned at the NUL,
2460 * unless "restart_edit" is set or 'virtualedit' contains "onemore".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002461 */
Bram Moolenaarca003e12006-03-17 23:19:38 +00002462 if (col > 0 && fixpos && restart_edit == 0
2463#ifdef FEAT_VIRTUALEDIT
2464 && (ve_flags & VE_ONEMORE) == 0
2465#endif
2466 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00002467 {
2468 --curwin->w_cursor.col;
2469#ifdef FEAT_VIRTUALEDIT
2470 curwin->w_cursor.coladd = 0;
2471#endif
2472#ifdef FEAT_MBYTE
2473 if (has_mbyte)
2474 curwin->w_cursor.col -=
2475 (*mb_head_off)(oldp, oldp + curwin->w_cursor.col);
2476#endif
2477 }
2478 count = oldlen - col;
2479 movelen = 1;
2480 }
2481
2482 /*
2483 * If the old line has been allocated the deletion can be done in the
2484 * existing line. Otherwise a new line has to be allocated
Bram Moolenaare21877a2008-02-13 09:58:14 +00002485 * Can't do this when using Netbeans, because we would need to invoke
2486 * netbeans_removed(), which deallocates the line. Let ml_replace() take
Bram Moolenaar1a509df2010-08-01 17:59:57 +02002487 * care of notifying Netbeans.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002488 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002489#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02002490 if (netbeans_active())
Bram Moolenaare21877a2008-02-13 09:58:14 +00002491 was_alloced = FALSE;
2492 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002493#endif
Bram Moolenaare21877a2008-02-13 09:58:14 +00002494 was_alloced = ml_line_alloced(); /* check if oldp was allocated */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002495 if (was_alloced)
2496 newp = oldp; /* use same allocated memory */
2497 else
2498 { /* need to allocate a new line */
2499 newp = alloc((unsigned)(oldlen + 1 - count));
2500 if (newp == NULL)
2501 return FAIL;
2502 mch_memmove(newp, oldp, (size_t)col);
2503 }
2504 mch_memmove(newp + col, oldp + col + count, (size_t)movelen);
2505 if (!was_alloced)
2506 ml_replace(lnum, newp, FALSE);
2507
2508 /* mark the buffer as changed and prepare for displaying */
2509 changed_bytes(lnum, curwin->w_cursor.col);
2510
2511 return OK;
2512}
2513
2514/*
2515 * Delete from cursor to end of line.
2516 * Caller must have prepared for undo.
2517 *
2518 * return FAIL for failure, OK otherwise
2519 */
2520 int
2521truncate_line(fixpos)
2522 int fixpos; /* if TRUE fix the cursor position when done */
2523{
2524 char_u *newp;
2525 linenr_T lnum = curwin->w_cursor.lnum;
2526 colnr_T col = curwin->w_cursor.col;
2527
2528 if (col == 0)
2529 newp = vim_strsave((char_u *)"");
2530 else
2531 newp = vim_strnsave(ml_get(lnum), col);
2532
2533 if (newp == NULL)
2534 return FAIL;
2535
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 /*
2542 * If "fixpos" is TRUE we don't want to end up positioned at the NUL.
2543 */
2544 if (fixpos && curwin->w_cursor.col > 0)
2545 --curwin->w_cursor.col;
2546
2547 return OK;
2548}
2549
2550/*
2551 * Delete "nlines" lines at the cursor.
2552 * Saves the lines for undo first if "undo" is TRUE.
2553 */
2554 void
2555del_lines(nlines, undo)
2556 long nlines; /* number of lines to delete */
2557 int undo; /* if TRUE, prepare for undo */
2558{
2559 long n;
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002560 linenr_T first = curwin->w_cursor.lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002561
2562 if (nlines <= 0)
2563 return;
2564
2565 /* save the deleted lines for undo */
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002566 if (undo && u_savedel(first, nlines) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002567 return;
2568
2569 for (n = 0; n < nlines; )
2570 {
2571 if (curbuf->b_ml.ml_flags & ML_EMPTY) /* nothing to delete */
2572 break;
2573
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002574 ml_delete(first, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002575 ++n;
2576
2577 /* If we delete the last line in the file, stop */
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002578 if (first > curbuf->b_ml.ml_line_count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002579 break;
2580 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002581
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002582 /* Correct the cursor position before calling deleted_lines_mark(), it may
2583 * trigger a callback to display the cursor. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002584 curwin->w_cursor.col = 0;
2585 check_cursor_lnum();
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002586
2587 /* adjust marks, mark the buffer as changed and prepare for displaying */
2588 deleted_lines_mark(first, n);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002589}
2590
2591 int
2592gchar_pos(pos)
2593 pos_T *pos;
2594{
2595 char_u *ptr = ml_get_pos(pos);
2596
2597#ifdef FEAT_MBYTE
2598 if (has_mbyte)
2599 return (*mb_ptr2char)(ptr);
2600#endif
2601 return (int)*ptr;
2602}
2603
2604 int
2605gchar_cursor()
2606{
2607#ifdef FEAT_MBYTE
2608 if (has_mbyte)
2609 return (*mb_ptr2char)(ml_get_cursor());
2610#endif
2611 return (int)*ml_get_cursor();
2612}
2613
2614/*
2615 * Write a character at the current cursor position.
2616 * It is directly written into the block.
2617 */
2618 void
2619pchar_cursor(c)
2620 int c;
2621{
2622 *(ml_get_buf(curbuf, curwin->w_cursor.lnum, TRUE)
2623 + curwin->w_cursor.col) = c;
2624}
2625
Bram Moolenaar071d4272004-06-13 20:20:40 +00002626/*
2627 * When extra == 0: Return TRUE if the cursor is before or on the first
2628 * non-blank in the line.
2629 * When extra == 1: Return TRUE if the cursor is before the first non-blank in
2630 * the line.
2631 */
2632 int
2633inindent(extra)
2634 int extra;
2635{
2636 char_u *ptr;
2637 colnr_T col;
2638
2639 for (col = 0, ptr = ml_get_curline(); vim_iswhite(*ptr); ++col)
2640 ++ptr;
2641 if (col >= curwin->w_cursor.col + extra)
2642 return TRUE;
2643 else
2644 return FALSE;
2645}
2646
2647/*
2648 * Skip to next part of an option argument: Skip space and comma.
2649 */
2650 char_u *
2651skip_to_option_part(p)
2652 char_u *p;
2653{
2654 if (*p == ',')
2655 ++p;
2656 while (*p == ' ')
2657 ++p;
2658 return p;
2659}
2660
2661/*
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002662 * Call this function when something in the current buffer is changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002663 *
2664 * Most often called through changed_bytes() and changed_lines(), which also
2665 * mark the area of the display to be redrawn.
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002666 *
2667 * Careful: may trigger autocommands that reload the buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002668 */
2669 void
2670changed()
2671{
2672#if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
2673 /* The text of the preediting area is inserted, but this doesn't
2674 * mean a change of the buffer yet. That is delayed until the
2675 * text is committed. (this means preedit becomes empty) */
2676 if (im_is_preediting() && !xim_changed_while_preediting)
2677 return;
2678 xim_changed_while_preediting = FALSE;
2679#endif
2680
2681 if (!curbuf->b_changed)
2682 {
2683 int save_msg_scroll = msg_scroll;
2684
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002685 /* Give a warning about changing a read-only file. This may also
2686 * check-out the file, thus change "curbuf"! */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002687 change_warning(0);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002688
Bram Moolenaar071d4272004-06-13 20:20:40 +00002689 /* Create a swap file if that is wanted.
2690 * Don't do this for "nofile" and "nowrite" buffer types. */
2691 if (curbuf->b_may_swap
2692#ifdef FEAT_QUICKFIX
2693 && !bt_dontwrite(curbuf)
2694#endif
2695 )
2696 {
2697 ml_open_file(curbuf);
2698
2699 /* The ml_open_file() can cause an ATTENTION message.
2700 * Wait two seconds, to make sure the user reads this unexpected
2701 * message. Since we could be anywhere, call wait_return() now,
2702 * and don't let the emsg() set msg_scroll. */
2703 if (need_wait_return && emsg_silent == 0)
2704 {
2705 out_flush();
2706 ui_delay(2000L, TRUE);
2707 wait_return(TRUE);
2708 msg_scroll = save_msg_scroll;
2709 }
2710 }
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02002711 changed_int();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002712 }
2713 ++curbuf->b_changedtick;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002714}
2715
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02002716/*
2717 * Internal part of changed(), no user interaction.
2718 */
2719 void
2720changed_int()
2721{
2722 curbuf->b_changed = TRUE;
2723 ml_setflags(curbuf);
2724#ifdef FEAT_WINDOWS
2725 check_status(curbuf);
2726 redraw_tabline = TRUE;
2727#endif
2728#ifdef FEAT_TITLE
2729 need_maketitle = TRUE; /* set window title later */
2730#endif
2731}
2732
Bram Moolenaardba8a912005-04-24 22:08:39 +00002733static void changedOneline __ARGS((buf_T *buf, linenr_T lnum));
2734static void changed_lines_buf __ARGS((buf_T *buf, linenr_T lnum, linenr_T lnume, long xtra));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002735static void changed_common __ARGS((linenr_T lnum, colnr_T col, linenr_T lnume, long xtra));
2736
2737/*
2738 * Changed bytes within a single line for the current buffer.
2739 * - marks the windows on this buffer to be redisplayed
2740 * - marks the buffer changed by calling changed()
2741 * - invalidates cached values
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002742 * Careful: may trigger autocommands that reload the buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002743 */
2744 void
2745changed_bytes(lnum, col)
2746 linenr_T lnum;
2747 colnr_T col;
2748{
Bram Moolenaardba8a912005-04-24 22:08:39 +00002749 changedOneline(curbuf, lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002750 changed_common(lnum, col, lnum + 1, 0L);
Bram Moolenaardba8a912005-04-24 22:08:39 +00002751
2752#ifdef FEAT_DIFF
2753 /* Diff highlighting in other diff windows may need to be updated too. */
2754 if (curwin->w_p_diff)
2755 {
2756 win_T *wp;
2757 linenr_T wlnum;
2758
2759 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2760 if (wp->w_p_diff && wp != curwin)
2761 {
2762 redraw_win_later(wp, VALID);
2763 wlnum = diff_lnum_win(lnum, wp);
2764 if (wlnum > 0)
2765 changedOneline(wp->w_buffer, wlnum);
2766 }
2767 }
2768#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002769}
2770
2771 static void
Bram Moolenaardba8a912005-04-24 22:08:39 +00002772changedOneline(buf, lnum)
2773 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002774 linenr_T lnum;
2775{
Bram Moolenaardba8a912005-04-24 22:08:39 +00002776 if (buf->b_mod_set)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002777 {
2778 /* find the maximum area that must be redisplayed */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002779 if (lnum < buf->b_mod_top)
2780 buf->b_mod_top = lnum;
2781 else if (lnum >= buf->b_mod_bot)
2782 buf->b_mod_bot = lnum + 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002783 }
2784 else
2785 {
2786 /* set the area that must be redisplayed to one line */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002787 buf->b_mod_set = TRUE;
2788 buf->b_mod_top = lnum;
2789 buf->b_mod_bot = lnum + 1;
2790 buf->b_mod_xlines = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002791 }
2792}
2793
2794/*
2795 * Appended "count" lines below line "lnum" in the current buffer.
2796 * Must be called AFTER the change and after mark_adjust().
2797 * Takes care of marking the buffer to be redrawn and sets the changed flag.
2798 */
2799 void
2800appended_lines(lnum, count)
2801 linenr_T lnum;
2802 long count;
2803{
2804 changed_lines(lnum + 1, 0, lnum + 1, count);
2805}
2806
2807/*
2808 * Like appended_lines(), but adjust marks first.
2809 */
2810 void
2811appended_lines_mark(lnum, count)
2812 linenr_T lnum;
2813 long count;
2814{
2815 mark_adjust(lnum + 1, (linenr_T)MAXLNUM, count, 0L);
2816 changed_lines(lnum + 1, 0, lnum + 1, count);
2817}
2818
2819/*
2820 * Deleted "count" lines at line "lnum" in the current buffer.
2821 * Must be called AFTER the change and after mark_adjust().
2822 * Takes care of marking the buffer to be redrawn and sets the changed flag.
2823 */
2824 void
2825deleted_lines(lnum, count)
2826 linenr_T lnum;
2827 long count;
2828{
2829 changed_lines(lnum, 0, lnum + count, -count);
2830}
2831
2832/*
2833 * Like deleted_lines(), but adjust marks first.
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002834 * Make sure the cursor is on a valid line before calling, a GUI callback may
2835 * be triggered to display the cursor.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002836 */
2837 void
2838deleted_lines_mark(lnum, count)
2839 linenr_T lnum;
2840 long count;
2841{
2842 mark_adjust(lnum, (linenr_T)(lnum + count - 1), (long)MAXLNUM, -count);
2843 changed_lines(lnum, 0, lnum + count, -count);
2844}
2845
2846/*
2847 * Changed lines for the current buffer.
2848 * Must be called AFTER the change and after mark_adjust().
2849 * - mark the buffer changed by calling changed()
2850 * - mark the windows on this buffer to be redisplayed
2851 * - invalidate cached values
2852 * "lnum" is the first line that needs displaying, "lnume" the first line
2853 * below the changed lines (BEFORE the change).
2854 * When only inserting lines, "lnum" and "lnume" are equal.
2855 * Takes care of calling changed() and updating b_mod_*.
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002856 * Careful: may trigger autocommands that reload the buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002857 */
2858 void
2859changed_lines(lnum, col, lnume, xtra)
2860 linenr_T lnum; /* first line with change */
2861 colnr_T col; /* column in first line with change */
2862 linenr_T lnume; /* line below last changed line */
2863 long xtra; /* number of extra lines (negative when deleting) */
2864{
Bram Moolenaardba8a912005-04-24 22:08:39 +00002865 changed_lines_buf(curbuf, lnum, lnume, xtra);
2866
2867#ifdef FEAT_DIFF
2868 if (xtra == 0 && curwin->w_p_diff)
2869 {
2870 /* When the number of lines doesn't change then mark_adjust() isn't
2871 * called and other diff buffers still need to be marked for
2872 * displaying. */
2873 win_T *wp;
2874 linenr_T wlnum;
2875
2876 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2877 if (wp->w_p_diff && wp != curwin)
2878 {
2879 redraw_win_later(wp, VALID);
2880 wlnum = diff_lnum_win(lnum, wp);
2881 if (wlnum > 0)
2882 changed_lines_buf(wp->w_buffer, wlnum,
2883 lnume - lnum + wlnum, 0L);
2884 }
2885 }
2886#endif
2887
2888 changed_common(lnum, col, lnume, xtra);
2889}
2890
2891 static void
2892changed_lines_buf(buf, lnum, lnume, xtra)
2893 buf_T *buf;
2894 linenr_T lnum; /* first line with change */
2895 linenr_T lnume; /* line below last changed line */
2896 long xtra; /* number of extra lines (negative when deleting) */
2897{
2898 if (buf->b_mod_set)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002899 {
2900 /* find the maximum area that must be redisplayed */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002901 if (lnum < buf->b_mod_top)
2902 buf->b_mod_top = lnum;
2903 if (lnum < buf->b_mod_bot)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002904 {
2905 /* adjust old bot position for xtra lines */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002906 buf->b_mod_bot += xtra;
2907 if (buf->b_mod_bot < lnum)
2908 buf->b_mod_bot = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002909 }
Bram Moolenaardba8a912005-04-24 22:08:39 +00002910 if (lnume + xtra > buf->b_mod_bot)
2911 buf->b_mod_bot = lnume + xtra;
2912 buf->b_mod_xlines += xtra;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002913 }
2914 else
2915 {
2916 /* set the area that must be redisplayed */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002917 buf->b_mod_set = TRUE;
2918 buf->b_mod_top = lnum;
2919 buf->b_mod_bot = lnume + xtra;
2920 buf->b_mod_xlines = xtra;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002921 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002922}
2923
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002924/*
2925 * Common code for when a change is was made.
2926 * See changed_lines() for the arguments.
2927 * Careful: may trigger autocommands that reload the buffer.
2928 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002929 static void
2930changed_common(lnum, col, lnume, xtra)
2931 linenr_T lnum;
2932 colnr_T col;
2933 linenr_T lnume;
2934 long xtra;
2935{
2936 win_T *wp;
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00002937#ifdef FEAT_WINDOWS
2938 tabpage_T *tp;
2939#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002940 int i;
2941#ifdef FEAT_JUMPLIST
2942 int cols;
2943 pos_T *p;
2944 int add;
2945#endif
2946
2947 /* mark the buffer as modified */
2948 changed();
2949
2950 /* set the '. mark */
2951 if (!cmdmod.keepjumps)
2952 {
2953 curbuf->b_last_change.lnum = lnum;
2954 curbuf->b_last_change.col = col;
2955
2956#ifdef FEAT_JUMPLIST
2957 /* Create a new entry if a new undo-able change was started or we
2958 * don't have an entry yet. */
2959 if (curbuf->b_new_change || curbuf->b_changelistlen == 0)
2960 {
2961 if (curbuf->b_changelistlen == 0)
2962 add = TRUE;
2963 else
2964 {
2965 /* Don't create a new entry when the line number is the same
2966 * as the last one and the column is not too far away. Avoids
2967 * creating many entries for typing "xxxxx". */
2968 p = &curbuf->b_changelist[curbuf->b_changelistlen - 1];
2969 if (p->lnum != lnum)
2970 add = TRUE;
2971 else
2972 {
2973 cols = comp_textwidth(FALSE);
2974 if (cols == 0)
2975 cols = 79;
2976 add = (p->col + cols < col || col + cols < p->col);
2977 }
2978 }
2979 if (add)
2980 {
2981 /* This is the first of a new sequence of undo-able changes
2982 * and it's at some distance of the last change. Use a new
2983 * position in the changelist. */
2984 curbuf->b_new_change = FALSE;
2985
2986 if (curbuf->b_changelistlen == JUMPLISTSIZE)
2987 {
2988 /* changelist is full: remove oldest entry */
2989 curbuf->b_changelistlen = JUMPLISTSIZE - 1;
2990 mch_memmove(curbuf->b_changelist, curbuf->b_changelist + 1,
2991 sizeof(pos_T) * (JUMPLISTSIZE - 1));
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00002992 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002993 {
2994 /* Correct position in changelist for other windows on
2995 * this buffer. */
2996 if (wp->w_buffer == curbuf && wp->w_changelistidx > 0)
2997 --wp->w_changelistidx;
2998 }
2999 }
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00003000 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003001 {
3002 /* For other windows, if the position in the changelist is
3003 * at the end it stays at the end. */
3004 if (wp->w_buffer == curbuf
3005 && wp->w_changelistidx == curbuf->b_changelistlen)
3006 ++wp->w_changelistidx;
3007 }
3008 ++curbuf->b_changelistlen;
3009 }
3010 }
3011 curbuf->b_changelist[curbuf->b_changelistlen - 1] =
3012 curbuf->b_last_change;
3013 /* The current window is always after the last change, so that "g,"
3014 * takes you back to it. */
3015 curwin->w_changelistidx = curbuf->b_changelistlen;
3016#endif
3017 }
3018
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00003019 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003020 {
3021 if (wp->w_buffer == curbuf)
3022 {
3023 /* Mark this window to be redrawn later. */
3024 if (wp->w_redr_type < VALID)
3025 wp->w_redr_type = VALID;
3026
3027 /* Check if a change in the buffer has invalidated the cached
3028 * values for the cursor. */
3029#ifdef FEAT_FOLDING
3030 /*
3031 * Update the folds for this window. Can't postpone this, because
3032 * a following operator might work on the whole fold: ">>dd".
3033 */
3034 foldUpdate(wp, lnum, lnume + xtra - 1);
3035
3036 /* The change may cause lines above or below the change to become
3037 * included in a fold. Set lnum/lnume to the first/last line that
3038 * might be displayed differently.
3039 * Set w_cline_folded here as an efficient way to update it when
3040 * inserting lines just above a closed fold. */
3041 i = hasFoldingWin(wp, lnum, &lnum, NULL, FALSE, NULL);
3042 if (wp->w_cursor.lnum == lnum)
3043 wp->w_cline_folded = i;
3044 i = hasFoldingWin(wp, lnume, NULL, &lnume, FALSE, NULL);
3045 if (wp->w_cursor.lnum == lnume)
3046 wp->w_cline_folded = i;
3047
3048 /* If the changed line is in a range of previously folded lines,
3049 * compare with the first line in that range. */
3050 if (wp->w_cursor.lnum <= lnum)
3051 {
3052 i = find_wl_entry(wp, lnum);
3053 if (i >= 0 && wp->w_cursor.lnum > wp->w_lines[i].wl_lnum)
3054 changed_line_abv_curs_win(wp);
3055 }
3056#endif
3057
3058 if (wp->w_cursor.lnum > lnum)
3059 changed_line_abv_curs_win(wp);
3060 else if (wp->w_cursor.lnum == lnum && wp->w_cursor.col >= col)
3061 changed_cline_bef_curs_win(wp);
3062 if (wp->w_botline >= lnum)
3063 {
3064 /* Assume that botline doesn't change (inserted lines make
3065 * other lines scroll down below botline). */
3066 approximate_botline_win(wp);
3067 }
3068
3069 /* Check if any w_lines[] entries have become invalid.
3070 * For entries below the change: Correct the lnums for
3071 * inserted/deleted lines. Makes it possible to stop displaying
3072 * after the change. */
3073 for (i = 0; i < wp->w_lines_valid; ++i)
3074 if (wp->w_lines[i].wl_valid)
3075 {
3076 if (wp->w_lines[i].wl_lnum >= lnum)
3077 {
3078 if (wp->w_lines[i].wl_lnum < lnume)
3079 {
3080 /* line included in change */
3081 wp->w_lines[i].wl_valid = FALSE;
3082 }
3083 else if (xtra != 0)
3084 {
3085 /* line below change */
3086 wp->w_lines[i].wl_lnum += xtra;
3087#ifdef FEAT_FOLDING
3088 wp->w_lines[i].wl_lastlnum += xtra;
3089#endif
3090 }
3091 }
3092#ifdef FEAT_FOLDING
3093 else if (wp->w_lines[i].wl_lastlnum >= lnum)
3094 {
3095 /* change somewhere inside this range of folded lines,
3096 * may need to be redrawn */
3097 wp->w_lines[i].wl_valid = FALSE;
3098 }
3099#endif
3100 }
Bram Moolenaar3234cc62009-11-03 17:47:12 +00003101
3102#ifdef FEAT_FOLDING
3103 /* Take care of side effects for setting w_topline when folds have
3104 * changed. Esp. when the buffer was changed in another window. */
3105 if (hasAnyFolding(wp))
3106 set_topline(wp, wp->w_topline);
3107#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003108 }
3109 }
3110
3111 /* Call update_screen() later, which checks out what needs to be redrawn,
3112 * since it notices b_mod_set and then uses b_mod_*. */
3113 if (must_redraw < VALID)
3114 must_redraw = VALID;
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00003115
3116#ifdef FEAT_AUTOCMD
3117 /* when the cursor line is changed always trigger CursorMoved */
Bram Moolenaare163f1c2006-10-17 09:12:21 +00003118 if (lnum <= curwin->w_cursor.lnum
3119 && lnume + (xtra < 0 ? -xtra : xtra) > curwin->w_cursor.lnum)
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00003120 last_cursormoved.lnum = 0;
3121#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003122}
3123
3124/*
3125 * unchanged() is called when the changed flag must be reset for buffer 'buf'
3126 */
3127 void
3128unchanged(buf, ff)
3129 buf_T *buf;
3130 int ff; /* also reset 'fileformat' */
3131{
Bram Moolenaar164c60f2011-01-22 00:11:50 +01003132 if (buf->b_changed || (ff && file_ff_differs(buf, FALSE)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003133 {
3134 buf->b_changed = 0;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003135 ml_setflags(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003136 if (ff)
3137 save_file_ff(buf);
3138#ifdef FEAT_WINDOWS
3139 check_status(buf);
Bram Moolenaar997fb4b2006-02-17 21:53:23 +00003140 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003141#endif
3142#ifdef FEAT_TITLE
3143 need_maketitle = TRUE; /* set window title later */
3144#endif
3145 }
3146 ++buf->b_changedtick;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003147#ifdef FEAT_NETBEANS_INTG
3148 netbeans_unmodified(buf);
3149#endif
3150}
3151
3152#if defined(FEAT_WINDOWS) || defined(PROTO)
3153/*
3154 * check_status: called when the status bars for the buffer 'buf'
3155 * need to be updated
3156 */
3157 void
3158check_status(buf)
3159 buf_T *buf;
3160{
3161 win_T *wp;
3162
3163 for (wp = firstwin; wp != NULL; wp = wp->w_next)
3164 if (wp->w_buffer == buf && wp->w_status_height)
3165 {
3166 wp->w_redr_status = TRUE;
3167 if (must_redraw < VALID)
3168 must_redraw = VALID;
3169 }
3170}
3171#endif
3172
3173/*
3174 * If the file is readonly, give a warning message with the first change.
3175 * Don't do this for autocommands.
3176 * Don't use emsg(), because it flushes the macro buffer.
Bram Moolenaard5cdbeb2005-10-10 20:59:28 +00003177 * If we have undone all changes b_changed will be FALSE, but "b_did_warn"
Bram Moolenaar071d4272004-06-13 20:20:40 +00003178 * will be TRUE.
Bram Moolenaarb0b50882010-07-07 18:26:28 +02003179 * Careful: may trigger autocommands that reload the buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003180 */
3181 void
3182change_warning(col)
3183 int col; /* column for message; non-zero when in insert
3184 mode and 'showmode' is on */
3185{
Bram Moolenaar496c5262009-03-18 14:42:00 +00003186 static char *w_readonly = N_("W10: Warning: Changing a readonly file");
3187
Bram Moolenaar071d4272004-06-13 20:20:40 +00003188 if (curbuf->b_did_warn == FALSE
3189 && curbufIsChanged() == 0
3190#ifdef FEAT_AUTOCMD
3191 && !autocmd_busy
3192#endif
3193 && curbuf->b_p_ro)
3194 {
3195#ifdef FEAT_AUTOCMD
Bram Moolenaar910f66f2006-04-05 20:41:53 +00003196 ++curbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003197 apply_autocmds(EVENT_FILECHANGEDRO, NULL, NULL, FALSE, curbuf);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00003198 --curbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003199 if (!curbuf->b_p_ro)
3200 return;
3201#endif
3202 /*
3203 * Do what msg() does, but with a column offset if the warning should
3204 * be after the mode message.
3205 */
3206 msg_start();
3207 if (msg_row == Rows - 1)
3208 msg_col = col;
Bram Moolenaar2df6dcc2004-07-12 15:53:54 +00003209 msg_source(hl_attr(HLF_W));
Bram Moolenaar496c5262009-03-18 14:42:00 +00003210 MSG_PUTS_ATTR(_(w_readonly), hl_attr(HLF_W) | MSG_HIST);
3211#ifdef FEAT_EVAL
3212 set_vim_var_string(VV_WARNINGMSG, (char_u *)_(w_readonly), -1);
3213#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003214 msg_clr_eos();
3215 (void)msg_end();
3216 if (msg_silent == 0 && !silent_mode)
3217 {
3218 out_flush();
3219 ui_delay(1000L, TRUE); /* give the user time to think about it */
3220 }
3221 curbuf->b_did_warn = TRUE;
3222 redraw_cmdline = FALSE; /* don't redraw and erase the message */
3223 if (msg_row < Rows - 1)
3224 showmode();
3225 }
3226}
3227
3228/*
3229 * Ask for a reply from the user, a 'y' or a 'n'.
3230 * No other characters are accepted, the message is repeated until a valid
3231 * reply is entered or CTRL-C is hit.
3232 * If direct is TRUE, don't use vgetc() but ui_inchar(), don't get characters
3233 * from any buffers but directly from the user.
3234 *
3235 * return the 'y' or 'n'
3236 */
3237 int
3238ask_yesno(str, direct)
3239 char_u *str;
3240 int direct;
3241{
3242 int r = ' ';
3243 int save_State = State;
3244
3245 if (exiting) /* put terminal in raw mode for this question */
3246 settmode(TMODE_RAW);
3247 ++no_wait_return;
3248#ifdef USE_ON_FLY_SCROLL
3249 dont_scroll = TRUE; /* disallow scrolling here */
3250#endif
3251 State = CONFIRM; /* mouse behaves like with :confirm */
3252#ifdef FEAT_MOUSE
3253 setmouse(); /* disables mouse for xterm */
3254#endif
3255 ++no_mapping;
3256 ++allow_keys; /* no mapping here, but recognize keys */
3257
3258 while (r != 'y' && r != 'n')
3259 {
3260 /* same highlighting as for wait_return */
3261 smsg_attr(hl_attr(HLF_R), (char_u *)"%s (y/n)?", str);
3262 if (direct)
3263 r = get_keystroke();
3264 else
Bram Moolenaar913626c2008-01-03 11:43:42 +00003265 r = plain_vgetc();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003266 if (r == Ctrl_C || r == ESC)
3267 r = 'n';
3268 msg_putchar(r); /* show what you typed */
3269 out_flush();
3270 }
3271 --no_wait_return;
3272 State = save_State;
3273#ifdef FEAT_MOUSE
3274 setmouse();
3275#endif
3276 --no_mapping;
3277 --allow_keys;
3278
3279 return r;
3280}
3281
3282/*
3283 * Get a key stroke directly from the user.
3284 * Ignores mouse clicks and scrollbar events, except a click for the left
3285 * button (used at the more prompt).
3286 * Doesn't use vgetc(), because it syncs undo and eats mapped characters.
3287 * Disadvantage: typeahead is ignored.
3288 * Translates the interrupt character for unix to ESC.
3289 */
3290 int
3291get_keystroke()
3292{
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003293 char_u *buf = NULL;
3294 int buflen = 150;
3295 int maxlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003296 int len = 0;
3297 int n;
3298 int save_mapped_ctrl_c = mapped_ctrl_c;
Bram Moolenaar4395a712006-09-05 18:57:57 +00003299 int waited = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003300
3301 mapped_ctrl_c = FALSE; /* mappings are not used here */
3302 for (;;)
3303 {
3304 cursor_on();
3305 out_flush();
3306
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003307 /* Leave some room for check_termcode() to insert a key code into (max
3308 * 5 chars plus NUL). And fix_input_buffer() can triple the number of
3309 * bytes. */
3310 maxlen = (buflen - 6 - len) / 3;
3311 if (buf == NULL)
3312 buf = alloc(buflen);
3313 else if (maxlen < 10)
3314 {
Bram Moolenaardc7e85e2012-06-20 12:40:08 +02003315 /* Need some more space. This might happen when receiving a long
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003316 * escape sequence. */
3317 buflen += 100;
3318 buf = vim_realloc(buf, buflen);
3319 maxlen = (buflen - 6 - len) / 3;
3320 }
3321 if (buf == NULL)
3322 {
3323 do_outofmem_msg((long_u)buflen);
3324 return ESC; /* panic! */
3325 }
3326
Bram Moolenaar071d4272004-06-13 20:20:40 +00003327 /* First time: blocking wait. Second time: wait up to 100ms for a
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003328 * terminal code to complete. */
3329 n = ui_inchar(buf + len, maxlen, len == 0 ? -1L : 100L, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003330 if (n > 0)
3331 {
3332 /* Replace zero and CSI by a special key code. */
3333 n = fix_input_buffer(buf + len, n, FALSE);
3334 len += n;
Bram Moolenaar4395a712006-09-05 18:57:57 +00003335 waited = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003336 }
Bram Moolenaar4395a712006-09-05 18:57:57 +00003337 else if (len > 0)
3338 ++waited; /* keep track of the waiting time */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003339
Bram Moolenaar4395a712006-09-05 18:57:57 +00003340 /* Incomplete termcode and not timed out yet: get more characters */
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003341 if ((n = check_termcode(1, buf, buflen, &len)) < 0
Bram Moolenaar4395a712006-09-05 18:57:57 +00003342 && (!p_ttimeout || waited * 100L < (p_ttm < 0 ? p_tm : p_ttm)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003343 continue;
Bram Moolenaar4395a712006-09-05 18:57:57 +00003344
Bram Moolenaar946ffd42010-12-30 12:30:31 +01003345 if (n == KEYLEN_REMOVED) /* key code removed */
Bram Moolenaar6eb634e2011-03-03 15:04:08 +01003346 {
Bram Moolenaarfd30cd42011-03-22 13:07:26 +01003347 if (must_redraw != 0 && !need_wait_return && (State & CMDLINE) == 0)
Bram Moolenaar6eb634e2011-03-03 15:04:08 +01003348 {
3349 /* Redrawing was postponed, do it now. */
3350 update_screen(0);
3351 setcursor(); /* put cursor back where it belongs */
3352 }
Bram Moolenaar946ffd42010-12-30 12:30:31 +01003353 continue;
Bram Moolenaar6eb634e2011-03-03 15:04:08 +01003354 }
Bram Moolenaar946ffd42010-12-30 12:30:31 +01003355 if (n > 0) /* found a termcode: adjust length */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003356 len = n;
Bram Moolenaar946ffd42010-12-30 12:30:31 +01003357 if (len == 0) /* nothing typed yet */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003358 continue;
3359
3360 /* Handle modifier and/or special key code. */
3361 n = buf[0];
3362 if (n == K_SPECIAL)
3363 {
3364 n = TO_SPECIAL(buf[1], buf[2]);
3365 if (buf[1] == KS_MODIFIER
3366 || n == K_IGNORE
3367#ifdef FEAT_MOUSE
3368 || n == K_LEFTMOUSE_NM
3369 || n == K_LEFTDRAG
3370 || n == K_LEFTRELEASE
3371 || n == K_LEFTRELEASE_NM
3372 || n == K_MIDDLEMOUSE
3373 || n == K_MIDDLEDRAG
3374 || n == K_MIDDLERELEASE
3375 || n == K_RIGHTMOUSE
3376 || n == K_RIGHTDRAG
3377 || n == K_RIGHTRELEASE
3378 || n == K_MOUSEDOWN
3379 || n == K_MOUSEUP
Bram Moolenaar8d9b40e2010-07-25 15:49:07 +02003380 || n == K_MOUSELEFT
3381 || n == K_MOUSERIGHT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003382 || n == K_X1MOUSE
3383 || n == K_X1DRAG
3384 || n == K_X1RELEASE
3385 || n == K_X2MOUSE
3386 || n == K_X2DRAG
3387 || n == K_X2RELEASE
3388# ifdef FEAT_GUI
3389 || n == K_VER_SCROLLBAR
3390 || n == K_HOR_SCROLLBAR
3391# endif
3392#endif
3393 )
3394 {
3395 if (buf[1] == KS_MODIFIER)
3396 mod_mask = buf[2];
3397 len -= 3;
3398 if (len > 0)
3399 mch_memmove(buf, buf + 3, (size_t)len);
3400 continue;
3401 }
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00003402 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003403 }
3404#ifdef FEAT_MBYTE
3405 if (has_mbyte)
3406 {
3407 if (MB_BYTE2LEN(n) > len)
3408 continue; /* more bytes to get */
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003409 buf[len >= buflen ? buflen - 1 : len] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003410 n = (*mb_ptr2char)(buf);
3411 }
3412#endif
3413#ifdef UNIX
3414 if (n == intr_char)
3415 n = ESC;
3416#endif
3417 break;
3418 }
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003419 vim_free(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003420
3421 mapped_ctrl_c = save_mapped_ctrl_c;
3422 return n;
3423}
3424
3425/*
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003426 * Get a number from the user.
3427 * When "mouse_used" is not NULL allow using the mouse.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003428 */
3429 int
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003430get_number(colon, mouse_used)
3431 int colon; /* allow colon to abort */
3432 int *mouse_used;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003433{
3434 int n = 0;
3435 int c;
Bram Moolenaar3991dab2006-03-27 17:01:56 +00003436 int typed = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003437
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003438 if (mouse_used != NULL)
3439 *mouse_used = FALSE;
3440
Bram Moolenaar071d4272004-06-13 20:20:40 +00003441 /* When not printing messages, the user won't know what to type, return a
3442 * zero (as if CR was hit). */
3443 if (msg_silent != 0)
3444 return 0;
3445
3446#ifdef USE_ON_FLY_SCROLL
3447 dont_scroll = TRUE; /* disallow scrolling here */
3448#endif
3449 ++no_mapping;
3450 ++allow_keys; /* no mapping here, but recognize keys */
3451 for (;;)
3452 {
3453 windgoto(msg_row, msg_col);
3454 c = safe_vgetc();
3455 if (VIM_ISDIGIT(c))
3456 {
3457 n = n * 10 + c - '0';
3458 msg_putchar(c);
Bram Moolenaar3991dab2006-03-27 17:01:56 +00003459 ++typed;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003460 }
3461 else if (c == K_DEL || c == K_KDEL || c == K_BS || c == Ctrl_H)
3462 {
Bram Moolenaar3991dab2006-03-27 17:01:56 +00003463 if (typed > 0)
3464 {
3465 MSG_PUTS("\b \b");
3466 --typed;
3467 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003468 n /= 10;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003469 }
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003470#ifdef FEAT_MOUSE
3471 else if (mouse_used != NULL && c == K_LEFTMOUSE)
3472 {
3473 *mouse_used = TRUE;
3474 n = mouse_row + 1;
3475 break;
3476 }
3477#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003478 else if (n == 0 && c == ':' && colon)
3479 {
3480 stuffcharReadbuff(':');
3481 if (!exmode_active)
3482 cmdline_row = msg_row;
3483 skip_redraw = TRUE; /* skip redraw once */
3484 do_redraw = FALSE;
3485 break;
3486 }
3487 else if (c == CAR || c == NL || c == Ctrl_C || c == ESC)
3488 break;
3489 }
3490 --no_mapping;
3491 --allow_keys;
3492 return n;
3493}
3494
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003495/*
3496 * Ask the user to enter a number.
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003497 * When "mouse_used" is not NULL allow using the mouse and in that case return
3498 * the line number.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003499 */
3500 int
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003501prompt_for_number(mouse_used)
3502 int *mouse_used;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003503{
3504 int i;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003505 int save_cmdline_row;
3506 int save_State;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003507
3508 /* When using ":silent" assume that <CR> was entered. */
Bram Moolenaar42eeac32005-06-29 22:40:58 +00003509 if (mouse_used != NULL)
Bram Moolenaard812df62008-11-09 12:46:09 +00003510 MSG_PUTS(_("Type number and <Enter> or click with mouse (empty cancels): "));
Bram Moolenaar42eeac32005-06-29 22:40:58 +00003511 else
Bram Moolenaard812df62008-11-09 12:46:09 +00003512 MSG_PUTS(_("Type number and <Enter> (empty cancels): "));
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003513
Bram Moolenaar203335e2006-09-03 14:35:42 +00003514 /* Set the state such that text can be selected/copied/pasted and we still
3515 * get mouse events. */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003516 save_cmdline_row = cmdline_row;
Bram Moolenaar203335e2006-09-03 14:35:42 +00003517 cmdline_row = 0;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003518 save_State = State;
Bram Moolenaar203335e2006-09-03 14:35:42 +00003519 State = CMDLINE;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003520
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003521 i = get_number(TRUE, mouse_used);
3522 if (KeyTyped)
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003523 {
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003524 /* don't call wait_return() now */
3525 /* msg_putchar('\n'); */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003526 cmdline_row = msg_row - 1;
3527 need_wait_return = FALSE;
3528 msg_didany = FALSE;
Bram Moolenaarb2450162009-07-22 09:04:20 +00003529 msg_didout = FALSE;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003530 }
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003531 else
3532 cmdline_row = save_cmdline_row;
3533 State = save_State;
3534
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003535 return i;
3536}
3537
Bram Moolenaar071d4272004-06-13 20:20:40 +00003538 void
3539msgmore(n)
3540 long n;
3541{
3542 long pn;
3543
3544 if (global_busy /* no messages now, wait until global is finished */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003545 || !messaging()) /* 'lazyredraw' set, don't do messages now */
3546 return;
3547
Bram Moolenaar7df2d662005-01-25 22:18:08 +00003548 /* We don't want to overwrite another important message, but do overwrite
3549 * a previous "more lines" or "fewer lines" message, so that "5dd" and
3550 * then "put" reports the last action. */
3551 if (keep_msg != NULL && !keep_msg_more)
3552 return;
3553
Bram Moolenaar071d4272004-06-13 20:20:40 +00003554 if (n > 0)
3555 pn = n;
3556 else
3557 pn = -n;
3558
3559 if (pn > p_report)
3560 {
3561 if (pn == 1)
3562 {
3563 if (n > 0)
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003564 vim_strncpy(msg_buf, (char_u *)_("1 more line"),
3565 MSG_BUF_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003566 else
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003567 vim_strncpy(msg_buf, (char_u *)_("1 line less"),
3568 MSG_BUF_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003569 }
3570 else
3571 {
3572 if (n > 0)
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003573 vim_snprintf((char *)msg_buf, MSG_BUF_LEN,
3574 _("%ld more lines"), pn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003575 else
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003576 vim_snprintf((char *)msg_buf, MSG_BUF_LEN,
3577 _("%ld fewer lines"), pn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003578 }
3579 if (got_int)
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003580 vim_strcat(msg_buf, (char_u *)_(" (Interrupted)"), MSG_BUF_LEN);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003581 if (msg(msg_buf))
3582 {
Bram Moolenaar238a5642006-02-21 22:12:05 +00003583 set_keep_msg(msg_buf, 0);
Bram Moolenaar7df2d662005-01-25 22:18:08 +00003584 keep_msg_more = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003585 }
3586 }
3587}
3588
3589/*
3590 * flush map and typeahead buffers and give a warning for an error
3591 */
3592 void
3593beep_flush()
3594{
3595 if (emsg_silent == 0)
3596 {
3597 flush_buffers(FALSE);
3598 vim_beep();
3599 }
3600}
3601
3602/*
3603 * give a warning for an error
3604 */
3605 void
3606vim_beep()
3607{
3608 if (emsg_silent == 0)
3609 {
3610 if (p_vb
3611#ifdef FEAT_GUI
3612 /* While the GUI is starting up the termcap is set for the GUI
3613 * but the output still goes to a terminal. */
3614 && !(gui.in_use && gui.starting)
3615#endif
3616 )
3617 {
3618 out_str(T_VB);
3619 }
3620 else
3621 {
3622#ifdef MSDOS
3623 /*
3624 * The number of beeps outputted is reduced to avoid having to wait
3625 * for all the beeps to finish. This is only a problem on systems
3626 * where the beeps don't overlap.
3627 */
3628 if (beep_count == 0 || beep_count == 10)
3629 {
3630 out_char(BELL);
3631 beep_count = 1;
3632 }
3633 else
3634 ++beep_count;
3635#else
3636 out_char(BELL);
3637#endif
3638 }
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003639
3640 /* When 'verbose' is set and we are sourcing a script or executing a
3641 * function give the user a hint where the beep comes from. */
3642 if (vim_strchr(p_debug, 'e') != NULL)
3643 {
3644 msg_source(hl_attr(HLF_W));
3645 msg_attr((char_u *)_("Beep!"), hl_attr(HLF_W));
3646 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003647 }
3648}
3649
3650/*
3651 * To get the "real" home directory:
3652 * - get value of $HOME
3653 * For Unix:
3654 * - go to that directory
3655 * - do mch_dirname() to get the real name of that directory.
3656 * This also works with mounts and links.
3657 * Don't do this for MS-DOS, it will change the "current dir" for a drive.
3658 */
3659static char_u *homedir = NULL;
3660
3661 void
3662init_homedir()
3663{
3664 char_u *var;
3665
Bram Moolenaar05159a02005-02-26 23:04:13 +00003666 /* In case we are called a second time (when 'encoding' changes). */
3667 vim_free(homedir);
3668 homedir = NULL;
3669
Bram Moolenaar071d4272004-06-13 20:20:40 +00003670#ifdef VMS
3671 var = mch_getenv((char_u *)"SYS$LOGIN");
3672#else
3673 var = mch_getenv((char_u *)"HOME");
3674#endif
3675
3676 if (var != NULL && *var == NUL) /* empty is same as not set */
3677 var = NULL;
3678
3679#ifdef WIN3264
3680 /*
3681 * Weird but true: $HOME may contain an indirect reference to another
3682 * variable, esp. "%USERPROFILE%". Happens when $USERPROFILE isn't set
3683 * when $HOME is being set.
3684 */
3685 if (var != NULL && *var == '%')
3686 {
3687 char_u *p;
3688 char_u *exp;
3689
3690 p = vim_strchr(var + 1, '%');
3691 if (p != NULL)
3692 {
Bram Moolenaarce0842a2005-07-18 21:58:11 +00003693 vim_strncpy(NameBuff, var + 1, p - (var + 1));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003694 exp = mch_getenv(NameBuff);
3695 if (exp != NULL && *exp != NUL
3696 && STRLEN(exp) + STRLEN(p) < MAXPATHL)
3697 {
Bram Moolenaar555b2802005-05-19 21:08:39 +00003698 vim_snprintf((char *)NameBuff, MAXPATHL, "%s%s", exp, p + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003699 var = NameBuff;
3700 /* Also set $HOME, it's needed for _viminfo. */
3701 vim_setenv((char_u *)"HOME", NameBuff);
3702 }
3703 }
3704 }
3705
3706 /*
3707 * Typically, $HOME is not defined on Windows, unless the user has
3708 * specifically defined it for Vim's sake. However, on Windows NT
3709 * platforms, $HOMEDRIVE and $HOMEPATH are automatically defined for
3710 * each user. Try constructing $HOME from these.
3711 */
3712 if (var == NULL)
3713 {
3714 char_u *homedrive, *homepath;
3715
3716 homedrive = mch_getenv((char_u *)"HOMEDRIVE");
3717 homepath = mch_getenv((char_u *)"HOMEPATH");
Bram Moolenaar6f977012010-01-06 17:53:38 +01003718 if (homepath == NULL || *homepath == NUL)
3719 homepath = "\\";
3720 if (homedrive != NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00003721 && STRLEN(homedrive) + STRLEN(homepath) < MAXPATHL)
3722 {
3723 sprintf((char *)NameBuff, "%s%s", homedrive, homepath);
3724 if (NameBuff[0] != NUL)
3725 {
3726 var = NameBuff;
3727 /* Also set $HOME, it's needed for _viminfo. */
3728 vim_setenv((char_u *)"HOME", NameBuff);
3729 }
3730 }
3731 }
Bram Moolenaar05159a02005-02-26 23:04:13 +00003732
3733# if defined(FEAT_MBYTE)
3734 if (enc_utf8 && var != NULL)
3735 {
3736 int len;
Bram Moolenaarb453a532011-04-28 17:48:44 +02003737 char_u *pp = NULL;
Bram Moolenaar05159a02005-02-26 23:04:13 +00003738
3739 /* Convert from active codepage to UTF-8. Other conversions are
3740 * not done, because they would fail for non-ASCII characters. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003741 acp_to_enc(var, (int)STRLEN(var), &pp, &len);
Bram Moolenaar05159a02005-02-26 23:04:13 +00003742 if (pp != NULL)
3743 {
3744 homedir = pp;
3745 return;
3746 }
3747 }
3748# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003749#endif
3750
3751#if defined(OS2) || defined(MSDOS) || defined(MSWIN)
3752 /*
3753 * Default home dir is C:/
3754 * Best assumption we can make in such a situation.
3755 */
3756 if (var == NULL)
3757 var = "C:/";
3758#endif
3759 if (var != NULL)
3760 {
3761#ifdef UNIX
3762 /*
3763 * Change to the directory and get the actual path. This resolves
3764 * links. Don't do it when we can't return.
3765 */
3766 if (mch_dirname(NameBuff, MAXPATHL) == OK
3767 && mch_chdir((char *)NameBuff) == 0)
3768 {
3769 if (!mch_chdir((char *)var) && mch_dirname(IObuff, IOSIZE) == OK)
3770 var = IObuff;
3771 if (mch_chdir((char *)NameBuff) != 0)
3772 EMSG(_(e_prev_dir));
3773 }
3774#endif
3775 homedir = vim_strsave(var);
3776 }
3777}
3778
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003779#if defined(EXITFREE) || defined(PROTO)
3780 void
3781free_homedir()
3782{
3783 vim_free(homedir);
3784}
3785#endif
3786
Bram Moolenaar071d4272004-06-13 20:20:40 +00003787/*
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003788 * Call expand_env() and store the result in an allocated string.
3789 * This is not very memory efficient, this expects the result to be freed
3790 * again soon.
3791 */
3792 char_u *
3793expand_env_save(src)
3794 char_u *src;
3795{
3796 return expand_env_save_opt(src, FALSE);
3797}
3798
3799/*
3800 * Idem, but when "one" is TRUE handle the string as one file name, only
3801 * expand "~" at the start.
3802 */
3803 char_u *
3804expand_env_save_opt(src, one)
3805 char_u *src;
3806 int one;
3807{
3808 char_u *p;
3809
3810 p = alloc(MAXPATHL);
3811 if (p != NULL)
3812 expand_env_esc(src, p, MAXPATHL, FALSE, one, NULL);
3813 return p;
3814}
3815
3816/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003817 * Expand environment variable with path name.
3818 * "~/" is also expanded, using $HOME. For Unix "~user/" is expanded.
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003819 * Skips over "\ ", "\~" and "\$" (not for Win32 though).
Bram Moolenaar071d4272004-06-13 20:20:40 +00003820 * If anything fails no expansion is done and dst equals src.
3821 */
3822 void
3823expand_env(src, dst, dstlen)
3824 char_u *src; /* input string e.g. "$HOME/vim.hlp" */
3825 char_u *dst; /* where to put the result */
3826 int dstlen; /* maximum length of the result */
3827{
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003828 expand_env_esc(src, dst, dstlen, FALSE, FALSE, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003829}
3830
3831 void
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003832expand_env_esc(srcp, dst, dstlen, esc, one, startstr)
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003833 char_u *srcp; /* input string e.g. "$HOME/vim.hlp" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003834 char_u *dst; /* where to put the result */
3835 int dstlen; /* maximum length of the result */
3836 int esc; /* escape spaces in expanded variables */
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003837 int one; /* "srcp" is one file name */
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003838 char_u *startstr; /* start again after this (can be NULL) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003839{
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003840 char_u *src;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003841 char_u *tail;
3842 int c;
3843 char_u *var;
3844 int copy_char;
3845 int mustfree; /* var was allocated, need to free it later */
3846 int at_start = TRUE; /* at start of a name */
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003847 int startstr_len = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003848
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003849 if (startstr != NULL)
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003850 startstr_len = (int)STRLEN(startstr);
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003851
3852 src = skipwhite(srcp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003853 --dstlen; /* leave one char space for "\," */
3854 while (*src && dstlen > 0)
3855 {
3856 copy_char = TRUE;
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003857 if ((*src == '$'
3858#ifdef VMS
3859 && at_start
3860#endif
3861 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003862#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3863 || *src == '%'
3864#endif
3865 || (*src == '~' && at_start))
3866 {
3867 mustfree = FALSE;
3868
3869 /*
3870 * The variable name is copied into dst temporarily, because it may
3871 * be a string in read-only memory and a NUL needs to be appended.
3872 */
3873 if (*src != '~') /* environment var */
3874 {
3875 tail = src + 1;
3876 var = dst;
3877 c = dstlen - 1;
3878
3879#ifdef UNIX
3880 /* Unix has ${var-name} type environment vars */
3881 if (*tail == '{' && !vim_isIDc('{'))
3882 {
3883 tail++; /* ignore '{' */
3884 while (c-- > 0 && *tail && *tail != '}')
3885 *var++ = *tail++;
3886 }
3887 else
3888#endif
3889 {
3890 while (c-- > 0 && *tail != NUL && ((vim_isIDc(*tail))
3891#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3892 || (*src == '%' && *tail != '%')
3893#endif
3894 ))
3895 {
3896#ifdef OS2 /* env vars only in uppercase */
3897 *var++ = TOUPPER_LOC(*tail);
3898 tail++; /* toupper() may be a macro! */
3899#else
3900 *var++ = *tail++;
3901#endif
3902 }
3903 }
3904
3905#if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
3906# ifdef UNIX
3907 if (src[1] == '{' && *tail != '}')
3908# else
3909 if (*src == '%' && *tail != '%')
3910# endif
3911 var = NULL;
3912 else
3913 {
3914# ifdef UNIX
3915 if (src[1] == '{')
3916# else
3917 if (*src == '%')
3918#endif
3919 ++tail;
3920#endif
3921 *var = NUL;
3922 var = vim_getenv(dst, &mustfree);
3923#if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
3924 }
3925#endif
3926 }
3927 /* home directory */
3928 else if ( src[1] == NUL
3929 || vim_ispathsep(src[1])
3930 || vim_strchr((char_u *)" ,\t\n", src[1]) != NULL)
3931 {
3932 var = homedir;
3933 tail = src + 1;
3934 }
3935 else /* user directory */
3936 {
3937#if defined(UNIX) || (defined(VMS) && defined(USER_HOME))
3938 /*
3939 * Copy ~user to dst[], so we can put a NUL after it.
3940 */
3941 tail = src;
3942 var = dst;
3943 c = dstlen - 1;
3944 while ( c-- > 0
3945 && *tail
3946 && vim_isfilec(*tail)
3947 && !vim_ispathsep(*tail))
3948 *var++ = *tail++;
3949 *var = NUL;
3950# ifdef UNIX
3951 /*
3952 * If the system supports getpwnam(), use it.
3953 * Otherwise, or if getpwnam() fails, the shell is used to
3954 * expand ~user. This is slower and may fail if the shell
3955 * does not support ~user (old versions of /bin/sh).
3956 */
3957# if defined(HAVE_GETPWNAM) && defined(HAVE_PWD_H)
3958 {
3959 struct passwd *pw;
3960
Bram Moolenaara40ceaf2006-01-13 22:35:40 +00003961 /* Note: memory allocated by getpwnam() is never freed.
3962 * Calling endpwent() apparently doesn't help. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003963 pw = getpwnam((char *)dst + 1);
3964 if (pw != NULL)
3965 var = (char_u *)pw->pw_dir;
3966 else
3967 var = NULL;
3968 }
3969 if (var == NULL)
3970# endif
3971 {
3972 expand_T xpc;
3973
3974 ExpandInit(&xpc);
3975 xpc.xp_context = EXPAND_FILES;
3976 var = ExpandOne(&xpc, dst, NULL,
3977 WILD_ADD_SLASH|WILD_SILENT, WILD_EXPAND_FREE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003978 mustfree = TRUE;
3979 }
3980
3981# else /* !UNIX, thus VMS */
3982 /*
3983 * USER_HOME is a comma-separated list of
3984 * directories to search for the user account in.
3985 */
3986 {
3987 char_u test[MAXPATHL], paths[MAXPATHL];
3988 char_u *path, *next_path, *ptr;
3989 struct stat st;
3990
3991 STRCPY(paths, USER_HOME);
3992 next_path = paths;
3993 while (*next_path)
3994 {
3995 for (path = next_path; *next_path && *next_path != ',';
3996 next_path++);
3997 if (*next_path)
3998 *next_path++ = NUL;
3999 STRCPY(test, path);
4000 STRCAT(test, "/");
4001 STRCAT(test, dst + 1);
4002 if (mch_stat(test, &st) == 0)
4003 {
4004 var = alloc(STRLEN(test) + 1);
4005 STRCPY(var, test);
4006 mustfree = TRUE;
4007 break;
4008 }
4009 }
4010 }
4011# endif /* UNIX */
4012#else
4013 /* cannot expand user's home directory, so don't try */
4014 var = NULL;
4015 tail = (char_u *)""; /* for gcc */
4016#endif /* UNIX || VMS */
4017 }
4018
4019#ifdef BACKSLASH_IN_FILENAME
4020 /* If 'shellslash' is set change backslashes to forward slashes.
4021 * Can't use slash_adjust(), p_ssl may be set temporarily. */
4022 if (p_ssl && var != NULL && vim_strchr(var, '\\') != NULL)
4023 {
4024 char_u *p = vim_strsave(var);
4025
4026 if (p != NULL)
4027 {
4028 if (mustfree)
4029 vim_free(var);
4030 var = p;
4031 mustfree = TRUE;
4032 forward_slash(var);
4033 }
4034 }
4035#endif
4036
4037 /* If "var" contains white space, escape it with a backslash.
4038 * Required for ":e ~/tt" when $HOME includes a space. */
4039 if (esc && var != NULL && vim_strpbrk(var, (char_u *)" \t") != NULL)
4040 {
4041 char_u *p = vim_strsave_escaped(var, (char_u *)" \t");
4042
4043 if (p != NULL)
4044 {
4045 if (mustfree)
4046 vim_free(var);
4047 var = p;
4048 mustfree = TRUE;
4049 }
4050 }
4051
4052 if (var != NULL && *var != NUL
4053 && (STRLEN(var) + STRLEN(tail) + 1 < (unsigned)dstlen))
4054 {
4055 STRCPY(dst, var);
4056 dstlen -= (int)STRLEN(var);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004057 c = (int)STRLEN(var);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004058 /* if var[] ends in a path separator and tail[] starts
4059 * with it, skip a character */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004060 if (*var != NUL && after_pathsep(dst, dst + c)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004061#if defined(BACKSLASH_IN_FILENAME) || defined(AMIGA)
4062 && dst[-1] != ':'
4063#endif
4064 && vim_ispathsep(*tail))
4065 ++tail;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004066 dst += c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004067 src = tail;
4068 copy_char = FALSE;
4069 }
4070 if (mustfree)
4071 vim_free(var);
4072 }
4073
4074 if (copy_char) /* copy at least one char */
4075 {
4076 /*
Bram Moolenaar25394022007-05-10 19:06:20 +00004077 * Recognize the start of a new name, for '~'.
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00004078 * Don't do this when "one" is TRUE, to avoid expanding "~" in
4079 * ":edit foo ~ foo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00004080 */
4081 at_start = FALSE;
4082 if (src[0] == '\\' && src[1] != NUL)
4083 {
4084 *dst++ = *src++;
4085 --dstlen;
4086 }
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00004087 else if ((src[0] == ' ' || src[0] == ',') && !one)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004088 at_start = TRUE;
4089 *dst++ = *src++;
4090 --dstlen;
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00004091
4092 if (startstr != NULL && src - startstr_len >= srcp
4093 && STRNCMP(src - startstr_len, startstr, startstr_len) == 0)
4094 at_start = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004095 }
4096 }
4097 *dst = NUL;
4098}
4099
4100/*
4101 * Vim's version of getenv().
4102 * Special handling of $HOME, $VIM and $VIMRUNTIME.
Bram Moolenaar2f6b0b82005-03-08 22:43:10 +00004103 * Also does ACP to 'enc' conversion for Win32.
Bram Moolenaarb453a532011-04-28 17:48:44 +02004104 * "mustfree" is set to TRUE when returned is allocated, it must be
4105 * initialized to FALSE by the caller.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004106 */
4107 char_u *
4108vim_getenv(name, mustfree)
4109 char_u *name;
Bram Moolenaarb453a532011-04-28 17:48:44 +02004110 int *mustfree;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004111{
4112 char_u *p;
4113 char_u *pend;
4114 int vimruntime;
4115
4116#if defined(OS2) || defined(MSDOS) || defined(MSWIN)
4117 /* use "C:/" when $HOME is not set */
4118 if (STRCMP(name, "HOME") == 0)
4119 return homedir;
4120#endif
4121
4122 p = mch_getenv(name);
4123 if (p != NULL && *p == NUL) /* empty is the same as not set */
4124 p = NULL;
4125
4126 if (p != NULL)
Bram Moolenaar05159a02005-02-26 23:04:13 +00004127 {
4128#if defined(FEAT_MBYTE) && defined(WIN3264)
4129 if (enc_utf8)
4130 {
4131 int len;
Bram Moolenaarb453a532011-04-28 17:48:44 +02004132 char_u *pp = NULL;
Bram Moolenaar05159a02005-02-26 23:04:13 +00004133
4134 /* Convert from active codepage to UTF-8. Other conversions are
4135 * not done, because they would fail for non-ASCII characters. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004136 acp_to_enc(p, (int)STRLEN(p), &pp, &len);
Bram Moolenaar05159a02005-02-26 23:04:13 +00004137 if (pp != NULL)
4138 {
4139 p = pp;
4140 *mustfree = TRUE;
4141 }
4142 }
4143#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004144 return p;
Bram Moolenaar05159a02005-02-26 23:04:13 +00004145 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004146
4147 vimruntime = (STRCMP(name, "VIMRUNTIME") == 0);
4148 if (!vimruntime && STRCMP(name, "VIM") != 0)
4149 return NULL;
4150
4151 /*
4152 * When expanding $VIMRUNTIME fails, try using $VIM/vim<version> or $VIM.
4153 * Don't do this when default_vimruntime_dir is non-empty.
4154 */
4155 if (vimruntime
4156#ifdef HAVE_PATHDEF
4157 && *default_vimruntime_dir == NUL
4158#endif
4159 )
4160 {
4161 p = mch_getenv((char_u *)"VIM");
4162 if (p != NULL && *p == NUL) /* empty is the same as not set */
4163 p = NULL;
4164 if (p != NULL)
4165 {
4166 p = vim_version_dir(p);
4167 if (p != NULL)
4168 *mustfree = TRUE;
4169 else
4170 p = mch_getenv((char_u *)"VIM");
Bram Moolenaar05159a02005-02-26 23:04:13 +00004171
4172#if defined(FEAT_MBYTE) && defined(WIN3264)
4173 if (enc_utf8)
4174 {
4175 int len;
Bram Moolenaarb453a532011-04-28 17:48:44 +02004176 char_u *pp = NULL;
Bram Moolenaar05159a02005-02-26 23:04:13 +00004177
4178 /* Convert from active codepage to UTF-8. Other conversions
4179 * are not done, because they would fail for non-ASCII
4180 * characters. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004181 acp_to_enc(p, (int)STRLEN(p), &pp, &len);
Bram Moolenaar05159a02005-02-26 23:04:13 +00004182 if (pp != NULL)
4183 {
Bram Moolenaarb453a532011-04-28 17:48:44 +02004184 if (*mustfree)
Bram Moolenaar05159a02005-02-26 23:04:13 +00004185 vim_free(p);
4186 p = pp;
4187 *mustfree = TRUE;
4188 }
4189 }
4190#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004191 }
4192 }
4193
4194 /*
4195 * When expanding $VIM or $VIMRUNTIME fails, try using:
4196 * - the directory name from 'helpfile' (unless it contains '$')
4197 * - the executable name from argv[0]
4198 */
4199 if (p == NULL)
4200 {
4201 if (p_hf != NULL && vim_strchr(p_hf, '$') == NULL)
4202 p = p_hf;
4203#ifdef USE_EXE_NAME
4204 /*
4205 * Use the name of the executable, obtained from argv[0].
4206 */
4207 else
4208 p = exe_name;
4209#endif
4210 if (p != NULL)
4211 {
4212 /* remove the file name */
4213 pend = gettail(p);
4214
4215 /* remove "doc/" from 'helpfile', if present */
4216 if (p == p_hf)
4217 pend = remove_tail(p, pend, (char_u *)"doc");
4218
4219#ifdef USE_EXE_NAME
4220# ifdef MACOS_X
Bram Moolenaar95e9b492006-03-15 23:04:43 +00004221 /* remove "MacOS" from exe_name and add "Resources/vim" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004222 if (p == exe_name)
4223 {
4224 char_u *pend1;
Bram Moolenaar95e9b492006-03-15 23:04:43 +00004225 char_u *pnew;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004226
Bram Moolenaar95e9b492006-03-15 23:04:43 +00004227 pend1 = remove_tail(p, pend, (char_u *)"MacOS");
4228 if (pend1 != pend)
4229 {
4230 pnew = alloc((unsigned)(pend1 - p) + 15);
4231 if (pnew != NULL)
4232 {
4233 STRNCPY(pnew, p, (pend1 - p));
4234 STRCPY(pnew + (pend1 - p), "Resources/vim");
4235 p = pnew;
4236 pend = p + STRLEN(p);
4237 }
4238 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004239 }
4240# endif
4241 /* remove "src/" from exe_name, if present */
4242 if (p == exe_name)
4243 pend = remove_tail(p, pend, (char_u *)"src");
4244#endif
4245
4246 /* for $VIM, remove "runtime/" or "vim54/", if present */
4247 if (!vimruntime)
4248 {
4249 pend = remove_tail(p, pend, (char_u *)RUNTIME_DIRNAME);
4250 pend = remove_tail(p, pend, (char_u *)VIM_VERSION_NODOT);
4251 }
4252
4253 /* remove trailing path separator */
4254#ifndef MACOS_CLASSIC
4255 /* With MacOS path (with colons) the final colon is required */
Bram Moolenaare21877a2008-02-13 09:58:14 +00004256 /* to avoid confusion between absolute and relative path */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004257 if (pend > p && after_pathsep(p, pend))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004258 --pend;
4259#endif
4260
Bram Moolenaar95e9b492006-03-15 23:04:43 +00004261#ifdef MACOS_X
4262 if (p == exe_name || p == p_hf)
4263#endif
4264 /* check that the result is a directory name */
4265 p = vim_strnsave(p, (int)(pend - p));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004266
4267 if (p != NULL && !mch_isdir(p))
4268 {
4269 vim_free(p);
4270 p = NULL;
4271 }
4272 else
4273 {
4274#ifdef USE_EXE_NAME
4275 /* may add "/vim54" or "/runtime" if it exists */
4276 if (vimruntime && (pend = vim_version_dir(p)) != NULL)
4277 {
4278 vim_free(p);
4279 p = pend;
4280 }
4281#endif
4282 *mustfree = TRUE;
4283 }
4284 }
4285 }
4286
4287#ifdef HAVE_PATHDEF
4288 /* When there is a pathdef.c file we can use default_vim_dir and
4289 * default_vimruntime_dir */
4290 if (p == NULL)
4291 {
4292 /* Only use default_vimruntime_dir when it is not empty */
4293 if (vimruntime && *default_vimruntime_dir != NUL)
4294 {
4295 p = default_vimruntime_dir;
4296 *mustfree = FALSE;
4297 }
4298 else if (*default_vim_dir != NUL)
4299 {
4300 if (vimruntime && (p = vim_version_dir(default_vim_dir)) != NULL)
4301 *mustfree = TRUE;
4302 else
4303 {
4304 p = default_vim_dir;
4305 *mustfree = FALSE;
4306 }
4307 }
4308 }
4309#endif
4310
4311 /*
4312 * Set the environment variable, so that the new value can be found fast
4313 * next time, and others can also use it (e.g. Perl).
4314 */
4315 if (p != NULL)
4316 {
4317 if (vimruntime)
4318 {
4319 vim_setenv((char_u *)"VIMRUNTIME", p);
4320 didset_vimruntime = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004321 }
4322 else
4323 {
4324 vim_setenv((char_u *)"VIM", p);
4325 didset_vim = TRUE;
4326 }
4327 }
4328 return p;
4329}
4330
4331/*
4332 * Check if the directory "vimdir/<version>" or "vimdir/runtime" exists.
4333 * Return NULL if not, return its name in allocated memory otherwise.
4334 */
4335 static char_u *
4336vim_version_dir(vimdir)
4337 char_u *vimdir;
4338{
4339 char_u *p;
4340
4341 if (vimdir == NULL || *vimdir == NUL)
4342 return NULL;
4343 p = concat_fnames(vimdir, (char_u *)VIM_VERSION_NODOT, TRUE);
4344 if (p != NULL && mch_isdir(p))
4345 return p;
4346 vim_free(p);
4347 p = concat_fnames(vimdir, (char_u *)RUNTIME_DIRNAME, TRUE);
4348 if (p != NULL && mch_isdir(p))
4349 return p;
4350 vim_free(p);
4351 return NULL;
4352}
4353
4354/*
4355 * If the string between "p" and "pend" ends in "name/", return "pend" minus
4356 * the length of "name/". Otherwise return "pend".
4357 */
4358 static char_u *
4359remove_tail(p, pend, name)
4360 char_u *p;
4361 char_u *pend;
4362 char_u *name;
4363{
4364 int len = (int)STRLEN(name) + 1;
4365 char_u *newend = pend - len;
4366
4367 if (newend >= p
4368 && fnamencmp(newend, name, len - 1) == 0
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004369 && (newend == p || after_pathsep(p, newend)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004370 return newend;
4371 return pend;
4372}
4373
Bram Moolenaar071d4272004-06-13 20:20:40 +00004374/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004375 * Our portable version of setenv.
4376 */
4377 void
4378vim_setenv(name, val)
4379 char_u *name;
4380 char_u *val;
4381{
4382#ifdef HAVE_SETENV
4383 mch_setenv((char *)name, (char *)val, 1);
4384#else
4385 char_u *envbuf;
4386
4387 /*
4388 * Putenv does not copy the string, it has to remain
4389 * valid. The allocated memory will never be freed.
4390 */
4391 envbuf = alloc((unsigned)(STRLEN(name) + STRLEN(val) + 2));
4392 if (envbuf != NULL)
4393 {
4394 sprintf((char *)envbuf, "%s=%s", name, val);
4395 putenv((char *)envbuf);
4396 }
4397#endif
Bram Moolenaar011a34d2012-02-29 13:49:09 +01004398#ifdef FEAT_GETTEXT
4399 /*
4400 * When setting $VIMRUNTIME adjust the directory to find message
4401 * translations to $VIMRUNTIME/lang.
4402 */
4403 if (*val != NUL && STRICMP(name, "VIMRUNTIME") == 0)
4404 {
4405 char_u *buf = concat_str(val, (char_u *)"/lang");
4406
4407 if (buf != NULL)
4408 {
4409 bindtextdomain(VIMPACKAGE, (char *)buf);
4410 vim_free(buf);
4411 }
4412 }
4413#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004414}
4415
4416#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
4417/*
4418 * Function given to ExpandGeneric() to obtain an environment variable name.
4419 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004420 char_u *
4421get_env_name(xp, idx)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00004422 expand_T *xp UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004423 int idx;
4424{
4425# if defined(AMIGA) || defined(__MRC__) || defined(__SC__)
4426 /*
4427 * No environ[] on the Amiga and on the Mac (using MPW).
4428 */
4429 return NULL;
4430# else
4431# ifndef __WIN32__
4432 /* Borland C++ 5.2 has this in a header file. */
4433 extern char **environ;
4434# endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00004435# define ENVNAMELEN 100
4436 static char_u name[ENVNAMELEN];
Bram Moolenaar071d4272004-06-13 20:20:40 +00004437 char_u *str;
4438 int n;
4439
4440 str = (char_u *)environ[idx];
4441 if (str == NULL)
4442 return NULL;
4443
Bram Moolenaar21cf8232004-07-16 20:18:37 +00004444 for (n = 0; n < ENVNAMELEN - 1; ++n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004445 {
4446 if (str[n] == '=' || str[n] == NUL)
4447 break;
4448 name[n] = str[n];
4449 }
4450 name[n] = NUL;
4451 return name;
4452# endif
4453}
4454#endif
4455
4456/*
4457 * Replace home directory by "~" in each space or comma separated file name in
4458 * 'src'.
4459 * If anything fails (except when out of space) dst equals src.
4460 */
4461 void
4462home_replace(buf, src, dst, dstlen, one)
4463 buf_T *buf; /* when not NULL, check for help files */
4464 char_u *src; /* input file name */
4465 char_u *dst; /* where to put the result */
4466 int dstlen; /* maximum length of the result */
4467 int one; /* if TRUE, only replace one file name, include
4468 spaces and commas in the file name. */
4469{
4470 size_t dirlen = 0, envlen = 0;
4471 size_t len;
Bram Moolenaar9158f9e2012-06-20 14:02:27 +02004472 char_u *homedir_env, *homedir_env_orig;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004473 char_u *p;
4474
4475 if (src == NULL)
4476 {
4477 *dst = NUL;
4478 return;
4479 }
4480
4481 /*
4482 * If the file is a help file, remove the path completely.
4483 */
4484 if (buf != NULL && buf->b_help)
4485 {
4486 STRCPY(dst, gettail(src));
4487 return;
4488 }
4489
4490 /*
4491 * We check both the value of the $HOME environment variable and the
4492 * "real" home directory.
4493 */
4494 if (homedir != NULL)
4495 dirlen = STRLEN(homedir);
4496
4497#ifdef VMS
Bram Moolenaar9158f9e2012-06-20 14:02:27 +02004498 homedir_env_orig = homedir_env = mch_getenv((char_u *)"SYS$LOGIN");
Bram Moolenaar071d4272004-06-13 20:20:40 +00004499#else
Bram Moolenaar9158f9e2012-06-20 14:02:27 +02004500 homedir_env_orig = homedir_env = mch_getenv((char_u *)"HOME");
4501#endif
Bram Moolenaarbef47902012-07-06 16:49:40 +02004502 /* Empty is the same as not set. */
4503 if (homedir_env != NULL && *homedir_env == NUL)
4504 homedir_env = NULL;
4505
Bram Moolenaar9158f9e2012-06-20 14:02:27 +02004506#if defined(FEAT_MODIFY_FNAME) || defined(WIN3264)
Bram Moolenaarbef47902012-07-06 16:49:40 +02004507 if (homedir_env != NULL && vim_strchr(homedir_env, '~') != NULL)
Bram Moolenaar9158f9e2012-06-20 14:02:27 +02004508 {
4509 int usedlen = 0;
4510 int flen;
4511 char_u *fbuf = NULL;
4512
4513 flen = (int)STRLEN(homedir_env);
Bram Moolenaard12f8112012-06-20 17:56:09 +02004514 (void)modify_fname((char_u *)":p", &usedlen,
4515 &homedir_env, &fbuf, &flen);
Bram Moolenaar9158f9e2012-06-20 14:02:27 +02004516 flen = (int)STRLEN(homedir_env);
4517 if (flen > 0 && vim_ispathsep(homedir_env[flen - 1]))
4518 /* Remove the trailing / that is added to a directory. */
4519 homedir_env[flen - 1] = NUL;
4520 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004521#endif
4522
Bram Moolenaar071d4272004-06-13 20:20:40 +00004523 if (homedir_env != NULL)
4524 envlen = STRLEN(homedir_env);
4525
4526 if (!one)
4527 src = skipwhite(src);
4528 while (*src && dstlen > 0)
4529 {
4530 /*
4531 * Here we are at the beginning of a file name.
4532 * First, check to see if the beginning of the file name matches
4533 * $HOME or the "real" home directory. Check that there is a '/'
4534 * after the match (so that if e.g. the file is "/home/pieter/bla",
4535 * and the home directory is "/home/piet", the file does not end up
4536 * as "~er/bla" (which would seem to indicate the file "bla" in user
4537 * er's home directory)).
4538 */
4539 p = homedir;
4540 len = dirlen;
4541 for (;;)
4542 {
4543 if ( len
4544 && fnamencmp(src, p, len) == 0
4545 && (vim_ispathsep(src[len])
4546 || (!one && (src[len] == ',' || src[len] == ' '))
4547 || src[len] == NUL))
4548 {
4549 src += len;
4550 if (--dstlen > 0)
4551 *dst++ = '~';
4552
4553 /*
4554 * If it's just the home directory, add "/".
4555 */
4556 if (!vim_ispathsep(src[0]) && --dstlen > 0)
4557 *dst++ = '/';
4558 break;
4559 }
4560 if (p == homedir_env)
4561 break;
4562 p = homedir_env;
4563 len = envlen;
4564 }
4565
4566 /* if (!one) skip to separator: space or comma */
4567 while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
4568 *dst++ = *src++;
4569 /* skip separator */
4570 while ((*src == ' ' || *src == ',') && --dstlen > 0)
4571 *dst++ = *src++;
4572 }
4573 /* if (dstlen == 0) out of space, what to do??? */
4574
4575 *dst = NUL;
Bram Moolenaar9158f9e2012-06-20 14:02:27 +02004576
4577 if (homedir_env != homedir_env_orig)
4578 vim_free(homedir_env);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004579}
4580
4581/*
4582 * Like home_replace, store the replaced string in allocated memory.
4583 * When something fails, NULL is returned.
4584 */
4585 char_u *
4586home_replace_save(buf, src)
4587 buf_T *buf; /* when not NULL, check for help files */
4588 char_u *src; /* input file name */
4589{
4590 char_u *dst;
4591 unsigned len;
4592
4593 len = 3; /* space for "~/" and trailing NUL */
4594 if (src != NULL) /* just in case */
4595 len += (unsigned)STRLEN(src);
4596 dst = alloc(len);
4597 if (dst != NULL)
4598 home_replace(buf, src, dst, len, TRUE);
4599 return dst;
4600}
4601
4602/*
4603 * Compare two file names and return:
4604 * FPC_SAME if they both exist and are the same file.
4605 * FPC_SAMEX if they both don't exist and have the same file name.
4606 * FPC_DIFF if they both exist and are different files.
4607 * FPC_NOTX if they both don't exist.
4608 * FPC_DIFFX if one of them doesn't exist.
4609 * For the first name environment variables are expanded
4610 */
4611 int
4612fullpathcmp(s1, s2, checkname)
4613 char_u *s1, *s2;
4614 int checkname; /* when both don't exist, check file names */
4615{
4616#ifdef UNIX
4617 char_u exp1[MAXPATHL];
4618 char_u full1[MAXPATHL];
4619 char_u full2[MAXPATHL];
4620 struct stat st1, st2;
4621 int r1, r2;
4622
4623 expand_env(s1, exp1, MAXPATHL);
4624 r1 = mch_stat((char *)exp1, &st1);
4625 r2 = mch_stat((char *)s2, &st2);
4626 if (r1 != 0 && r2 != 0)
4627 {
4628 /* if mch_stat() doesn't work, may compare the names */
4629 if (checkname)
4630 {
4631 if (fnamecmp(exp1, s2) == 0)
4632 return FPC_SAMEX;
4633 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4634 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4635 if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
4636 return FPC_SAMEX;
4637 }
4638 return FPC_NOTX;
4639 }
4640 if (r1 != 0 || r2 != 0)
4641 return FPC_DIFFX;
4642 if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
4643 return FPC_SAME;
4644 return FPC_DIFF;
4645#else
4646 char_u *exp1; /* expanded s1 */
4647 char_u *full1; /* full path of s1 */
4648 char_u *full2; /* full path of s2 */
4649 int retval = FPC_DIFF;
4650 int r1, r2;
4651
4652 /* allocate one buffer to store three paths (alloc()/free() is slow!) */
4653 if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
4654 {
4655 full1 = exp1 + MAXPATHL;
4656 full2 = full1 + MAXPATHL;
4657
4658 expand_env(s1, exp1, MAXPATHL);
4659 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4660 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4661
4662 /* If vim_FullName() fails, the file probably doesn't exist. */
4663 if (r1 != OK && r2 != OK)
4664 {
4665 if (checkname && fnamecmp(exp1, s2) == 0)
4666 retval = FPC_SAMEX;
4667 else
4668 retval = FPC_NOTX;
4669 }
4670 else if (r1 != OK || r2 != OK)
4671 retval = FPC_DIFFX;
4672 else if (fnamecmp(full1, full2))
4673 retval = FPC_DIFF;
4674 else
4675 retval = FPC_SAME;
4676 vim_free(exp1);
4677 }
4678 return retval;
4679#endif
4680}
4681
4682/*
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004683 * Get the tail of a path: the file name.
Bram Moolenaar31710262010-08-13 13:36:15 +02004684 * When the path ends in a path separator the tail is the NUL after it.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004685 * Fail safe: never returns NULL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004686 */
4687 char_u *
4688gettail(fname)
4689 char_u *fname;
4690{
4691 char_u *p1, *p2;
4692
4693 if (fname == NULL)
4694 return (char_u *)"";
4695 for (p1 = p2 = fname; *p2; ) /* find last part of path */
4696 {
4697 if (vim_ispathsep(*p2))
4698 p1 = p2 + 1;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004699 mb_ptr_adv(p2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004700 }
4701 return p1;
4702}
4703
Bram Moolenaar31710262010-08-13 13:36:15 +02004704#if defined(FEAT_SEARCHPATH)
4705static char_u *gettail_dir __ARGS((char_u *fname));
4706
4707/*
4708 * Return the end of the directory name, on the first path
4709 * separator:
4710 * "/path/file", "/path/dir/", "/path//dir", "/file"
4711 * ^ ^ ^ ^
4712 */
4713 static char_u *
4714gettail_dir(fname)
4715 char_u *fname;
4716{
4717 char_u *dir_end = fname;
4718 char_u *next_dir_end = fname;
4719 int look_for_sep = TRUE;
4720 char_u *p;
4721
4722 for (p = fname; *p != NUL; )
4723 {
4724 if (vim_ispathsep(*p))
4725 {
4726 if (look_for_sep)
4727 {
4728 next_dir_end = p;
4729 look_for_sep = FALSE;
4730 }
4731 }
4732 else
4733 {
4734 if (!look_for_sep)
4735 dir_end = next_dir_end;
4736 look_for_sep = TRUE;
4737 }
4738 mb_ptr_adv(p);
4739 }
4740 return dir_end;
4741}
4742#endif
4743
Bram Moolenaar071d4272004-06-13 20:20:40 +00004744/*
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004745 * Get pointer to tail of "fname", including path separators. Putting a NUL
4746 * here leaves the directory name. Takes care of "c:/" and "//".
4747 * Always returns a valid pointer.
4748 */
4749 char_u *
4750gettail_sep(fname)
4751 char_u *fname;
4752{
4753 char_u *p;
4754 char_u *t;
4755
4756 p = get_past_head(fname); /* don't remove the '/' from "c:/file" */
4757 t = gettail(fname);
4758 while (t > p && after_pathsep(fname, t))
4759 --t;
4760#ifdef VMS
4761 /* path separator is part of the path */
4762 ++t;
4763#endif
4764 return t;
4765}
4766
4767/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004768 * get the next path component (just after the next path separator).
4769 */
4770 char_u *
4771getnextcomp(fname)
4772 char_u *fname;
4773{
4774 while (*fname && !vim_ispathsep(*fname))
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004775 mb_ptr_adv(fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004776 if (*fname)
4777 ++fname;
4778 return fname;
4779}
4780
Bram Moolenaar071d4272004-06-13 20:20:40 +00004781/*
4782 * Get a pointer to one character past the head of a path name.
4783 * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
4784 * If there is no head, path is returned.
4785 */
4786 char_u *
4787get_past_head(path)
4788 char_u *path;
4789{
4790 char_u *retval;
4791
4792#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
4793 /* may skip "c:" */
4794 if (isalpha(path[0]) && path[1] == ':')
4795 retval = path + 2;
4796 else
4797 retval = path;
4798#else
4799# if defined(AMIGA)
4800 /* may skip "label:" */
4801 retval = vim_strchr(path, ':');
4802 if (retval == NULL)
4803 retval = path;
4804# else /* Unix */
4805 retval = path;
4806# endif
4807#endif
4808
4809 while (vim_ispathsep(*retval))
4810 ++retval;
4811
4812 return retval;
4813}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004814
4815/*
4816 * return TRUE if 'c' is a path separator.
4817 */
4818 int
4819vim_ispathsep(c)
4820 int c;
4821{
Bram Moolenaare60acc12011-05-10 16:41:25 +02004822#ifdef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00004823 return (c == '/'); /* UNIX has ':' inside file names */
Bram Moolenaare60acc12011-05-10 16:41:25 +02004824#else
4825# ifdef BACKSLASH_IN_FILENAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00004826 return (c == ':' || c == '/' || c == '\\');
Bram Moolenaare60acc12011-05-10 16:41:25 +02004827# else
4828# ifdef VMS
Bram Moolenaar071d4272004-06-13 20:20:40 +00004829 /* server"user passwd"::device:[full.path.name]fname.extension;version" */
4830 return (c == ':' || c == '[' || c == ']' || c == '/'
4831 || c == '<' || c == '>' || c == '"' );
Bram Moolenaare60acc12011-05-10 16:41:25 +02004832# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004833 return (c == ':' || c == '/');
Bram Moolenaare60acc12011-05-10 16:41:25 +02004834# endif /* VMS */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004835# endif
Bram Moolenaare60acc12011-05-10 16:41:25 +02004836#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004837}
4838
4839#if defined(FEAT_SEARCHPATH) || defined(PROTO)
4840/*
4841 * return TRUE if 'c' is a path list separator.
4842 */
4843 int
4844vim_ispathlistsep(c)
4845 int c;
4846{
4847#ifdef UNIX
4848 return (c == ':');
4849#else
Bram Moolenaar25394022007-05-10 19:06:20 +00004850 return (c == ';'); /* might not be right for every system... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004851#endif
4852}
4853#endif
4854
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004855#if defined(FEAT_GUI_TABLINE) || defined(FEAT_WINDOWS) \
4856 || defined(FEAT_EVAL) || defined(PROTO)
4857/*
4858 * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
4859 * It's done in-place.
4860 */
4861 void
4862shorten_dir(str)
4863 char_u *str;
4864{
4865 char_u *tail, *s, *d;
4866 int skip = FALSE;
4867
4868 tail = gettail(str);
4869 d = str;
4870 for (s = str; ; ++s)
4871 {
4872 if (s >= tail) /* copy the whole tail */
4873 {
4874 *d++ = *s;
4875 if (*s == NUL)
4876 break;
4877 }
4878 else if (vim_ispathsep(*s)) /* copy '/' and next char */
4879 {
4880 *d++ = *s;
4881 skip = FALSE;
4882 }
4883 else if (!skip)
4884 {
4885 *d++ = *s; /* copy next char */
4886 if (*s != '~' && *s != '.') /* and leading "~" and "." */
4887 skip = TRUE;
4888# ifdef FEAT_MBYTE
4889 if (has_mbyte)
4890 {
4891 int l = mb_ptr2len(s);
4892
4893 while (--l > 0)
Bram Moolenaarb6baca52006-08-15 20:24:14 +00004894 *d++ = *++s;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004895 }
4896# endif
4897 }
4898 }
4899}
4900#endif
4901
Bram Moolenaar900b4d72005-12-12 22:05:50 +00004902/*
4903 * Return TRUE if the directory of "fname" exists, FALSE otherwise.
4904 * Also returns TRUE if there is no directory name.
4905 * "fname" must be writable!.
4906 */
4907 int
4908dir_of_file_exists(fname)
4909 char_u *fname;
4910{
4911 char_u *p;
4912 int c;
4913 int retval;
4914
4915 p = gettail_sep(fname);
4916 if (p == fname)
4917 return TRUE;
4918 c = *p;
4919 *p = NUL;
4920 retval = mch_isdir(fname);
4921 *p = c;
4922 return retval;
4923}
4924
Bram Moolenaar071d4272004-06-13 20:20:40 +00004925#if (defined(CASE_INSENSITIVE_FILENAME) && defined(BACKSLASH_IN_FILENAME)) \
4926 || defined(PROTO)
4927/*
4928 * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally.
4929 */
4930 int
4931vim_fnamecmp(x, y)
4932 char_u *x, *y;
4933{
4934 return vim_fnamencmp(x, y, MAXPATHL);
4935}
4936
4937 int
4938vim_fnamencmp(x, y, len)
4939 char_u *x, *y;
4940 size_t len;
4941{
4942 while (len > 0 && *x && *y)
4943 {
4944 if (TOLOWER_LOC(*x) != TOLOWER_LOC(*y)
4945 && !(*x == '/' && *y == '\\')
4946 && !(*x == '\\' && *y == '/'))
4947 break;
4948 ++x;
4949 ++y;
4950 --len;
4951 }
4952 if (len == 0)
4953 return 0;
4954 return (*x - *y);
4955}
4956#endif
4957
4958/*
4959 * Concatenate file names fname1 and fname2 into allocated memory.
Bram Moolenaar25394022007-05-10 19:06:20 +00004960 * Only add a '/' or '\\' when 'sep' is TRUE and it is necessary.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004961 */
4962 char_u *
4963concat_fnames(fname1, fname2, sep)
4964 char_u *fname1;
4965 char_u *fname2;
4966 int sep;
4967{
4968 char_u *dest;
4969
4970 dest = alloc((unsigned)(STRLEN(fname1) + STRLEN(fname2) + 3));
4971 if (dest != NULL)
4972 {
4973 STRCPY(dest, fname1);
4974 if (sep)
4975 add_pathsep(dest);
4976 STRCAT(dest, fname2);
4977 }
4978 return dest;
4979}
4980
Bram Moolenaard6754642005-01-17 22:18:45 +00004981/*
4982 * Concatenate two strings and return the result in allocated memory.
4983 * Returns NULL when out of memory.
4984 */
4985 char_u *
4986concat_str(str1, str2)
4987 char_u *str1;
4988 char_u *str2;
4989{
4990 char_u *dest;
4991 size_t l = STRLEN(str1);
4992
4993 dest = alloc((unsigned)(l + STRLEN(str2) + 1L));
4994 if (dest != NULL)
4995 {
4996 STRCPY(dest, str1);
4997 STRCPY(dest + l, str2);
4998 }
4999 return dest;
5000}
Bram Moolenaard6754642005-01-17 22:18:45 +00005001
Bram Moolenaar071d4272004-06-13 20:20:40 +00005002/*
5003 * Add a path separator to a file name, unless it already ends in a path
5004 * separator.
5005 */
5006 void
5007add_pathsep(p)
5008 char_u *p;
5009{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005010 if (*p != NUL && !after_pathsep(p, p + STRLEN(p)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005011 STRCAT(p, PATHSEPSTR);
5012}
5013
5014/*
5015 * FullName_save - Make an allocated copy of a full file name.
5016 * Returns NULL when out of memory.
5017 */
5018 char_u *
5019FullName_save(fname, force)
5020 char_u *fname;
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +02005021 int force; /* force expansion, even when it already looks
5022 * like a full path name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005023{
5024 char_u *buf;
5025 char_u *new_fname = NULL;
5026
5027 if (fname == NULL)
5028 return NULL;
5029
5030 buf = alloc((unsigned)MAXPATHL);
5031 if (buf != NULL)
5032 {
5033 if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
5034 new_fname = vim_strsave(buf);
5035 else
5036 new_fname = vim_strsave(fname);
5037 vim_free(buf);
5038 }
5039 return new_fname;
5040}
5041
5042#if defined(FEAT_CINDENT) || defined(FEAT_SYN_HL)
5043
5044static char_u *skip_string __ARGS((char_u *p));
5045
5046/*
5047 * Find the start of a comment, not knowing if we are in a comment right now.
5048 * Search starts at w_cursor.lnum and goes backwards.
5049 */
5050 pos_T *
5051find_start_comment(ind_maxcomment) /* XXX */
5052 int ind_maxcomment;
5053{
5054 pos_T *pos;
5055 char_u *line;
5056 char_u *p;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005057 int cur_maxcomment = ind_maxcomment;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005058
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005059 for (;;)
5060 {
5061 pos = findmatchlimit(NULL, '*', FM_BACKWARD, cur_maxcomment);
5062 if (pos == NULL)
5063 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005064
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005065 /*
5066 * Check if the comment start we found is inside a string.
5067 * If it is then restrict the search to below this line and try again.
5068 */
5069 line = ml_get(pos->lnum);
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00005070 for (p = line; *p && (colnr_T)(p - line) < pos->col; ++p)
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005071 p = skip_string(p);
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00005072 if ((colnr_T)(p - line) <= pos->col)
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005073 break;
5074 cur_maxcomment = curwin->w_cursor.lnum - pos->lnum - 1;
5075 if (cur_maxcomment <= 0)
5076 {
5077 pos = NULL;
5078 break;
5079 }
5080 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005081 return pos;
5082}
5083
5084/*
5085 * Skip to the end of a "string" and a 'c' character.
5086 * If there is no string or character, return argument unmodified.
5087 */
5088 static char_u *
5089skip_string(p)
5090 char_u *p;
5091{
5092 int i;
5093
5094 /*
5095 * We loop, because strings may be concatenated: "date""time".
5096 */
5097 for ( ; ; ++p)
5098 {
5099 if (p[0] == '\'') /* 'c' or '\n' or '\000' */
5100 {
5101 if (!p[1]) /* ' at end of line */
5102 break;
5103 i = 2;
5104 if (p[1] == '\\') /* '\n' or '\000' */
5105 {
5106 ++i;
5107 while (vim_isdigit(p[i - 1])) /* '\000' */
5108 ++i;
5109 }
5110 if (p[i] == '\'') /* check for trailing ' */
5111 {
5112 p += i;
5113 continue;
5114 }
5115 }
5116 else if (p[0] == '"') /* start of string */
5117 {
5118 for (++p; p[0]; ++p)
5119 {
5120 if (p[0] == '\\' && p[1] != NUL)
5121 ++p;
5122 else if (p[0] == '"') /* end of string */
5123 break;
5124 }
5125 if (p[0] == '"')
5126 continue;
5127 }
5128 break; /* no string found */
5129 }
5130 if (!*p)
5131 --p; /* backup from NUL */
5132 return p;
5133}
5134#endif /* FEAT_CINDENT || FEAT_SYN_HL */
5135
5136#if defined(FEAT_CINDENT) || defined(PROTO)
5137
5138/*
5139 * Do C or expression indenting on the current line.
5140 */
5141 void
5142do_c_expr_indent()
5143{
5144# ifdef FEAT_EVAL
5145 if (*curbuf->b_p_inde != NUL)
5146 fixthisline(get_expr_indent);
5147 else
5148# endif
5149 fixthisline(get_c_indent);
5150}
5151
5152/*
5153 * Functions for C-indenting.
5154 * Most of this originally comes from Eric Fischer.
5155 */
5156/*
5157 * Below "XXX" means that this function may unlock the current line.
5158 */
5159
5160static char_u *cin_skipcomment __ARGS((char_u *));
5161static int cin_nocode __ARGS((char_u *));
5162static pos_T *find_line_comment __ARGS((void));
5163static int cin_islabel_skip __ARGS((char_u **));
5164static int cin_isdefault __ARGS((char_u *));
5165static char_u *after_label __ARGS((char_u *l));
5166static int get_indent_nolabel __ARGS((linenr_T lnum));
5167static int skip_label __ARGS((linenr_T, char_u **pp, int ind_maxcomment));
5168static int cin_first_id_amount __ARGS((void));
5169static int cin_get_equal_amount __ARGS((linenr_T lnum));
5170static int cin_ispreproc __ARGS((char_u *));
5171static int cin_ispreproc_cont __ARGS((char_u **pp, linenr_T *lnump));
5172static int cin_iscomment __ARGS((char_u *));
5173static int cin_islinecomment __ARGS((char_u *));
5174static int cin_isterminated __ARGS((char_u *, int, int));
5175static int cin_isinit __ARGS((void));
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005176static int cin_isfuncdecl __ARGS((char_u **, linenr_T, linenr_T, int, int));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005177static int cin_isif __ARGS((char_u *));
5178static int cin_iselse __ARGS((char_u *));
5179static int cin_isdo __ARGS((char_u *));
5180static int cin_iswhileofdo __ARGS((char_u *, linenr_T, int));
Bram Moolenaarb345d492012-04-09 20:42:26 +02005181static int cin_is_if_for_while_before_offset __ARGS((char_u *line, int *poffset));
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005182static int cin_iswhileofdo_end __ARGS((int terminated, int ind_maxparen, int ind_maxcomment));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005183static int cin_isbreak __ARGS((char_u *));
Bram Moolenaare7c56862007-08-04 10:14:52 +00005184static int cin_is_cpp_baseclass __ARGS((colnr_T *col));
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005185static int get_baseclass_amount __ARGS((int col, int ind_maxparen, int ind_maxcomment, int ind_cpp_baseclass));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005186static int cin_ends_in __ARGS((char_u *, char_u *, char_u *));
5187static int cin_skip2pos __ARGS((pos_T *trypos));
5188static pos_T *find_start_brace __ARGS((int));
5189static pos_T *find_match_paren __ARGS((int, int));
5190static int corr_ind_maxparen __ARGS((int ind_maxparen, pos_T *startpos));
5191static int find_last_paren __ARGS((char_u *l, int start, int end));
5192static int find_match __ARGS((int lookfor, linenr_T ourscope, int ind_maxparen, int ind_maxcomment));
Bram Moolenaared38b0a2011-05-25 15:16:18 +02005193static int cin_is_cpp_namespace __ARGS((char_u *));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005194
Bram Moolenaar39353fd2007-03-27 09:02:11 +00005195static int ind_hash_comment = 0; /* # starts a comment */
5196
Bram Moolenaar071d4272004-06-13 20:20:40 +00005197/*
5198 * Skip over white space and C comments within the line.
Bram Moolenaar39353fd2007-03-27 09:02:11 +00005199 * Also skip over Perl/shell comments if desired.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005200 */
5201 static char_u *
5202cin_skipcomment(s)
5203 char_u *s;
5204{
5205 while (*s)
5206 {
Bram Moolenaar39353fd2007-03-27 09:02:11 +00005207 char_u *prev_s = s;
5208
Bram Moolenaar071d4272004-06-13 20:20:40 +00005209 s = skipwhite(s);
Bram Moolenaar39353fd2007-03-27 09:02:11 +00005210
5211 /* Perl/shell # comment comment continues until eol. Require a space
5212 * before # to avoid recognizing $#array. */
5213 if (ind_hash_comment != 0 && s != prev_s && *s == '#')
5214 {
5215 s += STRLEN(s);
5216 break;
5217 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005218 if (*s != '/')
5219 break;
5220 ++s;
5221 if (*s == '/') /* slash-slash comment continues till eol */
5222 {
5223 s += STRLEN(s);
5224 break;
5225 }
5226 if (*s != '*')
5227 break;
5228 for (++s; *s; ++s) /* skip slash-star comment */
5229 if (s[0] == '*' && s[1] == '/')
5230 {
5231 s += 2;
5232 break;
5233 }
5234 }
5235 return s;
5236}
5237
5238/*
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005239 * Return TRUE if there is no code at *s. White space and comments are
Bram Moolenaar071d4272004-06-13 20:20:40 +00005240 * not considered code.
5241 */
5242 static int
5243cin_nocode(s)
5244 char_u *s;
5245{
5246 return *cin_skipcomment(s) == NUL;
5247}
5248
5249/*
5250 * Check previous lines for a "//" line comment, skipping over blank lines.
5251 */
5252 static pos_T *
5253find_line_comment() /* XXX */
5254{
5255 static pos_T pos;
5256 char_u *line;
5257 char_u *p;
5258
5259 pos = curwin->w_cursor;
5260 while (--pos.lnum > 0)
5261 {
5262 line = ml_get(pos.lnum);
5263 p = skipwhite(line);
5264 if (cin_islinecomment(p))
5265 {
5266 pos.col = (int)(p - line);
5267 return &pos;
5268 }
5269 if (*p != NUL)
5270 break;
5271 }
5272 return NULL;
5273}
5274
5275/*
5276 * Check if string matches "label:"; move to character after ':' if true.
5277 */
5278 static int
5279cin_islabel_skip(s)
5280 char_u **s;
5281{
5282 if (!vim_isIDc(**s)) /* need at least one ID character */
5283 return FALSE;
5284
5285 while (vim_isIDc(**s))
5286 (*s)++;
5287
5288 *s = cin_skipcomment(*s);
5289
5290 /* "::" is not a label, it's C++ */
5291 return (**s == ':' && *++*s != ':');
5292}
5293
5294/*
5295 * Recognize a label: "label:".
5296 * Note: curwin->w_cursor must be where we are looking for the label.
5297 */
5298 int
5299cin_islabel(ind_maxcomment) /* XXX */
5300 int ind_maxcomment;
5301{
5302 char_u *s;
5303
5304 s = cin_skipcomment(ml_get_curline());
5305
5306 /*
5307 * Exclude "default" from labels, since it should be indented
5308 * like a switch label. Same for C++ scope declarations.
5309 */
5310 if (cin_isdefault(s))
5311 return FALSE;
5312 if (cin_isscopedecl(s))
5313 return FALSE;
5314
5315 if (cin_islabel_skip(&s))
5316 {
5317 /*
5318 * Only accept a label if the previous line is terminated or is a case
5319 * label.
5320 */
5321 pos_T cursor_save;
5322 pos_T *trypos;
5323 char_u *line;
5324
5325 cursor_save = curwin->w_cursor;
5326 while (curwin->w_cursor.lnum > 1)
5327 {
5328 --curwin->w_cursor.lnum;
5329
5330 /*
5331 * If we're in a comment now, skip to the start of the comment.
5332 */
5333 curwin->w_cursor.col = 0;
5334 if ((trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
5335 curwin->w_cursor = *trypos;
5336
5337 line = ml_get_curline();
5338 if (cin_ispreproc(line)) /* ignore #defines, #if, etc. */
5339 continue;
5340 if (*(line = cin_skipcomment(line)) == NUL)
5341 continue;
5342
5343 curwin->w_cursor = cursor_save;
5344 if (cin_isterminated(line, TRUE, FALSE)
5345 || cin_isscopedecl(line)
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005346 || cin_iscase(line, TRUE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005347 || (cin_islabel_skip(&line) && cin_nocode(line)))
5348 return TRUE;
5349 return FALSE;
5350 }
5351 curwin->w_cursor = cursor_save;
5352 return TRUE; /* label at start of file??? */
5353 }
5354 return FALSE;
5355}
5356
5357/*
5358 * Recognize structure initialization and enumerations.
5359 * Q&D-Implementation:
5360 * check for "=" at end or "[typedef] enum" at beginning of line.
5361 */
5362 static int
5363cin_isinit(void)
5364{
5365 char_u *s;
5366
5367 s = cin_skipcomment(ml_get_curline());
5368
5369 if (STRNCMP(s, "typedef", 7) == 0 && !vim_isIDc(s[7]))
5370 s = cin_skipcomment(s + 7);
5371
Bram Moolenaara5285652011-12-14 20:05:21 +01005372 if (STRNCMP(s, "static", 6) == 0 && !vim_isIDc(s[6]))
5373 s = cin_skipcomment(s + 6);
5374
Bram Moolenaar071d4272004-06-13 20:20:40 +00005375 if (STRNCMP(s, "enum", 4) == 0 && !vim_isIDc(s[4]))
5376 return TRUE;
5377
5378 if (cin_ends_in(s, (char_u *)"=", (char_u *)"{"))
5379 return TRUE;
5380
5381 return FALSE;
5382}
5383
5384/*
5385 * Recognize a switch label: "case .*:" or "default:".
5386 */
5387 int
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005388cin_iscase(s, strict)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005389 char_u *s;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005390 int strict; /* Allow relaxed check of case statement for JS */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005391{
5392 s = cin_skipcomment(s);
5393 if (STRNCMP(s, "case", 4) == 0 && !vim_isIDc(s[4]))
5394 {
5395 for (s += 4; *s; ++s)
5396 {
5397 s = cin_skipcomment(s);
5398 if (*s == ':')
5399 {
5400 if (s[1] == ':') /* skip over "::" for C++ */
5401 ++s;
5402 else
5403 return TRUE;
5404 }
5405 if (*s == '\'' && s[1] && s[2] == '\'')
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005406 s += 2; /* skip over ':' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005407 else if (*s == '/' && (s[1] == '*' || s[1] == '/'))
5408 return FALSE; /* stop at comment */
5409 else if (*s == '"')
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005410 {
5411 /* JS etc. */
5412 if (strict)
5413 return FALSE; /* stop at string */
5414 else
5415 return TRUE;
5416 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005417 }
5418 return FALSE;
5419 }
5420
5421 if (cin_isdefault(s))
5422 return TRUE;
5423 return FALSE;
5424}
5425
5426/*
5427 * Recognize a "default" switch label.
5428 */
5429 static int
5430cin_isdefault(s)
5431 char_u *s;
5432{
5433 return (STRNCMP(s, "default", 7) == 0
5434 && *(s = cin_skipcomment(s + 7)) == ':'
5435 && s[1] != ':');
5436}
5437
5438/*
Bram Moolenaar1a509df2010-08-01 17:59:57 +02005439 * Recognize a "public/private/protected" scope declaration label.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005440 */
5441 int
5442cin_isscopedecl(s)
5443 char_u *s;
5444{
5445 int i;
5446
5447 s = cin_skipcomment(s);
5448 if (STRNCMP(s, "public", 6) == 0)
5449 i = 6;
5450 else if (STRNCMP(s, "protected", 9) == 0)
5451 i = 9;
5452 else if (STRNCMP(s, "private", 7) == 0)
5453 i = 7;
5454 else
5455 return FALSE;
5456 return (*(s = cin_skipcomment(s + i)) == ':' && s[1] != ':');
5457}
5458
Bram Moolenaared38b0a2011-05-25 15:16:18 +02005459/* Maximum number of lines to search back for a "namespace" line. */
5460#define FIND_NAMESPACE_LIM 20
5461
5462/*
5463 * Recognize a "namespace" scope declaration.
5464 */
5465 static int
5466cin_is_cpp_namespace(s)
5467 char_u *s;
5468{
5469 char_u *p;
5470 int has_name = FALSE;
5471
5472 s = cin_skipcomment(s);
5473 if (STRNCMP(s, "namespace", 9) == 0 && (s[9] == NUL || !vim_iswordc(s[9])))
5474 {
5475 p = cin_skipcomment(skipwhite(s + 9));
5476 while (*p != NUL)
5477 {
5478 if (vim_iswhite(*p))
5479 {
5480 has_name = TRUE; /* found end of a name */
5481 p = cin_skipcomment(skipwhite(p));
5482 }
5483 else if (*p == '{')
5484 {
5485 break;
5486 }
5487 else if (vim_iswordc(*p))
5488 {
5489 if (has_name)
5490 return FALSE; /* word character after skipping past name */
5491 ++p;
5492 }
5493 else
5494 {
5495 return FALSE;
5496 }
5497 }
5498 return TRUE;
5499 }
5500 return FALSE;
5501}
5502
Bram Moolenaar071d4272004-06-13 20:20:40 +00005503/*
5504 * Return a pointer to the first non-empty non-comment character after a ':'.
5505 * Return NULL if not found.
5506 * case 234: a = b;
5507 * ^
5508 */
5509 static char_u *
5510after_label(l)
5511 char_u *l;
5512{
5513 for ( ; *l; ++l)
5514 {
5515 if (*l == ':')
5516 {
5517 if (l[1] == ':') /* skip over "::" for C++ */
5518 ++l;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005519 else if (!cin_iscase(l + 1, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005520 break;
5521 }
5522 else if (*l == '\'' && l[1] && l[2] == '\'')
5523 l += 2; /* skip over 'x' */
5524 }
5525 if (*l == NUL)
5526 return NULL;
5527 l = cin_skipcomment(l + 1);
5528 if (*l == NUL)
5529 return NULL;
5530 return l;
5531}
5532
5533/*
5534 * Get indent of line "lnum", skipping a label.
5535 * Return 0 if there is nothing after the label.
5536 */
5537 static int
5538get_indent_nolabel(lnum) /* XXX */
5539 linenr_T lnum;
5540{
5541 char_u *l;
5542 pos_T fp;
5543 colnr_T col;
5544 char_u *p;
5545
5546 l = ml_get(lnum);
5547 p = after_label(l);
5548 if (p == NULL)
5549 return 0;
5550
5551 fp.col = (colnr_T)(p - l);
5552 fp.lnum = lnum;
5553 getvcol(curwin, &fp, &col, NULL, NULL);
5554 return (int)col;
5555}
5556
5557/*
5558 * Find indent for line "lnum", ignoring any case or jump label.
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005559 * Also return a pointer to the text (after the label) in "pp".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005560 * label: if (asdf && asdfasdf)
5561 * ^
5562 */
5563 static int
5564skip_label(lnum, pp, ind_maxcomment)
5565 linenr_T lnum;
5566 char_u **pp;
5567 int ind_maxcomment;
5568{
5569 char_u *l;
5570 int amount;
5571 pos_T cursor_save;
5572
5573 cursor_save = curwin->w_cursor;
5574 curwin->w_cursor.lnum = lnum;
5575 l = ml_get_curline();
5576 /* XXX */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005577 if (cin_iscase(l, FALSE) || cin_isscopedecl(l)
5578 || cin_islabel(ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005579 {
5580 amount = get_indent_nolabel(lnum);
5581 l = after_label(ml_get_curline());
5582 if (l == NULL) /* just in case */
5583 l = ml_get_curline();
5584 }
5585 else
5586 {
5587 amount = get_indent();
5588 l = ml_get_curline();
5589 }
5590 *pp = l;
5591
5592 curwin->w_cursor = cursor_save;
5593 return amount;
5594}
5595
5596/*
5597 * Return the indent of the first variable name after a type in a declaration.
5598 * int a, indent of "a"
5599 * static struct foo b, indent of "b"
5600 * enum bla c, indent of "c"
5601 * Returns zero when it doesn't look like a declaration.
5602 */
5603 static int
5604cin_first_id_amount()
5605{
5606 char_u *line, *p, *s;
5607 int len;
5608 pos_T fp;
5609 colnr_T col;
5610
5611 line = ml_get_curline();
5612 p = skipwhite(line);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005613 len = (int)(skiptowhite(p) - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005614 if (len == 6 && STRNCMP(p, "static", 6) == 0)
5615 {
5616 p = skipwhite(p + 6);
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00005617 len = (int)(skiptowhite(p) - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005618 }
5619 if (len == 6 && STRNCMP(p, "struct", 6) == 0)
5620 p = skipwhite(p + 6);
5621 else if (len == 4 && STRNCMP(p, "enum", 4) == 0)
5622 p = skipwhite(p + 4);
5623 else if ((len == 8 && STRNCMP(p, "unsigned", 8) == 0)
5624 || (len == 6 && STRNCMP(p, "signed", 6) == 0))
5625 {
5626 s = skipwhite(p + len);
5627 if ((STRNCMP(s, "int", 3) == 0 && vim_iswhite(s[3]))
5628 || (STRNCMP(s, "long", 4) == 0 && vim_iswhite(s[4]))
5629 || (STRNCMP(s, "short", 5) == 0 && vim_iswhite(s[5]))
5630 || (STRNCMP(s, "char", 4) == 0 && vim_iswhite(s[4])))
5631 p = s;
5632 }
5633 for (len = 0; vim_isIDc(p[len]); ++len)
5634 ;
5635 if (len == 0 || !vim_iswhite(p[len]) || cin_nocode(p))
5636 return 0;
5637
5638 p = skipwhite(p + len);
5639 fp.lnum = curwin->w_cursor.lnum;
5640 fp.col = (colnr_T)(p - line);
5641 getvcol(curwin, &fp, &col, NULL, NULL);
5642 return (int)col;
5643}
5644
5645/*
5646 * Return the indent of the first non-blank after an equal sign.
5647 * char *foo = "here";
5648 * Return zero if no (useful) equal sign found.
5649 * Return -1 if the line above "lnum" ends in a backslash.
5650 * foo = "asdf\
5651 * asdf\
5652 * here";
5653 */
5654 static int
5655cin_get_equal_amount(lnum)
5656 linenr_T lnum;
5657{
5658 char_u *line;
5659 char_u *s;
5660 colnr_T col;
5661 pos_T fp;
5662
5663 if (lnum > 1)
5664 {
5665 line = ml_get(lnum - 1);
5666 if (*line != NUL && line[STRLEN(line) - 1] == '\\')
5667 return -1;
5668 }
5669
5670 line = s = ml_get(lnum);
5671 while (*s != NUL && vim_strchr((char_u *)"=;{}\"'", *s) == NULL)
5672 {
5673 if (cin_iscomment(s)) /* ignore comments */
5674 s = cin_skipcomment(s);
5675 else
5676 ++s;
5677 }
5678 if (*s != '=')
5679 return 0;
5680
5681 s = skipwhite(s + 1);
5682 if (cin_nocode(s))
5683 return 0;
5684
5685 if (*s == '"') /* nice alignment for continued strings */
5686 ++s;
5687
5688 fp.lnum = lnum;
5689 fp.col = (colnr_T)(s - line);
5690 getvcol(curwin, &fp, &col, NULL, NULL);
5691 return (int)col;
5692}
5693
5694/*
5695 * Recognize a preprocessor statement: Any line that starts with '#'.
5696 */
5697 static int
5698cin_ispreproc(s)
5699 char_u *s;
5700{
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005701 if (*skipwhite(s) == '#')
Bram Moolenaar071d4272004-06-13 20:20:40 +00005702 return TRUE;
5703 return FALSE;
5704}
5705
5706/*
5707 * Return TRUE if line "*pp" at "*lnump" is a preprocessor statement or a
5708 * continuation line of a preprocessor statement. Decrease "*lnump" to the
5709 * start and return the line in "*pp".
5710 */
5711 static int
5712cin_ispreproc_cont(pp, lnump)
5713 char_u **pp;
5714 linenr_T *lnump;
5715{
5716 char_u *line = *pp;
5717 linenr_T lnum = *lnump;
5718 int retval = FALSE;
5719
Bram Moolenaard8e9bb22005-07-09 21:14:46 +00005720 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005721 {
5722 if (cin_ispreproc(line))
5723 {
5724 retval = TRUE;
5725 *lnump = lnum;
5726 break;
5727 }
5728 if (lnum == 1)
5729 break;
5730 line = ml_get(--lnum);
5731 if (*line == NUL || line[STRLEN(line) - 1] != '\\')
5732 break;
5733 }
5734
5735 if (lnum != *lnump)
5736 *pp = ml_get(*lnump);
5737 return retval;
5738}
5739
5740/*
5741 * Recognize the start of a C or C++ comment.
5742 */
5743 static int
5744cin_iscomment(p)
5745 char_u *p;
5746{
5747 return (p[0] == '/' && (p[1] == '*' || p[1] == '/'));
5748}
5749
5750/*
5751 * Recognize the start of a "//" comment.
5752 */
5753 static int
5754cin_islinecomment(p)
5755 char_u *p;
5756{
5757 return (p[0] == '/' && p[1] == '/');
5758}
5759
5760/*
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005761 * Recognize a line that starts with '{' or '}', or ends with ';', ',', '{' or
5762 * '}'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005763 * Don't consider "} else" a terminated line.
Bram Moolenaar496f9512011-05-19 16:35:09 +02005764 * If a line begins with an "else", only consider it terminated if no unmatched
5765 * opening braces follow (handle "else { foo();" correctly).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005766 * Return the character terminating the line (ending char's have precedence if
5767 * both apply in order to determine initializations).
5768 */
5769 static int
5770cin_isterminated(s, incl_open, incl_comma)
5771 char_u *s;
5772 int incl_open; /* include '{' at the end as terminator */
5773 int incl_comma; /* recognize a trailing comma */
5774{
Bram Moolenaar496f9512011-05-19 16:35:09 +02005775 char_u found_start = 0;
5776 unsigned n_open = 0;
5777 int is_else = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005778
5779 s = cin_skipcomment(s);
5780
5781 if (*s == '{' || (*s == '}' && !cin_iselse(s)))
5782 found_start = *s;
5783
Bram Moolenaar496f9512011-05-19 16:35:09 +02005784 if (!found_start)
5785 is_else = cin_iselse(s);
5786
Bram Moolenaar071d4272004-06-13 20:20:40 +00005787 while (*s)
5788 {
5789 /* skip over comments, "" strings and 'c'haracters */
5790 s = skip_string(cin_skipcomment(s));
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005791 if (*s == '}' && n_open > 0)
5792 --n_open;
Bram Moolenaar496f9512011-05-19 16:35:09 +02005793 if ((!is_else || n_open == 0)
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005794 && (*s == ';' || *s == '}' || (incl_comma && *s == ','))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005795 && cin_nocode(s + 1))
5796 return *s;
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005797 else if (*s == '{')
5798 {
5799 if (incl_open && cin_nocode(s + 1))
5800 return *s;
5801 else
5802 ++n_open;
5803 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005804
5805 if (*s)
5806 s++;
5807 }
5808 return found_start;
5809}
5810
5811/*
5812 * Recognize the basic picture of a function declaration -- it needs to
5813 * have an open paren somewhere and a close paren at the end of the line and
5814 * no semicolons anywhere.
5815 * When a line ends in a comma we continue looking in the next line.
5816 * "sp" points to a string with the line. When looking at other lines it must
5817 * be restored to the line. When it's NULL fetch lines here.
5818 * "lnum" is where we start looking.
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005819 * "min_lnum" is the line before which we will not be looking.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005820 */
5821 static int
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005822cin_isfuncdecl(sp, first_lnum, min_lnum, ind_maxparen, ind_maxcomment)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005823 char_u **sp;
5824 linenr_T first_lnum;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005825 linenr_T min_lnum;
5826 int ind_maxparen;
5827 int ind_maxcomment;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005828{
5829 char_u *s;
5830 linenr_T lnum = first_lnum;
5831 int retval = FALSE;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005832 pos_T *trypos;
5833 int just_started = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005834
5835 if (sp == NULL)
5836 s = ml_get(lnum);
5837 else
5838 s = *sp;
5839
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005840 if (find_last_paren(s, '(', ')')
5841 && (trypos = find_match_paren(ind_maxparen, ind_maxcomment)) != NULL)
5842 {
5843 lnum = trypos->lnum;
5844 if (lnum < min_lnum)
5845 return FALSE;
5846
5847 s = ml_get(lnum);
5848 }
5849
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005850 /* Ignore line starting with #. */
5851 if (cin_ispreproc(s))
5852 return FALSE;
5853
Bram Moolenaar071d4272004-06-13 20:20:40 +00005854 while (*s && *s != '(' && *s != ';' && *s != '\'' && *s != '"')
5855 {
5856 if (cin_iscomment(s)) /* ignore comments */
5857 s = cin_skipcomment(s);
5858 else
5859 ++s;
5860 }
5861 if (*s != '(')
5862 return FALSE; /* ';', ' or " before any () or no '(' */
5863
5864 while (*s && *s != ';' && *s != '\'' && *s != '"')
5865 {
5866 if (*s == ')' && cin_nocode(s + 1))
5867 {
5868 /* ')' at the end: may have found a match
5869 * Check for he previous line not to end in a backslash:
5870 * #if defined(x) && \
5871 * defined(y)
5872 */
5873 lnum = first_lnum - 1;
5874 s = ml_get(lnum);
5875 if (*s == NUL || s[STRLEN(s) - 1] != '\\')
5876 retval = TRUE;
5877 goto done;
5878 }
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005879 if ((*s == ',' && cin_nocode(s + 1)) || s[1] == NUL || cin_nocode(s))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005880 {
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005881 int comma = (*s == ',');
5882
5883 /* ',' at the end: continue looking in the next line.
5884 * At the end: check for ',' in the next line, for this style:
5885 * func(arg1
5886 * , arg2) */
5887 for (;;)
5888 {
5889 if (lnum >= curbuf->b_ml.ml_line_count)
5890 break;
5891 s = ml_get(++lnum);
5892 if (!cin_ispreproc(s))
5893 break;
5894 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005895 if (lnum >= curbuf->b_ml.ml_line_count)
5896 break;
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005897 /* Require a comma at end of the line or a comma or ')' at the
5898 * start of next line. */
5899 s = skipwhite(s);
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005900 if (!just_started && (!comma && *s != ',' && *s != ')'))
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005901 break;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005902 just_started = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005903 }
5904 else if (cin_iscomment(s)) /* ignore comments */
5905 s = cin_skipcomment(s);
5906 else
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005907 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005908 ++s;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005909 just_started = FALSE;
5910 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005911 }
5912
5913done:
5914 if (lnum != first_lnum && sp != NULL)
5915 *sp = ml_get(first_lnum);
5916
5917 return retval;
5918}
5919
5920 static int
5921cin_isif(p)
5922 char_u *p;
5923{
5924 return (STRNCMP(p, "if", 2) == 0 && !vim_isIDc(p[2]));
5925}
5926
5927 static int
5928cin_iselse(p)
5929 char_u *p;
5930{
5931 if (*p == '}') /* accept "} else" */
5932 p = cin_skipcomment(p + 1);
5933 return (STRNCMP(p, "else", 4) == 0 && !vim_isIDc(p[4]));
5934}
5935
5936 static int
5937cin_isdo(p)
5938 char_u *p;
5939{
5940 return (STRNCMP(p, "do", 2) == 0 && !vim_isIDc(p[2]));
5941}
5942
5943/*
5944 * Check if this is a "while" that should have a matching "do".
5945 * We only accept a "while (condition) ;", with only white space between the
5946 * ')' and ';'. The condition may be spread over several lines.
5947 */
5948 static int
5949cin_iswhileofdo(p, lnum, ind_maxparen) /* XXX */
5950 char_u *p;
5951 linenr_T lnum;
5952 int ind_maxparen;
5953{
5954 pos_T cursor_save;
5955 pos_T *trypos;
5956 int retval = FALSE;
5957
5958 p = cin_skipcomment(p);
5959 if (*p == '}') /* accept "} while (cond);" */
5960 p = cin_skipcomment(p + 1);
5961 if (STRNCMP(p, "while", 5) == 0 && !vim_isIDc(p[5]))
5962 {
5963 cursor_save = curwin->w_cursor;
5964 curwin->w_cursor.lnum = lnum;
5965 curwin->w_cursor.col = 0;
5966 p = ml_get_curline();
5967 while (*p && *p != 'w') /* skip any '}', until the 'w' of the "while" */
5968 {
5969 ++p;
5970 ++curwin->w_cursor.col;
5971 }
5972 if ((trypos = findmatchlimit(NULL, 0, 0, ind_maxparen)) != NULL
5973 && *cin_skipcomment(ml_get_pos(trypos) + 1) == ';')
5974 retval = TRUE;
5975 curwin->w_cursor = cursor_save;
5976 }
5977 return retval;
5978}
5979
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005980/*
Bram Moolenaarb345d492012-04-09 20:42:26 +02005981 * Check whether in "p" there is an "if", "for" or "while" before "*poffset".
Bram Moolenaar3675fa02012-04-05 17:17:42 +02005982 * Return 0 if there is none.
5983 * Otherwise return !0 and update "*poffset" to point to the place where the
5984 * string was found.
5985 */
5986 static int
Bram Moolenaarb345d492012-04-09 20:42:26 +02005987cin_is_if_for_while_before_offset(line, poffset)
Bram Moolenaar3675fa02012-04-05 17:17:42 +02005988 char_u *line;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02005989 int *poffset;
5990{
Bram Moolenaarb345d492012-04-09 20:42:26 +02005991 int offset = *poffset;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02005992
5993 if (offset-- < 2)
5994 return 0;
5995 while (offset > 2 && vim_iswhite(line[offset]))
5996 --offset;
5997
5998 offset -= 1;
5999 if (!STRNCMP(line + offset, "if", 2))
6000 goto probablyFound;
6001
6002 if (offset >= 1)
6003 {
6004 offset -= 1;
6005 if (!STRNCMP(line + offset, "for", 3))
6006 goto probablyFound;
6007
6008 if (offset >= 2)
6009 {
6010 offset -= 2;
6011 if (!STRNCMP(line + offset, "while", 5))
6012 goto probablyFound;
6013 }
6014 }
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006015 return 0;
Bram Moolenaarb345d492012-04-09 20:42:26 +02006016
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006017probablyFound:
6018 if (!offset || !vim_isIDc(line[offset - 1]))
6019 {
6020 *poffset = offset;
6021 return 1;
6022 }
6023 return 0;
6024}
6025
6026/*
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006027 * Return TRUE if we are at the end of a do-while.
6028 * do
6029 * nothing;
6030 * while (foo
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00006031 * && bar); <-- here
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006032 * Adjust the cursor to the line with "while".
6033 */
6034 static int
6035cin_iswhileofdo_end(terminated, ind_maxparen, ind_maxcomment)
6036 int terminated;
6037 int ind_maxparen;
6038 int ind_maxcomment;
6039{
6040 char_u *line;
6041 char_u *p;
6042 char_u *s;
6043 pos_T *trypos;
6044 int i;
6045
6046 if (terminated != ';') /* there must be a ';' at the end */
6047 return FALSE;
6048
6049 p = line = ml_get_curline();
6050 while (*p != NUL)
6051 {
6052 p = cin_skipcomment(p);
6053 if (*p == ')')
6054 {
6055 s = skipwhite(p + 1);
6056 if (*s == ';' && cin_nocode(s + 1))
6057 {
6058 /* Found ");" at end of the line, now check there is "while"
6059 * before the matching '('. XXX */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006060 i = (int)(p - line);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006061 curwin->w_cursor.col = i;
6062 trypos = find_match_paren(ind_maxparen, ind_maxcomment);
6063 if (trypos != NULL)
6064 {
6065 s = cin_skipcomment(ml_get(trypos->lnum));
6066 if (*s == '}') /* accept "} while (cond);" */
6067 s = cin_skipcomment(s + 1);
6068 if (STRNCMP(s, "while", 5) == 0 && !vim_isIDc(s[5]))
6069 {
6070 curwin->w_cursor.lnum = trypos->lnum;
6071 return TRUE;
6072 }
6073 }
6074
6075 /* Searching may have made "line" invalid, get it again. */
6076 line = ml_get_curline();
6077 p = line + i;
6078 }
6079 }
6080 if (*p != NUL)
6081 ++p;
6082 }
6083 return FALSE;
6084}
6085
Bram Moolenaar071d4272004-06-13 20:20:40 +00006086 static int
6087cin_isbreak(p)
6088 char_u *p;
6089{
6090 return (STRNCMP(p, "break", 5) == 0 && !vim_isIDc(p[5]));
6091}
6092
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006093/*
6094 * Find the position of a C++ base-class declaration or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006095 * constructor-initialization. eg:
6096 *
6097 * class MyClass :
6098 * baseClass <-- here
6099 * class MyClass : public baseClass,
6100 * anotherBaseClass <-- here (should probably lineup ??)
6101 * MyClass::MyClass(...) :
6102 * baseClass(...) <-- here (constructor-initialization)
Bram Moolenaar18144c82006-04-12 21:52:12 +00006103 *
6104 * This is a lot of guessing. Watch out for "cond ? func() : foo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00006105 */
6106 static int
Bram Moolenaare7c56862007-08-04 10:14:52 +00006107cin_is_cpp_baseclass(col)
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006108 colnr_T *col; /* return: column to align with */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006109{
6110 char_u *s;
6111 int class_or_struct, lookfor_ctor_init, cpp_base_class;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006112 linenr_T lnum = curwin->w_cursor.lnum;
Bram Moolenaare7c56862007-08-04 10:14:52 +00006113 char_u *line = ml_get_curline();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006114
6115 *col = 0;
6116
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006117 s = skipwhite(line);
6118 if (*s == '#') /* skip #define FOO x ? (x) : x */
6119 return FALSE;
6120 s = cin_skipcomment(s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006121 if (*s == NUL)
6122 return FALSE;
6123
6124 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
6125
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006126 /* Search for a line starting with '#', empty, ending in ';' or containing
6127 * '{' or '}' and start below it. This handles the following situations:
6128 * a = cond ?
6129 * func() :
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00006130 * asdf;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006131 * func::foo()
6132 * : something
6133 * {}
6134 * Foo::Foo (int one, int two)
6135 * : something(4),
6136 * somethingelse(3)
6137 * {}
6138 */
6139 while (lnum > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006140 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00006141 line = ml_get(lnum - 1);
6142 s = skipwhite(line);
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006143 if (*s == '#' || *s == NUL)
6144 break;
6145 while (*s != NUL)
6146 {
6147 s = cin_skipcomment(s);
6148 if (*s == '{' || *s == '}'
6149 || (*s == ';' && cin_nocode(s + 1)))
6150 break;
6151 if (*s != NUL)
6152 ++s;
6153 }
6154 if (*s != NUL)
6155 break;
6156 --lnum;
6157 }
6158
Bram Moolenaare7c56862007-08-04 10:14:52 +00006159 line = ml_get(lnum);
6160 s = cin_skipcomment(line);
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006161 for (;;)
6162 {
6163 if (*s == NUL)
6164 {
6165 if (lnum == curwin->w_cursor.lnum)
6166 break;
6167 /* Continue in the cursor line. */
Bram Moolenaare7c56862007-08-04 10:14:52 +00006168 line = ml_get(++lnum);
6169 s = cin_skipcomment(line);
6170 if (*s == NUL)
6171 continue;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006172 }
6173
Bram Moolenaaraede6ce2011-05-10 11:56:30 +02006174 if (s[0] == '"')
6175 s = skip_string(s) + 1;
6176 else if (s[0] == ':')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006177 {
6178 if (s[1] == ':')
6179 {
6180 /* skip double colon. It can't be a constructor
6181 * initialization any more */
6182 lookfor_ctor_init = FALSE;
6183 s = cin_skipcomment(s + 2);
6184 }
6185 else if (lookfor_ctor_init || class_or_struct)
6186 {
6187 /* we have something found, that looks like the start of
Bram Moolenaare21877a2008-02-13 09:58:14 +00006188 * cpp-base-class-declaration or constructor-initialization */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006189 cpp_base_class = TRUE;
6190 lookfor_ctor_init = class_or_struct = FALSE;
6191 *col = 0;
6192 s = cin_skipcomment(s + 1);
6193 }
6194 else
6195 s = cin_skipcomment(s + 1);
6196 }
6197 else if ((STRNCMP(s, "class", 5) == 0 && !vim_isIDc(s[5]))
6198 || (STRNCMP(s, "struct", 6) == 0 && !vim_isIDc(s[6])))
6199 {
6200 class_or_struct = TRUE;
6201 lookfor_ctor_init = FALSE;
6202
6203 if (*s == 'c')
6204 s = cin_skipcomment(s + 5);
6205 else
6206 s = cin_skipcomment(s + 6);
6207 }
6208 else
6209 {
6210 if (s[0] == '{' || s[0] == '}' || s[0] == ';')
6211 {
6212 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
6213 }
6214 else if (s[0] == ')')
6215 {
6216 /* Constructor-initialization is assumed if we come across
6217 * something like "):" */
6218 class_or_struct = FALSE;
6219 lookfor_ctor_init = TRUE;
6220 }
Bram Moolenaar18144c82006-04-12 21:52:12 +00006221 else if (s[0] == '?')
6222 {
6223 /* Avoid seeing '() :' after '?' as constructor init. */
6224 return FALSE;
6225 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006226 else if (!vim_isIDc(s[0]))
6227 {
6228 /* if it is not an identifier, we are wrong */
6229 class_or_struct = FALSE;
6230 lookfor_ctor_init = FALSE;
6231 }
6232 else if (*col == 0)
6233 {
6234 /* it can't be a constructor-initialization any more */
6235 lookfor_ctor_init = FALSE;
6236
6237 /* the first statement starts here: lineup with this one... */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006238 if (cpp_base_class)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006239 *col = (colnr_T)(s - line);
6240 }
6241
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006242 /* When the line ends in a comma don't align with it. */
6243 if (lnum == curwin->w_cursor.lnum && *s == ',' && cin_nocode(s + 1))
6244 *col = 0;
6245
Bram Moolenaar071d4272004-06-13 20:20:40 +00006246 s = cin_skipcomment(s + 1);
6247 }
6248 }
6249
6250 return cpp_base_class;
6251}
6252
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006253 static int
6254get_baseclass_amount(col, ind_maxparen, ind_maxcomment, ind_cpp_baseclass)
6255 int col;
6256 int ind_maxparen;
6257 int ind_maxcomment;
6258 int ind_cpp_baseclass;
6259{
6260 int amount;
6261 colnr_T vcol;
6262 pos_T *trypos;
6263
6264 if (col == 0)
6265 {
6266 amount = get_indent();
6267 if (find_last_paren(ml_get_curline(), '(', ')')
6268 && (trypos = find_match_paren(ind_maxparen,
6269 ind_maxcomment)) != NULL)
6270 amount = get_indent_lnum(trypos->lnum); /* XXX */
6271 if (!cin_ends_in(ml_get_curline(), (char_u *)",", NULL))
6272 amount += ind_cpp_baseclass;
6273 }
6274 else
6275 {
6276 curwin->w_cursor.col = col;
6277 getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
6278 amount = (int)vcol;
6279 }
6280 if (amount < ind_cpp_baseclass)
6281 amount = ind_cpp_baseclass;
6282 return amount;
6283}
6284
Bram Moolenaar071d4272004-06-13 20:20:40 +00006285/*
6286 * Return TRUE if string "s" ends with the string "find", possibly followed by
6287 * white space and comments. Skip strings and comments.
6288 * Ignore "ignore" after "find" if it's not NULL.
6289 */
6290 static int
6291cin_ends_in(s, find, ignore)
6292 char_u *s;
6293 char_u *find;
6294 char_u *ignore;
6295{
6296 char_u *p = s;
6297 char_u *r;
6298 int len = (int)STRLEN(find);
6299
6300 while (*p != NUL)
6301 {
6302 p = cin_skipcomment(p);
6303 if (STRNCMP(p, find, len) == 0)
6304 {
6305 r = skipwhite(p + len);
6306 if (ignore != NULL && STRNCMP(r, ignore, STRLEN(ignore)) == 0)
6307 r = skipwhite(r + STRLEN(ignore));
6308 if (cin_nocode(r))
6309 return TRUE;
6310 }
6311 if (*p != NUL)
6312 ++p;
6313 }
6314 return FALSE;
6315}
6316
6317/*
6318 * Skip strings, chars and comments until at or past "trypos".
6319 * Return the column found.
6320 */
6321 static int
6322cin_skip2pos(trypos)
6323 pos_T *trypos;
6324{
6325 char_u *line;
6326 char_u *p;
6327
6328 p = line = ml_get(trypos->lnum);
6329 while (*p && (colnr_T)(p - line) < trypos->col)
6330 {
6331 if (cin_iscomment(p))
6332 p = cin_skipcomment(p);
6333 else
6334 {
6335 p = skip_string(p);
6336 ++p;
6337 }
6338 }
6339 return (int)(p - line);
6340}
6341
6342/*
6343 * Find the '{' at the start of the block we are in.
6344 * Return NULL if no match found.
6345 * Ignore a '{' that is in a comment, makes indenting the next three lines
6346 * work. */
6347/* foo() */
6348/* { */
6349/* } */
6350
6351 static pos_T *
6352find_start_brace(ind_maxcomment) /* XXX */
6353 int ind_maxcomment;
6354{
6355 pos_T cursor_save;
6356 pos_T *trypos;
6357 pos_T *pos;
6358 static pos_T pos_copy;
6359
6360 cursor_save = curwin->w_cursor;
6361 while ((trypos = findmatchlimit(NULL, '{', FM_BLOCKSTOP, 0)) != NULL)
6362 {
6363 pos_copy = *trypos; /* copy pos_T, next findmatch will change it */
6364 trypos = &pos_copy;
6365 curwin->w_cursor = *trypos;
6366 pos = NULL;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006367 /* ignore the { if it's in a // or / * * / comment */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006368 if ((colnr_T)cin_skip2pos(trypos) == trypos->col
6369 && (pos = find_start_comment(ind_maxcomment)) == NULL) /* XXX */
6370 break;
6371 if (pos != NULL)
6372 curwin->w_cursor.lnum = pos->lnum;
6373 }
6374 curwin->w_cursor = cursor_save;
6375 return trypos;
6376}
6377
6378/*
6379 * Find the matching '(', failing if it is in a comment.
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006380 * Return NULL if no match found.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006381 */
6382 static pos_T *
6383find_match_paren(ind_maxparen, ind_maxcomment) /* XXX */
6384 int ind_maxparen;
6385 int ind_maxcomment;
6386{
6387 pos_T cursor_save;
6388 pos_T *trypos;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006389 static pos_T pos_copy;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006390
6391 cursor_save = curwin->w_cursor;
6392 if ((trypos = findmatchlimit(NULL, '(', 0, ind_maxparen)) != NULL)
6393 {
6394 /* check if the ( is in a // comment */
6395 if ((colnr_T)cin_skip2pos(trypos) > trypos->col)
6396 trypos = NULL;
6397 else
6398 {
6399 pos_copy = *trypos; /* copy trypos, findmatch will change it */
6400 trypos = &pos_copy;
6401 curwin->w_cursor = *trypos;
6402 if (find_start_comment(ind_maxcomment) != NULL) /* XXX */
6403 trypos = NULL;
6404 }
6405 }
6406 curwin->w_cursor = cursor_save;
6407 return trypos;
6408}
6409
6410/*
6411 * Return ind_maxparen corrected for the difference in line number between the
6412 * cursor position and "startpos". This makes sure that searching for a
6413 * matching paren above the cursor line doesn't find a match because of
6414 * looking a few lines further.
6415 */
6416 static int
6417corr_ind_maxparen(ind_maxparen, startpos)
6418 int ind_maxparen;
6419 pos_T *startpos;
6420{
6421 long n = (long)startpos->lnum - (long)curwin->w_cursor.lnum;
6422
6423 if (n > 0 && n < ind_maxparen / 2)
6424 return ind_maxparen - (int)n;
6425 return ind_maxparen;
6426}
6427
6428/*
6429 * Set w_cursor.col to the column number of the last unmatched ')' or '{' in
Bram Moolenaar6d8f9c62011-11-30 13:03:28 +01006430 * line "l". "l" must point to the start of the line.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006431 */
6432 static int
6433find_last_paren(l, start, end)
6434 char_u *l;
6435 int start, end;
6436{
6437 int i;
6438 int retval = FALSE;
6439 int open_count = 0;
6440
6441 curwin->w_cursor.col = 0; /* default is start of line */
6442
Bram Moolenaar6d8f9c62011-11-30 13:03:28 +01006443 for (i = 0; l[i] != NUL; i++)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006444 {
6445 i = (int)(cin_skipcomment(l + i) - l); /* ignore parens in comments */
6446 i = (int)(skip_string(l + i) - l); /* ignore parens in quotes */
6447 if (l[i] == start)
6448 ++open_count;
6449 else if (l[i] == end)
6450 {
6451 if (open_count > 0)
6452 --open_count;
6453 else
6454 {
6455 curwin->w_cursor.col = i;
6456 retval = TRUE;
6457 }
6458 }
6459 }
6460 return retval;
6461}
6462
6463 int
6464get_c_indent()
6465{
Bram Moolenaar14f24742012-08-08 18:01:05 +02006466 int sw = (int)get_sw_value();
6467
Bram Moolenaar071d4272004-06-13 20:20:40 +00006468 /*
6469 * spaces from a block's opening brace the prevailing indent for that
6470 * block should be
6471 */
Bram Moolenaar14f24742012-08-08 18:01:05 +02006472
6473 int ind_level = sw;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006474
6475 /*
6476 * spaces from the edge of the line an open brace that's at the end of a
6477 * line is imagined to be.
6478 */
6479 int ind_open_imag = 0;
6480
6481 /*
Bram Moolenaar1a509df2010-08-01 17:59:57 +02006482 * spaces from the prevailing indent for a line that is not preceded by
Bram Moolenaar071d4272004-06-13 20:20:40 +00006483 * an opening brace.
6484 */
6485 int ind_no_brace = 0;
6486
6487 /*
6488 * column where the first { of a function should be located }
6489 */
6490 int ind_first_open = 0;
6491
6492 /*
6493 * spaces from the prevailing indent a leftmost open brace should be
6494 * located
6495 */
6496 int ind_open_extra = 0;
6497
6498 /*
6499 * spaces from the matching open brace (real location for one at the left
6500 * edge; imaginary location from one that ends a line) the matching close
6501 * brace should be located
6502 */
6503 int ind_close_extra = 0;
6504
6505 /*
6506 * spaces from the edge of the line an open brace sitting in the leftmost
6507 * column is imagined to be
6508 */
6509 int ind_open_left_imag = 0;
6510
6511 /*
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006512 * Spaces jump labels should be shifted to the left if N is non-negative,
6513 * otherwise the jump label will be put to column 1.
6514 */
6515 int ind_jump_label = -1;
6516
6517 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006518 * spaces from the switch() indent a "case xx" label should be located
6519 */
Bram Moolenaar14f24742012-08-08 18:01:05 +02006520 int ind_case = sw;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006521
6522 /*
6523 * spaces from the "case xx:" code after a switch() should be located
6524 */
Bram Moolenaar14f24742012-08-08 18:01:05 +02006525 int ind_case_code = sw;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006526
6527 /*
6528 * lineup break at end of case in switch() with case label
6529 */
6530 int ind_case_break = 0;
6531
6532 /*
6533 * spaces from the class declaration indent a scope declaration label
6534 * should be located
6535 */
Bram Moolenaar14f24742012-08-08 18:01:05 +02006536 int ind_scopedecl = sw;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006537
6538 /*
6539 * spaces from the scope declaration label code should be located
6540 */
Bram Moolenaar14f24742012-08-08 18:01:05 +02006541 int ind_scopedecl_code = sw;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006542
6543 /*
6544 * amount K&R-style parameters should be indented
6545 */
Bram Moolenaar14f24742012-08-08 18:01:05 +02006546 int ind_param = sw;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006547
6548 /*
6549 * amount a function type spec should be indented
6550 */
Bram Moolenaar14f24742012-08-08 18:01:05 +02006551 int ind_func_type = sw;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006552
6553 /*
6554 * amount a cpp base class declaration or constructor initialization
6555 * should be indented
6556 */
Bram Moolenaar14f24742012-08-08 18:01:05 +02006557 int ind_cpp_baseclass = sw;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006558
6559 /*
6560 * additional spaces beyond the prevailing indent a continuation line
6561 * should be located
6562 */
Bram Moolenaar14f24742012-08-08 18:01:05 +02006563 int ind_continuation = sw;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006564
6565 /*
6566 * spaces from the indent of the line with an unclosed parentheses
6567 */
Bram Moolenaar14f24742012-08-08 18:01:05 +02006568 int ind_unclosed = sw * 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006569
6570 /*
6571 * spaces from the indent of the line with an unclosed parentheses, which
6572 * itself is also unclosed
6573 */
Bram Moolenaar14f24742012-08-08 18:01:05 +02006574 int ind_unclosed2 = sw;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006575
6576 /*
6577 * suppress ignoring spaces from the indent of a line starting with an
6578 * unclosed parentheses.
6579 */
6580 int ind_unclosed_noignore = 0;
6581
6582 /*
6583 * If the opening paren is the last nonwhite character on the line, and
6584 * ind_unclosed_wrapped is nonzero, use this indent relative to the outer
6585 * context (for very long lines).
6586 */
6587 int ind_unclosed_wrapped = 0;
6588
6589 /*
6590 * suppress ignoring white space when lining up with the character after
6591 * an unclosed parentheses.
6592 */
6593 int ind_unclosed_whiteok = 0;
6594
6595 /*
6596 * indent a closing parentheses under the line start of the matching
6597 * opening parentheses.
6598 */
6599 int ind_matching_paren = 0;
6600
6601 /*
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006602 * indent a closing parentheses under the previous line.
6603 */
6604 int ind_paren_prev = 0;
6605
6606 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006607 * Extra indent for comments.
6608 */
6609 int ind_comment = 0;
6610
6611 /*
6612 * spaces from the comment opener when there is nothing after it.
6613 */
6614 int ind_in_comment = 3;
6615
6616 /*
6617 * boolean: if non-zero, use ind_in_comment even if there is something
6618 * after the comment opener.
6619 */
6620 int ind_in_comment2 = 0;
6621
6622 /*
6623 * max lines to search for an open paren
6624 */
6625 int ind_maxparen = 20;
6626
6627 /*
6628 * max lines to search for an open comment
6629 */
6630 int ind_maxcomment = 70;
6631
6632 /*
6633 * handle braces for java code
6634 */
6635 int ind_java = 0;
6636
6637 /*
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006638 * not to confuse JS object properties with labels
6639 */
6640 int ind_js = 0;
6641
6642 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006643 * handle blocked cases correctly
6644 */
6645 int ind_keep_case_label = 0;
6646
Bram Moolenaared38b0a2011-05-25 15:16:18 +02006647 /*
6648 * handle C++ namespace
6649 */
6650 int ind_cpp_namespace = 0;
6651
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006652 /*
6653 * handle continuation lines containing conditions of if(), for() and
6654 * while()
6655 */
6656 int ind_if_for_while = 0;
6657
Bram Moolenaar071d4272004-06-13 20:20:40 +00006658 pos_T cur_curpos;
6659 int amount;
6660 int scope_amount;
Bram Moolenaarb21e5842006-04-16 18:30:08 +00006661 int cur_amount = MAXCOL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006662 colnr_T col;
6663 char_u *theline;
6664 char_u *linecopy;
6665 pos_T *trypos;
6666 pos_T *tryposBrace = NULL;
6667 pos_T our_paren_pos;
6668 char_u *start;
6669 int start_brace;
Bram Moolenaare21877a2008-02-13 09:58:14 +00006670#define BRACE_IN_COL0 1 /* '{' is in column 0 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006671#define BRACE_AT_START 2 /* '{' is at start of line */
6672#define BRACE_AT_END 3 /* '{' is at end of line */
6673 linenr_T ourscope;
6674 char_u *l;
6675 char_u *look;
6676 char_u terminated;
6677 int lookfor;
6678#define LOOKFOR_INITIAL 0
6679#define LOOKFOR_IF 1
6680#define LOOKFOR_DO 2
6681#define LOOKFOR_CASE 3
6682#define LOOKFOR_ANY 4
6683#define LOOKFOR_TERM 5
6684#define LOOKFOR_UNTERM 6
6685#define LOOKFOR_SCOPEDECL 7
6686#define LOOKFOR_NOBREAK 8
6687#define LOOKFOR_CPP_BASECLASS 9
6688#define LOOKFOR_ENUM_OR_INIT 10
6689
6690 int whilelevel;
6691 linenr_T lnum;
6692 char_u *options;
Bram Moolenaar48d27922012-06-13 13:40:48 +02006693 char_u *digits;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006694 int fraction = 0; /* init for GCC */
6695 int divider;
6696 int n;
6697 int iscase;
6698 int lookfor_break;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02006699 int lookfor_cpp_namespace = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006700 int cont_amount = 0; /* amount for continuation line */
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006701 int original_line_islabel;
Bram Moolenaare79d1532011-10-04 18:03:47 +02006702 int added_to_amount = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006703
6704 for (options = curbuf->b_p_cino; *options; )
6705 {
6706 l = options++;
6707 if (*options == '-')
6708 ++options;
Bram Moolenaar48d27922012-06-13 13:40:48 +02006709 digits = options; /* remember where the digits start */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006710 n = getdigits(&options);
6711 divider = 0;
6712 if (*options == '.') /* ".5s" means a fraction */
6713 {
6714 fraction = atol((char *)++options);
6715 while (VIM_ISDIGIT(*options))
6716 {
6717 ++options;
6718 if (divider)
6719 divider *= 10;
6720 else
6721 divider = 10;
6722 }
6723 }
6724 if (*options == 's') /* "2s" means two times 'shiftwidth' */
6725 {
Bram Moolenaar48d27922012-06-13 13:40:48 +02006726 if (options == digits)
Bram Moolenaar14f24742012-08-08 18:01:05 +02006727 n = sw; /* just "s" is one 'shiftwidth' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006728 else
6729 {
Bram Moolenaar14f24742012-08-08 18:01:05 +02006730 n *= sw;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006731 if (divider)
Bram Moolenaar14f24742012-08-08 18:01:05 +02006732 n += (sw * fraction + divider / 2) / divider;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006733 }
6734 ++options;
6735 }
6736 if (l[1] == '-')
6737 n = -n;
6738 /* When adding an entry here, also update the default 'cinoptions' in
Bram Moolenaar39353fd2007-03-27 09:02:11 +00006739 * doc/indent.txt, and add explanation for it! */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006740 switch (*l)
6741 {
6742 case '>': ind_level = n; break;
6743 case 'e': ind_open_imag = n; break;
6744 case 'n': ind_no_brace = n; break;
6745 case 'f': ind_first_open = n; break;
6746 case '{': ind_open_extra = n; break;
6747 case '}': ind_close_extra = n; break;
6748 case '^': ind_open_left_imag = n; break;
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006749 case 'L': ind_jump_label = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006750 case ':': ind_case = n; break;
6751 case '=': ind_case_code = n; break;
6752 case 'b': ind_case_break = n; break;
6753 case 'p': ind_param = n; break;
6754 case 't': ind_func_type = n; break;
6755 case '/': ind_comment = n; break;
6756 case 'c': ind_in_comment = n; break;
6757 case 'C': ind_in_comment2 = n; break;
6758 case 'i': ind_cpp_baseclass = n; break;
6759 case '+': ind_continuation = n; break;
6760 case '(': ind_unclosed = n; break;
6761 case 'u': ind_unclosed2 = n; break;
6762 case 'U': ind_unclosed_noignore = n; break;
6763 case 'W': ind_unclosed_wrapped = n; break;
6764 case 'w': ind_unclosed_whiteok = n; break;
6765 case 'm': ind_matching_paren = n; break;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006766 case 'M': ind_paren_prev = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006767 case ')': ind_maxparen = n; break;
6768 case '*': ind_maxcomment = n; break;
6769 case 'g': ind_scopedecl = n; break;
6770 case 'h': ind_scopedecl_code = n; break;
6771 case 'j': ind_java = n; break;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006772 case 'J': ind_js = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006773 case 'l': ind_keep_case_label = n; break;
Bram Moolenaar39353fd2007-03-27 09:02:11 +00006774 case '#': ind_hash_comment = n; break;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02006775 case 'N': ind_cpp_namespace = n; break;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006776 case 'k': ind_if_for_while = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006777 }
Bram Moolenaardfdf3c42010-03-23 18:22:46 +01006778 if (*options == ',')
6779 ++options;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006780 }
6781
6782 /* remember where the cursor was when we started */
6783 cur_curpos = curwin->w_cursor;
6784
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006785 /* if we are at line 1 0 is fine, right? */
6786 if (cur_curpos.lnum == 1)
6787 return 0;
6788
Bram Moolenaar071d4272004-06-13 20:20:40 +00006789 /* Get a copy of the current contents of the line.
6790 * This is required, because only the most recent line obtained with
6791 * ml_get is valid! */
6792 linecopy = vim_strsave(ml_get(cur_curpos.lnum));
6793 if (linecopy == NULL)
6794 return 0;
6795
6796 /*
6797 * In insert mode and the cursor is on a ')' truncate the line at the
6798 * cursor position. We don't want to line up with the matching '(' when
6799 * inserting new stuff.
6800 * For unknown reasons the cursor might be past the end of the line, thus
6801 * check for that.
6802 */
6803 if ((State & INSERT)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006804 && curwin->w_cursor.col < (colnr_T)STRLEN(linecopy)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006805 && linecopy[curwin->w_cursor.col] == ')')
6806 linecopy[curwin->w_cursor.col] = NUL;
6807
6808 theline = skipwhite(linecopy);
6809
6810 /* move the cursor to the start of the line */
6811
6812 curwin->w_cursor.col = 0;
6813
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006814 original_line_islabel = cin_islabel(ind_maxcomment); /* XXX */
6815
Bram Moolenaar071d4272004-06-13 20:20:40 +00006816 /*
6817 * #defines and so on always go at the left when included in 'cinkeys'.
6818 */
6819 if (*theline == '#' && (*linecopy == '#' || in_cinkeys('#', ' ', TRUE)))
6820 {
6821 amount = 0;
6822 }
6823
6824 /*
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006825 * Is it a non-case label? Then that goes at the left margin too unless:
6826 * - JS flag is set.
6827 * - 'L' item has a positive value.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006828 */
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006829 else if (original_line_islabel && !ind_js && ind_jump_label < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006830 {
6831 amount = 0;
6832 }
6833
6834 /*
6835 * If we're inside a "//" comment and there is a "//" comment in a
6836 * previous line, lineup with that one.
6837 */
6838 else if (cin_islinecomment(theline)
6839 && (trypos = find_line_comment()) != NULL) /* XXX */
6840 {
6841 /* find how indented the line beginning the comment is */
6842 getvcol(curwin, trypos, &col, NULL, NULL);
6843 amount = col;
6844 }
6845
6846 /*
6847 * If we're inside a comment and not looking at the start of the
6848 * comment, try using the 'comments' option.
6849 */
6850 else if (!cin_iscomment(theline)
6851 && (trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
6852 {
6853 int lead_start_len = 2;
6854 int lead_middle_len = 1;
6855 char_u lead_start[COM_MAX_LEN]; /* start-comment string */
6856 char_u lead_middle[COM_MAX_LEN]; /* middle-comment string */
6857 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
6858 char_u *p;
6859 int start_align = 0;
6860 int start_off = 0;
6861 int done = FALSE;
6862
6863 /* find how indented the line beginning the comment is */
6864 getvcol(curwin, trypos, &col, NULL, NULL);
6865 amount = col;
Bram Moolenaar4aa97422011-04-11 14:27:38 +02006866 *lead_start = NUL;
6867 *lead_middle = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006868
6869 p = curbuf->b_p_com;
6870 while (*p != NUL)
6871 {
6872 int align = 0;
6873 int off = 0;
6874 int what = 0;
6875
6876 while (*p != NUL && *p != ':')
6877 {
6878 if (*p == COM_START || *p == COM_END || *p == COM_MIDDLE)
6879 what = *p++;
6880 else if (*p == COM_LEFT || *p == COM_RIGHT)
6881 align = *p++;
6882 else if (VIM_ISDIGIT(*p) || *p == '-')
6883 off = getdigits(&p);
6884 else
6885 ++p;
6886 }
6887
6888 if (*p == ':')
6889 ++p;
6890 (void)copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
6891 if (what == COM_START)
6892 {
6893 STRCPY(lead_start, lead_end);
6894 lead_start_len = (int)STRLEN(lead_start);
6895 start_off = off;
6896 start_align = align;
6897 }
6898 else if (what == COM_MIDDLE)
6899 {
6900 STRCPY(lead_middle, lead_end);
6901 lead_middle_len = (int)STRLEN(lead_middle);
6902 }
6903 else if (what == COM_END)
6904 {
6905 /* If our line starts with the middle comment string, line it
6906 * up with the comment opener per the 'comments' option. */
6907 if (STRNCMP(theline, lead_middle, lead_middle_len) == 0
6908 && STRNCMP(theline, lead_end, STRLEN(lead_end)) != 0)
6909 {
6910 done = TRUE;
6911 if (curwin->w_cursor.lnum > 1)
6912 {
6913 /* If the start comment string matches in the previous
Bram Moolenaare21877a2008-02-13 09:58:14 +00006914 * line, use the indent of that line plus offset. If
Bram Moolenaar071d4272004-06-13 20:20:40 +00006915 * the middle comment string matches in the previous
6916 * line, use the indent of that line. XXX */
6917 look = skipwhite(ml_get(curwin->w_cursor.lnum - 1));
6918 if (STRNCMP(look, lead_start, lead_start_len) == 0)
6919 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6920 else if (STRNCMP(look, lead_middle,
6921 lead_middle_len) == 0)
6922 {
6923 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6924 break;
6925 }
6926 /* If the start comment string doesn't match with the
6927 * start of the comment, skip this entry. XXX */
6928 else if (STRNCMP(ml_get(trypos->lnum) + trypos->col,
6929 lead_start, lead_start_len) != 0)
6930 continue;
6931 }
6932 if (start_off != 0)
6933 amount += start_off;
6934 else if (start_align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006935 amount += vim_strsize(lead_start)
6936 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006937 break;
6938 }
6939
6940 /* If our line starts with the end comment string, line it up
6941 * with the middle comment */
6942 if (STRNCMP(theline, lead_middle, lead_middle_len) != 0
6943 && STRNCMP(theline, lead_end, STRLEN(lead_end)) == 0)
6944 {
6945 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6946 /* XXX */
6947 if (off != 0)
6948 amount += off;
6949 else if (align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006950 amount += vim_strsize(lead_start)
6951 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006952 done = TRUE;
6953 break;
6954 }
6955 }
6956 }
6957
6958 /* If our line starts with an asterisk, line up with the
6959 * asterisk in the comment opener; otherwise, line up
6960 * with the first character of the comment text.
6961 */
6962 if (done)
6963 ;
6964 else if (theline[0] == '*')
6965 amount += 1;
6966 else
6967 {
6968 /*
6969 * If we are more than one line away from the comment opener, take
6970 * the indent of the previous non-empty line. If 'cino' has "CO"
6971 * and we are just below the comment opener and there are any
6972 * white characters after it line up with the text after it;
6973 * otherwise, add the amount specified by "c" in 'cino'
6974 */
6975 amount = -1;
6976 for (lnum = cur_curpos.lnum - 1; lnum > trypos->lnum; --lnum)
6977 {
6978 if (linewhite(lnum)) /* skip blank lines */
6979 continue;
6980 amount = get_indent_lnum(lnum); /* XXX */
6981 break;
6982 }
6983 if (amount == -1) /* use the comment opener */
6984 {
6985 if (!ind_in_comment2)
6986 {
6987 start = ml_get(trypos->lnum);
6988 look = start + trypos->col + 2; /* skip / and * */
6989 if (*look != NUL) /* if something after it */
6990 trypos->col = (colnr_T)(skipwhite(look) - start);
6991 }
6992 getvcol(curwin, trypos, &col, NULL, NULL);
6993 amount = col;
6994 if (ind_in_comment2 || *look == NUL)
6995 amount += ind_in_comment;
6996 }
6997 }
6998 }
6999
7000 /*
7001 * Are we inside parentheses or braces?
7002 */ /* XXX */
7003 else if (((trypos = find_match_paren(ind_maxparen, ind_maxcomment)) != NULL
7004 && ind_java == 0)
7005 || (tryposBrace = find_start_brace(ind_maxcomment)) != NULL
7006 || trypos != NULL)
7007 {
7008 if (trypos != NULL && tryposBrace != NULL)
7009 {
7010 /* Both an unmatched '(' and '{' is found. Use the one which is
7011 * closer to the current cursor position, set the other to NULL. */
7012 if (trypos->lnum != tryposBrace->lnum
7013 ? trypos->lnum < tryposBrace->lnum
7014 : trypos->col < tryposBrace->col)
7015 trypos = NULL;
7016 else
7017 tryposBrace = NULL;
7018 }
7019
7020 if (trypos != NULL)
7021 {
7022 /*
7023 * If the matching paren is more than one line away, use the indent of
7024 * a previous non-empty line that matches the same paren.
7025 */
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007026 if (theline[0] == ')' && ind_paren_prev)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007027 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007028 /* Line up with the start of the matching paren line. */
7029 amount = get_indent_lnum(curwin->w_cursor.lnum - 1); /* XXX */
7030 }
7031 else
7032 {
7033 amount = -1;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007034 our_paren_pos = *trypos;
7035 for (lnum = cur_curpos.lnum - 1; lnum > our_paren_pos.lnum; --lnum)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007036 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007037 l = skipwhite(ml_get(lnum));
7038 if (cin_nocode(l)) /* skip comment lines */
7039 continue;
7040 if (cin_ispreproc_cont(&l, &lnum))
7041 continue; /* ignore #define, #if, etc. */
7042 curwin->w_cursor.lnum = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007043
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007044 /* Skip a comment. XXX */
7045 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
7046 {
7047 lnum = trypos->lnum + 1;
7048 continue;
7049 }
7050
7051 /* XXX */
7052 if ((trypos = find_match_paren(
7053 corr_ind_maxparen(ind_maxparen, &cur_curpos),
Bram Moolenaar071d4272004-06-13 20:20:40 +00007054 ind_maxcomment)) != NULL
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007055 && trypos->lnum == our_paren_pos.lnum
7056 && trypos->col == our_paren_pos.col)
7057 {
7058 amount = get_indent_lnum(lnum); /* XXX */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007059
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007060 if (theline[0] == ')')
7061 {
7062 if (our_paren_pos.lnum != lnum
7063 && cur_amount > amount)
7064 cur_amount = amount;
7065 amount = -1;
7066 }
7067 break;
7068 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007069 }
7070 }
7071
7072 /*
7073 * Line up with line where the matching paren is. XXX
7074 * If the line starts with a '(' or the indent for unclosed
7075 * parentheses is zero, line up with the unclosed parentheses.
7076 */
7077 if (amount == -1)
7078 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007079 int ignore_paren_col = 0;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007080 int is_if_for_while = 0;
7081
7082 if (ind_if_for_while)
7083 {
7084 /* Look for the outermost opening parenthesis on this line
7085 * and check whether it belongs to an "if", "for" or "while". */
7086
7087 pos_T cursor_save = curwin->w_cursor;
7088 pos_T outermost;
7089 char_u *line;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007090
7091 trypos = &our_paren_pos;
7092 do {
7093 outermost = *trypos;
7094 curwin->w_cursor.lnum = outermost.lnum;
7095 curwin->w_cursor.col = outermost.col;
7096
7097 trypos = find_match_paren(ind_maxparen, ind_maxcomment);
7098 } while (trypos && trypos->lnum == outermost.lnum);
7099
7100 curwin->w_cursor = cursor_save;
7101
7102 line = ml_get(outermost.lnum);
7103
7104 is_if_for_while =
Bram Moolenaarb345d492012-04-09 20:42:26 +02007105 cin_is_if_for_while_before_offset(line, &outermost.col);
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007106 }
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007107
Bram Moolenaar071d4272004-06-13 20:20:40 +00007108 amount = skip_label(our_paren_pos.lnum, &look, ind_maxcomment);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007109 look = skipwhite(look);
7110 if (*look == '(')
7111 {
7112 linenr_T save_lnum = curwin->w_cursor.lnum;
7113 char_u *line;
7114 int look_col;
7115
7116 /* Ignore a '(' in front of the line that has a match before
7117 * our matching '('. */
7118 curwin->w_cursor.lnum = our_paren_pos.lnum;
7119 line = ml_get_curline();
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007120 look_col = (int)(look - line);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007121 curwin->w_cursor.col = look_col + 1;
7122 if ((trypos = findmatchlimit(NULL, ')', 0, ind_maxparen))
7123 != NULL
7124 && trypos->lnum == our_paren_pos.lnum
7125 && trypos->col < our_paren_pos.col)
7126 ignore_paren_col = trypos->col + 1;
7127
7128 curwin->w_cursor.lnum = save_lnum;
7129 look = ml_get(our_paren_pos.lnum) + look_col;
7130 }
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007131 if (theline[0] == ')' || (ind_unclosed == 0 && is_if_for_while == 0)
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007132 || (!ind_unclosed_noignore && *look == '('
7133 && ignore_paren_col == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007134 {
7135 /*
7136 * If we're looking at a close paren, line up right there;
7137 * otherwise, line up with the next (non-white) character.
7138 * When ind_unclosed_wrapped is set and the matching paren is
7139 * the last nonwhite character of the line, use either the
7140 * indent of the current line or the indentation of the next
7141 * outer paren and add ind_unclosed_wrapped (for very long
7142 * lines).
7143 */
7144 if (theline[0] != ')')
7145 {
7146 cur_amount = MAXCOL;
7147 l = ml_get(our_paren_pos.lnum);
7148 if (ind_unclosed_wrapped
7149 && cin_ends_in(l, (char_u *)"(", NULL))
7150 {
7151 /* look for opening unmatched paren, indent one level
7152 * for each additional level */
7153 n = 1;
7154 for (col = 0; col < our_paren_pos.col; ++col)
7155 {
7156 switch (l[col])
7157 {
7158 case '(':
7159 case '{': ++n;
7160 break;
7161
7162 case ')':
7163 case '}': if (n > 1)
7164 --n;
7165 break;
7166 }
7167 }
7168
7169 our_paren_pos.col = 0;
7170 amount += n * ind_unclosed_wrapped;
7171 }
7172 else if (ind_unclosed_whiteok)
7173 our_paren_pos.col++;
7174 else
7175 {
7176 col = our_paren_pos.col + 1;
7177 while (vim_iswhite(l[col]))
7178 col++;
7179 if (l[col] != NUL) /* In case of trailing space */
7180 our_paren_pos.col = col;
7181 else
7182 our_paren_pos.col++;
7183 }
7184 }
7185
7186 /*
7187 * Find how indented the paren is, or the character after it
7188 * if we did the above "if".
7189 */
7190 if (our_paren_pos.col > 0)
7191 {
7192 getvcol(curwin, &our_paren_pos, &col, NULL, NULL);
7193 if (cur_amount > (int)col)
7194 cur_amount = col;
7195 }
7196 }
7197
7198 if (theline[0] == ')' && ind_matching_paren)
7199 {
7200 /* Line up with the start of the matching paren line. */
7201 }
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007202 else if ((ind_unclosed == 0 && is_if_for_while == 0)
7203 || (!ind_unclosed_noignore
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007204 && *look == '(' && ignore_paren_col == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007205 {
7206 if (cur_amount != MAXCOL)
7207 amount = cur_amount;
7208 }
7209 else
7210 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007211 /* Add ind_unclosed2 for each '(' before our matching one, but
7212 * ignore (void) before the line (ignore_paren_col). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007213 col = our_paren_pos.col;
Bram Moolenaarb21e5842006-04-16 18:30:08 +00007214 while ((int)our_paren_pos.col > ignore_paren_col)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007215 {
7216 --our_paren_pos.col;
7217 switch (*ml_get_pos(&our_paren_pos))
7218 {
7219 case '(': amount += ind_unclosed2;
7220 col = our_paren_pos.col;
7221 break;
7222 case ')': amount -= ind_unclosed2;
7223 col = MAXCOL;
7224 break;
7225 }
7226 }
7227
7228 /* Use ind_unclosed once, when the first '(' is not inside
7229 * braces */
7230 if (col == MAXCOL)
7231 amount += ind_unclosed;
7232 else
7233 {
7234 curwin->w_cursor.lnum = our_paren_pos.lnum;
7235 curwin->w_cursor.col = col;
Bram Moolenaar367bec82011-04-11 14:26:19 +02007236 if (find_match_paren(ind_maxparen, ind_maxcomment) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007237 amount += ind_unclosed2;
7238 else
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007239 {
7240 if (is_if_for_while)
7241 amount += ind_if_for_while;
7242 else
7243 amount += ind_unclosed;
7244 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007245 }
7246 /*
7247 * For a line starting with ')' use the minimum of the two
7248 * positions, to avoid giving it more indent than the previous
7249 * lines:
7250 * func_long_name( if (x
7251 * arg && yy
7252 * ) ^ not here ) ^ not here
7253 */
7254 if (cur_amount < amount)
7255 amount = cur_amount;
7256 }
7257 }
7258
7259 /* add extra indent for a comment */
7260 if (cin_iscomment(theline))
7261 amount += ind_comment;
7262 }
7263
7264 /*
7265 * Are we at least inside braces, then?
7266 */
7267 else
7268 {
7269 trypos = tryposBrace;
7270
7271 ourscope = trypos->lnum;
7272 start = ml_get(ourscope);
7273
7274 /*
7275 * Now figure out how indented the line is in general.
7276 * If the brace was at the start of the line, we use that;
7277 * otherwise, check out the indentation of the line as
7278 * a whole and then add the "imaginary indent" to that.
7279 */
7280 look = skipwhite(start);
7281 if (*look == '{')
7282 {
7283 getvcol(curwin, trypos, &col, NULL, NULL);
7284 amount = col;
7285 if (*start == '{')
7286 start_brace = BRACE_IN_COL0;
7287 else
7288 start_brace = BRACE_AT_START;
7289 }
7290 else
7291 {
7292 /*
7293 * that opening brace might have been on a continuation
7294 * line. if so, find the start of the line.
7295 */
7296 curwin->w_cursor.lnum = ourscope;
7297
7298 /*
7299 * position the cursor over the rightmost paren, so that
7300 * matching it will take us back to the start of the line.
7301 */
7302 lnum = ourscope;
7303 if (find_last_paren(start, '(', ')')
7304 && (trypos = find_match_paren(ind_maxparen,
7305 ind_maxcomment)) != NULL)
7306 lnum = trypos->lnum;
7307
7308 /*
7309 * It could have been something like
7310 * case 1: if (asdf &&
7311 * ldfd) {
7312 * }
7313 */
Bram Moolenaar6ec154b2011-06-12 21:51:08 +02007314 if (ind_js || (ind_keep_case_label
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007315 && cin_iscase(skipwhite(ml_get_curline()), FALSE)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007316 amount = get_indent();
7317 else
7318 amount = skip_label(lnum, &l, ind_maxcomment);
7319
7320 start_brace = BRACE_AT_END;
7321 }
7322
7323 /*
7324 * if we're looking at a closing brace, that's where
7325 * we want to be. otherwise, add the amount of room
7326 * that an indent is supposed to be.
7327 */
7328 if (theline[0] == '}')
7329 {
7330 /*
7331 * they may want closing braces to line up with something
7332 * other than the open brace. indulge them, if so.
7333 */
7334 amount += ind_close_extra;
7335 }
7336 else
7337 {
7338 /*
7339 * If we're looking at an "else", try to find an "if"
7340 * to match it with.
7341 * If we're looking at a "while", try to find a "do"
7342 * to match it with.
7343 */
7344 lookfor = LOOKFOR_INITIAL;
7345 if (cin_iselse(theline))
7346 lookfor = LOOKFOR_IF;
7347 else if (cin_iswhileofdo(theline, cur_curpos.lnum, ind_maxparen))
7348 /* XXX */
7349 lookfor = LOOKFOR_DO;
7350 if (lookfor != LOOKFOR_INITIAL)
7351 {
7352 curwin->w_cursor.lnum = cur_curpos.lnum;
7353 if (find_match(lookfor, ourscope, ind_maxparen,
7354 ind_maxcomment) == OK)
7355 {
7356 amount = get_indent(); /* XXX */
7357 goto theend;
7358 }
7359 }
7360
7361 /*
7362 * We get here if we are not on an "while-of-do" or "else" (or
7363 * failed to find a matching "if").
7364 * Search backwards for something to line up with.
7365 * First set amount for when we don't find anything.
7366 */
7367
7368 /*
7369 * if the '{' is _really_ at the left margin, use the imaginary
7370 * location of a left-margin brace. Otherwise, correct the
7371 * location for ind_open_extra.
7372 */
7373
7374 if (start_brace == BRACE_IN_COL0) /* '{' is in column 0 */
7375 {
7376 amount = ind_open_left_imag;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007377 lookfor_cpp_namespace = TRUE;
7378 }
7379 else if (start_brace == BRACE_AT_START &&
7380 lookfor_cpp_namespace) /* '{' is at start */
7381 {
7382
7383 lookfor_cpp_namespace = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007384 }
7385 else
7386 {
7387 if (start_brace == BRACE_AT_END) /* '{' is at end of line */
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007388 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007389 amount += ind_open_imag;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007390
7391 l = skipwhite(ml_get_curline());
7392 if (cin_is_cpp_namespace(l))
7393 amount += ind_cpp_namespace;
7394 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007395 else
7396 {
7397 /* Compensate for adding ind_open_extra later. */
7398 amount -= ind_open_extra;
7399 if (amount < 0)
7400 amount = 0;
7401 }
7402 }
7403
7404 lookfor_break = FALSE;
7405
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007406 if (cin_iscase(theline, FALSE)) /* it's a switch() label */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007407 {
7408 lookfor = LOOKFOR_CASE; /* find a previous switch() label */
7409 amount += ind_case;
7410 }
7411 else if (cin_isscopedecl(theline)) /* private:, ... */
7412 {
7413 lookfor = LOOKFOR_SCOPEDECL; /* class decl is this block */
7414 amount += ind_scopedecl;
7415 }
7416 else
7417 {
7418 if (ind_case_break && cin_isbreak(theline)) /* break; ... */
7419 lookfor_break = TRUE;
7420
7421 lookfor = LOOKFOR_INITIAL;
7422 amount += ind_level; /* ind_level from start of block */
7423 }
7424 scope_amount = amount;
7425 whilelevel = 0;
7426
7427 /*
7428 * Search backwards. If we find something we recognize, line up
7429 * with that.
7430 *
7431 * if we're looking at an open brace, indent
7432 * the usual amount relative to the conditional
7433 * that opens the block.
7434 */
7435 curwin->w_cursor = cur_curpos;
7436 for (;;)
7437 {
7438 curwin->w_cursor.lnum--;
7439 curwin->w_cursor.col = 0;
7440
7441 /*
7442 * If we went all the way back to the start of our scope, line
7443 * up with it.
7444 */
7445 if (curwin->w_cursor.lnum <= ourscope)
7446 {
7447 /* we reached end of scope:
7448 * if looking for a enum or structure initialization
7449 * go further back:
7450 * if it is an initializer (enum xxx or xxx =), then
7451 * don't add ind_continuation, otherwise it is a variable
7452 * declaration:
7453 * int x,
7454 * here; <-- add ind_continuation
7455 */
7456 if (lookfor == LOOKFOR_ENUM_OR_INIT)
7457 {
7458 if (curwin->w_cursor.lnum == 0
7459 || curwin->w_cursor.lnum
7460 < ourscope - ind_maxparen)
7461 {
7462 /* nothing found (abuse ind_maxparen as limit)
7463 * assume terminated line (i.e. a variable
7464 * initialization) */
7465 if (cont_amount > 0)
7466 amount = cont_amount;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007467 else if (!ind_js)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007468 amount += ind_continuation;
7469 break;
7470 }
7471
7472 l = ml_get_curline();
7473
7474 /*
7475 * If we're in a comment now, skip to the start of the
7476 * comment.
7477 */
7478 trypos = find_start_comment(ind_maxcomment);
7479 if (trypos != NULL)
7480 {
7481 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007482 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007483 continue;
7484 }
7485
7486 /*
7487 * Skip preprocessor directives and blank lines.
7488 */
7489 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7490 continue;
7491
7492 if (cin_nocode(l))
7493 continue;
7494
7495 terminated = cin_isterminated(l, FALSE, TRUE);
7496
7497 /*
7498 * If we are at top level and the line looks like a
7499 * function declaration, we are done
7500 * (it's a variable declaration).
7501 */
7502 if (start_brace != BRACE_IN_COL0
Bram Moolenaarc367faa2011-12-14 20:21:35 +01007503 || !cin_isfuncdecl(&l, curwin->w_cursor.lnum,
7504 0, ind_maxparen, ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007505 {
7506 /* if the line is terminated with another ','
7507 * it is a continued variable initialization.
7508 * don't add extra indent.
7509 * TODO: does not work, if a function
7510 * declaration is split over multiple lines:
7511 * cin_isfuncdecl returns FALSE then.
7512 */
7513 if (terminated == ',')
7514 break;
7515
7516 /* if it es a enum declaration or an assignment,
7517 * we are done.
7518 */
7519 if (terminated != ';' && cin_isinit())
7520 break;
7521
7522 /* nothing useful found */
7523 if (terminated == 0 || terminated == '{')
7524 continue;
7525 }
7526
7527 if (terminated != ';')
7528 {
7529 /* Skip parens and braces. Position the cursor
7530 * over the rightmost paren, so that matching it
7531 * will take us back to the start of the line.
7532 */ /* XXX */
7533 trypos = NULL;
7534 if (find_last_paren(l, '(', ')'))
7535 trypos = find_match_paren(ind_maxparen,
7536 ind_maxcomment);
7537
7538 if (trypos == NULL && find_last_paren(l, '{', '}'))
7539 trypos = find_start_brace(ind_maxcomment);
7540
7541 if (trypos != NULL)
7542 {
7543 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007544 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007545 continue;
7546 }
7547 }
7548
7549 /* it's a variable declaration, add indentation
7550 * like in
7551 * int a,
7552 * b;
7553 */
7554 if (cont_amount > 0)
7555 amount = cont_amount;
7556 else
7557 amount += ind_continuation;
7558 }
7559 else if (lookfor == LOOKFOR_UNTERM)
7560 {
7561 if (cont_amount > 0)
7562 amount = cont_amount;
7563 else
7564 amount += ind_continuation;
7565 }
Bram Moolenaare79d1532011-10-04 18:03:47 +02007566 else
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007567 {
Bram Moolenaare79d1532011-10-04 18:03:47 +02007568 if (lookfor != LOOKFOR_TERM
Bram Moolenaar071d4272004-06-13 20:20:40 +00007569 && lookfor != LOOKFOR_CPP_BASECLASS)
Bram Moolenaare79d1532011-10-04 18:03:47 +02007570 {
7571 amount = scope_amount;
7572 if (theline[0] == '{')
7573 {
7574 amount += ind_open_extra;
7575 added_to_amount = ind_open_extra;
7576 }
7577 }
7578
7579 if (lookfor_cpp_namespace)
7580 {
7581 /*
7582 * Looking for C++ namespace, need to look further
7583 * back.
7584 */
7585 if (curwin->w_cursor.lnum == ourscope)
7586 continue;
7587
7588 if (curwin->w_cursor.lnum == 0
7589 || curwin->w_cursor.lnum
7590 < ourscope - FIND_NAMESPACE_LIM)
7591 break;
7592
7593 l = ml_get_curline();
7594
7595 /* If we're in a comment now, skip to the start of
7596 * the comment. */
7597 trypos = find_start_comment(ind_maxcomment);
7598 if (trypos != NULL)
7599 {
7600 curwin->w_cursor.lnum = trypos->lnum + 1;
7601 curwin->w_cursor.col = 0;
7602 continue;
7603 }
7604
7605 /* Skip preprocessor directives and blank lines. */
7606 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7607 continue;
7608
7609 /* Finally the actual check for "namespace". */
7610 if (cin_is_cpp_namespace(l))
7611 {
7612 amount += ind_cpp_namespace - added_to_amount;
7613 break;
7614 }
7615
7616 if (cin_nocode(l))
7617 continue;
7618 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007619 }
7620 break;
7621 }
7622
7623 /*
7624 * If we're in a comment now, skip to the start of the comment.
7625 */ /* XXX */
7626 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
7627 {
7628 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007629 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007630 continue;
7631 }
7632
7633 l = ml_get_curline();
7634
7635 /*
7636 * If this is a switch() label, may line up relative to that.
Bram Moolenaar18144c82006-04-12 21:52:12 +00007637 * If this is a C++ scope declaration, do the same.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007638 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007639 iscase = cin_iscase(l, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007640 if (iscase || cin_isscopedecl(l))
7641 {
7642 /* we are only looking for cpp base class
7643 * declaration/initialization any longer */
7644 if (lookfor == LOOKFOR_CPP_BASECLASS)
7645 break;
7646
7647 /* When looking for a "do" we are not interested in
7648 * labels. */
7649 if (whilelevel > 0)
7650 continue;
7651
7652 /*
7653 * case xx:
7654 * c = 99 + <- this indent plus continuation
7655 *-> here;
7656 */
7657 if (lookfor == LOOKFOR_UNTERM
7658 || lookfor == LOOKFOR_ENUM_OR_INIT)
7659 {
7660 if (cont_amount > 0)
7661 amount = cont_amount;
7662 else
7663 amount += ind_continuation;
7664 break;
7665 }
7666
7667 /*
7668 * case xx: <- line up with this case
7669 * x = 333;
7670 * case yy:
7671 */
7672 if ( (iscase && lookfor == LOOKFOR_CASE)
7673 || (iscase && lookfor_break)
7674 || (!iscase && lookfor == LOOKFOR_SCOPEDECL))
7675 {
7676 /*
7677 * Check that this case label is not for another
7678 * switch()
7679 */ /* XXX */
7680 if ((trypos = find_start_brace(ind_maxcomment)) ==
7681 NULL || trypos->lnum == ourscope)
7682 {
7683 amount = get_indent(); /* XXX */
7684 break;
7685 }
7686 continue;
7687 }
7688
7689 n = get_indent_nolabel(curwin->w_cursor.lnum); /* XXX */
7690
7691 /*
7692 * case xx: if (cond) <- line up with this if
7693 * y = y + 1;
7694 * -> s = 99;
7695 *
7696 * case xx:
7697 * if (cond) <- line up with this line
7698 * y = y + 1;
7699 * -> s = 99;
7700 */
7701 if (lookfor == LOOKFOR_TERM)
7702 {
7703 if (n)
7704 amount = n;
7705
7706 if (!lookfor_break)
7707 break;
7708 }
7709
7710 /*
7711 * case xx: x = x + 1; <- line up with this x
7712 * -> y = y + 1;
7713 *
7714 * case xx: if (cond) <- line up with this if
7715 * -> y = y + 1;
7716 */
7717 if (n)
7718 {
7719 amount = n;
7720 l = after_label(ml_get_curline());
7721 if (l != NULL && cin_is_cinword(l))
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007722 {
7723 if (theline[0] == '{')
7724 amount += ind_open_extra;
7725 else
7726 amount += ind_level + ind_no_brace;
7727 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007728 break;
7729 }
7730
7731 /*
7732 * Try to get the indent of a statement before the switch
7733 * label. If nothing is found, line up relative to the
7734 * switch label.
7735 * break; <- may line up with this line
7736 * case xx:
7737 * -> y = 1;
7738 */
7739 scope_amount = get_indent() + (iscase /* XXX */
7740 ? ind_case_code : ind_scopedecl_code);
7741 lookfor = ind_case_break ? LOOKFOR_NOBREAK : LOOKFOR_ANY;
7742 continue;
7743 }
7744
7745 /*
7746 * Looking for a switch() label or C++ scope declaration,
7747 * ignore other lines, skip {}-blocks.
7748 */
7749 if (lookfor == LOOKFOR_CASE || lookfor == LOOKFOR_SCOPEDECL)
7750 {
7751 if (find_last_paren(l, '{', '}') && (trypos =
7752 find_start_brace(ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007753 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007754 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007755 curwin->w_cursor.col = 0;
7756 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007757 continue;
7758 }
7759
7760 /*
7761 * Ignore jump labels with nothing after them.
7762 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007763 if (!ind_js && cin_islabel(ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007764 {
7765 l = after_label(ml_get_curline());
7766 if (l == NULL || cin_nocode(l))
7767 continue;
7768 }
7769
7770 /*
7771 * Ignore #defines, #if, etc.
7772 * Ignore comment and empty lines.
7773 * (need to get the line again, cin_islabel() may have
7774 * unlocked it)
7775 */
7776 l = ml_get_curline();
7777 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum)
7778 || cin_nocode(l))
7779 continue;
7780
7781 /*
7782 * Are we at the start of a cpp base class declaration or
7783 * constructor initialization?
7784 */ /* XXX */
Bram Moolenaar18144c82006-04-12 21:52:12 +00007785 n = FALSE;
7786 if (lookfor != LOOKFOR_TERM && ind_cpp_baseclass > 0)
7787 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00007788 n = cin_is_cpp_baseclass(&col);
Bram Moolenaar18144c82006-04-12 21:52:12 +00007789 l = ml_get_curline();
7790 }
7791 if (n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007792 {
7793 if (lookfor == LOOKFOR_UNTERM)
7794 {
7795 if (cont_amount > 0)
7796 amount = cont_amount;
7797 else
7798 amount += ind_continuation;
7799 }
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007800 else if (theline[0] == '{')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007801 {
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007802 /* Need to find start of the declaration. */
7803 lookfor = LOOKFOR_UNTERM;
7804 ind_continuation = 0;
7805 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007806 }
7807 else
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007808 /* XXX */
7809 amount = get_baseclass_amount(col, ind_maxparen,
7810 ind_maxcomment, ind_cpp_baseclass);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007811 break;
7812 }
7813 else if (lookfor == LOOKFOR_CPP_BASECLASS)
7814 {
7815 /* only look, whether there is a cpp base class
Bram Moolenaar18144c82006-04-12 21:52:12 +00007816 * declaration or initialization before the opening brace.
7817 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007818 if (cin_isterminated(l, TRUE, FALSE))
7819 break;
7820 else
7821 continue;
7822 }
7823
7824 /*
7825 * What happens next depends on the line being terminated.
7826 * If terminated with a ',' only consider it terminating if
Bram Moolenaar25394022007-05-10 19:06:20 +00007827 * there is another unterminated statement behind, eg:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007828 * 123,
7829 * sizeof
7830 * here
7831 * Otherwise check whether it is a enumeration or structure
7832 * initialisation (not indented) or a variable declaration
7833 * (indented).
7834 */
7835 terminated = cin_isterminated(l, FALSE, TRUE);
7836
7837 if (terminated == 0 || (lookfor != LOOKFOR_UNTERM
7838 && terminated == ','))
7839 {
7840 /*
7841 * if we're in the middle of a paren thing,
7842 * go back to the line that starts it so
7843 * we can get the right prevailing indent
7844 * if ( foo &&
7845 * bar )
7846 */
7847 /*
7848 * position the cursor over the rightmost paren, so that
7849 * matching it will take us back to the start of the line.
7850 */
7851 (void)find_last_paren(l, '(', ')');
7852 trypos = find_match_paren(
7853 corr_ind_maxparen(ind_maxparen, &cur_curpos),
7854 ind_maxcomment);
7855
7856 /*
7857 * If we are looking for ',', we also look for matching
7858 * braces.
7859 */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007860 if (trypos == NULL && terminated == ','
7861 && find_last_paren(l, '{', '}'))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007862 trypos = find_start_brace(ind_maxcomment);
7863
7864 if (trypos != NULL)
7865 {
7866 /*
7867 * Check if we are on a case label now. This is
7868 * handled above.
7869 * case xx: if ( asdf &&
7870 * asdf)
7871 */
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007872 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007873 l = ml_get_curline();
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007874 if (cin_iscase(l, FALSE) || cin_isscopedecl(l))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007875 {
7876 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007877 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007878 continue;
7879 }
7880 }
7881
7882 /*
7883 * Skip over continuation lines to find the one to get the
7884 * indent from
7885 * char *usethis = "bla\
7886 * bla",
7887 * here;
7888 */
7889 if (terminated == ',')
7890 {
7891 while (curwin->w_cursor.lnum > 1)
7892 {
7893 l = ml_get(curwin->w_cursor.lnum - 1);
7894 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
7895 break;
7896 --curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007897 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007898 }
7899 }
7900
7901 /*
7902 * Get indent and pointer to text for current line,
7903 * ignoring any jump label. XXX
7904 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007905 if (!ind_js)
7906 cur_amount = skip_label(curwin->w_cursor.lnum,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007907 &l, ind_maxcomment);
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007908 else
7909 cur_amount = get_indent();
Bram Moolenaar071d4272004-06-13 20:20:40 +00007910 /*
7911 * If this is just above the line we are indenting, and it
7912 * starts with a '{', line it up with this line.
7913 * while (not)
7914 * -> {
7915 * }
7916 */
7917 if (terminated != ',' && lookfor != LOOKFOR_TERM
7918 && theline[0] == '{')
7919 {
7920 amount = cur_amount;
7921 /*
7922 * Only add ind_open_extra when the current line
7923 * doesn't start with a '{', which must have a match
7924 * in the same line (scope is the same). Probably:
7925 * { 1, 2 },
7926 * -> { 3, 4 }
7927 */
7928 if (*skipwhite(l) != '{')
7929 amount += ind_open_extra;
7930
7931 if (ind_cpp_baseclass)
7932 {
7933 /* have to look back, whether it is a cpp base
7934 * class declaration or initialization */
7935 lookfor = LOOKFOR_CPP_BASECLASS;
7936 continue;
7937 }
7938 break;
7939 }
7940
7941 /*
7942 * Check if we are after an "if", "while", etc.
7943 * Also allow " } else".
7944 */
7945 if (cin_is_cinword(l) || cin_iselse(skipwhite(l)))
7946 {
7947 /*
7948 * Found an unterminated line after an if (), line up
7949 * with the last one.
7950 * if (cond)
7951 * 100 +
7952 * -> here;
7953 */
7954 if (lookfor == LOOKFOR_UNTERM
7955 || lookfor == LOOKFOR_ENUM_OR_INIT)
7956 {
7957 if (cont_amount > 0)
7958 amount = cont_amount;
7959 else
7960 amount += ind_continuation;
7961 break;
7962 }
7963
7964 /*
7965 * If this is just above the line we are indenting, we
7966 * are finished.
7967 * while (not)
7968 * -> here;
7969 * Otherwise this indent can be used when the line
7970 * before this is terminated.
7971 * yyy;
7972 * if (stat)
7973 * while (not)
7974 * xxx;
7975 * -> here;
7976 */
7977 amount = cur_amount;
7978 if (theline[0] == '{')
7979 amount += ind_open_extra;
7980 if (lookfor != LOOKFOR_TERM)
7981 {
7982 amount += ind_level + ind_no_brace;
7983 break;
7984 }
7985
7986 /*
7987 * Special trick: when expecting the while () after a
7988 * do, line up with the while()
7989 * do
7990 * x = 1;
7991 * -> here
7992 */
7993 l = skipwhite(ml_get_curline());
7994 if (cin_isdo(l))
7995 {
7996 if (whilelevel == 0)
7997 break;
7998 --whilelevel;
7999 }
8000
8001 /*
8002 * When searching for a terminated line, don't use the
Bram Moolenaar334adf02011-05-25 13:34:04 +02008003 * one between the "if" and the matching "else".
Bram Moolenaar071d4272004-06-13 20:20:40 +00008004 * Need to use the scope of this "else". XXX
8005 * If whilelevel != 0 continue looking for a "do {".
8006 */
Bram Moolenaar334adf02011-05-25 13:34:04 +02008007 if (cin_iselse(l) && whilelevel == 0)
8008 {
8009 /* If we're looking at "} else", let's make sure we
8010 * find the opening brace of the enclosing scope,
8011 * not the one from "if () {". */
8012 if (*l == '}')
8013 curwin->w_cursor.col =
Bram Moolenaar9b83c2f2011-05-25 17:29:44 +02008014 (colnr_T)(l - ml_get_curline()) + 1;
Bram Moolenaar334adf02011-05-25 13:34:04 +02008015
8016 if ((trypos = find_start_brace(ind_maxcomment))
8017 == NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00008018 || find_match(LOOKFOR_IF, trypos->lnum,
Bram Moolenaar334adf02011-05-25 13:34:04 +02008019 ind_maxparen, ind_maxcomment) == FAIL)
8020 break;
8021 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008022 }
8023
8024 /*
8025 * If we're below an unterminated line that is not an
8026 * "if" or something, we may line up with this line or
Bram Moolenaar25394022007-05-10 19:06:20 +00008027 * add something for a continuation line, depending on
Bram Moolenaar071d4272004-06-13 20:20:40 +00008028 * the line before this one.
8029 */
8030 else
8031 {
8032 /*
8033 * Found two unterminated lines on a row, line up with
8034 * the last one.
8035 * c = 99 +
8036 * 100 +
8037 * -> here;
8038 */
8039 if (lookfor == LOOKFOR_UNTERM)
8040 {
8041 /* When line ends in a comma add extra indent */
8042 if (terminated == ',')
8043 amount += ind_continuation;
8044 break;
8045 }
8046
8047 if (lookfor == LOOKFOR_ENUM_OR_INIT)
8048 {
8049 /* Found two lines ending in ',', lineup with the
8050 * lowest one, but check for cpp base class
8051 * declaration/initialization, if it is an
8052 * opening brace or we are looking just for
8053 * enumerations/initializations. */
8054 if (terminated == ',')
8055 {
8056 if (ind_cpp_baseclass == 0)
8057 break;
8058
8059 lookfor = LOOKFOR_CPP_BASECLASS;
8060 continue;
8061 }
8062
8063 /* Ignore unterminated lines in between, but
8064 * reduce indent. */
8065 if (amount > cur_amount)
8066 amount = cur_amount;
8067 }
8068 else
8069 {
8070 /*
8071 * Found first unterminated line on a row, may
8072 * line up with this line, remember its indent
8073 * 100 +
8074 * -> here;
8075 */
8076 amount = cur_amount;
8077
8078 /*
8079 * If previous line ends in ',', check whether we
8080 * are in an initialization or enum
8081 * struct xxx =
8082 * {
8083 * sizeof a,
8084 * 124 };
8085 * or a normal possible continuation line.
8086 * but only, of no other statement has been found
8087 * yet.
8088 */
8089 if (lookfor == LOOKFOR_INITIAL && terminated == ',')
8090 {
8091 lookfor = LOOKFOR_ENUM_OR_INIT;
8092 cont_amount = cin_first_id_amount();
8093 }
8094 else
8095 {
8096 if (lookfor == LOOKFOR_INITIAL
8097 && *l != NUL
8098 && l[STRLEN(l) - 1] == '\\')
8099 /* XXX */
8100 cont_amount = cin_get_equal_amount(
8101 curwin->w_cursor.lnum);
8102 if (lookfor != LOOKFOR_TERM)
8103 lookfor = LOOKFOR_UNTERM;
8104 }
8105 }
8106 }
8107 }
8108
8109 /*
8110 * Check if we are after a while (cond);
8111 * If so: Ignore until the matching "do".
8112 */
8113 /* XXX */
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00008114 else if (cin_iswhileofdo_end(terminated, ind_maxparen,
8115 ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008116 {
8117 /*
8118 * Found an unterminated line after a while ();, line up
8119 * with the last one.
8120 * while (cond);
8121 * 100 + <- line up with this one
8122 * -> here;
8123 */
8124 if (lookfor == LOOKFOR_UNTERM
8125 || lookfor == LOOKFOR_ENUM_OR_INIT)
8126 {
8127 if (cont_amount > 0)
8128 amount = cont_amount;
8129 else
8130 amount += ind_continuation;
8131 break;
8132 }
8133
8134 if (whilelevel == 0)
8135 {
8136 lookfor = LOOKFOR_TERM;
8137 amount = get_indent(); /* XXX */
8138 if (theline[0] == '{')
8139 amount += ind_open_extra;
8140 }
8141 ++whilelevel;
8142 }
8143
8144 /*
8145 * We are after a "normal" statement.
8146 * If we had another statement we can stop now and use the
8147 * indent of that other statement.
8148 * Otherwise the indent of the current statement may be used,
8149 * search backwards for the next "normal" statement.
8150 */
8151 else
8152 {
8153 /*
8154 * Skip single break line, if before a switch label. It
8155 * may be lined up with the case label.
8156 */
8157 if (lookfor == LOOKFOR_NOBREAK
8158 && cin_isbreak(skipwhite(ml_get_curline())))
8159 {
8160 lookfor = LOOKFOR_ANY;
8161 continue;
8162 }
8163
8164 /*
8165 * Handle "do {" line.
8166 */
8167 if (whilelevel > 0)
8168 {
8169 l = cin_skipcomment(ml_get_curline());
8170 if (cin_isdo(l))
8171 {
8172 amount = get_indent(); /* XXX */
8173 --whilelevel;
8174 continue;
8175 }
8176 }
8177
8178 /*
8179 * Found a terminated line above an unterminated line. Add
8180 * the amount for a continuation line.
8181 * x = 1;
8182 * y = foo +
8183 * -> here;
8184 * or
8185 * int x = 1;
8186 * int foo,
8187 * -> here;
8188 */
8189 if (lookfor == LOOKFOR_UNTERM
8190 || lookfor == LOOKFOR_ENUM_OR_INIT)
8191 {
8192 if (cont_amount > 0)
8193 amount = cont_amount;
8194 else
8195 amount += ind_continuation;
8196 break;
8197 }
8198
8199 /*
8200 * Found a terminated line above a terminated line or "if"
8201 * etc. line. Use the amount of the line below us.
8202 * x = 1; x = 1;
8203 * if (asdf) y = 2;
8204 * while (asdf) ->here;
8205 * here;
8206 * ->foo;
8207 */
8208 if (lookfor == LOOKFOR_TERM)
8209 {
8210 if (!lookfor_break && whilelevel == 0)
8211 break;
8212 }
8213
8214 /*
8215 * First line above the one we're indenting is terminated.
8216 * To know what needs to be done look further backward for
8217 * a terminated line.
8218 */
8219 else
8220 {
8221 /*
8222 * position the cursor over the rightmost paren, so
8223 * that matching it will take us back to the start of
8224 * the line. Helps for:
8225 * func(asdr,
8226 * asdfasdf);
8227 * here;
8228 */
8229term_again:
8230 l = ml_get_curline();
8231 if (find_last_paren(l, '(', ')')
8232 && (trypos = find_match_paren(ind_maxparen,
8233 ind_maxcomment)) != NULL)
8234 {
8235 /*
8236 * Check if we are on a case label now. This is
8237 * handled above.
8238 * case xx: if ( asdf &&
8239 * asdf)
8240 */
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008241 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008242 l = ml_get_curline();
Bram Moolenaar3acfc302010-07-11 17:23:02 +02008243 if (cin_iscase(l, FALSE) || cin_isscopedecl(l))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008244 {
8245 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008246 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008247 continue;
8248 }
8249 }
8250
8251 /* When aligning with the case statement, don't align
8252 * with a statement after it.
8253 * case 1: { <-- don't use this { position
8254 * stat;
8255 * }
8256 * case 2:
8257 * stat;
8258 * }
8259 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02008260 iscase = (ind_keep_case_label && cin_iscase(l, FALSE));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008261
8262 /*
8263 * Get indent and pointer to text for current line,
8264 * ignoring any jump label.
8265 */
8266 amount = skip_label(curwin->w_cursor.lnum,
8267 &l, ind_maxcomment);
8268
8269 if (theline[0] == '{')
8270 amount += ind_open_extra;
8271 /* See remark above: "Only add ind_open_extra.." */
Bram Moolenaar18144c82006-04-12 21:52:12 +00008272 l = skipwhite(l);
8273 if (*l == '{')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008274 amount -= ind_open_extra;
8275 lookfor = iscase ? LOOKFOR_ANY : LOOKFOR_TERM;
8276
8277 /*
Bram Moolenaar18144c82006-04-12 21:52:12 +00008278 * When a terminated line starts with "else" skip to
8279 * the matching "if":
8280 * else 3;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008281 * indent this;
Bram Moolenaar18144c82006-04-12 21:52:12 +00008282 * Need to use the scope of this "else". XXX
8283 * If whilelevel != 0 continue looking for a "do {".
8284 */
8285 if (lookfor == LOOKFOR_TERM
8286 && *l != '}'
8287 && cin_iselse(l)
8288 && whilelevel == 0)
8289 {
8290 if ((trypos = find_start_brace(ind_maxcomment))
8291 == NULL
8292 || find_match(LOOKFOR_IF, trypos->lnum,
8293 ind_maxparen, ind_maxcomment) == FAIL)
8294 break;
8295 continue;
8296 }
8297
8298 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008299 * If we're at the end of a block, skip to the start of
8300 * that block.
8301 */
Bram Moolenaar6d8f9c62011-11-30 13:03:28 +01008302 l = ml_get_curline();
Bram Moolenaar50f42ca2011-07-15 14:12:30 +02008303 if (find_last_paren(l, '{', '}')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008304 && (trypos = find_start_brace(ind_maxcomment))
8305 != NULL) /* XXX */
8306 {
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008307 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008308 /* if not "else {" check for terminated again */
8309 /* but skip block for "} else {" */
8310 l = cin_skipcomment(ml_get_curline());
8311 if (*l == '}' || !cin_iselse(l))
8312 goto term_again;
8313 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008314 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008315 }
8316 }
8317 }
8318 }
8319 }
8320 }
8321
8322 /* add extra indent for a comment */
8323 if (cin_iscomment(theline))
8324 amount += ind_comment;
Bram Moolenaar02c707a2010-07-17 17:12:06 +02008325
8326 /* subtract extra left-shift for jump labels */
8327 if (ind_jump_label > 0 && original_line_islabel)
8328 amount -= ind_jump_label;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008329 }
8330
8331 /*
8332 * ok -- we're not inside any sort of structure at all!
8333 *
8334 * this means we're at the top level, and everything should
8335 * basically just match where the previous line is, except
8336 * for the lines immediately following a function declaration,
8337 * which are K&R-style parameters and need to be indented.
8338 */
8339 else
8340 {
8341 /*
8342 * if our line starts with an open brace, forget about any
8343 * prevailing indent and make sure it looks like the start
8344 * of a function
8345 */
8346
8347 if (theline[0] == '{')
8348 {
8349 amount = ind_first_open;
8350 }
8351
8352 /*
8353 * If the NEXT line is a function declaration, the current
8354 * line needs to be indented as a function type spec.
Bram Moolenaar1a89bbe2010-03-02 12:38:22 +01008355 * Don't do this if the current line looks like a comment or if the
8356 * current line is terminated, ie. ends in ';', or if the current line
8357 * contains { or }: "void f() {\n if (1)"
Bram Moolenaar071d4272004-06-13 20:20:40 +00008358 */
8359 else if (cur_curpos.lnum < curbuf->b_ml.ml_line_count
8360 && !cin_nocode(theline)
Bram Moolenaar1a89bbe2010-03-02 12:38:22 +01008361 && vim_strchr(theline, '{') == NULL
8362 && vim_strchr(theline, '}') == NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00008363 && !cin_ends_in(theline, (char_u *)":", NULL)
8364 && !cin_ends_in(theline, (char_u *)",", NULL)
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008365 && cin_isfuncdecl(NULL, cur_curpos.lnum + 1,
8366 cur_curpos.lnum + 1,
8367 ind_maxparen, ind_maxcomment)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008368 && !cin_isterminated(theline, FALSE, TRUE))
8369 {
8370 amount = ind_func_type;
8371 }
8372 else
8373 {
8374 amount = 0;
8375 curwin->w_cursor = cur_curpos;
8376
8377 /* search backwards until we find something we recognize */
8378
8379 while (curwin->w_cursor.lnum > 1)
8380 {
8381 curwin->w_cursor.lnum--;
8382 curwin->w_cursor.col = 0;
8383
8384 l = ml_get_curline();
8385
8386 /*
8387 * If we're in a comment now, skip to the start of the comment.
8388 */ /* XXX */
8389 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
8390 {
8391 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008392 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008393 continue;
8394 }
8395
8396 /*
Bram Moolenaar18144c82006-04-12 21:52:12 +00008397 * Are we at the start of a cpp base class declaration or
8398 * constructor initialization?
Bram Moolenaar071d4272004-06-13 20:20:40 +00008399 */ /* XXX */
Bram Moolenaar18144c82006-04-12 21:52:12 +00008400 n = FALSE;
8401 if (ind_cpp_baseclass != 0 && theline[0] != '{')
8402 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00008403 n = cin_is_cpp_baseclass(&col);
Bram Moolenaar18144c82006-04-12 21:52:12 +00008404 l = ml_get_curline();
8405 }
8406 if (n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008407 {
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00008408 /* XXX */
8409 amount = get_baseclass_amount(col, ind_maxparen,
8410 ind_maxcomment, ind_cpp_baseclass);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008411 break;
8412 }
8413
8414 /*
8415 * Skip preprocessor directives and blank lines.
8416 */
8417 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
8418 continue;
8419
8420 if (cin_nocode(l))
8421 continue;
8422
8423 /*
8424 * If the previous line ends in ',', use one level of
8425 * indentation:
8426 * int foo,
8427 * bar;
8428 * do this before checking for '}' in case of eg.
8429 * enum foobar
8430 * {
8431 * ...
8432 * } foo,
8433 * bar;
8434 */
8435 n = 0;
8436 if (cin_ends_in(l, (char_u *)",", NULL)
8437 || (*l != NUL && (n = l[STRLEN(l) - 1]) == '\\'))
8438 {
8439 /* take us back to opening paren */
8440 if (find_last_paren(l, '(', ')')
8441 && (trypos = find_match_paren(ind_maxparen,
8442 ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008443 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008444
8445 /* For a line ending in ',' that is a continuation line go
8446 * back to the first line with a backslash:
8447 * char *foo = "bla\
8448 * bla",
8449 * here;
8450 */
8451 while (n == 0 && curwin->w_cursor.lnum > 1)
8452 {
8453 l = ml_get(curwin->w_cursor.lnum - 1);
8454 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
8455 break;
8456 --curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008457 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008458 }
8459
8460 amount = get_indent(); /* XXX */
8461
8462 if (amount == 0)
8463 amount = cin_first_id_amount();
8464 if (amount == 0)
8465 amount = ind_continuation;
8466 break;
8467 }
8468
8469 /*
8470 * If the line looks like a function declaration, and we're
8471 * not in a comment, put it the left margin.
8472 */
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008473 if (cin_isfuncdecl(NULL, cur_curpos.lnum, 0,
8474 ind_maxparen, ind_maxcomment)) /* XXX */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008475 break;
8476 l = ml_get_curline();
8477
8478 /*
8479 * Finding the closing '}' of a previous function. Put
8480 * current line at the left margin. For when 'cino' has "fs".
8481 */
8482 if (*skipwhite(l) == '}')
8483 break;
8484
8485 /* (matching {)
8486 * If the previous line ends on '};' (maybe followed by
8487 * comments) align at column 0. For example:
8488 * char *string_array[] = { "foo",
8489 * / * x * / "b};ar" }; / * foobar * /
8490 */
8491 if (cin_ends_in(l, (char_u *)"};", NULL))
8492 break;
8493
8494 /*
Bram Moolenaar3388bb42011-11-30 17:20:23 +01008495 * Find a line only has a semicolon that belongs to a previous
8496 * line ending in '}', e.g. before an #endif. Don't increase
8497 * indent then.
8498 */
8499 if (*(look = skipwhite(l)) == ';' && cin_nocode(look + 1))
8500 {
8501 pos_T curpos_save = curwin->w_cursor;
8502
8503 while (curwin->w_cursor.lnum > 1)
8504 {
8505 look = ml_get(--curwin->w_cursor.lnum);
8506 if (!(cin_nocode(look) || cin_ispreproc_cont(
8507 &look, &curwin->w_cursor.lnum)))
8508 break;
8509 }
8510 if (curwin->w_cursor.lnum > 0
8511 && cin_ends_in(look, (char_u *)"}", NULL))
8512 break;
8513
8514 curwin->w_cursor = curpos_save;
8515 }
8516
8517 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008518 * If the PREVIOUS line is a function declaration, the current
8519 * line (and the ones that follow) needs to be indented as
8520 * parameters.
8521 */
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008522 if (cin_isfuncdecl(&l, curwin->w_cursor.lnum, 0,
8523 ind_maxparen, ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008524 {
8525 amount = ind_param;
8526 break;
8527 }
8528
8529 /*
8530 * If the previous line ends in ';' and the line before the
8531 * previous line ends in ',' or '\', ident to column zero:
8532 * int foo,
8533 * bar;
8534 * indent_to_0 here;
8535 */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00008536 if (cin_ends_in(l, (char_u *)";", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008537 {
8538 l = ml_get(curwin->w_cursor.lnum - 1);
8539 if (cin_ends_in(l, (char_u *)",", NULL)
8540 || (*l != NUL && l[STRLEN(l) - 1] == '\\'))
8541 break;
8542 l = ml_get_curline();
8543 }
8544
8545 /*
8546 * Doesn't look like anything interesting -- so just
8547 * use the indent of this line.
8548 *
8549 * Position the cursor over the rightmost paren, so that
8550 * matching it will take us back to the start of the line.
8551 */
8552 find_last_paren(l, '(', ')');
8553
8554 if ((trypos = find_match_paren(ind_maxparen,
8555 ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008556 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008557 amount = get_indent(); /* XXX */
8558 break;
8559 }
8560
8561 /* add extra indent for a comment */
8562 if (cin_iscomment(theline))
8563 amount += ind_comment;
8564
8565 /* add extra indent if the previous line ended in a backslash:
8566 * "asdfasdf\
8567 * here";
8568 * char *foo = "asdf\
8569 * here";
8570 */
8571 if (cur_curpos.lnum > 1)
8572 {
8573 l = ml_get(cur_curpos.lnum - 1);
8574 if (*l != NUL && l[STRLEN(l) - 1] == '\\')
8575 {
8576 cur_amount = cin_get_equal_amount(cur_curpos.lnum - 1);
8577 if (cur_amount > 0)
8578 amount = cur_amount;
8579 else if (cur_amount == 0)
8580 amount += ind_continuation;
8581 }
8582 }
8583 }
8584 }
8585
8586theend:
8587 /* put the cursor back where it belongs */
8588 curwin->w_cursor = cur_curpos;
8589
8590 vim_free(linecopy);
8591
8592 if (amount < 0)
8593 return 0;
8594 return amount;
8595}
8596
8597 static int
8598find_match(lookfor, ourscope, ind_maxparen, ind_maxcomment)
8599 int lookfor;
8600 linenr_T ourscope;
8601 int ind_maxparen;
8602 int ind_maxcomment;
8603{
8604 char_u *look;
8605 pos_T *theirscope;
8606 char_u *mightbeif;
8607 int elselevel;
8608 int whilelevel;
8609
8610 if (lookfor == LOOKFOR_IF)
8611 {
8612 elselevel = 1;
8613 whilelevel = 0;
8614 }
8615 else
8616 {
8617 elselevel = 0;
8618 whilelevel = 1;
8619 }
8620
8621 curwin->w_cursor.col = 0;
8622
8623 while (curwin->w_cursor.lnum > ourscope + 1)
8624 {
8625 curwin->w_cursor.lnum--;
8626 curwin->w_cursor.col = 0;
8627
8628 look = cin_skipcomment(ml_get_curline());
8629 if (cin_iselse(look)
8630 || cin_isif(look)
8631 || cin_isdo(look) /* XXX */
8632 || cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
8633 {
8634 /*
8635 * if we've gone outside the braces entirely,
8636 * we must be out of scope...
8637 */
8638 theirscope = find_start_brace(ind_maxcomment); /* XXX */
8639 if (theirscope == NULL)
8640 break;
8641
8642 /*
8643 * and if the brace enclosing this is further
8644 * back than the one enclosing the else, we're
8645 * out of luck too.
8646 */
8647 if (theirscope->lnum < ourscope)
8648 break;
8649
8650 /*
8651 * and if they're enclosed in a *deeper* brace,
8652 * then we can ignore it because it's in a
8653 * different scope...
8654 */
8655 if (theirscope->lnum > ourscope)
8656 continue;
8657
8658 /*
8659 * if it was an "else" (that's not an "else if")
8660 * then we need to go back to another if, so
8661 * increment elselevel
8662 */
8663 look = cin_skipcomment(ml_get_curline());
8664 if (cin_iselse(look))
8665 {
8666 mightbeif = cin_skipcomment(look + 4);
8667 if (!cin_isif(mightbeif))
8668 ++elselevel;
8669 continue;
8670 }
8671
8672 /*
8673 * if it was a "while" then we need to go back to
8674 * another "do", so increment whilelevel. XXX
8675 */
8676 if (cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
8677 {
8678 ++whilelevel;
8679 continue;
8680 }
8681
8682 /* If it's an "if" decrement elselevel */
8683 look = cin_skipcomment(ml_get_curline());
8684 if (cin_isif(look))
8685 {
8686 elselevel--;
8687 /*
8688 * When looking for an "if" ignore "while"s that
8689 * get in the way.
8690 */
8691 if (elselevel == 0 && lookfor == LOOKFOR_IF)
8692 whilelevel = 0;
8693 }
8694
8695 /* If it's a "do" decrement whilelevel */
8696 if (cin_isdo(look))
8697 whilelevel--;
8698
8699 /*
8700 * if we've used up all the elses, then
8701 * this must be the if that we want!
8702 * match the indent level of that if.
8703 */
8704 if (elselevel <= 0 && whilelevel <= 0)
8705 {
8706 return OK;
8707 }
8708 }
8709 }
8710 return FAIL;
8711}
8712
8713# if defined(FEAT_EVAL) || defined(PROTO)
8714/*
8715 * Get indent level from 'indentexpr'.
8716 */
8717 int
8718get_expr_indent()
8719{
8720 int indent;
8721 pos_T pos;
8722 int save_State;
Bram Moolenaard1f56e62006-02-22 21:25:37 +00008723 int use_sandbox = was_set_insecurely((char_u *)"indentexpr",
8724 OPT_LOCAL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008725
8726 pos = curwin->w_cursor;
8727 set_vim_var_nr(VV_LNUM, curwin->w_cursor.lnum);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00008728 if (use_sandbox)
8729 ++sandbox;
8730 ++textlock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008731 indent = eval_to_number(curbuf->b_p_inde);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00008732 if (use_sandbox)
8733 --sandbox;
8734 --textlock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008735
8736 /* Restore the cursor position so that 'indentexpr' doesn't need to.
8737 * Pretend to be in Insert mode, allow cursor past end of line for "o"
8738 * command. */
8739 save_State = State;
8740 State = INSERT;
8741 curwin->w_cursor = pos;
8742 check_cursor();
8743 State = save_State;
8744
8745 /* If there is an error, just keep the current indent. */
8746 if (indent < 0)
8747 indent = get_indent();
8748
8749 return indent;
8750}
8751# endif
8752
8753#endif /* FEAT_CINDENT */
8754
8755#if defined(FEAT_LISP) || defined(PROTO)
8756
8757static int lisp_match __ARGS((char_u *p));
8758
8759 static int
8760lisp_match(p)
8761 char_u *p;
8762{
8763 char_u buf[LSIZE];
8764 int len;
8765 char_u *word = p_lispwords;
8766
8767 while (*word != NUL)
8768 {
8769 (void)copy_option_part(&word, buf, LSIZE, ",");
8770 len = (int)STRLEN(buf);
8771 if (STRNCMP(buf, p, len) == 0 && p[len] == ' ')
8772 return TRUE;
8773 }
8774 return FALSE;
8775}
8776
8777/*
8778 * When 'p' is present in 'cpoptions, a Vi compatible method is used.
8779 * The incompatible newer method is quite a bit better at indenting
8780 * code in lisp-like languages than the traditional one; it's still
8781 * mostly heuristics however -- Dirk van Deun, dirk@rave.org
8782 *
8783 * TODO:
8784 * Findmatch() should be adapted for lisp, also to make showmatch
8785 * work correctly: now (v5.3) it seems all C/C++ oriented:
8786 * - it does not recognize the #\( and #\) notations as character literals
8787 * - it doesn't know about comments starting with a semicolon
8788 * - it incorrectly interprets '(' as a character literal
8789 * All this messes up get_lisp_indent in some rare cases.
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008790 * Update from Sergey Khorev:
8791 * I tried to fix the first two issues.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008792 */
8793 int
8794get_lisp_indent()
8795{
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008796 pos_T *pos, realpos, paren;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008797 int amount;
8798 char_u *that;
8799 colnr_T col;
8800 colnr_T firsttry;
8801 int parencount, quotecount;
8802 int vi_lisp;
8803
8804 /* Set vi_lisp to use the vi-compatible method */
8805 vi_lisp = (vim_strchr(p_cpo, CPO_LISP) != NULL);
8806
8807 realpos = curwin->w_cursor;
8808 curwin->w_cursor.col = 0;
8809
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008810 if ((pos = findmatch(NULL, '(')) == NULL)
8811 pos = findmatch(NULL, '[');
8812 else
8813 {
8814 paren = *pos;
8815 pos = findmatch(NULL, '[');
8816 if (pos == NULL || ltp(pos, &paren))
8817 pos = &paren;
8818 }
8819 if (pos != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008820 {
8821 /* Extra trick: Take the indent of the first previous non-white
8822 * line that is at the same () level. */
8823 amount = -1;
8824 parencount = 0;
8825
8826 while (--curwin->w_cursor.lnum >= pos->lnum)
8827 {
8828 if (linewhite(curwin->w_cursor.lnum))
8829 continue;
8830 for (that = ml_get_curline(); *that != NUL; ++that)
8831 {
8832 if (*that == ';')
8833 {
8834 while (*(that + 1) != NUL)
8835 ++that;
8836 continue;
8837 }
8838 if (*that == '\\')
8839 {
8840 if (*(that + 1) != NUL)
8841 ++that;
8842 continue;
8843 }
8844 if (*that == '"' && *(that + 1) != NUL)
8845 {
Bram Moolenaar15ff6c12006-09-15 18:18:09 +00008846 while (*++that && *that != '"')
8847 {
8848 /* skipping escaped characters in the string */
8849 if (*that == '\\')
8850 {
8851 if (*++that == NUL)
8852 break;
8853 if (that[1] == NUL)
8854 {
8855 ++that;
8856 break;
8857 }
8858 }
8859 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008860 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008861 if (*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008862 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008863 else if (*that == ')' || *that == ']')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008864 --parencount;
8865 }
8866 if (parencount == 0)
8867 {
8868 amount = get_indent();
8869 break;
8870 }
8871 }
8872
8873 if (amount == -1)
8874 {
8875 curwin->w_cursor.lnum = pos->lnum;
8876 curwin->w_cursor.col = pos->col;
8877 col = pos->col;
8878
8879 that = ml_get_curline();
8880
8881 if (vi_lisp && get_indent() == 0)
8882 amount = 2;
8883 else
8884 {
8885 amount = 0;
8886 while (*that && col)
8887 {
8888 amount += lbr_chartabsize_adv(&that, (colnr_T)amount);
8889 col--;
8890 }
8891
8892 /*
8893 * Some keywords require "body" indenting rules (the
8894 * non-standard-lisp ones are Scheme special forms):
8895 *
8896 * (let ((a 1)) instead (let ((a 1))
8897 * (...)) of (...))
8898 */
8899
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008900 if (!vi_lisp && (*that == '(' || *that == '[')
8901 && lisp_match(that + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008902 amount += 2;
8903 else
8904 {
8905 that++;
8906 amount++;
8907 firsttry = amount;
8908
8909 while (vim_iswhite(*that))
8910 {
8911 amount += lbr_chartabsize(that, (colnr_T)amount);
8912 ++that;
8913 }
8914
8915 if (*that && *that != ';') /* not a comment line */
8916 {
Bram Moolenaare21877a2008-02-13 09:58:14 +00008917 /* test *that != '(' to accommodate first let/do
Bram Moolenaar071d4272004-06-13 20:20:40 +00008918 * argument if it is more than one line */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008919 if (!vi_lisp && *that != '(' && *that != '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008920 firsttry++;
8921
8922 parencount = 0;
8923 quotecount = 0;
8924
8925 if (vi_lisp
8926 || (*that != '"'
8927 && *that != '\''
8928 && *that != '#'
8929 && (*that < '0' || *that > '9')))
8930 {
8931 while (*that
8932 && (!vim_iswhite(*that)
8933 || quotecount
8934 || parencount)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008935 && (!((*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008936 && !quotecount
8937 && !parencount
8938 && vi_lisp)))
8939 {
8940 if (*that == '"')
8941 quotecount = !quotecount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008942 if ((*that == '(' || *that == '[')
8943 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008944 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008945 if ((*that == ')' || *that == ']')
8946 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008947 --parencount;
8948 if (*that == '\\' && *(that+1) != NUL)
8949 amount += lbr_chartabsize_adv(&that,
8950 (colnr_T)amount);
8951 amount += lbr_chartabsize_adv(&that,
8952 (colnr_T)amount);
8953 }
8954 }
8955 while (vim_iswhite(*that))
8956 {
8957 amount += lbr_chartabsize(that, (colnr_T)amount);
8958 that++;
8959 }
8960 if (!*that || *that == ';')
8961 amount = firsttry;
8962 }
8963 }
8964 }
8965 }
8966 }
8967 else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008968 amount = 0; /* no matching '(' or '[' found, use zero indent */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008969
8970 curwin->w_cursor = realpos;
8971
8972 return amount;
8973}
8974#endif /* FEAT_LISP */
8975
8976 void
8977prepare_to_exit()
8978{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00008979#if defined(SIGHUP) && defined(SIG_IGN)
8980 /* Ignore SIGHUP, because a dropped connection causes a read error, which
8981 * makes Vim exit and then handling SIGHUP causes various reentrance
8982 * problems. */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00008983 signal(SIGHUP, SIG_IGN);
8984#endif
8985
Bram Moolenaar071d4272004-06-13 20:20:40 +00008986#ifdef FEAT_GUI
8987 if (gui.in_use)
8988 {
8989 gui.dying = TRUE;
8990 out_trash(); /* trash any pending output */
8991 }
8992 else
8993#endif
8994 {
8995 windgoto((int)Rows - 1, 0);
8996
8997 /*
8998 * Switch terminal mode back now, so messages end up on the "normal"
8999 * screen (if there are two screens).
9000 */
9001 settmode(TMODE_COOK);
9002#ifdef WIN3264
9003 if (can_end_termcap_mode(FALSE) == TRUE)
9004#endif
9005 stoptermcap();
9006 out_flush();
9007 }
9008}
9009
9010/*
9011 * Preserve files and exit.
9012 * When called IObuff must contain a message.
9013 */
9014 void
9015preserve_exit()
9016{
9017 buf_T *buf;
9018
9019 prepare_to_exit();
9020
Bram Moolenaar4770d092006-01-12 23:22:24 +00009021 /* Setting this will prevent free() calls. That avoids calling free()
9022 * recursively when free() was invoked with a bad pointer. */
9023 really_exiting = TRUE;
9024
Bram Moolenaar071d4272004-06-13 20:20:40 +00009025 out_str(IObuff);
9026 screen_start(); /* don't know where cursor is now */
9027 out_flush();
9028
9029 ml_close_notmod(); /* close all not-modified buffers */
9030
9031 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
9032 {
9033 if (buf->b_ml.ml_mfp != NULL && buf->b_ml.ml_mfp->mf_fname != NULL)
9034 {
9035 OUT_STR(_("Vim: preserving files...\n"));
9036 screen_start(); /* don't know where cursor is now */
9037 out_flush();
9038 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
9039 break;
9040 }
9041 }
9042
9043 ml_close_all(FALSE); /* close all memfiles, without deleting */
9044
9045 OUT_STR(_("Vim: Finished.\n"));
9046
9047 getout(1);
9048}
9049
9050/*
9051 * return TRUE if "fname" exists.
9052 */
9053 int
9054vim_fexists(fname)
9055 char_u *fname;
9056{
9057 struct stat st;
9058
9059 if (mch_stat((char *)fname, &st))
9060 return FALSE;
9061 return TRUE;
9062}
9063
9064/*
9065 * Check for CTRL-C pressed, but only once in a while.
9066 * Should be used instead of ui_breakcheck() for functions that check for
9067 * each line in the file. Calling ui_breakcheck() each time takes too much
9068 * time, because it can be a system call.
9069 */
9070
9071#ifndef BREAKCHECK_SKIP
9072# ifdef FEAT_GUI /* assume the GUI only runs on fast computers */
9073# define BREAKCHECK_SKIP 200
9074# else
9075# define BREAKCHECK_SKIP 32
9076# endif
9077#endif
9078
9079static int breakcheck_count = 0;
9080
9081 void
9082line_breakcheck()
9083{
9084 if (++breakcheck_count >= BREAKCHECK_SKIP)
9085 {
9086 breakcheck_count = 0;
9087 ui_breakcheck();
9088 }
9089}
9090
9091/*
9092 * Like line_breakcheck() but check 10 times less often.
9093 */
9094 void
9095fast_breakcheck()
9096{
9097 if (++breakcheck_count >= BREAKCHECK_SKIP * 10)
9098 {
9099 breakcheck_count = 0;
9100 ui_breakcheck();
9101 }
9102}
9103
9104/*
Bram Moolenaard7834d32009-12-02 16:14:36 +00009105 * Invoke expand_wildcards() for one pattern.
9106 * Expand items like "%:h" before the expansion.
9107 * Returns OK or FAIL.
9108 */
9109 int
9110expand_wildcards_eval(pat, num_file, file, flags)
9111 char_u **pat; /* pointer to input pattern */
9112 int *num_file; /* resulting number of files */
9113 char_u ***file; /* array of resulting files */
9114 int flags; /* EW_DIR, etc. */
9115{
9116 int ret = FAIL;
9117 char_u *eval_pat = NULL;
9118 char_u *exp_pat = *pat;
9119 char_u *ignored_msg;
9120 int usedlen;
9121
9122 if (*exp_pat == '%' || *exp_pat == '#' || *exp_pat == '<')
9123 {
9124 ++emsg_off;
9125 eval_pat = eval_vars(exp_pat, exp_pat, &usedlen,
9126 NULL, &ignored_msg, NULL);
9127 --emsg_off;
9128 if (eval_pat != NULL)
9129 exp_pat = concat_str(eval_pat, exp_pat + usedlen);
9130 }
9131
9132 if (exp_pat != NULL)
9133 ret = expand_wildcards(1, &exp_pat, num_file, file, flags);
9134
9135 if (eval_pat != NULL)
9136 {
9137 vim_free(exp_pat);
9138 vim_free(eval_pat);
9139 }
9140
9141 return ret;
9142}
9143
9144/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00009145 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching
9146 * 'wildignore'.
Bram Moolenaar9e193ac2010-07-19 23:11:27 +02009147 * Returns OK or FAIL. When FAIL then "num_file" won't be set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009148 */
9149 int
9150expand_wildcards(num_pat, pat, num_file, file, flags)
9151 int num_pat; /* number of input patterns */
9152 char_u **pat; /* array of input patterns */
9153 int *num_file; /* resulting number of files */
9154 char_u ***file; /* array of resulting files */
9155 int flags; /* EW_DIR, etc. */
9156{
9157 int retval;
9158 int i, j;
9159 char_u *p;
9160 int non_suf_match; /* number without matching suffix */
9161
9162 retval = gen_expand_wildcards(num_pat, pat, num_file, file, flags);
9163
9164 /* When keeping all matches, return here */
Bram Moolenaar9e193ac2010-07-19 23:11:27 +02009165 if ((flags & EW_KEEPALL) || retval == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009166 return retval;
9167
9168#ifdef FEAT_WILDIGN
9169 /*
9170 * Remove names that match 'wildignore'.
9171 */
9172 if (*p_wig)
9173 {
9174 char_u *ffname;
9175
9176 /* check all files in (*file)[] */
9177 for (i = 0; i < *num_file; ++i)
9178 {
9179 ffname = FullName_save((*file)[i], FALSE);
9180 if (ffname == NULL) /* out of memory */
9181 break;
9182# ifdef VMS
9183 vms_remove_version(ffname);
9184# endif
9185 if (match_file_list(p_wig, (*file)[i], ffname))
9186 {
9187 /* remove this matching file from the list */
9188 vim_free((*file)[i]);
9189 for (j = i; j + 1 < *num_file; ++j)
9190 (*file)[j] = (*file)[j + 1];
9191 --*num_file;
9192 --i;
9193 }
9194 vim_free(ffname);
9195 }
9196 }
9197#endif
9198
9199 /*
9200 * Move the names where 'suffixes' match to the end.
9201 */
9202 if (*num_file > 1)
9203 {
9204 non_suf_match = 0;
9205 for (i = 0; i < *num_file; ++i)
9206 {
9207 if (!match_suffix((*file)[i]))
9208 {
9209 /*
9210 * Move the name without matching suffix to the front
9211 * of the list.
9212 */
9213 p = (*file)[i];
9214 for (j = i; j > non_suf_match; --j)
9215 (*file)[j] = (*file)[j - 1];
9216 (*file)[non_suf_match++] = p;
9217 }
9218 }
9219 }
9220
9221 return retval;
9222}
9223
9224/*
9225 * Return TRUE if "fname" matches with an entry in 'suffixes'.
9226 */
9227 int
9228match_suffix(fname)
9229 char_u *fname;
9230{
9231 int fnamelen, setsuflen;
9232 char_u *setsuf;
9233#define MAXSUFLEN 30 /* maximum length of a file suffix */
9234 char_u suf_buf[MAXSUFLEN];
9235
9236 fnamelen = (int)STRLEN(fname);
9237 setsuflen = 0;
9238 for (setsuf = p_su; *setsuf; )
9239 {
9240 setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
Bram Moolenaar055a2ba2009-07-14 19:40:21 +00009241 if (setsuflen == 0)
9242 {
9243 char_u *tail = gettail(fname);
9244
9245 /* empty entry: match name without a '.' */
9246 if (vim_strchr(tail, '.') == NULL)
9247 {
9248 setsuflen = 1;
9249 break;
9250 }
9251 }
9252 else
9253 {
9254 if (fnamelen >= setsuflen
9255 && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
9256 (size_t)setsuflen) == 0)
9257 break;
9258 setsuflen = 0;
9259 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009260 }
9261 return (setsuflen != 0);
9262}
9263
9264#if !defined(NO_EXPANDPATH) || defined(PROTO)
9265
9266# ifdef VIM_BACKTICK
9267static int vim_backtick __ARGS((char_u *p));
9268static int expand_backtick __ARGS((garray_T *gap, char_u *pat, int flags));
9269# endif
9270
9271# if defined(MSDOS) || defined(FEAT_GUI_W16) || defined(WIN3264)
9272/*
9273 * File name expansion code for MS-DOS, Win16 and Win32. It's here because
9274 * it's shared between these systems.
9275 */
9276# if defined(DJGPP) || defined(PROTO)
9277# define _cdecl /* DJGPP doesn't have this */
9278# else
9279# ifdef __BORLANDC__
9280# define _cdecl _RTLENTRYF
9281# endif
9282# endif
9283
9284/*
9285 * comparison function for qsort in dos_expandpath()
9286 */
9287 static int _cdecl
9288pstrcmp(const void *a, const void *b)
9289{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00009290 return (pathcmp(*(char **)a, *(char **)b, -1));
Bram Moolenaar071d4272004-06-13 20:20:40 +00009291}
9292
9293# ifndef WIN3264
9294 static void
9295namelowcpy(
9296 char_u *d,
9297 char_u *s)
9298{
9299# ifdef DJGPP
9300 if (USE_LONG_FNAME) /* don't lower case on Windows 95/NT systems */
9301 while (*s)
9302 *d++ = *s++;
9303 else
9304# endif
9305 while (*s)
9306 *d++ = TOLOWER_LOC(*s++);
9307 *d = NUL;
9308}
9309# endif
9310
9311/*
Bram Moolenaar231334e2005-07-25 20:46:57 +00009312 * Recursively expand one path component into all matching files and/or
9313 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009314 * Return the number of matches found.
9315 * "path" has backslashes before chars that are not to be expanded, starting
9316 * at "path[wildoff]".
Bram Moolenaar231334e2005-07-25 20:46:57 +00009317 * Return the number of matches found.
9318 * NOTE: much of this is identical to unix_expandpath(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00009319 */
9320 static int
9321dos_expandpath(
9322 garray_T *gap,
9323 char_u *path,
9324 int wildoff,
Bram Moolenaar231334e2005-07-25 20:46:57 +00009325 int flags, /* EW_* flags */
Bram Moolenaar25394022007-05-10 19:06:20 +00009326 int didstar) /* expanded "**" once already */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009327{
Bram Moolenaar231334e2005-07-25 20:46:57 +00009328 char_u *buf;
9329 char_u *path_end;
9330 char_u *p, *s, *e;
9331 int start_len = gap->ga_len;
9332 char_u *pat;
9333 regmatch_T regmatch;
9334 int starts_with_dot;
9335 int matches;
9336 int len;
9337 int starstar = FALSE;
9338 static int stardepth = 0; /* depth for "**" expansion */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009339#ifdef WIN3264
9340 WIN32_FIND_DATA fb;
9341 HANDLE hFind = (HANDLE)0;
9342# ifdef FEAT_MBYTE
9343 WIN32_FIND_DATAW wfb;
9344 WCHAR *wn = NULL; /* UCS-2 name, NULL when not used. */
9345# endif
9346#else
9347 struct ffblk fb;
9348#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009349 char_u *matchname;
Bram Moolenaar231334e2005-07-25 20:46:57 +00009350 int ok;
9351
9352 /* Expanding "**" may take a long time, check for CTRL-C. */
9353 if (stardepth > 0)
9354 {
9355 ui_breakcheck();
9356 if (got_int)
9357 return 0;
9358 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009359
9360 /* make room for file name */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009361 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009362 if (buf == NULL)
9363 return 0;
9364
9365 /*
9366 * Find the first part in the path name that contains a wildcard or a ~1.
9367 * Copy it into buf, including the preceding characters.
9368 */
9369 p = buf;
9370 s = buf;
9371 e = NULL;
9372 path_end = path;
9373 while (*path_end != NUL)
9374 {
9375 /* May ignore a wildcard that has a backslash before it; it will
9376 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
9377 if (path_end >= path + wildoff && rem_backslash(path_end))
9378 *p++ = *path_end++;
9379 else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
9380 {
9381 if (e != NULL)
9382 break;
9383 s = p + 1;
9384 }
9385 else if (path_end >= path + wildoff
9386 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
9387 e = p;
9388#ifdef FEAT_MBYTE
9389 if (has_mbyte)
9390 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00009391 len = (*mb_ptr2len)(path_end);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009392 STRNCPY(p, path_end, len);
9393 p += len;
9394 path_end += len;
9395 }
9396 else
9397#endif
9398 *p++ = *path_end++;
9399 }
9400 e = p;
9401 *e = NUL;
9402
9403 /* now we have one wildcard component between s and e */
9404 /* Remove backslashes between "wildoff" and the start of the wildcard
9405 * component. */
9406 for (p = buf + wildoff; p < s; ++p)
9407 if (rem_backslash(p))
9408 {
Bram Moolenaar8c8de832008-06-24 22:58:06 +00009409 STRMOVE(p, p + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009410 --e;
9411 --s;
9412 }
9413
Bram Moolenaar231334e2005-07-25 20:46:57 +00009414 /* Check for "**" between "s" and "e". */
9415 for (p = s; p < e; ++p)
9416 if (p[0] == '*' && p[1] == '*')
9417 starstar = TRUE;
9418
Bram Moolenaar071d4272004-06-13 20:20:40 +00009419 starts_with_dot = (*s == '.');
9420 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
9421 if (pat == NULL)
9422 {
9423 vim_free(buf);
9424 return 0;
9425 }
9426
9427 /* compile the regexp into a program */
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009428 if (flags & (EW_NOERROR | EW_NOTWILD))
Bram Moolenaarb5609832011-07-20 15:04:58 +02009429 ++emsg_silent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009430 regmatch.rm_ic = TRUE; /* Always ignore case */
9431 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009432 if (flags & (EW_NOERROR | EW_NOTWILD))
Bram Moolenaarb5609832011-07-20 15:04:58 +02009433 --emsg_silent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009434 vim_free(pat);
9435
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009436 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009437 {
9438 vim_free(buf);
9439 return 0;
9440 }
9441
9442 /* remember the pattern or file name being looked for */
9443 matchname = vim_strsave(s);
9444
Bram Moolenaar231334e2005-07-25 20:46:57 +00009445 /* If "**" is by itself, this is the first time we encounter it and more
9446 * is following then find matches without any directory. */
9447 if (!didstar && stardepth < 100 && starstar && e - s == 2
9448 && *path_end == '/')
9449 {
9450 STRCPY(s, path_end + 1);
9451 ++stardepth;
9452 (void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
9453 --stardepth;
9454 }
9455
Bram Moolenaar071d4272004-06-13 20:20:40 +00009456 /* Scan all files in the directory with "dir/ *.*" */
9457 STRCPY(s, "*.*");
9458#ifdef WIN3264
9459# ifdef FEAT_MBYTE
9460 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
9461 {
9462 /* The active codepage differs from 'encoding'. Attempt using the
9463 * wide function. If it fails because it is not implemented fall back
9464 * to the non-wide version (for Windows 98) */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009465 wn = enc_to_utf16(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009466 if (wn != NULL)
9467 {
9468 hFind = FindFirstFileW(wn, &wfb);
9469 if (hFind == INVALID_HANDLE_VALUE
9470 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
9471 {
9472 vim_free(wn);
9473 wn = NULL;
9474 }
9475 }
9476 }
9477
9478 if (wn == NULL)
9479# endif
9480 hFind = FindFirstFile(buf, &fb);
9481 ok = (hFind != INVALID_HANDLE_VALUE);
9482#else
9483 /* If we are expanding wildcards we try both files and directories */
9484 ok = (findfirst((char *)buf, &fb,
9485 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
9486#endif
9487
9488 while (ok)
9489 {
9490#ifdef WIN3264
9491# ifdef FEAT_MBYTE
9492 if (wn != NULL)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009493 p = utf16_to_enc(wfb.cFileName, NULL); /* p is allocated here */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009494 else
9495# endif
9496 p = (char_u *)fb.cFileName;
9497#else
9498 p = (char_u *)fb.ff_name;
9499#endif
9500 /* Ignore entries starting with a dot, unless when asked for. Accept
9501 * all entries found with "matchname". */
9502 if ((p[0] != '.' || starts_with_dot)
9503 && (matchname == NULL
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009504 || (regmatch.regprog != NULL
9505 && vim_regexec(&regmatch, p, (colnr_T)0))
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009506 || ((flags & EW_NOTWILD)
9507 && fnamencmp(path + (s - buf), p, e - s) == 0)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009508 {
9509#ifdef WIN3264
9510 STRCPY(s, p);
9511#else
9512 namelowcpy(s, p);
9513#endif
9514 len = (int)STRLEN(buf);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009515
9516 if (starstar && stardepth < 100)
9517 {
9518 /* For "**" in the pattern first go deeper in the tree to
9519 * find matches. */
9520 STRCPY(buf + len, "/**");
9521 STRCPY(buf + len + 3, path_end);
9522 ++stardepth;
9523 (void)dos_expandpath(gap, buf, len + 1, flags, TRUE);
9524 --stardepth;
9525 }
9526
Bram Moolenaar071d4272004-06-13 20:20:40 +00009527 STRCPY(buf + len, path_end);
9528 if (mch_has_exp_wildcard(path_end))
9529 {
9530 /* need to expand another component of the path */
9531 /* remove backslashes for the remaining components only */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009532 (void)dos_expandpath(gap, buf, len + 1, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009533 }
9534 else
9535 {
9536 /* no more wildcards, check if there is a match */
9537 /* remove backslashes for the remaining components only */
9538 if (*path_end != 0)
9539 backslash_halve(buf + len + 1);
9540 if (mch_getperm(buf) >= 0) /* add existing file */
9541 addfile(gap, buf, flags);
9542 }
9543 }
9544
9545#ifdef WIN3264
9546# ifdef FEAT_MBYTE
9547 if (wn != NULL)
9548 {
9549 vim_free(p);
9550 ok = FindNextFileW(hFind, &wfb);
9551 }
9552 else
9553# endif
9554 ok = FindNextFile(hFind, &fb);
9555#else
9556 ok = (findnext(&fb) == 0);
9557#endif
9558
9559 /* If no more matches and no match was used, try expanding the name
9560 * itself. Finds the long name of a short filename. */
9561 if (!ok && matchname != NULL && gap->ga_len == start_len)
9562 {
9563 STRCPY(s, matchname);
9564#ifdef WIN3264
9565 FindClose(hFind);
9566# ifdef FEAT_MBYTE
9567 if (wn != NULL)
9568 {
9569 vim_free(wn);
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009570 wn = enc_to_utf16(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009571 if (wn != NULL)
9572 hFind = FindFirstFileW(wn, &wfb);
9573 }
9574 if (wn == NULL)
9575# endif
9576 hFind = FindFirstFile(buf, &fb);
9577 ok = (hFind != INVALID_HANDLE_VALUE);
9578#else
9579 ok = (findfirst((char *)buf, &fb,
9580 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
9581#endif
9582 vim_free(matchname);
9583 matchname = NULL;
9584 }
9585 }
9586
9587#ifdef WIN3264
9588 FindClose(hFind);
9589# ifdef FEAT_MBYTE
9590 vim_free(wn);
9591# endif
9592#endif
9593 vim_free(buf);
9594 vim_free(regmatch.regprog);
9595 vim_free(matchname);
9596
9597 matches = gap->ga_len - start_len;
9598 if (matches > 0)
9599 qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
9600 sizeof(char_u *), pstrcmp);
9601 return matches;
9602}
9603
9604 int
9605mch_expandpath(
9606 garray_T *gap,
9607 char_u *path,
9608 int flags) /* EW_* flags */
9609{
Bram Moolenaar231334e2005-07-25 20:46:57 +00009610 return dos_expandpath(gap, path, 0, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009611}
9612# endif /* MSDOS || FEAT_GUI_W16 || WIN3264 */
9613
Bram Moolenaar231334e2005-07-25 20:46:57 +00009614#if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
9615 || defined(PROTO)
9616/*
9617 * Unix style wildcard expansion code.
9618 * It's here because it's used both for Unix and Mac.
9619 */
9620static int pstrcmp __ARGS((const void *, const void *));
9621
9622 static int
9623pstrcmp(a, b)
9624 const void *a, *b;
9625{
9626 return (pathcmp(*(char **)a, *(char **)b, -1));
9627}
9628
9629/*
9630 * Recursively expand one path component into all matching files and/or
9631 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
9632 * "path" has backslashes before chars that are not to be expanded, starting
9633 * at "path + wildoff".
9634 * Return the number of matches found.
9635 * NOTE: much of this is identical to dos_expandpath(), keep in sync!
9636 */
9637 int
9638unix_expandpath(gap, path, wildoff, flags, didstar)
9639 garray_T *gap;
9640 char_u *path;
9641 int wildoff;
9642 int flags; /* EW_* flags */
9643 int didstar; /* expanded "**" once already */
9644{
9645 char_u *buf;
9646 char_u *path_end;
9647 char_u *p, *s, *e;
9648 int start_len = gap->ga_len;
9649 char_u *pat;
9650 regmatch_T regmatch;
9651 int starts_with_dot;
9652 int matches;
9653 int len;
9654 int starstar = FALSE;
9655 static int stardepth = 0; /* depth for "**" expansion */
9656
9657 DIR *dirp;
9658 struct dirent *dp;
9659
9660 /* Expanding "**" may take a long time, check for CTRL-C. */
9661 if (stardepth > 0)
9662 {
9663 ui_breakcheck();
9664 if (got_int)
9665 return 0;
9666 }
9667
9668 /* make room for file name */
9669 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
9670 if (buf == NULL)
9671 return 0;
9672
9673 /*
9674 * Find the first part in the path name that contains a wildcard.
Bram Moolenaar2d0b92f2012-04-30 21:09:43 +02009675 * When EW_ICASE is set every letter is considered to be a wildcard.
Bram Moolenaar231334e2005-07-25 20:46:57 +00009676 * Copy it into "buf", including the preceding characters.
9677 */
9678 p = buf;
9679 s = buf;
9680 e = NULL;
9681 path_end = path;
9682 while (*path_end != NUL)
9683 {
9684 /* May ignore a wildcard that has a backslash before it; it will
9685 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
9686 if (path_end >= path + wildoff && rem_backslash(path_end))
9687 *p++ = *path_end++;
9688 else if (*path_end == '/')
9689 {
9690 if (e != NULL)
9691 break;
9692 s = p + 1;
9693 }
9694 else if (path_end >= path + wildoff
Bram Moolenaar2d0b92f2012-04-30 21:09:43 +02009695 && (vim_strchr((char_u *)"*?[{~$", *path_end) != NULL
9696#ifndef CASE_INSENSITIVE_FILENAME
9697 || ((flags & EW_ICASE)
9698 && isalpha(PTR2CHAR(path_end)))
9699#endif
9700 ))
Bram Moolenaar231334e2005-07-25 20:46:57 +00009701 e = p;
9702#ifdef FEAT_MBYTE
9703 if (has_mbyte)
9704 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00009705 len = (*mb_ptr2len)(path_end);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009706 STRNCPY(p, path_end, len);
9707 p += len;
9708 path_end += len;
9709 }
9710 else
9711#endif
9712 *p++ = *path_end++;
9713 }
9714 e = p;
9715 *e = NUL;
9716
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009717 /* Now we have one wildcard component between "s" and "e". */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009718 /* Remove backslashes between "wildoff" and the start of the wildcard
9719 * component. */
9720 for (p = buf + wildoff; p < s; ++p)
9721 if (rem_backslash(p))
9722 {
Bram Moolenaar8c8de832008-06-24 22:58:06 +00009723 STRMOVE(p, p + 1);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009724 --e;
9725 --s;
9726 }
9727
9728 /* Check for "**" between "s" and "e". */
9729 for (p = s; p < e; ++p)
9730 if (p[0] == '*' && p[1] == '*')
9731 starstar = TRUE;
9732
9733 /* convert the file pattern to a regexp pattern */
9734 starts_with_dot = (*s == '.');
9735 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
9736 if (pat == NULL)
9737 {
9738 vim_free(buf);
9739 return 0;
9740 }
9741
9742 /* compile the regexp into a program */
Bram Moolenaarcc016f52005-12-10 20:23:46 +00009743#ifdef CASE_INSENSITIVE_FILENAME
Bram Moolenaar231334e2005-07-25 20:46:57 +00009744 regmatch.rm_ic = TRUE; /* Behave like Terminal.app */
9745#else
Bram Moolenaar94950a92010-12-02 16:01:29 +01009746 if (flags & EW_ICASE)
9747 regmatch.rm_ic = TRUE; /* 'wildignorecase' set */
9748 else
9749 regmatch.rm_ic = FALSE; /* Don't ignore case */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009750#endif
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009751 if (flags & (EW_NOERROR | EW_NOTWILD))
9752 ++emsg_silent;
Bram Moolenaar231334e2005-07-25 20:46:57 +00009753 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009754 if (flags & (EW_NOERROR | EW_NOTWILD))
9755 --emsg_silent;
Bram Moolenaar231334e2005-07-25 20:46:57 +00009756 vim_free(pat);
9757
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009758 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
Bram Moolenaar231334e2005-07-25 20:46:57 +00009759 {
9760 vim_free(buf);
9761 return 0;
9762 }
9763
9764 /* If "**" is by itself, this is the first time we encounter it and more
9765 * is following then find matches without any directory. */
9766 if (!didstar && stardepth < 100 && starstar && e - s == 2
9767 && *path_end == '/')
9768 {
9769 STRCPY(s, path_end + 1);
9770 ++stardepth;
9771 (void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
9772 --stardepth;
9773 }
9774
9775 /* open the directory for scanning */
9776 *s = NUL;
9777 dirp = opendir(*buf == NUL ? "." : (char *)buf);
9778
9779 /* Find all matching entries */
9780 if (dirp != NULL)
9781 {
9782 for (;;)
9783 {
9784 dp = readdir(dirp);
9785 if (dp == NULL)
9786 break;
9787 if ((dp->d_name[0] != '.' || starts_with_dot)
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009788 && ((regmatch.regprog != NULL && vim_regexec(&regmatch,
9789 (char_u *)dp->d_name, (colnr_T)0))
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009790 || ((flags & EW_NOTWILD)
9791 && fnamencmp(path + (s - buf), dp->d_name, e - s) == 0)))
Bram Moolenaar231334e2005-07-25 20:46:57 +00009792 {
9793 STRCPY(s, dp->d_name);
9794 len = STRLEN(buf);
9795
9796 if (starstar && stardepth < 100)
9797 {
9798 /* For "**" in the pattern first go deeper in the tree to
9799 * find matches. */
9800 STRCPY(buf + len, "/**");
9801 STRCPY(buf + len + 3, path_end);
9802 ++stardepth;
9803 (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
9804 --stardepth;
9805 }
9806
9807 STRCPY(buf + len, path_end);
9808 if (mch_has_exp_wildcard(path_end)) /* handle more wildcards */
9809 {
9810 /* need to expand another component of the path */
9811 /* remove backslashes for the remaining components only */
9812 (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
9813 }
9814 else
9815 {
9816 /* no more wildcards, check if there is a match */
9817 /* remove backslashes for the remaining components only */
9818 if (*path_end != NUL)
9819 backslash_halve(buf + len + 1);
9820 if (mch_getperm(buf) >= 0) /* add existing file */
9821 {
Bram Moolenaar95e9b492006-03-15 23:04:43 +00009822#ifdef MACOS_CONVERT
Bram Moolenaar231334e2005-07-25 20:46:57 +00009823 size_t precomp_len = STRLEN(buf)+1;
9824 char_u *precomp_buf =
9825 mac_precompose_path(buf, precomp_len, &precomp_len);
Bram Moolenaar95e9b492006-03-15 23:04:43 +00009826
Bram Moolenaar231334e2005-07-25 20:46:57 +00009827 if (precomp_buf)
9828 {
9829 mch_memmove(buf, precomp_buf, precomp_len);
9830 vim_free(precomp_buf);
9831 }
9832#endif
9833 addfile(gap, buf, flags);
9834 }
9835 }
9836 }
9837 }
9838
9839 closedir(dirp);
9840 }
9841
9842 vim_free(buf);
9843 vim_free(regmatch.regprog);
9844
9845 matches = gap->ga_len - start_len;
9846 if (matches > 0)
9847 qsort(((char_u **)gap->ga_data) + start_len, matches,
9848 sizeof(char_u *), pstrcmp);
9849 return matches;
9850}
9851#endif
9852
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009853#if defined(FEAT_SEARCHPATH)
9854static int find_previous_pathsep __ARGS((char_u *path, char_u **psep));
9855static int is_unique __ARGS((char_u *maybe_unique, garray_T *gap, int i));
Bram Moolenaar162bd912010-07-28 22:29:10 +02009856static void expand_path_option __ARGS((char_u *curdir, garray_T *gap));
9857static char_u *get_path_cutoff __ARGS((char_u *fname, garray_T *gap));
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009858static void uniquefy_paths __ARGS((garray_T *gap, char_u *pattern));
9859static int expand_in_path __ARGS((garray_T *gap, char_u *pattern, int flags));
9860
9861/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009862 * Moves "*psep" back to the previous path separator in "path".
9863 * Returns FAIL is "*psep" ends up at the beginning of "path".
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009864 */
9865 static int
9866find_previous_pathsep(path, psep)
9867 char_u *path;
9868 char_u **psep;
9869{
9870 /* skip the current separator */
9871 if (*psep > path && vim_ispathsep(**psep))
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009872 --*psep;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009873
9874 /* find the previous separator */
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009875 while (*psep > path)
9876 {
9877 if (vim_ispathsep(**psep))
9878 return OK;
9879 mb_ptr_back(path, *psep);
9880 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009881
9882 return FAIL;
9883}
9884
9885/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009886 * Returns TRUE if "maybe_unique" is unique wrt other_paths in "gap".
9887 * "maybe_unique" is the end portion of "((char_u **)gap->ga_data)[i]".
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009888 */
9889 static int
9890is_unique(maybe_unique, gap, i)
9891 char_u *maybe_unique;
9892 garray_T *gap;
9893 int i;
9894{
9895 int j;
9896 int candidate_len;
9897 int other_path_len;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009898 char_u **other_paths = (char_u **)gap->ga_data;
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009899 char_u *rival;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009900
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009901 for (j = 0; j < gap->ga_len; j++)
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009902 {
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009903 if (j == i)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009904 continue; /* don't compare it with itself */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009905
Bram Moolenaar624c7aa2010-07-16 20:38:52 +02009906 candidate_len = (int)STRLEN(maybe_unique);
9907 other_path_len = (int)STRLEN(other_paths[j]);
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009908 if (other_path_len < candidate_len)
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009909 continue; /* it's different when it's shorter */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009910
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009911 rival = other_paths[j] + other_path_len - candidate_len;
Bram Moolenaarda9836c2010-08-16 21:53:27 +02009912 if (fnamecmp(maybe_unique, rival) == 0
9913 && (rival == other_paths[j] || vim_ispathsep(*(rival - 1))))
Bram Moolenaar162bd912010-07-28 22:29:10 +02009914 return FALSE; /* match */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009915 }
9916
Bram Moolenaar162bd912010-07-28 22:29:10 +02009917 return TRUE; /* no match found */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009918}
9919
9920/*
Bram Moolenaar1a509df2010-08-01 17:59:57 +02009921 * Split the 'path' option into an array of strings in garray_T. Relative
Bram Moolenaar162bd912010-07-28 22:29:10 +02009922 * paths are expanded to their equivalent fullpath. This includes the "."
9923 * (relative to current buffer directory) and empty path (relative to current
9924 * directory) notations.
9925 *
9926 * TODO: handle upward search (;) and path limiter (**N) notations by
9927 * expanding each into their equivalent path(s).
9928 */
9929 static void
9930expand_path_option(curdir, gap)
9931 char_u *curdir;
9932 garray_T *gap;
9933{
9934 char_u *path_option = *curbuf->b_p_path == NUL
9935 ? p_path : curbuf->b_p_path;
9936 char_u *buf;
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009937 char_u *p;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009938 int len;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009939
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +02009940 if ((buf = alloc((int)MAXPATHL)) == NULL)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009941 return;
9942
9943 while (*path_option != NUL)
9944 {
9945 copy_option_part(&path_option, buf, MAXPATHL, " ,");
9946
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009947 if (buf[0] == '.' && (buf[1] == NUL || vim_ispathsep(buf[1])))
Bram Moolenaar162bd912010-07-28 22:29:10 +02009948 {
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009949 /* Relative to current buffer:
9950 * "/path/file" + "." -> "/path/"
9951 * "/path/file" + "./subdir" -> "/path/subdir" */
Bram Moolenaar162bd912010-07-28 22:29:10 +02009952 if (curbuf->b_ffname == NULL)
9953 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009954 p = gettail(curbuf->b_ffname);
9955 len = (int)(p - curbuf->b_ffname);
9956 if (len + (int)STRLEN(buf) >= MAXPATHL)
9957 continue;
9958 if (buf[1] == NUL)
9959 buf[len] = NUL;
9960 else
9961 STRMOVE(buf + len, buf + 2);
9962 mch_memmove(buf, curbuf->b_ffname, len);
9963 simplify_filename(buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009964 }
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009965 else if (buf[0] == NUL)
9966 /* relative to current directory */
Bram Moolenaar162bd912010-07-28 22:29:10 +02009967 STRCPY(buf, curdir);
Bram Moolenaar84f888a2010-08-05 21:40:16 +02009968 else if (path_with_url(buf))
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009969 /* URL can't be used here */
Bram Moolenaar84f888a2010-08-05 21:40:16 +02009970 continue;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009971 else if (!mch_isFullName(buf))
9972 {
9973 /* Expand relative path to their full path equivalent */
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009974 len = (int)STRLEN(curdir);
9975 if (len + (int)STRLEN(buf) + 3 > MAXPATHL)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009976 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009977 STRMOVE(buf + len + 1, buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009978 STRCPY(buf, curdir);
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009979 buf[len] = PATHSEP;
Bram Moolenaar57adda12010-08-03 22:11:29 +02009980 simplify_filename(buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009981 }
9982
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009983 if (ga_grow(gap, 1) == FAIL)
9984 break;
9985 p = vim_strsave(buf);
9986 if (p == NULL)
9987 break;
9988 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009989 }
9990
9991 vim_free(buf);
9992}
9993
9994/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009995 * Returns a pointer to the file or directory name in "fname" that matches the
9996 * longest path in "ga"p, or NULL if there is no match. For example:
Bram Moolenaar162bd912010-07-28 22:29:10 +02009997 *
9998 * path: /foo/bar/baz
9999 * fname: /foo/bar/baz/quux.txt
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010000 * returns: ^this
Bram Moolenaar162bd912010-07-28 22:29:10 +020010001 */
10002 static char_u *
10003get_path_cutoff(fname, gap)
10004 char_u *fname;
10005 garray_T *gap;
10006{
10007 int i;
10008 int maxlen = 0;
10009 char_u **path_part = (char_u **)gap->ga_data;
10010 char_u *cutoff = NULL;
10011
10012 for (i = 0; i < gap->ga_len; i++)
10013 {
10014 int j = 0;
10015
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010016 while ((fname[j] == path_part[i][j]
Bram Moolenaar2d7c47d2010-08-10 19:50:26 +020010017# if defined(MSWIN) || defined(MSDOS)
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010018 || (vim_ispathsep(fname[j]) && vim_ispathsep(path_part[i][j]))
10019#endif
10020 ) && fname[j] != NUL && path_part[i][j] != NUL)
Bram Moolenaar162bd912010-07-28 22:29:10 +020010021 j++;
10022 if (j > maxlen)
10023 {
10024 maxlen = j;
10025 cutoff = &fname[j];
10026 }
10027 }
10028
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010029 /* skip to the file or directory name */
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010030 if (cutoff != NULL)
Bram Moolenaar31710262010-08-13 13:36:15 +020010031 while (vim_ispathsep(*cutoff))
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010032 mb_ptr_adv(cutoff);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010033
10034 return cutoff;
10035}
10036
10037/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010038 * Sorts, removes duplicates and modifies all the fullpath names in "gap" so
10039 * that they are unique with respect to each other while conserving the part
10040 * that matches the pattern. Beware, this is at least O(n^2) wrt "gap->ga_len".
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010041 */
10042 static void
10043uniquefy_paths(gap, pattern)
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +020010044 garray_T *gap;
10045 char_u *pattern;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010046{
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +020010047 int i;
10048 int len;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010049 char_u **fnames = (char_u **)gap->ga_data;
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010050 int sort_again = FALSE;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010051 char_u *pat;
10052 char_u *file_pattern;
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010053 char_u *curdir;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010054 regmatch_T regmatch;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010055 garray_T path_ga;
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010056 char_u **in_curdir = NULL;
10057 char_u *short_name;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010058
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +020010059 remove_duplicates(gap);
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010060 ga_init2(&path_ga, (int)sizeof(char_u *), 1);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010061
10062 /*
10063 * We need to prepend a '*' at the beginning of file_pattern so that the
10064 * regex matches anywhere in the path. FIXME: is this valid for all
Bram Moolenaarb31e4382010-07-24 16:01:56 +020010065 * possible patterns?
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010066 */
Bram Moolenaar624c7aa2010-07-16 20:38:52 +020010067 len = (int)STRLEN(pattern);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010068 file_pattern = alloc(len + 2);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010069 if (file_pattern == NULL)
10070 return;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010071 file_pattern[0] = '*';
Bram Moolenaar162bd912010-07-28 22:29:10 +020010072 file_pattern[1] = NUL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010073 STRCAT(file_pattern, pattern);
10074 pat = file_pat_to_reg_pat(file_pattern, NULL, NULL, TRUE);
10075 vim_free(file_pattern);
Bram Moolenaarb31e4382010-07-24 16:01:56 +020010076 if (pat == NULL)
10077 return;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010078
Bram Moolenaarb31e4382010-07-24 16:01:56 +020010079 regmatch.rm_ic = TRUE; /* always ignore case */
10080 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
10081 vim_free(pat);
10082 if (regmatch.regprog == NULL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010083 return;
10084
Bram Moolenaar162bd912010-07-28 22:29:10 +020010085 if ((curdir = alloc((int)(MAXPATHL))) == NULL)
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010086 goto theend;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010087 mch_dirname(curdir, MAXPATHL);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010088 expand_path_option(curdir, &path_ga);
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010089
10090 in_curdir = (char_u **)alloc_clear(gap->ga_len * sizeof(char_u *));
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010091 if (in_curdir == NULL)
10092 goto theend;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010093
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010094 for (i = 0; i < gap->ga_len && !got_int; i++)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010095 {
Bram Moolenaar162bd912010-07-28 22:29:10 +020010096 char_u *path = fnames[i];
10097 int is_in_curdir;
Bram Moolenaar31710262010-08-13 13:36:15 +020010098 char_u *dir_end = gettail_dir(path);
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010099 char_u *pathsep_p;
10100 char_u *path_cutoff;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010101
Bram Moolenaar624c7aa2010-07-16 20:38:52 +020010102 len = (int)STRLEN(path);
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010103 is_in_curdir = fnamencmp(curdir, path, dir_end - path) == 0
Bram Moolenaar162bd912010-07-28 22:29:10 +020010104 && curdir[dir_end - path] == NUL;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010105 if (is_in_curdir)
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010106 in_curdir[i] = vim_strsave(path);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010107
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010108 /* Shorten the filename while maintaining its uniqueness */
10109 path_cutoff = get_path_cutoff(path, &path_ga);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010110
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010111 /* we start at the end of the path */
10112 pathsep_p = path + len - 1;
10113
10114 while (find_previous_pathsep(path, &pathsep_p))
10115 if (vim_regexec(&regmatch, pathsep_p + 1, (colnr_T)0)
10116 && is_unique(pathsep_p + 1, gap, i)
10117 && path_cutoff != NULL && pathsep_p + 1 >= path_cutoff)
10118 {
10119 sort_again = TRUE;
10120 mch_memmove(path, pathsep_p + 1, STRLEN(pathsep_p));
10121 break;
10122 }
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010123
10124 if (mch_isFullName(path))
10125 {
10126 /*
10127 * Last resort: shorten relative to curdir if possible.
10128 * 'possible' means:
10129 * 1. It is under the current directory.
10130 * 2. The result is actually shorter than the original.
10131 *
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010132 * Before curdir After
10133 * /foo/bar/file.txt /foo/bar ./file.txt
10134 * c:\foo\bar\file.txt c:\foo\bar .\file.txt
10135 * /file.txt / /file.txt
10136 * c:\file.txt c:\ .\file.txt
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010137 */
10138 short_name = shorten_fname(path, curdir);
Bram Moolenaar31710262010-08-13 13:36:15 +020010139 if (short_name != NULL && short_name > path + 1
10140#if defined(MSWIN) || defined(MSDOS)
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010141 /* On windows,
Bram Moolenaar31710262010-08-13 13:36:15 +020010142 * shorten_fname("c:\a\a.txt", "c:\a\b")
Bram Moolenaar31710262010-08-13 13:36:15 +020010143 * returns "\a\a.txt", which is not really the short
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010144 * name, hence: */
Bram Moolenaar31710262010-08-13 13:36:15 +020010145 && !vim_ispathsep(*short_name)
10146#endif
10147 )
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010148 {
10149 STRCPY(path, ".");
10150 add_pathsep(path);
Bram Moolenaarcda000e2010-08-14 13:34:39 +020010151 STRMOVE(path + STRLEN(path), short_name);
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010152 }
10153 }
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010154 ui_breakcheck();
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010155 }
10156
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010157 /* Shorten filenames in /in/current/directory/{filename} */
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010158 for (i = 0; i < gap->ga_len && !got_int; i++)
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010159 {
10160 char_u *rel_path;
10161 char_u *path = in_curdir[i];
10162
10163 if (path == NULL)
10164 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010165
10166 /* If the {filename} is not unique, change it to ./{filename}.
10167 * Else reduce it to {filename} */
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010168 short_name = shorten_fname(path, curdir);
10169 if (short_name == NULL)
10170 short_name = path;
10171 if (is_unique(short_name, gap, i))
10172 {
10173 STRCPY(fnames[i], short_name);
10174 continue;
10175 }
10176
10177 rel_path = alloc((int)(STRLEN(short_name) + STRLEN(PATHSEPSTR) + 2));
10178 if (rel_path == NULL)
10179 goto theend;
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010180 STRCPY(rel_path, ".");
10181 add_pathsep(rel_path);
10182 STRCAT(rel_path, short_name);
10183
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010184 vim_free(fnames[i]);
10185 fnames[i] = rel_path;
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010186 sort_again = TRUE;
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010187 ui_breakcheck();
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010188 }
10189
Bram Moolenaar162bd912010-07-28 22:29:10 +020010190theend:
10191 vim_free(curdir);
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010192 if (in_curdir != NULL)
10193 {
10194 for (i = 0; i < gap->ga_len; i++)
10195 vim_free(in_curdir[i]);
10196 vim_free(in_curdir);
10197 }
Bram Moolenaar162bd912010-07-28 22:29:10 +020010198 ga_clear_strings(&path_ga);
Bram Moolenaarb31e4382010-07-24 16:01:56 +020010199 vim_free(regmatch.regprog);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010200
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010201 if (sort_again)
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +020010202 remove_duplicates(gap);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010203}
10204
10205/*
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010206 * Calls globpath() with 'path' values for the given pattern and stores the
10207 * result in "gap".
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010208 * Returns the total number of matches.
10209 */
10210 static int
10211expand_in_path(gap, pattern, flags)
10212 garray_T *gap;
10213 char_u *pattern;
10214 int flags; /* EW_* flags */
10215{
Bram Moolenaar162bd912010-07-28 22:29:10 +020010216 char_u *curdir;
10217 garray_T path_ga;
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010218 char_u *files = NULL;
10219 char_u *s; /* start */
10220 char_u *e; /* end */
10221 char_u *paths = NULL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010222
Bram Moolenaar7f0f6212010-08-03 22:21:00 +020010223 if ((curdir = alloc((unsigned)MAXPATHL)) == NULL)
Bram Moolenaar162bd912010-07-28 22:29:10 +020010224 return 0;
10225 mch_dirname(curdir, MAXPATHL);
10226
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010227 ga_init2(&path_ga, (int)sizeof(char_u *), 1);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010228 expand_path_option(curdir, &path_ga);
10229 vim_free(curdir);
Bram Moolenaar006d2b02010-08-04 12:39:44 +020010230 if (path_ga.ga_len == 0)
10231 return 0;
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010232
10233 paths = ga_concat_strings(&path_ga);
10234 ga_clear_strings(&path_ga);
10235 if (paths == NULL)
Bram Moolenaar7f0f6212010-08-03 22:21:00 +020010236 return 0;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010237
Bram Moolenaar94950a92010-12-02 16:01:29 +010010238 files = globpath(paths, pattern, (flags & EW_ICASE) ? WILD_ICASE : 0);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010239 vim_free(paths);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010240 if (files == NULL)
10241 return 0;
10242
10243 /* Copy each path in files into gap */
10244 s = e = files;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010245 while (*s != NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010246 {
Bram Moolenaar162bd912010-07-28 22:29:10 +020010247 while (*e != '\n' && *e != NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010248 e++;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010249 if (*e == NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010250 {
10251 addfile(gap, s, flags);
10252 break;
10253 }
10254 else
10255 {
10256 /* *e is '\n' */
Bram Moolenaar162bd912010-07-28 22:29:10 +020010257 *e = NUL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010258 addfile(gap, s, flags);
10259 e++;
10260 s = e;
10261 }
10262 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010263 vim_free(files);
10264
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010265 return gap->ga_len;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010266}
10267#endif
10268
Bram Moolenaar1587a1e2010-07-29 20:59:59 +020010269#if defined(FEAT_SEARCHPATH) || defined(FEAT_CMDL_COMPL) || defined(PROTO)
10270/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010271 * Sort "gap" and remove duplicate entries. "gap" is expected to contain a
10272 * list of file names in allocated memory.
Bram Moolenaar1587a1e2010-07-29 20:59:59 +020010273 */
10274 void
10275remove_duplicates(gap)
10276 garray_T *gap;
10277{
10278 int i;
10279 int j;
10280 char_u **fnames = (char_u **)gap->ga_data;
10281
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010282 sort_strings(fnames, gap->ga_len);
Bram Moolenaar1587a1e2010-07-29 20:59:59 +020010283 for (i = gap->ga_len - 1; i > 0; --i)
10284 if (fnamecmp(fnames[i - 1], fnames[i]) == 0)
10285 {
10286 vim_free(fnames[i]);
10287 for (j = i + 1; j < gap->ga_len; ++j)
10288 fnames[j - 1] = fnames[j];
10289 --gap->ga_len;
10290 }
10291}
10292#endif
10293
Bram Moolenaar071d4272004-06-13 20:20:40 +000010294/*
10295 * Generic wildcard expansion code.
10296 *
10297 * Characters in "pat" that should not be expanded must be preceded with a
10298 * backslash. E.g., "/path\ with\ spaces/my\*star*"
10299 *
10300 * Return FAIL when no single file was found. In this case "num_file" is not
10301 * set, and "file" may contain an error message.
10302 * Return OK when some files found. "num_file" is set to the number of
10303 * matches, "file" to the array of matches. Call FreeWild() later.
10304 */
10305 int
10306gen_expand_wildcards(num_pat, pat, num_file, file, flags)
10307 int num_pat; /* number of input patterns */
10308 char_u **pat; /* array of input patterns */
10309 int *num_file; /* resulting number of files */
10310 char_u ***file; /* array of resulting files */
10311 int flags; /* EW_* flags */
10312{
10313 int i;
10314 garray_T ga;
10315 char_u *p;
10316 static int recursive = FALSE;
10317 int add_pat;
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010318#if defined(FEAT_SEARCHPATH)
10319 int did_expand_in_path = FALSE;
10320#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000010321
10322 /*
10323 * expand_env() is called to expand things like "~user". If this fails,
10324 * it calls ExpandOne(), which brings us back here. In this case, always
10325 * call the machine specific expansion function, if possible. Otherwise,
10326 * return FAIL.
10327 */
10328 if (recursive)
10329#ifdef SPECIAL_WILDCHAR
10330 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
10331#else
10332 return FAIL;
10333#endif
10334
10335#ifdef SPECIAL_WILDCHAR
10336 /*
10337 * If there are any special wildcard characters which we cannot handle
10338 * here, call machine specific function for all the expansion. This
10339 * avoids starting the shell for each argument separately.
10340 * For `=expr` do use the internal function.
10341 */
10342 for (i = 0; i < num_pat; i++)
10343 {
10344 if (vim_strpbrk(pat[i], (char_u *)SPECIAL_WILDCHAR) != NULL
10345# ifdef VIM_BACKTICK
10346 && !(vim_backtick(pat[i]) && pat[i][1] == '=')
10347# endif
10348 )
10349 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
10350 }
10351#endif
10352
10353 recursive = TRUE;
10354
10355 /*
10356 * The matching file names are stored in a growarray. Init it empty.
10357 */
10358 ga_init2(&ga, (int)sizeof(char_u *), 30);
10359
10360 for (i = 0; i < num_pat; ++i)
10361 {
10362 add_pat = -1;
10363 p = pat[i];
10364
10365#ifdef VIM_BACKTICK
10366 if (vim_backtick(p))
10367 add_pat = expand_backtick(&ga, p, flags);
10368 else
10369#endif
10370 {
10371 /*
10372 * First expand environment variables, "~/" and "~user/".
10373 */
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010374 if (vim_strchr(p, '$') != NULL || *p == '~')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010375 {
Bram Moolenaar9f0545d2007-09-26 20:36:32 +000010376 p = expand_env_save_opt(p, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010377 if (p == NULL)
10378 p = pat[i];
10379#ifdef UNIX
10380 /*
10381 * On Unix, if expand_env() can't expand an environment
10382 * variable, use the shell to do that. Discard previously
10383 * found file names and start all over again.
10384 */
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010385 else if (vim_strchr(p, '$') != NULL || *p == '~')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010386 {
10387 vim_free(p);
Bram Moolenaar782027e2009-06-24 14:25:49 +000010388 ga_clear_strings(&ga);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010389 i = mch_expand_wildcards(num_pat, pat, num_file, file,
10390 flags);
10391 recursive = FALSE;
10392 return i;
10393 }
10394#endif
10395 }
10396
10397 /*
10398 * If there are wildcards: Expand file names and add each match to
10399 * the list. If there is no match, and EW_NOTFOUND is given, add
10400 * the pattern.
10401 * If there are no wildcards: Add the file name if it exists or
10402 * when EW_NOTFOUND is given.
10403 */
10404 if (mch_has_exp_wildcard(p))
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010405 {
10406#if defined(FEAT_SEARCHPATH)
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010407 if ((flags & EW_PATH)
10408 && !mch_isFullName(p)
10409 && !(p[0] == '.'
10410 && (vim_ispathsep(p[1])
10411 || (p[1] == '.' && vim_ispathsep(p[2]))))
10412 )
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010413 {
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010414 /* :find completion where 'path' is used.
10415 * Recursiveness is OK here. */
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010416 recursive = FALSE;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010417 add_pat = expand_in_path(&ga, p, flags);
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010418 recursive = TRUE;
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010419 did_expand_in_path = TRUE;
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010420 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010421 else
10422#endif
10423 add_pat = mch_expandpath(&ga, p, flags);
10424 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010425 }
10426
10427 if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
10428 {
10429 char_u *t = backslash_halve_save(p);
10430
10431#if defined(MACOS_CLASSIC)
10432 slash_to_colon(t);
10433#endif
10434 /* When EW_NOTFOUND is used, always add files and dirs. Makes
10435 * "vim c:/" work. */
10436 if (flags & EW_NOTFOUND)
10437 addfile(&ga, t, flags | EW_DIR | EW_FILE);
10438 else if (mch_getperm(t) >= 0)
10439 addfile(&ga, t, flags);
10440 vim_free(t);
10441 }
10442
Bram Moolenaarb28ebbc2010-07-14 16:59:57 +020010443#if defined(FEAT_SEARCHPATH)
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010444 if (did_expand_in_path && ga.ga_len > 0 && (flags & EW_PATH))
Bram Moolenaarb28ebbc2010-07-14 16:59:57 +020010445 uniquefy_paths(&ga, p);
10446#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000010447 if (p != pat[i])
10448 vim_free(p);
10449 }
10450
10451 *num_file = ga.ga_len;
10452 *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data : (char_u **)"";
10453
10454 recursive = FALSE;
10455
10456 return (ga.ga_data != NULL) ? OK : FAIL;
10457}
10458
10459# ifdef VIM_BACKTICK
10460
10461/*
10462 * Return TRUE if we can expand this backtick thing here.
10463 */
10464 static int
10465vim_backtick(p)
10466 char_u *p;
10467{
10468 return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
10469}
10470
10471/*
10472 * Expand an item in `backticks` by executing it as a command.
10473 * Currently only works when pat[] starts and ends with a `.
10474 * Returns number of file names found.
10475 */
10476 static int
10477expand_backtick(gap, pat, flags)
10478 garray_T *gap;
10479 char_u *pat;
10480 int flags; /* EW_* flags */
10481{
10482 char_u *p;
10483 char_u *cmd;
10484 char_u *buffer;
10485 int cnt = 0;
10486 int i;
10487
10488 /* Create the command: lop off the backticks. */
10489 cmd = vim_strnsave(pat + 1, (int)STRLEN(pat) - 2);
10490 if (cmd == NULL)
10491 return 0;
10492
10493#ifdef FEAT_EVAL
10494 if (*cmd == '=') /* `={expr}`: Expand expression */
Bram Moolenaar362e1a32006-03-06 23:29:24 +000010495 buffer = eval_to_string(cmd + 1, &p, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010496 else
10497#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010498 buffer = get_cmd_output(cmd, NULL,
10499 (flags & EW_SILENT) ? SHELL_SILENT : 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010500 vim_free(cmd);
10501 if (buffer == NULL)
10502 return 0;
10503
10504 cmd = buffer;
10505 while (*cmd != NUL)
10506 {
10507 cmd = skipwhite(cmd); /* skip over white space */
10508 p = cmd;
10509 while (*p != NUL && *p != '\r' && *p != '\n') /* skip over entry */
10510 ++p;
10511 /* add an entry if it is not empty */
10512 if (p > cmd)
10513 {
10514 i = *p;
10515 *p = NUL;
10516 addfile(gap, cmd, flags);
10517 *p = i;
10518 ++cnt;
10519 }
10520 cmd = p;
10521 while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
10522 ++cmd;
10523 }
10524
10525 vim_free(buffer);
10526 return cnt;
10527}
10528# endif /* VIM_BACKTICK */
10529
10530/*
10531 * Add a file to a file list. Accepted flags:
10532 * EW_DIR add directories
10533 * EW_FILE add files
Bram Moolenaar1f35bf92006-03-07 22:38:47 +000010534 * EW_EXEC add executable files
Bram Moolenaar071d4272004-06-13 20:20:40 +000010535 * EW_NOTFOUND add even when it doesn't exist
10536 * EW_ADDSLASH add slash after directory name
10537 */
10538 void
10539addfile(gap, f, flags)
10540 garray_T *gap;
10541 char_u *f; /* filename */
10542 int flags;
10543{
10544 char_u *p;
10545 int isdir;
10546
10547 /* if the file/dir doesn't exist, may not add it */
10548 if (!(flags & EW_NOTFOUND) && mch_getperm(f) < 0)
10549 return;
10550
10551#ifdef FNAME_ILLEGAL
10552 /* if the file/dir contains illegal characters, don't add it */
10553 if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
10554 return;
10555#endif
10556
10557 isdir = mch_isdir(f);
10558 if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
10559 return;
10560
Bram Moolenaar1f35bf92006-03-07 22:38:47 +000010561 /* If the file isn't executable, may not add it. Do accept directories. */
10562 if (!isdir && (flags & EW_EXEC) && !mch_can_exe(f))
10563 return;
10564
Bram Moolenaar071d4272004-06-13 20:20:40 +000010565 /* Make room for another item in the file list. */
10566 if (ga_grow(gap, 1) == FAIL)
10567 return;
10568
10569 p = alloc((unsigned)(STRLEN(f) + 1 + isdir));
10570 if (p == NULL)
10571 return;
10572
10573 STRCPY(p, f);
10574#ifdef BACKSLASH_IN_FILENAME
10575 slash_adjust(p);
10576#endif
10577 /*
10578 * Append a slash or backslash after directory names if none is present.
10579 */
10580#ifndef DONT_ADD_PATHSEP_TO_DIR
10581 if (isdir && (flags & EW_ADDSLASH))
10582 add_pathsep(p);
10583#endif
10584 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010585}
10586#endif /* !NO_EXPANDPATH */
10587
10588#if defined(VIM_BACKTICK) || defined(FEAT_EVAL) || defined(PROTO)
10589
10590#ifndef SEEK_SET
10591# define SEEK_SET 0
10592#endif
10593#ifndef SEEK_END
10594# define SEEK_END 2
10595#endif
10596
10597/*
10598 * Get the stdout of an external command.
10599 * Returns an allocated string, or NULL for error.
10600 */
10601 char_u *
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010602get_cmd_output(cmd, infile, flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010603 char_u *cmd;
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010604 char_u *infile; /* optional input file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010605 int flags; /* can be SHELL_SILENT */
10606{
10607 char_u *tempname;
10608 char_u *command;
10609 char_u *buffer = NULL;
10610 int len;
10611 int i = 0;
10612 FILE *fd;
10613
10614 if (check_restricted() || check_secure())
10615 return NULL;
10616
10617 /* get a name for the temp file */
10618 if ((tempname = vim_tempname('o')) == NULL)
10619 {
10620 EMSG(_(e_notmp));
10621 return NULL;
10622 }
10623
10624 /* Add the redirection stuff */
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010625 command = make_filter_cmd(cmd, infile, tempname);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010626 if (command == NULL)
10627 goto done;
10628
10629 /*
10630 * Call the shell to execute the command (errors are ignored).
10631 * Don't check timestamps here.
10632 */
10633 ++no_check_timestamps;
10634 call_shell(command, SHELL_DOOUT | SHELL_EXPAND | flags);
10635 --no_check_timestamps;
10636
10637 vim_free(command);
10638
10639 /*
10640 * read the names from the file into memory
10641 */
10642# ifdef VMS
Bram Moolenaar25394022007-05-10 19:06:20 +000010643 /* created temporary file is not always readable as binary */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010644 fd = mch_fopen((char *)tempname, "r");
10645# else
10646 fd = mch_fopen((char *)tempname, READBIN);
10647# endif
10648
10649 if (fd == NULL)
10650 {
10651 EMSG2(_(e_notopen), tempname);
10652 goto done;
10653 }
10654
10655 fseek(fd, 0L, SEEK_END);
10656 len = ftell(fd); /* get size of temp file */
10657 fseek(fd, 0L, SEEK_SET);
10658
10659 buffer = alloc(len + 1);
10660 if (buffer != NULL)
10661 i = (int)fread((char *)buffer, (size_t)1, (size_t)len, fd);
10662 fclose(fd);
10663 mch_remove(tempname);
10664 if (buffer == NULL)
10665 goto done;
10666#ifdef VMS
10667 len = i; /* VMS doesn't give us what we asked for... */
10668#endif
10669 if (i != len)
10670 {
10671 EMSG2(_(e_notread), tempname);
10672 vim_free(buffer);
10673 buffer = NULL;
10674 }
10675 else
Bram Moolenaar162bd912010-07-28 22:29:10 +020010676 buffer[len] = NUL; /* make sure the buffer is terminated */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010677
10678done:
10679 vim_free(tempname);
10680 return buffer;
10681}
10682#endif
10683
10684/*
10685 * Free the list of files returned by expand_wildcards() or other expansion
10686 * functions.
10687 */
10688 void
10689FreeWild(count, files)
10690 int count;
10691 char_u **files;
10692{
Bram Moolenaarfc1421e2006-04-20 22:17:20 +000010693 if (count <= 0 || files == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010694 return;
10695#if defined(__EMX__) && defined(__ALWAYS_HAS_TRAILING_NULL_POINTER) /* XXX */
10696 /*
10697 * Is this still OK for when other functions than expand_wildcards() have
10698 * been used???
10699 */
10700 _fnexplodefree((char **)files);
10701#else
10702 while (count--)
10703 vim_free(files[count]);
10704 vim_free(files);
10705#endif
10706}
10707
10708/*
Bram Moolenaara9dc3752010-07-11 20:46:53 +020010709 * Return TRUE when need to go to Insert mode because of 'insertmode'.
Bram Moolenaar071d4272004-06-13 20:20:40 +000010710 * Don't do this when still processing a command or a mapping.
10711 * Don't do this when inside a ":normal" command.
10712 */
10713 int
10714goto_im()
10715{
10716 return (p_im && stuff_empty() && typebuf_typed());
10717}