blob: 99881dccdfc7ea0e0ff1946fdbbb79b285b80adf [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, " ");
1332 newcol++;
1333 }
1334 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001335 STRCAT(leader, p_extra);
1336 p_extra = leader;
1337 did_ai = TRUE; /* So truncating blanks works with comments */
1338 less_cols -= lead_len;
1339 }
1340 else
1341 end_comment_pending = NUL; /* turns out there was no leader */
1342#endif
1343
1344 old_cursor = curwin->w_cursor;
1345 if (dir == BACKWARD)
1346 --curwin->w_cursor.lnum;
1347#ifdef FEAT_VREPLACE
1348 if (!(State & VREPLACE_FLAG) || old_cursor.lnum >= orig_line_count)
1349#endif
1350 {
1351 if (ml_append(curwin->w_cursor.lnum, p_extra, (colnr_T)0, FALSE)
1352 == FAIL)
1353 goto theend;
1354 /* Postpone calling changed_lines(), because it would mess up folding
1355 * with markers. */
1356 mark_adjust(curwin->w_cursor.lnum + 1, (linenr_T)MAXLNUM, 1L, 0L);
1357 did_append = TRUE;
1358 }
1359#ifdef FEAT_VREPLACE
1360 else
1361 {
1362 /*
1363 * In VREPLACE mode we are starting to replace the next line.
1364 */
1365 curwin->w_cursor.lnum++;
1366 if (curwin->w_cursor.lnum >= Insstart.lnum + vr_lines_changed)
1367 {
1368 /* In case we NL to a new line, BS to the previous one, and NL
1369 * again, we don't want to save the new line for undo twice.
1370 */
1371 (void)u_save_cursor(); /* errors are ignored! */
1372 vr_lines_changed++;
1373 }
1374 ml_replace(curwin->w_cursor.lnum, p_extra, TRUE);
1375 changed_bytes(curwin->w_cursor.lnum, 0);
1376 curwin->w_cursor.lnum--;
1377 did_append = FALSE;
1378 }
1379#endif
1380
1381 if (newindent
1382#ifdef FEAT_SMARTINDENT
1383 || did_si
1384#endif
1385 )
1386 {
1387 ++curwin->w_cursor.lnum;
1388#ifdef FEAT_SMARTINDENT
1389 if (did_si)
1390 {
1391 if (p_sr)
1392 newindent -= newindent % (int)curbuf->b_p_sw;
1393 newindent += (int)curbuf->b_p_sw;
1394 }
1395#endif
Bram Moolenaar5002c292007-07-24 13:26:15 +00001396 /* Copy the indent */
1397 if (curbuf->b_p_ci)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001398 {
1399 (void)copy_indent(newindent, saved_line);
1400
1401 /*
1402 * Set the 'preserveindent' option so that any further screwing
1403 * with the line doesn't entirely destroy our efforts to preserve
1404 * it. It gets restored at the function end.
1405 */
1406 curbuf->b_p_pi = TRUE;
1407 }
1408 else
1409 (void)set_indent(newindent, SIN_INSERT);
1410 less_cols -= curwin->w_cursor.col;
1411
1412 ai_col = curwin->w_cursor.col;
1413
1414 /*
1415 * In REPLACE mode, for each character in the new indent, there must
1416 * be a NUL on the replace stack, for when it is deleted with BS
1417 */
1418 if (REPLACE_NORMAL(State))
1419 for (n = 0; n < (int)curwin->w_cursor.col; ++n)
1420 replace_push(NUL);
1421 newcol += curwin->w_cursor.col;
1422#ifdef FEAT_SMARTINDENT
1423 if (no_si)
1424 did_si = FALSE;
1425#endif
1426 }
1427
1428#ifdef FEAT_COMMENTS
1429 /*
1430 * In REPLACE mode, for each character in the extra leader, there must be
1431 * a NUL on the replace stack, for when it is deleted with BS.
1432 */
1433 if (REPLACE_NORMAL(State))
1434 while (lead_len-- > 0)
1435 replace_push(NUL);
1436#endif
1437
1438 curwin->w_cursor = old_cursor;
1439
1440 if (dir == FORWARD)
1441 {
1442 if (trunc_line || (State & INSERT))
1443 {
1444 /* truncate current line at cursor */
1445 saved_line[curwin->w_cursor.col] = NUL;
1446 /* Remove trailing white space, unless OPENLINE_KEEPTRAIL used. */
1447 if (trunc_line && !(flags & OPENLINE_KEEPTRAIL))
1448 truncate_spaces(saved_line);
1449 ml_replace(curwin->w_cursor.lnum, saved_line, FALSE);
1450 saved_line = NULL;
1451 if (did_append)
1452 {
1453 changed_lines(curwin->w_cursor.lnum, curwin->w_cursor.col,
1454 curwin->w_cursor.lnum + 1, 1L);
1455 did_append = FALSE;
1456
1457 /* Move marks after the line break to the new line. */
1458 if (flags & OPENLINE_MARKFIX)
1459 mark_col_adjust(curwin->w_cursor.lnum,
1460 curwin->w_cursor.col + less_cols_off,
1461 1L, (long)-less_cols);
1462 }
1463 else
1464 changed_bytes(curwin->w_cursor.lnum, curwin->w_cursor.col);
1465 }
1466
1467 /*
1468 * Put the cursor on the new line. Careful: the scrollup() above may
1469 * have moved w_cursor, we must use old_cursor.
1470 */
1471 curwin->w_cursor.lnum = old_cursor.lnum + 1;
1472 }
1473 if (did_append)
1474 changed_lines(curwin->w_cursor.lnum, 0, curwin->w_cursor.lnum, 1L);
1475
1476 curwin->w_cursor.col = newcol;
1477#ifdef FEAT_VIRTUALEDIT
1478 curwin->w_cursor.coladd = 0;
1479#endif
1480
1481#if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
1482 /*
1483 * In VREPLACE mode, we are handling the replace stack ourselves, so stop
1484 * fixthisline() from doing it (via change_indent()) by telling it we're in
1485 * normal INSERT mode.
1486 */
1487 if (State & VREPLACE_FLAG)
1488 {
1489 vreplace_mode = State; /* So we know to put things right later */
1490 State = INSERT;
1491 }
1492 else
1493 vreplace_mode = 0;
1494#endif
1495#ifdef FEAT_LISP
1496 /*
1497 * May do lisp indenting.
1498 */
1499 if (!p_paste
1500# ifdef FEAT_COMMENTS
1501 && leader == NULL
1502# endif
1503 && curbuf->b_p_lisp
1504 && curbuf->b_p_ai)
1505 {
1506 fixthisline(get_lisp_indent);
1507 p = ml_get_curline();
1508 ai_col = (colnr_T)(skipwhite(p) - p);
1509 }
1510#endif
1511#ifdef FEAT_CINDENT
1512 /*
1513 * May do indenting after opening a new line.
1514 */
1515 if (!p_paste
1516 && (curbuf->b_p_cin
1517# ifdef FEAT_EVAL
1518 || *curbuf->b_p_inde != NUL
1519# endif
1520 )
1521 && in_cinkeys(dir == FORWARD
1522 ? KEY_OPEN_FORW
1523 : KEY_OPEN_BACK, ' ', linewhite(curwin->w_cursor.lnum)))
1524 {
1525 do_c_expr_indent();
1526 p = ml_get_curline();
1527 ai_col = (colnr_T)(skipwhite(p) - p);
1528 }
1529#endif
1530#if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
1531 if (vreplace_mode != 0)
1532 State = vreplace_mode;
1533#endif
1534
1535#ifdef FEAT_VREPLACE
1536 /*
1537 * Finally, VREPLACE gets the stuff on the new line, then puts back the
1538 * original line, and inserts the new stuff char by char, pushing old stuff
1539 * onto the replace stack (via ins_char()).
1540 */
1541 if (State & VREPLACE_FLAG)
1542 {
1543 /* Put new line in p_extra */
1544 p_extra = vim_strsave(ml_get_curline());
1545 if (p_extra == NULL)
1546 goto theend;
1547
1548 /* Put back original line */
1549 ml_replace(curwin->w_cursor.lnum, next_line, FALSE);
1550
1551 /* Insert new stuff into line again */
1552 curwin->w_cursor.col = 0;
1553#ifdef FEAT_VIRTUALEDIT
1554 curwin->w_cursor.coladd = 0;
1555#endif
1556 ins_bytes(p_extra); /* will call changed_bytes() */
1557 vim_free(p_extra);
1558 next_line = NULL;
1559 }
1560#endif
1561
1562 retval = TRUE; /* success! */
1563theend:
1564 curbuf->b_p_pi = saved_pi;
1565 vim_free(saved_line);
1566 vim_free(next_line);
1567 vim_free(allocated);
1568 return retval;
1569}
1570
1571#if defined(FEAT_COMMENTS) || defined(PROTO)
1572/*
1573 * get_leader_len() returns the length of the prefix of the given string
1574 * which introduces a comment. If this string is not a comment then 0 is
1575 * returned.
1576 * When "flags" is not NULL, it is set to point to the flags of the recognized
1577 * comment leader.
1578 * "backward" must be true for the "O" command.
Bram Moolenaar81340392012-06-06 16:12:59 +02001579 * If "include_space" is set, include trailing whitespace while calculating the
1580 * length.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001581 */
1582 int
Bram Moolenaar81340392012-06-06 16:12:59 +02001583get_leader_len(line, flags, backward, include_space)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001584 char_u *line;
1585 char_u **flags;
1586 int backward;
Bram Moolenaar81340392012-06-06 16:12:59 +02001587 int include_space;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001588{
1589 int i, j;
Bram Moolenaar81340392012-06-06 16:12:59 +02001590 int result;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001591 int got_com = FALSE;
1592 int found_one;
1593 char_u part_buf[COM_MAX_LEN]; /* buffer for one option part */
1594 char_u *string; /* pointer to comment string */
1595 char_u *list;
Bram Moolenaara4271d52011-05-10 13:38:27 +02001596 int middle_match_len = 0;
1597 char_u *prev_list;
Bram Moolenaar05da4282011-05-10 14:44:11 +02001598 char_u *saved_flags = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001599
Bram Moolenaar81340392012-06-06 16:12:59 +02001600 result = i = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001601 while (vim_iswhite(line[i])) /* leading white space is ignored */
1602 ++i;
1603
1604 /*
1605 * Repeat to match several nested comment strings.
1606 */
Bram Moolenaara4271d52011-05-10 13:38:27 +02001607 while (line[i] != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001608 {
1609 /*
1610 * scan through the 'comments' option for a match
1611 */
1612 found_one = FALSE;
1613 for (list = curbuf->b_p_com; *list; )
1614 {
Bram Moolenaara4271d52011-05-10 13:38:27 +02001615 /* Get one option part into part_buf[]. Advance "list" to next
1616 * one. Put "string" at start of string. */
1617 if (!got_com && flags != NULL)
1618 *flags = list; /* remember where flags started */
1619 prev_list = list;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001620 (void)copy_option_part(&list, part_buf, COM_MAX_LEN, ",");
1621 string = vim_strchr(part_buf, ':');
1622 if (string == NULL) /* missing ':', ignore this part */
1623 continue;
1624 *string++ = NUL; /* isolate flags from string */
1625
Bram Moolenaara4271d52011-05-10 13:38:27 +02001626 /* If we found a middle match previously, use that match when this
1627 * is not a middle or end. */
1628 if (middle_match_len != 0
1629 && vim_strchr(part_buf, COM_MIDDLE) == NULL
1630 && vim_strchr(part_buf, COM_END) == NULL)
1631 break;
1632
1633 /* When we already found a nested comment, only accept further
1634 * nested comments. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001635 if (got_com && vim_strchr(part_buf, COM_NEST) == NULL)
1636 continue;
1637
Bram Moolenaara4271d52011-05-10 13:38:27 +02001638 /* When 'O' flag present and using "O" command skip this one. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001639 if (backward && vim_strchr(part_buf, COM_NOBACK) != NULL)
1640 continue;
1641
Bram Moolenaara4271d52011-05-10 13:38:27 +02001642 /* Line contents and string must match.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001643 * When string starts with white space, must have some white space
1644 * (but the amount does not need to match, there might be a mix of
Bram Moolenaara4271d52011-05-10 13:38:27 +02001645 * TABs and spaces). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001646 if (vim_iswhite(string[0]))
1647 {
1648 if (i == 0 || !vim_iswhite(line[i - 1]))
Bram Moolenaara4271d52011-05-10 13:38:27 +02001649 continue; /* missing shite space */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001650 while (vim_iswhite(string[0]))
1651 ++string;
1652 }
1653 for (j = 0; string[j] != NUL && string[j] == line[i + j]; ++j)
1654 ;
1655 if (string[j] != NUL)
Bram Moolenaara4271d52011-05-10 13:38:27 +02001656 continue; /* string doesn't match */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001657
Bram Moolenaara4271d52011-05-10 13:38:27 +02001658 /* When 'b' flag used, there must be white space or an
1659 * end-of-line after the string in the line. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001660 if (vim_strchr(part_buf, COM_BLANK) != NULL
1661 && !vim_iswhite(line[i + j]) && line[i + j] != NUL)
1662 continue;
1663
Bram Moolenaara4271d52011-05-10 13:38:27 +02001664 /* We have found a match, stop searching unless this is a middle
1665 * comment. The middle comment can be a substring of the end
1666 * comment in which case it's better to return the length of the
1667 * end comment and its flags. Thus we keep searching with middle
1668 * and end matches and use an end match if it matches better. */
1669 if (vim_strchr(part_buf, COM_MIDDLE) != NULL)
1670 {
1671 if (middle_match_len == 0)
1672 {
1673 middle_match_len = j;
1674 saved_flags = prev_list;
1675 }
1676 continue;
1677 }
1678 if (middle_match_len != 0 && j > middle_match_len)
1679 /* Use this match instead of the middle match, since it's a
1680 * longer thus better match. */
1681 middle_match_len = 0;
1682
1683 if (middle_match_len == 0)
1684 i += j;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001685 found_one = TRUE;
1686 break;
1687 }
1688
Bram Moolenaara4271d52011-05-10 13:38:27 +02001689 if (middle_match_len != 0)
1690 {
1691 /* Use the previously found middle match after failing to find a
1692 * match with an end. */
1693 if (!got_com && flags != NULL)
1694 *flags = saved_flags;
1695 i += middle_match_len;
1696 found_one = TRUE;
1697 }
1698
1699 /* No match found, stop scanning. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001700 if (!found_one)
1701 break;
1702
Bram Moolenaar81340392012-06-06 16:12:59 +02001703 result = i;
1704
Bram Moolenaara4271d52011-05-10 13:38:27 +02001705 /* Include any trailing white space. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001706 while (vim_iswhite(line[i]))
1707 ++i;
1708
Bram Moolenaar81340392012-06-06 16:12:59 +02001709 if (include_space)
1710 result = i;
1711
Bram Moolenaara4271d52011-05-10 13:38:27 +02001712 /* If this comment doesn't nest, stop here. */
1713 got_com = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001714 if (vim_strchr(part_buf, COM_NEST) == NULL)
1715 break;
1716 }
Bram Moolenaar81340392012-06-06 16:12:59 +02001717 return result;
1718}
Bram Moolenaara4271d52011-05-10 13:38:27 +02001719
Bram Moolenaar81340392012-06-06 16:12:59 +02001720/*
1721 * Return the offset at which the last comment in line starts. If there is no
1722 * comment in the whole line, -1 is returned.
1723 *
1724 * When "flags" is not null, it is set to point to the flags describing the
1725 * recognized comment leader.
1726 */
1727 int
1728get_last_leader_offset(line, flags)
1729 char_u *line;
1730 char_u **flags;
1731{
1732 int result = -1;
1733 int i, j;
1734 int lower_check_bound = 0;
1735 char_u *string;
1736 char_u *com_leader;
1737 char_u *com_flags;
1738 char_u *list;
1739 int found_one;
1740 char_u part_buf[COM_MAX_LEN]; /* buffer for one option part */
1741
1742 /*
1743 * Repeat to match several nested comment strings.
1744 */
1745 i = (int)STRLEN(line);
1746 while (--i >= lower_check_bound)
1747 {
1748 /*
1749 * scan through the 'comments' option for a match
1750 */
1751 found_one = FALSE;
1752 for (list = curbuf->b_p_com; *list; )
1753 {
1754 char_u *flags_save = list;
1755
1756 /*
1757 * Get one option part into part_buf[]. Advance list to next one.
1758 * put string at start of string.
1759 */
1760 (void)copy_option_part(&list, part_buf, COM_MAX_LEN, ",");
1761 string = vim_strchr(part_buf, ':');
1762 if (string == NULL) /* If everything is fine, this cannot actually
1763 * happen. */
1764 {
1765 continue;
1766 }
1767 *string++ = NUL; /* Isolate flags from string. */
1768 com_leader = string;
1769
1770 /*
1771 * Line contents and string must match.
1772 * When string starts with white space, must have some white space
1773 * (but the amount does not need to match, there might be a mix of
1774 * TABs and spaces).
1775 */
1776 if (vim_iswhite(string[0]))
1777 {
1778 if (i == 0 || !vim_iswhite(line[i - 1]))
1779 continue;
1780 while (vim_iswhite(string[0]))
1781 ++string;
1782 }
1783 for (j = 0; string[j] != NUL && string[j] == line[i + j]; ++j)
1784 /* do nothing */;
1785 if (string[j] != NUL)
1786 continue;
1787
1788 /*
1789 * When 'b' flag used, there must be white space or an
1790 * end-of-line after the string in the line.
1791 */
1792 if (vim_strchr(part_buf, COM_BLANK) != NULL
1793 && !vim_iswhite(line[i + j]) && line[i + j] != NUL)
1794 {
1795 continue;
1796 }
1797
1798 /*
1799 * We have found a match, stop searching.
1800 */
1801 found_one = TRUE;
1802
1803 if (flags)
1804 *flags = flags_save;
1805 com_flags = flags_save;
1806
1807 break;
1808 }
1809
1810 if (found_one)
1811 {
1812 char_u part_buf2[COM_MAX_LEN]; /* buffer for one option part */
1813 int len1, len2, off;
1814
1815 result = i;
1816 /*
1817 * If this comment nests, continue searching.
1818 */
1819 if (vim_strchr(part_buf, COM_NEST) != NULL)
1820 continue;
1821
1822 lower_check_bound = i;
1823
1824 /* Let's verify whether the comment leader found is a substring
1825 * of other comment leaders. If it is, let's adjust the
1826 * lower_check_bound so that we make sure that we have determined
1827 * the comment leader correctly.
1828 */
1829
1830 while (vim_iswhite(*com_leader))
1831 ++com_leader;
1832 len1 = (int)STRLEN(com_leader);
1833
1834 for (list = curbuf->b_p_com; *list; )
1835 {
1836 char_u *flags_save = list;
1837
1838 (void)copy_option_part(&list, part_buf2, COM_MAX_LEN, ",");
1839 if (flags_save == com_flags)
1840 continue;
1841 string = vim_strchr(part_buf2, ':');
1842 ++string;
1843 while (vim_iswhite(*string))
1844 ++string;
1845 len2 = (int)STRLEN(string);
1846 if (len2 == 0)
1847 continue;
1848
1849 /* Now we have to verify whether string ends with a substring
1850 * beginning the com_leader. */
1851 for (off = (len2 > i ? i : len2); off > 0 && off + len1 > len2;)
1852 {
1853 --off;
1854 if (!STRNCMP(string + off, com_leader, len2 - off))
1855 {
1856 if (i - off < lower_check_bound)
1857 lower_check_bound = i - off;
1858 }
1859 }
1860 }
1861 }
1862 }
1863 return result;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001864}
1865#endif
1866
1867/*
1868 * Return the number of window lines occupied by buffer line "lnum".
1869 */
1870 int
1871plines(lnum)
1872 linenr_T lnum;
1873{
1874 return plines_win(curwin, lnum, TRUE);
1875}
1876
1877 int
1878plines_win(wp, lnum, winheight)
1879 win_T *wp;
1880 linenr_T lnum;
1881 int winheight; /* when TRUE limit to window height */
1882{
1883#if defined(FEAT_DIFF) || defined(PROTO)
1884 /* Check for filler lines above this buffer line. When folded the result
1885 * is one line anyway. */
1886 return plines_win_nofill(wp, lnum, winheight) + diff_check_fill(wp, lnum);
1887}
1888
1889 int
1890plines_nofill(lnum)
1891 linenr_T lnum;
1892{
1893 return plines_win_nofill(curwin, lnum, TRUE);
1894}
1895
1896 int
1897plines_win_nofill(wp, lnum, winheight)
1898 win_T *wp;
1899 linenr_T lnum;
1900 int winheight; /* when TRUE limit to window height */
1901{
1902#endif
1903 int lines;
1904
1905 if (!wp->w_p_wrap)
1906 return 1;
1907
1908#ifdef FEAT_VERTSPLIT
1909 if (wp->w_width == 0)
1910 return 1;
1911#endif
1912
1913#ifdef FEAT_FOLDING
1914 /* A folded lines is handled just like an empty line. */
1915 /* NOTE: Caller must handle lines that are MAYBE folded. */
1916 if (lineFolded(wp, lnum) == TRUE)
1917 return 1;
1918#endif
1919
1920 lines = plines_win_nofold(wp, lnum);
1921 if (winheight > 0 && lines > wp->w_height)
1922 return (int)wp->w_height;
1923 return lines;
1924}
1925
1926/*
1927 * Return number of window lines physical line "lnum" will occupy in window
1928 * "wp". Does not care about folding, 'wrap' or 'diff'.
1929 */
1930 int
1931plines_win_nofold(wp, lnum)
1932 win_T *wp;
1933 linenr_T lnum;
1934{
1935 char_u *s;
1936 long col;
1937 int width;
1938
1939 s = ml_get_buf(wp->w_buffer, lnum, FALSE);
1940 if (*s == NUL) /* empty line */
1941 return 1;
1942 col = win_linetabsize(wp, s, (colnr_T)MAXCOL);
1943
1944 /*
1945 * If list mode is on, then the '$' at the end of the line may take up one
1946 * extra column.
1947 */
1948 if (wp->w_p_list && lcs_eol != NUL)
1949 col += 1;
1950
1951 /*
Bram Moolenaar64486672010-05-16 15:46:46 +02001952 * Add column offset for 'number', 'relativenumber' and 'foldcolumn'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001953 */
1954 width = W_WIDTH(wp) - win_col_off(wp);
1955 if (width <= 0)
1956 return 32000;
1957 if (col <= width)
1958 return 1;
1959 col -= width;
1960 width += win_col_off2(wp);
1961 return (col + (width - 1)) / width + 1;
1962}
1963
1964/*
1965 * Like plines_win(), but only reports the number of physical screen lines
1966 * used from the start of the line to the given column number.
1967 */
1968 int
1969plines_win_col(wp, lnum, column)
1970 win_T *wp;
1971 linenr_T lnum;
1972 long column;
1973{
1974 long col;
1975 char_u *s;
1976 int lines = 0;
1977 int width;
1978
1979#ifdef FEAT_DIFF
1980 /* Check for filler lines above this buffer line. When folded the result
1981 * is one line anyway. */
1982 lines = diff_check_fill(wp, lnum);
1983#endif
1984
1985 if (!wp->w_p_wrap)
1986 return lines + 1;
1987
1988#ifdef FEAT_VERTSPLIT
1989 if (wp->w_width == 0)
1990 return lines + 1;
1991#endif
1992
1993 s = ml_get_buf(wp->w_buffer, lnum, FALSE);
1994
1995 col = 0;
1996 while (*s != NUL && --column >= 0)
1997 {
1998 col += win_lbr_chartabsize(wp, s, (colnr_T)col, NULL);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001999 mb_ptr_adv(s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002000 }
2001
2002 /*
2003 * If *s is a TAB, and the TAB is not displayed as ^I, and we're not in
2004 * INSERT mode, then col must be adjusted so that it represents the last
2005 * screen position of the TAB. This only fixes an error when the TAB wraps
2006 * from one screen line to the next (when 'columns' is not a multiple of
2007 * 'ts') -- webb.
2008 */
2009 if (*s == TAB && (State & NORMAL) && (!wp->w_p_list || lcs_tab1))
2010 col += win_lbr_chartabsize(wp, s, (colnr_T)col, NULL) - 1;
2011
2012 /*
Bram Moolenaar64486672010-05-16 15:46:46 +02002013 * Add column offset for 'number', 'relativenumber', 'foldcolumn', etc.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002014 */
2015 width = W_WIDTH(wp) - win_col_off(wp);
Bram Moolenaar26470632006-10-24 19:12:40 +00002016 if (width <= 0)
2017 return 9999;
2018
2019 lines += 1;
2020 if (col > width)
2021 lines += (col - width) / (width + win_col_off2(wp)) + 1;
2022 return lines;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002023}
2024
2025 int
2026plines_m_win(wp, first, last)
2027 win_T *wp;
2028 linenr_T first, last;
2029{
2030 int count = 0;
2031
2032 while (first <= last)
2033 {
2034#ifdef FEAT_FOLDING
2035 int x;
2036
2037 /* Check if there are any really folded lines, but also included lines
2038 * that are maybe folded. */
2039 x = foldedCount(wp, first, NULL);
2040 if (x > 0)
2041 {
2042 ++count; /* count 1 for "+-- folded" line */
2043 first += x;
2044 }
2045 else
2046#endif
2047 {
2048#ifdef FEAT_DIFF
2049 if (first == wp->w_topline)
2050 count += plines_win_nofill(wp, first, TRUE) + wp->w_topfill;
2051 else
2052#endif
2053 count += plines_win(wp, first, TRUE);
2054 ++first;
2055 }
2056 }
2057 return (count);
2058}
2059
2060#if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) || defined(PROTO)
2061/*
2062 * Insert string "p" at the cursor position. Stops at a NUL byte.
2063 * Handles Replace mode and multi-byte characters.
2064 */
2065 void
2066ins_bytes(p)
2067 char_u *p;
2068{
2069 ins_bytes_len(p, (int)STRLEN(p));
2070}
2071#endif
2072
2073#if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) \
2074 || defined(FEAT_COMMENTS) || defined(FEAT_MBYTE) || defined(PROTO)
2075/*
2076 * Insert string "p" with length "len" at the cursor position.
2077 * Handles Replace mode and multi-byte characters.
2078 */
2079 void
2080ins_bytes_len(p, len)
2081 char_u *p;
2082 int len;
2083{
2084 int i;
2085# ifdef FEAT_MBYTE
2086 int n;
2087
Bram Moolenaar176dd1e2008-06-21 14:30:28 +00002088 if (has_mbyte)
2089 for (i = 0; i < len; i += n)
2090 {
2091 if (enc_utf8)
2092 /* avoid reading past p[len] */
2093 n = utfc_ptr2len_len(p + i, len - i);
2094 else
2095 n = (*mb_ptr2len)(p + i);
2096 ins_char_bytes(p + i, n);
2097 }
2098 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002099# endif
Bram Moolenaar176dd1e2008-06-21 14:30:28 +00002100 for (i = 0; i < len; ++i)
2101 ins_char(p[i]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002102}
2103#endif
2104
2105/*
2106 * Insert or replace a single character at the cursor position.
2107 * When in REPLACE or VREPLACE mode, replace any existing character.
2108 * Caller must have prepared for undo.
2109 * For multi-byte characters we get the whole character, the caller must
2110 * convert bytes to a character.
2111 */
2112 void
2113ins_char(c)
2114 int c;
2115{
2116#if defined(FEAT_MBYTE) || defined(PROTO)
Bram Moolenaar9a920d82012-06-01 15:21:02 +02002117 char_u buf[MB_MAXBYTES + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002118 int n;
2119
2120 n = (*mb_char2bytes)(c, buf);
2121
2122 /* When "c" is 0x100, 0x200, etc. we don't want to insert a NUL byte.
2123 * Happens for CTRL-Vu9900. */
2124 if (buf[0] == 0)
2125 buf[0] = '\n';
2126
2127 ins_char_bytes(buf, n);
2128}
2129
2130 void
2131ins_char_bytes(buf, charlen)
2132 char_u *buf;
2133 int charlen;
2134{
2135 int c = buf[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002136#endif
2137 int newlen; /* nr of bytes inserted */
2138 int oldlen; /* nr of bytes deleted (0 when not replacing) */
2139 char_u *p;
2140 char_u *newp;
2141 char_u *oldp;
2142 int linelen; /* length of old line including NUL */
2143 colnr_T col;
2144 linenr_T lnum = curwin->w_cursor.lnum;
2145 int i;
2146
2147#ifdef FEAT_VIRTUALEDIT
2148 /* Break tabs if needed. */
2149 if (virtual_active() && curwin->w_cursor.coladd > 0)
2150 coladvance_force(getviscol());
2151#endif
2152
2153 col = curwin->w_cursor.col;
2154 oldp = ml_get(lnum);
2155 linelen = (int)STRLEN(oldp) + 1;
2156
2157 /* The lengths default to the values for when not replacing. */
2158 oldlen = 0;
2159#ifdef FEAT_MBYTE
2160 newlen = charlen;
2161#else
2162 newlen = 1;
2163#endif
2164
2165 if (State & REPLACE_FLAG)
2166 {
2167#ifdef FEAT_VREPLACE
2168 if (State & VREPLACE_FLAG)
2169 {
2170 colnr_T new_vcol = 0; /* init for GCC */
2171 colnr_T vcol;
2172 int old_list;
2173#ifndef FEAT_MBYTE
2174 char_u buf[2];
2175#endif
2176
2177 /*
2178 * Disable 'list' temporarily, unless 'cpo' contains the 'L' flag.
2179 * Returns the old value of list, so when finished,
2180 * curwin->w_p_list should be set back to this.
2181 */
2182 old_list = curwin->w_p_list;
2183 if (old_list && vim_strchr(p_cpo, CPO_LISTWM) == NULL)
2184 curwin->w_p_list = FALSE;
2185
2186 /*
2187 * In virtual replace mode each character may replace one or more
2188 * characters (zero if it's a TAB). Count the number of bytes to
2189 * be deleted to make room for the new character, counting screen
2190 * cells. May result in adding spaces to fill a gap.
2191 */
2192 getvcol(curwin, &curwin->w_cursor, NULL, &vcol, NULL);
2193#ifndef FEAT_MBYTE
2194 buf[0] = c;
2195 buf[1] = NUL;
2196#endif
2197 new_vcol = vcol + chartabsize(buf, vcol);
2198 while (oldp[col + oldlen] != NUL && vcol < new_vcol)
2199 {
2200 vcol += chartabsize(oldp + col + oldlen, vcol);
2201 /* Don't need to remove a TAB that takes us to the right
2202 * position. */
2203 if (vcol > new_vcol && oldp[col + oldlen] == TAB)
2204 break;
2205#ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002206 oldlen += (*mb_ptr2len)(oldp + col + oldlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002207#else
2208 ++oldlen;
2209#endif
2210 /* Deleted a bit too much, insert spaces. */
2211 if (vcol > new_vcol)
2212 newlen += vcol - new_vcol;
2213 }
2214 curwin->w_p_list = old_list;
2215 }
2216 else
2217#endif
2218 if (oldp[col] != NUL)
2219 {
2220 /* normal replace */
2221#ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002222 oldlen = (*mb_ptr2len)(oldp + col);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002223#else
2224 oldlen = 1;
2225#endif
2226 }
2227
2228
2229 /* Push the replaced bytes onto the replace stack, so that they can be
2230 * put back when BS is used. The bytes of a multi-byte character are
2231 * done the other way around, so that the first byte is popped off
2232 * first (it tells the byte length of the character). */
2233 replace_push(NUL);
2234 for (i = 0; i < oldlen; ++i)
2235 {
2236#ifdef FEAT_MBYTE
Bram Moolenaar2c994e82008-01-02 16:49:36 +00002237 if (has_mbyte)
2238 i += replace_push_mb(oldp + col + i) - 1;
2239 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002240#endif
Bram Moolenaar2c994e82008-01-02 16:49:36 +00002241 replace_push(oldp[col + i]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002242 }
2243 }
2244
2245 newp = alloc_check((unsigned)(linelen + newlen - oldlen));
2246 if (newp == NULL)
2247 return;
2248
2249 /* Copy bytes before the cursor. */
2250 if (col > 0)
2251 mch_memmove(newp, oldp, (size_t)col);
2252
2253 /* Copy bytes after the changed character(s). */
2254 p = newp + col;
2255 mch_memmove(p + newlen, oldp + col + oldlen,
2256 (size_t)(linelen - col - oldlen));
2257
2258 /* Insert or overwrite the new character. */
2259#ifdef FEAT_MBYTE
2260 mch_memmove(p, buf, charlen);
2261 i = charlen;
2262#else
2263 *p = c;
2264 i = 1;
2265#endif
2266
2267 /* Fill with spaces when necessary. */
2268 while (i < newlen)
2269 p[i++] = ' ';
2270
2271 /* Replace the line in the buffer. */
2272 ml_replace(lnum, newp, FALSE);
2273
2274 /* mark the buffer as changed and prepare for displaying */
2275 changed_bytes(lnum, col);
2276
2277 /*
2278 * If we're in Insert or Replace mode and 'showmatch' is set, then briefly
2279 * show the match for right parens and braces.
2280 */
2281 if (p_sm && (State & INSERT)
2282 && msg_silent == 0
2283#ifdef FEAT_MBYTE
2284 && charlen == 1
2285#endif
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00002286#ifdef FEAT_INS_EXPAND
2287 && !ins_compl_active()
2288#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002289 )
2290 showmatch(c);
2291
2292#ifdef FEAT_RIGHTLEFT
2293 if (!p_ri || (State & REPLACE_FLAG))
2294#endif
2295 {
2296 /* Normal insert: move cursor right */
2297#ifdef FEAT_MBYTE
2298 curwin->w_cursor.col += charlen;
2299#else
2300 ++curwin->w_cursor.col;
2301#endif
2302 }
2303 /*
2304 * TODO: should try to update w_row here, to avoid recomputing it later.
2305 */
2306}
2307
2308/*
2309 * Insert a string at the cursor position.
2310 * Note: Does NOT handle Replace mode.
2311 * Caller must have prepared for undo.
2312 */
2313 void
2314ins_str(s)
2315 char_u *s;
2316{
2317 char_u *oldp, *newp;
2318 int newlen = (int)STRLEN(s);
2319 int oldlen;
2320 colnr_T col;
2321 linenr_T lnum = curwin->w_cursor.lnum;
2322
2323#ifdef FEAT_VIRTUALEDIT
2324 if (virtual_active() && curwin->w_cursor.coladd > 0)
2325 coladvance_force(getviscol());
2326#endif
2327
2328 col = curwin->w_cursor.col;
2329 oldp = ml_get(lnum);
2330 oldlen = (int)STRLEN(oldp);
2331
2332 newp = alloc_check((unsigned)(oldlen + newlen + 1));
2333 if (newp == NULL)
2334 return;
2335 if (col > 0)
2336 mch_memmove(newp, oldp, (size_t)col);
2337 mch_memmove(newp + col, s, (size_t)newlen);
2338 mch_memmove(newp + col + newlen, oldp + col, (size_t)(oldlen - col + 1));
2339 ml_replace(lnum, newp, FALSE);
2340 changed_bytes(lnum, col);
2341 curwin->w_cursor.col += newlen;
2342}
2343
2344/*
2345 * Delete one character under the cursor.
2346 * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
2347 * Caller must have prepared for undo.
2348 *
2349 * return FAIL for failure, OK otherwise
2350 */
2351 int
2352del_char(fixpos)
2353 int fixpos;
2354{
2355#ifdef FEAT_MBYTE
2356 if (has_mbyte)
2357 {
2358 /* Make sure the cursor is at the start of a character. */
2359 mb_adjust_cursor();
2360 if (*ml_get_cursor() == NUL)
2361 return FAIL;
2362 return del_chars(1L, fixpos);
2363 }
2364#endif
Bram Moolenaare3226be2005-12-18 22:10:00 +00002365 return del_bytes(1L, fixpos, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002366}
2367
2368#if defined(FEAT_MBYTE) || defined(PROTO)
2369/*
2370 * Like del_bytes(), but delete characters instead of bytes.
2371 */
2372 int
2373del_chars(count, fixpos)
2374 long count;
2375 int fixpos;
2376{
2377 long bytes = 0;
2378 long i;
2379 char_u *p;
2380 int l;
2381
2382 p = ml_get_cursor();
2383 for (i = 0; i < count && *p != NUL; ++i)
2384 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002385 l = (*mb_ptr2len)(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002386 bytes += l;
2387 p += l;
2388 }
Bram Moolenaare3226be2005-12-18 22:10:00 +00002389 return del_bytes(bytes, fixpos, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002390}
2391#endif
2392
2393/*
2394 * Delete "count" bytes under the cursor.
2395 * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
2396 * Caller must have prepared for undo.
2397 *
2398 * return FAIL for failure, OK otherwise
2399 */
2400 int
Bram Moolenaarca003e12006-03-17 23:19:38 +00002401del_bytes(count, fixpos_arg, use_delcombine)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002402 long count;
Bram Moolenaarca003e12006-03-17 23:19:38 +00002403 int fixpos_arg;
Bram Moolenaar78a15312009-05-15 19:33:18 +00002404 int use_delcombine UNUSED; /* 'delcombine' option applies */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002405{
2406 char_u *oldp, *newp;
2407 colnr_T oldlen;
2408 linenr_T lnum = curwin->w_cursor.lnum;
2409 colnr_T col = curwin->w_cursor.col;
2410 int was_alloced;
2411 long movelen;
Bram Moolenaarca003e12006-03-17 23:19:38 +00002412 int fixpos = fixpos_arg;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002413
2414 oldp = ml_get(lnum);
2415 oldlen = (int)STRLEN(oldp);
2416
2417 /*
2418 * Can't do anything when the cursor is on the NUL after the line.
2419 */
2420 if (col >= oldlen)
2421 return FAIL;
2422
2423#ifdef FEAT_MBYTE
2424 /* If 'delcombine' is set and deleting (less than) one character, only
2425 * delete the last combining character. */
Bram Moolenaare3226be2005-12-18 22:10:00 +00002426 if (p_deco && use_delcombine && enc_utf8
2427 && utfc_ptr2len(oldp + col) >= count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002428 {
Bram Moolenaar362e1a32006-03-06 23:29:24 +00002429 int cc[MAX_MCO];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002430 int n;
2431
Bram Moolenaar362e1a32006-03-06 23:29:24 +00002432 (void)utfc_ptr2char(oldp + col, cc);
2433 if (cc[0] != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002434 {
2435 /* Find the last composing char, there can be several. */
2436 n = col;
2437 do
2438 {
2439 col = n;
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002440 count = utf_ptr2len(oldp + n);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002441 n += count;
2442 } while (UTF_COMPOSINGLIKE(oldp + col, oldp + n));
2443 fixpos = 0;
2444 }
2445 }
2446#endif
2447
2448 /*
2449 * When count is too big, reduce it.
2450 */
2451 movelen = (long)oldlen - (long)col - count + 1; /* includes trailing NUL */
2452 if (movelen <= 1)
2453 {
2454 /*
2455 * If we just took off the last character of a non-blank line, and
Bram Moolenaarca003e12006-03-17 23:19:38 +00002456 * fixpos is TRUE, we don't want to end up positioned at the NUL,
2457 * unless "restart_edit" is set or 'virtualedit' contains "onemore".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002458 */
Bram Moolenaarca003e12006-03-17 23:19:38 +00002459 if (col > 0 && fixpos && restart_edit == 0
2460#ifdef FEAT_VIRTUALEDIT
2461 && (ve_flags & VE_ONEMORE) == 0
2462#endif
2463 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00002464 {
2465 --curwin->w_cursor.col;
2466#ifdef FEAT_VIRTUALEDIT
2467 curwin->w_cursor.coladd = 0;
2468#endif
2469#ifdef FEAT_MBYTE
2470 if (has_mbyte)
2471 curwin->w_cursor.col -=
2472 (*mb_head_off)(oldp, oldp + curwin->w_cursor.col);
2473#endif
2474 }
2475 count = oldlen - col;
2476 movelen = 1;
2477 }
2478
2479 /*
2480 * If the old line has been allocated the deletion can be done in the
2481 * existing line. Otherwise a new line has to be allocated
Bram Moolenaare21877a2008-02-13 09:58:14 +00002482 * Can't do this when using Netbeans, because we would need to invoke
2483 * netbeans_removed(), which deallocates the line. Let ml_replace() take
Bram Moolenaar1a509df2010-08-01 17:59:57 +02002484 * care of notifying Netbeans.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002485 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002486#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02002487 if (netbeans_active())
Bram Moolenaare21877a2008-02-13 09:58:14 +00002488 was_alloced = FALSE;
2489 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002490#endif
Bram Moolenaare21877a2008-02-13 09:58:14 +00002491 was_alloced = ml_line_alloced(); /* check if oldp was allocated */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002492 if (was_alloced)
2493 newp = oldp; /* use same allocated memory */
2494 else
2495 { /* need to allocate a new line */
2496 newp = alloc((unsigned)(oldlen + 1 - count));
2497 if (newp == NULL)
2498 return FAIL;
2499 mch_memmove(newp, oldp, (size_t)col);
2500 }
2501 mch_memmove(newp + col, oldp + col + count, (size_t)movelen);
2502 if (!was_alloced)
2503 ml_replace(lnum, newp, FALSE);
2504
2505 /* mark the buffer as changed and prepare for displaying */
2506 changed_bytes(lnum, curwin->w_cursor.col);
2507
2508 return OK;
2509}
2510
2511/*
2512 * Delete from cursor to end of line.
2513 * Caller must have prepared for undo.
2514 *
2515 * return FAIL for failure, OK otherwise
2516 */
2517 int
2518truncate_line(fixpos)
2519 int fixpos; /* if TRUE fix the cursor position when done */
2520{
2521 char_u *newp;
2522 linenr_T lnum = curwin->w_cursor.lnum;
2523 colnr_T col = curwin->w_cursor.col;
2524
2525 if (col == 0)
2526 newp = vim_strsave((char_u *)"");
2527 else
2528 newp = vim_strnsave(ml_get(lnum), col);
2529
2530 if (newp == NULL)
2531 return FAIL;
2532
2533 ml_replace(lnum, newp, FALSE);
2534
2535 /* mark the buffer as changed and prepare for displaying */
2536 changed_bytes(lnum, curwin->w_cursor.col);
2537
2538 /*
2539 * If "fixpos" is TRUE we don't want to end up positioned at the NUL.
2540 */
2541 if (fixpos && curwin->w_cursor.col > 0)
2542 --curwin->w_cursor.col;
2543
2544 return OK;
2545}
2546
2547/*
2548 * Delete "nlines" lines at the cursor.
2549 * Saves the lines for undo first if "undo" is TRUE.
2550 */
2551 void
2552del_lines(nlines, undo)
2553 long nlines; /* number of lines to delete */
2554 int undo; /* if TRUE, prepare for undo */
2555{
2556 long n;
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002557 linenr_T first = curwin->w_cursor.lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002558
2559 if (nlines <= 0)
2560 return;
2561
2562 /* save the deleted lines for undo */
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002563 if (undo && u_savedel(first, nlines) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002564 return;
2565
2566 for (n = 0; n < nlines; )
2567 {
2568 if (curbuf->b_ml.ml_flags & ML_EMPTY) /* nothing to delete */
2569 break;
2570
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002571 ml_delete(first, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002572 ++n;
2573
2574 /* If we delete the last line in the file, stop */
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002575 if (first > curbuf->b_ml.ml_line_count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002576 break;
2577 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002578
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002579 /* Correct the cursor position before calling deleted_lines_mark(), it may
2580 * trigger a callback to display the cursor. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002581 curwin->w_cursor.col = 0;
2582 check_cursor_lnum();
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002583
2584 /* adjust marks, mark the buffer as changed and prepare for displaying */
2585 deleted_lines_mark(first, n);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002586}
2587
2588 int
2589gchar_pos(pos)
2590 pos_T *pos;
2591{
2592 char_u *ptr = ml_get_pos(pos);
2593
2594#ifdef FEAT_MBYTE
2595 if (has_mbyte)
2596 return (*mb_ptr2char)(ptr);
2597#endif
2598 return (int)*ptr;
2599}
2600
2601 int
2602gchar_cursor()
2603{
2604#ifdef FEAT_MBYTE
2605 if (has_mbyte)
2606 return (*mb_ptr2char)(ml_get_cursor());
2607#endif
2608 return (int)*ml_get_cursor();
2609}
2610
2611/*
2612 * Write a character at the current cursor position.
2613 * It is directly written into the block.
2614 */
2615 void
2616pchar_cursor(c)
2617 int c;
2618{
2619 *(ml_get_buf(curbuf, curwin->w_cursor.lnum, TRUE)
2620 + curwin->w_cursor.col) = c;
2621}
2622
Bram Moolenaar071d4272004-06-13 20:20:40 +00002623/*
2624 * When extra == 0: Return TRUE if the cursor is before or on the first
2625 * non-blank in the line.
2626 * When extra == 1: Return TRUE if the cursor is before the first non-blank in
2627 * the line.
2628 */
2629 int
2630inindent(extra)
2631 int extra;
2632{
2633 char_u *ptr;
2634 colnr_T col;
2635
2636 for (col = 0, ptr = ml_get_curline(); vim_iswhite(*ptr); ++col)
2637 ++ptr;
2638 if (col >= curwin->w_cursor.col + extra)
2639 return TRUE;
2640 else
2641 return FALSE;
2642}
2643
2644/*
2645 * Skip to next part of an option argument: Skip space and comma.
2646 */
2647 char_u *
2648skip_to_option_part(p)
2649 char_u *p;
2650{
2651 if (*p == ',')
2652 ++p;
2653 while (*p == ' ')
2654 ++p;
2655 return p;
2656}
2657
2658/*
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002659 * Call this function when something in the current buffer is changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002660 *
2661 * Most often called through changed_bytes() and changed_lines(), which also
2662 * mark the area of the display to be redrawn.
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002663 *
2664 * Careful: may trigger autocommands that reload the buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002665 */
2666 void
2667changed()
2668{
2669#if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
2670 /* The text of the preediting area is inserted, but this doesn't
2671 * mean a change of the buffer yet. That is delayed until the
2672 * text is committed. (this means preedit becomes empty) */
2673 if (im_is_preediting() && !xim_changed_while_preediting)
2674 return;
2675 xim_changed_while_preediting = FALSE;
2676#endif
2677
2678 if (!curbuf->b_changed)
2679 {
2680 int save_msg_scroll = msg_scroll;
2681
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002682 /* Give a warning about changing a read-only file. This may also
2683 * check-out the file, thus change "curbuf"! */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002684 change_warning(0);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002685
Bram Moolenaar071d4272004-06-13 20:20:40 +00002686 /* Create a swap file if that is wanted.
2687 * Don't do this for "nofile" and "nowrite" buffer types. */
2688 if (curbuf->b_may_swap
2689#ifdef FEAT_QUICKFIX
2690 && !bt_dontwrite(curbuf)
2691#endif
2692 )
2693 {
2694 ml_open_file(curbuf);
2695
2696 /* The ml_open_file() can cause an ATTENTION message.
2697 * Wait two seconds, to make sure the user reads this unexpected
2698 * message. Since we could be anywhere, call wait_return() now,
2699 * and don't let the emsg() set msg_scroll. */
2700 if (need_wait_return && emsg_silent == 0)
2701 {
2702 out_flush();
2703 ui_delay(2000L, TRUE);
2704 wait_return(TRUE);
2705 msg_scroll = save_msg_scroll;
2706 }
2707 }
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02002708 changed_int();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002709 }
2710 ++curbuf->b_changedtick;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002711}
2712
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02002713/*
2714 * Internal part of changed(), no user interaction.
2715 */
2716 void
2717changed_int()
2718{
2719 curbuf->b_changed = TRUE;
2720 ml_setflags(curbuf);
2721#ifdef FEAT_WINDOWS
2722 check_status(curbuf);
2723 redraw_tabline = TRUE;
2724#endif
2725#ifdef FEAT_TITLE
2726 need_maketitle = TRUE; /* set window title later */
2727#endif
2728}
2729
Bram Moolenaardba8a912005-04-24 22:08:39 +00002730static void changedOneline __ARGS((buf_T *buf, linenr_T lnum));
2731static void changed_lines_buf __ARGS((buf_T *buf, linenr_T lnum, linenr_T lnume, long xtra));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002732static void changed_common __ARGS((linenr_T lnum, colnr_T col, linenr_T lnume, long xtra));
2733
2734/*
2735 * Changed bytes within a single line for the current buffer.
2736 * - marks the windows on this buffer to be redisplayed
2737 * - marks the buffer changed by calling changed()
2738 * - invalidates cached values
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002739 * Careful: may trigger autocommands that reload the buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002740 */
2741 void
2742changed_bytes(lnum, col)
2743 linenr_T lnum;
2744 colnr_T col;
2745{
Bram Moolenaardba8a912005-04-24 22:08:39 +00002746 changedOneline(curbuf, lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002747 changed_common(lnum, col, lnum + 1, 0L);
Bram Moolenaardba8a912005-04-24 22:08:39 +00002748
2749#ifdef FEAT_DIFF
2750 /* Diff highlighting in other diff windows may need to be updated too. */
2751 if (curwin->w_p_diff)
2752 {
2753 win_T *wp;
2754 linenr_T wlnum;
2755
2756 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2757 if (wp->w_p_diff && wp != curwin)
2758 {
2759 redraw_win_later(wp, VALID);
2760 wlnum = diff_lnum_win(lnum, wp);
2761 if (wlnum > 0)
2762 changedOneline(wp->w_buffer, wlnum);
2763 }
2764 }
2765#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002766}
2767
2768 static void
Bram Moolenaardba8a912005-04-24 22:08:39 +00002769changedOneline(buf, lnum)
2770 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002771 linenr_T lnum;
2772{
Bram Moolenaardba8a912005-04-24 22:08:39 +00002773 if (buf->b_mod_set)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002774 {
2775 /* find the maximum area that must be redisplayed */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002776 if (lnum < buf->b_mod_top)
2777 buf->b_mod_top = lnum;
2778 else if (lnum >= buf->b_mod_bot)
2779 buf->b_mod_bot = lnum + 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002780 }
2781 else
2782 {
2783 /* set the area that must be redisplayed to one line */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002784 buf->b_mod_set = TRUE;
2785 buf->b_mod_top = lnum;
2786 buf->b_mod_bot = lnum + 1;
2787 buf->b_mod_xlines = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002788 }
2789}
2790
2791/*
2792 * Appended "count" lines below line "lnum" in the current buffer.
2793 * Must be called AFTER the change and after mark_adjust().
2794 * Takes care of marking the buffer to be redrawn and sets the changed flag.
2795 */
2796 void
2797appended_lines(lnum, count)
2798 linenr_T lnum;
2799 long count;
2800{
2801 changed_lines(lnum + 1, 0, lnum + 1, count);
2802}
2803
2804/*
2805 * Like appended_lines(), but adjust marks first.
2806 */
2807 void
2808appended_lines_mark(lnum, count)
2809 linenr_T lnum;
2810 long count;
2811{
2812 mark_adjust(lnum + 1, (linenr_T)MAXLNUM, count, 0L);
2813 changed_lines(lnum + 1, 0, lnum + 1, count);
2814}
2815
2816/*
2817 * Deleted "count" lines at line "lnum" in the current buffer.
2818 * Must be called AFTER the change and after mark_adjust().
2819 * Takes care of marking the buffer to be redrawn and sets the changed flag.
2820 */
2821 void
2822deleted_lines(lnum, count)
2823 linenr_T lnum;
2824 long count;
2825{
2826 changed_lines(lnum, 0, lnum + count, -count);
2827}
2828
2829/*
2830 * Like deleted_lines(), but adjust marks first.
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002831 * Make sure the cursor is on a valid line before calling, a GUI callback may
2832 * be triggered to display the cursor.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002833 */
2834 void
2835deleted_lines_mark(lnum, count)
2836 linenr_T lnum;
2837 long count;
2838{
2839 mark_adjust(lnum, (linenr_T)(lnum + count - 1), (long)MAXLNUM, -count);
2840 changed_lines(lnum, 0, lnum + count, -count);
2841}
2842
2843/*
2844 * Changed lines for the current buffer.
2845 * Must be called AFTER the change and after mark_adjust().
2846 * - mark the buffer changed by calling changed()
2847 * - mark the windows on this buffer to be redisplayed
2848 * - invalidate cached values
2849 * "lnum" is the first line that needs displaying, "lnume" the first line
2850 * below the changed lines (BEFORE the change).
2851 * When only inserting lines, "lnum" and "lnume" are equal.
2852 * Takes care of calling changed() and updating b_mod_*.
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002853 * Careful: may trigger autocommands that reload the buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002854 */
2855 void
2856changed_lines(lnum, col, lnume, xtra)
2857 linenr_T lnum; /* first line with change */
2858 colnr_T col; /* column in first line with change */
2859 linenr_T lnume; /* line below last changed line */
2860 long xtra; /* number of extra lines (negative when deleting) */
2861{
Bram Moolenaardba8a912005-04-24 22:08:39 +00002862 changed_lines_buf(curbuf, lnum, lnume, xtra);
2863
2864#ifdef FEAT_DIFF
2865 if (xtra == 0 && curwin->w_p_diff)
2866 {
2867 /* When the number of lines doesn't change then mark_adjust() isn't
2868 * called and other diff buffers still need to be marked for
2869 * displaying. */
2870 win_T *wp;
2871 linenr_T wlnum;
2872
2873 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2874 if (wp->w_p_diff && wp != curwin)
2875 {
2876 redraw_win_later(wp, VALID);
2877 wlnum = diff_lnum_win(lnum, wp);
2878 if (wlnum > 0)
2879 changed_lines_buf(wp->w_buffer, wlnum,
2880 lnume - lnum + wlnum, 0L);
2881 }
2882 }
2883#endif
2884
2885 changed_common(lnum, col, lnume, xtra);
2886}
2887
2888 static void
2889changed_lines_buf(buf, lnum, lnume, xtra)
2890 buf_T *buf;
2891 linenr_T lnum; /* first line with change */
2892 linenr_T lnume; /* line below last changed line */
2893 long xtra; /* number of extra lines (negative when deleting) */
2894{
2895 if (buf->b_mod_set)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002896 {
2897 /* find the maximum area that must be redisplayed */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002898 if (lnum < buf->b_mod_top)
2899 buf->b_mod_top = lnum;
2900 if (lnum < buf->b_mod_bot)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002901 {
2902 /* adjust old bot position for xtra lines */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002903 buf->b_mod_bot += xtra;
2904 if (buf->b_mod_bot < lnum)
2905 buf->b_mod_bot = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002906 }
Bram Moolenaardba8a912005-04-24 22:08:39 +00002907 if (lnume + xtra > buf->b_mod_bot)
2908 buf->b_mod_bot = lnume + xtra;
2909 buf->b_mod_xlines += xtra;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002910 }
2911 else
2912 {
2913 /* set the area that must be redisplayed */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002914 buf->b_mod_set = TRUE;
2915 buf->b_mod_top = lnum;
2916 buf->b_mod_bot = lnume + xtra;
2917 buf->b_mod_xlines = xtra;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002918 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002919}
2920
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002921/*
2922 * Common code for when a change is was made.
2923 * See changed_lines() for the arguments.
2924 * Careful: may trigger autocommands that reload the buffer.
2925 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002926 static void
2927changed_common(lnum, col, lnume, xtra)
2928 linenr_T lnum;
2929 colnr_T col;
2930 linenr_T lnume;
2931 long xtra;
2932{
2933 win_T *wp;
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00002934#ifdef FEAT_WINDOWS
2935 tabpage_T *tp;
2936#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002937 int i;
2938#ifdef FEAT_JUMPLIST
2939 int cols;
2940 pos_T *p;
2941 int add;
2942#endif
2943
2944 /* mark the buffer as modified */
2945 changed();
2946
2947 /* set the '. mark */
2948 if (!cmdmod.keepjumps)
2949 {
2950 curbuf->b_last_change.lnum = lnum;
2951 curbuf->b_last_change.col = col;
2952
2953#ifdef FEAT_JUMPLIST
2954 /* Create a new entry if a new undo-able change was started or we
2955 * don't have an entry yet. */
2956 if (curbuf->b_new_change || curbuf->b_changelistlen == 0)
2957 {
2958 if (curbuf->b_changelistlen == 0)
2959 add = TRUE;
2960 else
2961 {
2962 /* Don't create a new entry when the line number is the same
2963 * as the last one and the column is not too far away. Avoids
2964 * creating many entries for typing "xxxxx". */
2965 p = &curbuf->b_changelist[curbuf->b_changelistlen - 1];
2966 if (p->lnum != lnum)
2967 add = TRUE;
2968 else
2969 {
2970 cols = comp_textwidth(FALSE);
2971 if (cols == 0)
2972 cols = 79;
2973 add = (p->col + cols < col || col + cols < p->col);
2974 }
2975 }
2976 if (add)
2977 {
2978 /* This is the first of a new sequence of undo-able changes
2979 * and it's at some distance of the last change. Use a new
2980 * position in the changelist. */
2981 curbuf->b_new_change = FALSE;
2982
2983 if (curbuf->b_changelistlen == JUMPLISTSIZE)
2984 {
2985 /* changelist is full: remove oldest entry */
2986 curbuf->b_changelistlen = JUMPLISTSIZE - 1;
2987 mch_memmove(curbuf->b_changelist, curbuf->b_changelist + 1,
2988 sizeof(pos_T) * (JUMPLISTSIZE - 1));
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00002989 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002990 {
2991 /* Correct position in changelist for other windows on
2992 * this buffer. */
2993 if (wp->w_buffer == curbuf && wp->w_changelistidx > 0)
2994 --wp->w_changelistidx;
2995 }
2996 }
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00002997 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002998 {
2999 /* For other windows, if the position in the changelist is
3000 * at the end it stays at the end. */
3001 if (wp->w_buffer == curbuf
3002 && wp->w_changelistidx == curbuf->b_changelistlen)
3003 ++wp->w_changelistidx;
3004 }
3005 ++curbuf->b_changelistlen;
3006 }
3007 }
3008 curbuf->b_changelist[curbuf->b_changelistlen - 1] =
3009 curbuf->b_last_change;
3010 /* The current window is always after the last change, so that "g,"
3011 * takes you back to it. */
3012 curwin->w_changelistidx = curbuf->b_changelistlen;
3013#endif
3014 }
3015
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00003016 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003017 {
3018 if (wp->w_buffer == curbuf)
3019 {
3020 /* Mark this window to be redrawn later. */
3021 if (wp->w_redr_type < VALID)
3022 wp->w_redr_type = VALID;
3023
3024 /* Check if a change in the buffer has invalidated the cached
3025 * values for the cursor. */
3026#ifdef FEAT_FOLDING
3027 /*
3028 * Update the folds for this window. Can't postpone this, because
3029 * a following operator might work on the whole fold: ">>dd".
3030 */
3031 foldUpdate(wp, lnum, lnume + xtra - 1);
3032
3033 /* The change may cause lines above or below the change to become
3034 * included in a fold. Set lnum/lnume to the first/last line that
3035 * might be displayed differently.
3036 * Set w_cline_folded here as an efficient way to update it when
3037 * inserting lines just above a closed fold. */
3038 i = hasFoldingWin(wp, lnum, &lnum, NULL, FALSE, NULL);
3039 if (wp->w_cursor.lnum == lnum)
3040 wp->w_cline_folded = i;
3041 i = hasFoldingWin(wp, lnume, NULL, &lnume, FALSE, NULL);
3042 if (wp->w_cursor.lnum == lnume)
3043 wp->w_cline_folded = i;
3044
3045 /* If the changed line is in a range of previously folded lines,
3046 * compare with the first line in that range. */
3047 if (wp->w_cursor.lnum <= lnum)
3048 {
3049 i = find_wl_entry(wp, lnum);
3050 if (i >= 0 && wp->w_cursor.lnum > wp->w_lines[i].wl_lnum)
3051 changed_line_abv_curs_win(wp);
3052 }
3053#endif
3054
3055 if (wp->w_cursor.lnum > lnum)
3056 changed_line_abv_curs_win(wp);
3057 else if (wp->w_cursor.lnum == lnum && wp->w_cursor.col >= col)
3058 changed_cline_bef_curs_win(wp);
3059 if (wp->w_botline >= lnum)
3060 {
3061 /* Assume that botline doesn't change (inserted lines make
3062 * other lines scroll down below botline). */
3063 approximate_botline_win(wp);
3064 }
3065
3066 /* Check if any w_lines[] entries have become invalid.
3067 * For entries below the change: Correct the lnums for
3068 * inserted/deleted lines. Makes it possible to stop displaying
3069 * after the change. */
3070 for (i = 0; i < wp->w_lines_valid; ++i)
3071 if (wp->w_lines[i].wl_valid)
3072 {
3073 if (wp->w_lines[i].wl_lnum >= lnum)
3074 {
3075 if (wp->w_lines[i].wl_lnum < lnume)
3076 {
3077 /* line included in change */
3078 wp->w_lines[i].wl_valid = FALSE;
3079 }
3080 else if (xtra != 0)
3081 {
3082 /* line below change */
3083 wp->w_lines[i].wl_lnum += xtra;
3084#ifdef FEAT_FOLDING
3085 wp->w_lines[i].wl_lastlnum += xtra;
3086#endif
3087 }
3088 }
3089#ifdef FEAT_FOLDING
3090 else if (wp->w_lines[i].wl_lastlnum >= lnum)
3091 {
3092 /* change somewhere inside this range of folded lines,
3093 * may need to be redrawn */
3094 wp->w_lines[i].wl_valid = FALSE;
3095 }
3096#endif
3097 }
Bram Moolenaar3234cc62009-11-03 17:47:12 +00003098
3099#ifdef FEAT_FOLDING
3100 /* Take care of side effects for setting w_topline when folds have
3101 * changed. Esp. when the buffer was changed in another window. */
3102 if (hasAnyFolding(wp))
3103 set_topline(wp, wp->w_topline);
3104#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003105 }
3106 }
3107
3108 /* Call update_screen() later, which checks out what needs to be redrawn,
3109 * since it notices b_mod_set and then uses b_mod_*. */
3110 if (must_redraw < VALID)
3111 must_redraw = VALID;
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00003112
3113#ifdef FEAT_AUTOCMD
3114 /* when the cursor line is changed always trigger CursorMoved */
Bram Moolenaare163f1c2006-10-17 09:12:21 +00003115 if (lnum <= curwin->w_cursor.lnum
3116 && lnume + (xtra < 0 ? -xtra : xtra) > curwin->w_cursor.lnum)
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00003117 last_cursormoved.lnum = 0;
3118#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003119}
3120
3121/*
3122 * unchanged() is called when the changed flag must be reset for buffer 'buf'
3123 */
3124 void
3125unchanged(buf, ff)
3126 buf_T *buf;
3127 int ff; /* also reset 'fileformat' */
3128{
Bram Moolenaar164c60f2011-01-22 00:11:50 +01003129 if (buf->b_changed || (ff && file_ff_differs(buf, FALSE)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003130 {
3131 buf->b_changed = 0;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003132 ml_setflags(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003133 if (ff)
3134 save_file_ff(buf);
3135#ifdef FEAT_WINDOWS
3136 check_status(buf);
Bram Moolenaar997fb4b2006-02-17 21:53:23 +00003137 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003138#endif
3139#ifdef FEAT_TITLE
3140 need_maketitle = TRUE; /* set window title later */
3141#endif
3142 }
3143 ++buf->b_changedtick;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003144#ifdef FEAT_NETBEANS_INTG
3145 netbeans_unmodified(buf);
3146#endif
3147}
3148
3149#if defined(FEAT_WINDOWS) || defined(PROTO)
3150/*
3151 * check_status: called when the status bars for the buffer 'buf'
3152 * need to be updated
3153 */
3154 void
3155check_status(buf)
3156 buf_T *buf;
3157{
3158 win_T *wp;
3159
3160 for (wp = firstwin; wp != NULL; wp = wp->w_next)
3161 if (wp->w_buffer == buf && wp->w_status_height)
3162 {
3163 wp->w_redr_status = TRUE;
3164 if (must_redraw < VALID)
3165 must_redraw = VALID;
3166 }
3167}
3168#endif
3169
3170/*
3171 * If the file is readonly, give a warning message with the first change.
3172 * Don't do this for autocommands.
3173 * Don't use emsg(), because it flushes the macro buffer.
Bram Moolenaard5cdbeb2005-10-10 20:59:28 +00003174 * If we have undone all changes b_changed will be FALSE, but "b_did_warn"
Bram Moolenaar071d4272004-06-13 20:20:40 +00003175 * will be TRUE.
Bram Moolenaarb0b50882010-07-07 18:26:28 +02003176 * Careful: may trigger autocommands that reload the buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003177 */
3178 void
3179change_warning(col)
3180 int col; /* column for message; non-zero when in insert
3181 mode and 'showmode' is on */
3182{
Bram Moolenaar496c5262009-03-18 14:42:00 +00003183 static char *w_readonly = N_("W10: Warning: Changing a readonly file");
3184
Bram Moolenaar071d4272004-06-13 20:20:40 +00003185 if (curbuf->b_did_warn == FALSE
3186 && curbufIsChanged() == 0
3187#ifdef FEAT_AUTOCMD
3188 && !autocmd_busy
3189#endif
3190 && curbuf->b_p_ro)
3191 {
3192#ifdef FEAT_AUTOCMD
Bram Moolenaar910f66f2006-04-05 20:41:53 +00003193 ++curbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003194 apply_autocmds(EVENT_FILECHANGEDRO, NULL, NULL, FALSE, curbuf);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00003195 --curbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003196 if (!curbuf->b_p_ro)
3197 return;
3198#endif
3199 /*
3200 * Do what msg() does, but with a column offset if the warning should
3201 * be after the mode message.
3202 */
3203 msg_start();
3204 if (msg_row == Rows - 1)
3205 msg_col = col;
Bram Moolenaar2df6dcc2004-07-12 15:53:54 +00003206 msg_source(hl_attr(HLF_W));
Bram Moolenaar496c5262009-03-18 14:42:00 +00003207 MSG_PUTS_ATTR(_(w_readonly), hl_attr(HLF_W) | MSG_HIST);
3208#ifdef FEAT_EVAL
3209 set_vim_var_string(VV_WARNINGMSG, (char_u *)_(w_readonly), -1);
3210#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003211 msg_clr_eos();
3212 (void)msg_end();
3213 if (msg_silent == 0 && !silent_mode)
3214 {
3215 out_flush();
3216 ui_delay(1000L, TRUE); /* give the user time to think about it */
3217 }
3218 curbuf->b_did_warn = TRUE;
3219 redraw_cmdline = FALSE; /* don't redraw and erase the message */
3220 if (msg_row < Rows - 1)
3221 showmode();
3222 }
3223}
3224
3225/*
3226 * Ask for a reply from the user, a 'y' or a 'n'.
3227 * No other characters are accepted, the message is repeated until a valid
3228 * reply is entered or CTRL-C is hit.
3229 * If direct is TRUE, don't use vgetc() but ui_inchar(), don't get characters
3230 * from any buffers but directly from the user.
3231 *
3232 * return the 'y' or 'n'
3233 */
3234 int
3235ask_yesno(str, direct)
3236 char_u *str;
3237 int direct;
3238{
3239 int r = ' ';
3240 int save_State = State;
3241
3242 if (exiting) /* put terminal in raw mode for this question */
3243 settmode(TMODE_RAW);
3244 ++no_wait_return;
3245#ifdef USE_ON_FLY_SCROLL
3246 dont_scroll = TRUE; /* disallow scrolling here */
3247#endif
3248 State = CONFIRM; /* mouse behaves like with :confirm */
3249#ifdef FEAT_MOUSE
3250 setmouse(); /* disables mouse for xterm */
3251#endif
3252 ++no_mapping;
3253 ++allow_keys; /* no mapping here, but recognize keys */
3254
3255 while (r != 'y' && r != 'n')
3256 {
3257 /* same highlighting as for wait_return */
3258 smsg_attr(hl_attr(HLF_R), (char_u *)"%s (y/n)?", str);
3259 if (direct)
3260 r = get_keystroke();
3261 else
Bram Moolenaar913626c2008-01-03 11:43:42 +00003262 r = plain_vgetc();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003263 if (r == Ctrl_C || r == ESC)
3264 r = 'n';
3265 msg_putchar(r); /* show what you typed */
3266 out_flush();
3267 }
3268 --no_wait_return;
3269 State = save_State;
3270#ifdef FEAT_MOUSE
3271 setmouse();
3272#endif
3273 --no_mapping;
3274 --allow_keys;
3275
3276 return r;
3277}
3278
3279/*
3280 * Get a key stroke directly from the user.
3281 * Ignores mouse clicks and scrollbar events, except a click for the left
3282 * button (used at the more prompt).
3283 * Doesn't use vgetc(), because it syncs undo and eats mapped characters.
3284 * Disadvantage: typeahead is ignored.
3285 * Translates the interrupt character for unix to ESC.
3286 */
3287 int
3288get_keystroke()
3289{
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003290 char_u *buf = NULL;
3291 int buflen = 150;
3292 int maxlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003293 int len = 0;
3294 int n;
3295 int save_mapped_ctrl_c = mapped_ctrl_c;
Bram Moolenaar4395a712006-09-05 18:57:57 +00003296 int waited = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003297
3298 mapped_ctrl_c = FALSE; /* mappings are not used here */
3299 for (;;)
3300 {
3301 cursor_on();
3302 out_flush();
3303
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003304 /* Leave some room for check_termcode() to insert a key code into (max
3305 * 5 chars plus NUL). And fix_input_buffer() can triple the number of
3306 * bytes. */
3307 maxlen = (buflen - 6 - len) / 3;
3308 if (buf == NULL)
3309 buf = alloc(buflen);
3310 else if (maxlen < 10)
3311 {
Bram Moolenaardc7e85e2012-06-20 12:40:08 +02003312 /* Need some more space. This might happen when receiving a long
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003313 * escape sequence. */
3314 buflen += 100;
3315 buf = vim_realloc(buf, buflen);
3316 maxlen = (buflen - 6 - len) / 3;
3317 }
3318 if (buf == NULL)
3319 {
3320 do_outofmem_msg((long_u)buflen);
3321 return ESC; /* panic! */
3322 }
3323
Bram Moolenaar071d4272004-06-13 20:20:40 +00003324 /* First time: blocking wait. Second time: wait up to 100ms for a
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003325 * terminal code to complete. */
3326 n = ui_inchar(buf + len, maxlen, len == 0 ? -1L : 100L, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003327 if (n > 0)
3328 {
3329 /* Replace zero and CSI by a special key code. */
3330 n = fix_input_buffer(buf + len, n, FALSE);
3331 len += n;
Bram Moolenaar4395a712006-09-05 18:57:57 +00003332 waited = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003333 }
Bram Moolenaar4395a712006-09-05 18:57:57 +00003334 else if (len > 0)
3335 ++waited; /* keep track of the waiting time */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003336
Bram Moolenaar4395a712006-09-05 18:57:57 +00003337 /* Incomplete termcode and not timed out yet: get more characters */
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003338 if ((n = check_termcode(1, buf, buflen, &len)) < 0
Bram Moolenaar4395a712006-09-05 18:57:57 +00003339 && (!p_ttimeout || waited * 100L < (p_ttm < 0 ? p_tm : p_ttm)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003340 continue;
Bram Moolenaar4395a712006-09-05 18:57:57 +00003341
Bram Moolenaar946ffd42010-12-30 12:30:31 +01003342 if (n == KEYLEN_REMOVED) /* key code removed */
Bram Moolenaar6eb634e2011-03-03 15:04:08 +01003343 {
Bram Moolenaarfd30cd42011-03-22 13:07:26 +01003344 if (must_redraw != 0 && !need_wait_return && (State & CMDLINE) == 0)
Bram Moolenaar6eb634e2011-03-03 15:04:08 +01003345 {
3346 /* Redrawing was postponed, do it now. */
3347 update_screen(0);
3348 setcursor(); /* put cursor back where it belongs */
3349 }
Bram Moolenaar946ffd42010-12-30 12:30:31 +01003350 continue;
Bram Moolenaar6eb634e2011-03-03 15:04:08 +01003351 }
Bram Moolenaar946ffd42010-12-30 12:30:31 +01003352 if (n > 0) /* found a termcode: adjust length */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003353 len = n;
Bram Moolenaar946ffd42010-12-30 12:30:31 +01003354 if (len == 0) /* nothing typed yet */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003355 continue;
3356
3357 /* Handle modifier and/or special key code. */
3358 n = buf[0];
3359 if (n == K_SPECIAL)
3360 {
3361 n = TO_SPECIAL(buf[1], buf[2]);
3362 if (buf[1] == KS_MODIFIER
3363 || n == K_IGNORE
3364#ifdef FEAT_MOUSE
3365 || n == K_LEFTMOUSE_NM
3366 || n == K_LEFTDRAG
3367 || n == K_LEFTRELEASE
3368 || n == K_LEFTRELEASE_NM
3369 || n == K_MIDDLEMOUSE
3370 || n == K_MIDDLEDRAG
3371 || n == K_MIDDLERELEASE
3372 || n == K_RIGHTMOUSE
3373 || n == K_RIGHTDRAG
3374 || n == K_RIGHTRELEASE
3375 || n == K_MOUSEDOWN
3376 || n == K_MOUSEUP
Bram Moolenaar8d9b40e2010-07-25 15:49:07 +02003377 || n == K_MOUSELEFT
3378 || n == K_MOUSERIGHT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003379 || n == K_X1MOUSE
3380 || n == K_X1DRAG
3381 || n == K_X1RELEASE
3382 || n == K_X2MOUSE
3383 || n == K_X2DRAG
3384 || n == K_X2RELEASE
3385# ifdef FEAT_GUI
3386 || n == K_VER_SCROLLBAR
3387 || n == K_HOR_SCROLLBAR
3388# endif
3389#endif
3390 )
3391 {
3392 if (buf[1] == KS_MODIFIER)
3393 mod_mask = buf[2];
3394 len -= 3;
3395 if (len > 0)
3396 mch_memmove(buf, buf + 3, (size_t)len);
3397 continue;
3398 }
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00003399 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003400 }
3401#ifdef FEAT_MBYTE
3402 if (has_mbyte)
3403 {
3404 if (MB_BYTE2LEN(n) > len)
3405 continue; /* more bytes to get */
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003406 buf[len >= buflen ? buflen - 1 : len] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003407 n = (*mb_ptr2char)(buf);
3408 }
3409#endif
3410#ifdef UNIX
3411 if (n == intr_char)
3412 n = ESC;
3413#endif
3414 break;
3415 }
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003416 vim_free(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003417
3418 mapped_ctrl_c = save_mapped_ctrl_c;
3419 return n;
3420}
3421
3422/*
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003423 * Get a number from the user.
3424 * When "mouse_used" is not NULL allow using the mouse.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003425 */
3426 int
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003427get_number(colon, mouse_used)
3428 int colon; /* allow colon to abort */
3429 int *mouse_used;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003430{
3431 int n = 0;
3432 int c;
Bram Moolenaar3991dab2006-03-27 17:01:56 +00003433 int typed = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003434
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003435 if (mouse_used != NULL)
3436 *mouse_used = FALSE;
3437
Bram Moolenaar071d4272004-06-13 20:20:40 +00003438 /* When not printing messages, the user won't know what to type, return a
3439 * zero (as if CR was hit). */
3440 if (msg_silent != 0)
3441 return 0;
3442
3443#ifdef USE_ON_FLY_SCROLL
3444 dont_scroll = TRUE; /* disallow scrolling here */
3445#endif
3446 ++no_mapping;
3447 ++allow_keys; /* no mapping here, but recognize keys */
3448 for (;;)
3449 {
3450 windgoto(msg_row, msg_col);
3451 c = safe_vgetc();
3452 if (VIM_ISDIGIT(c))
3453 {
3454 n = n * 10 + c - '0';
3455 msg_putchar(c);
Bram Moolenaar3991dab2006-03-27 17:01:56 +00003456 ++typed;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003457 }
3458 else if (c == K_DEL || c == K_KDEL || c == K_BS || c == Ctrl_H)
3459 {
Bram Moolenaar3991dab2006-03-27 17:01:56 +00003460 if (typed > 0)
3461 {
3462 MSG_PUTS("\b \b");
3463 --typed;
3464 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003465 n /= 10;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003466 }
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003467#ifdef FEAT_MOUSE
3468 else if (mouse_used != NULL && c == K_LEFTMOUSE)
3469 {
3470 *mouse_used = TRUE;
3471 n = mouse_row + 1;
3472 break;
3473 }
3474#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003475 else if (n == 0 && c == ':' && colon)
3476 {
3477 stuffcharReadbuff(':');
3478 if (!exmode_active)
3479 cmdline_row = msg_row;
3480 skip_redraw = TRUE; /* skip redraw once */
3481 do_redraw = FALSE;
3482 break;
3483 }
3484 else if (c == CAR || c == NL || c == Ctrl_C || c == ESC)
3485 break;
3486 }
3487 --no_mapping;
3488 --allow_keys;
3489 return n;
3490}
3491
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003492/*
3493 * Ask the user to enter a number.
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003494 * When "mouse_used" is not NULL allow using the mouse and in that case return
3495 * the line number.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003496 */
3497 int
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003498prompt_for_number(mouse_used)
3499 int *mouse_used;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003500{
3501 int i;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003502 int save_cmdline_row;
3503 int save_State;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003504
3505 /* When using ":silent" assume that <CR> was entered. */
Bram Moolenaar42eeac32005-06-29 22:40:58 +00003506 if (mouse_used != NULL)
Bram Moolenaard812df62008-11-09 12:46:09 +00003507 MSG_PUTS(_("Type number and <Enter> or click with mouse (empty cancels): "));
Bram Moolenaar42eeac32005-06-29 22:40:58 +00003508 else
Bram Moolenaard812df62008-11-09 12:46:09 +00003509 MSG_PUTS(_("Type number and <Enter> (empty cancels): "));
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003510
Bram Moolenaar203335e2006-09-03 14:35:42 +00003511 /* Set the state such that text can be selected/copied/pasted and we still
3512 * get mouse events. */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003513 save_cmdline_row = cmdline_row;
Bram Moolenaar203335e2006-09-03 14:35:42 +00003514 cmdline_row = 0;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003515 save_State = State;
Bram Moolenaar203335e2006-09-03 14:35:42 +00003516 State = CMDLINE;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003517
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003518 i = get_number(TRUE, mouse_used);
3519 if (KeyTyped)
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003520 {
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003521 /* don't call wait_return() now */
3522 /* msg_putchar('\n'); */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003523 cmdline_row = msg_row - 1;
3524 need_wait_return = FALSE;
3525 msg_didany = FALSE;
Bram Moolenaarb2450162009-07-22 09:04:20 +00003526 msg_didout = FALSE;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003527 }
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003528 else
3529 cmdline_row = save_cmdline_row;
3530 State = save_State;
3531
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003532 return i;
3533}
3534
Bram Moolenaar071d4272004-06-13 20:20:40 +00003535 void
3536msgmore(n)
3537 long n;
3538{
3539 long pn;
3540
3541 if (global_busy /* no messages now, wait until global is finished */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003542 || !messaging()) /* 'lazyredraw' set, don't do messages now */
3543 return;
3544
Bram Moolenaar7df2d662005-01-25 22:18:08 +00003545 /* We don't want to overwrite another important message, but do overwrite
3546 * a previous "more lines" or "fewer lines" message, so that "5dd" and
3547 * then "put" reports the last action. */
3548 if (keep_msg != NULL && !keep_msg_more)
3549 return;
3550
Bram Moolenaar071d4272004-06-13 20:20:40 +00003551 if (n > 0)
3552 pn = n;
3553 else
3554 pn = -n;
3555
3556 if (pn > p_report)
3557 {
3558 if (pn == 1)
3559 {
3560 if (n > 0)
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003561 vim_strncpy(msg_buf, (char_u *)_("1 more line"),
3562 MSG_BUF_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003563 else
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003564 vim_strncpy(msg_buf, (char_u *)_("1 line less"),
3565 MSG_BUF_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003566 }
3567 else
3568 {
3569 if (n > 0)
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003570 vim_snprintf((char *)msg_buf, MSG_BUF_LEN,
3571 _("%ld more lines"), pn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003572 else
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003573 vim_snprintf((char *)msg_buf, MSG_BUF_LEN,
3574 _("%ld fewer lines"), pn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003575 }
3576 if (got_int)
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003577 vim_strcat(msg_buf, (char_u *)_(" (Interrupted)"), MSG_BUF_LEN);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003578 if (msg(msg_buf))
3579 {
Bram Moolenaar238a5642006-02-21 22:12:05 +00003580 set_keep_msg(msg_buf, 0);
Bram Moolenaar7df2d662005-01-25 22:18:08 +00003581 keep_msg_more = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003582 }
3583 }
3584}
3585
3586/*
3587 * flush map and typeahead buffers and give a warning for an error
3588 */
3589 void
3590beep_flush()
3591{
3592 if (emsg_silent == 0)
3593 {
3594 flush_buffers(FALSE);
3595 vim_beep();
3596 }
3597}
3598
3599/*
3600 * give a warning for an error
3601 */
3602 void
3603vim_beep()
3604{
3605 if (emsg_silent == 0)
3606 {
3607 if (p_vb
3608#ifdef FEAT_GUI
3609 /* While the GUI is starting up the termcap is set for the GUI
3610 * but the output still goes to a terminal. */
3611 && !(gui.in_use && gui.starting)
3612#endif
3613 )
3614 {
3615 out_str(T_VB);
3616 }
3617 else
3618 {
3619#ifdef MSDOS
3620 /*
3621 * The number of beeps outputted is reduced to avoid having to wait
3622 * for all the beeps to finish. This is only a problem on systems
3623 * where the beeps don't overlap.
3624 */
3625 if (beep_count == 0 || beep_count == 10)
3626 {
3627 out_char(BELL);
3628 beep_count = 1;
3629 }
3630 else
3631 ++beep_count;
3632#else
3633 out_char(BELL);
3634#endif
3635 }
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003636
3637 /* When 'verbose' is set and we are sourcing a script or executing a
3638 * function give the user a hint where the beep comes from. */
3639 if (vim_strchr(p_debug, 'e') != NULL)
3640 {
3641 msg_source(hl_attr(HLF_W));
3642 msg_attr((char_u *)_("Beep!"), hl_attr(HLF_W));
3643 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003644 }
3645}
3646
3647/*
3648 * To get the "real" home directory:
3649 * - get value of $HOME
3650 * For Unix:
3651 * - go to that directory
3652 * - do mch_dirname() to get the real name of that directory.
3653 * This also works with mounts and links.
3654 * Don't do this for MS-DOS, it will change the "current dir" for a drive.
3655 */
3656static char_u *homedir = NULL;
3657
3658 void
3659init_homedir()
3660{
3661 char_u *var;
3662
Bram Moolenaar05159a02005-02-26 23:04:13 +00003663 /* In case we are called a second time (when 'encoding' changes). */
3664 vim_free(homedir);
3665 homedir = NULL;
3666
Bram Moolenaar071d4272004-06-13 20:20:40 +00003667#ifdef VMS
3668 var = mch_getenv((char_u *)"SYS$LOGIN");
3669#else
3670 var = mch_getenv((char_u *)"HOME");
3671#endif
3672
3673 if (var != NULL && *var == NUL) /* empty is same as not set */
3674 var = NULL;
3675
3676#ifdef WIN3264
3677 /*
3678 * Weird but true: $HOME may contain an indirect reference to another
3679 * variable, esp. "%USERPROFILE%". Happens when $USERPROFILE isn't set
3680 * when $HOME is being set.
3681 */
3682 if (var != NULL && *var == '%')
3683 {
3684 char_u *p;
3685 char_u *exp;
3686
3687 p = vim_strchr(var + 1, '%');
3688 if (p != NULL)
3689 {
Bram Moolenaarce0842a2005-07-18 21:58:11 +00003690 vim_strncpy(NameBuff, var + 1, p - (var + 1));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003691 exp = mch_getenv(NameBuff);
3692 if (exp != NULL && *exp != NUL
3693 && STRLEN(exp) + STRLEN(p) < MAXPATHL)
3694 {
Bram Moolenaar555b2802005-05-19 21:08:39 +00003695 vim_snprintf((char *)NameBuff, MAXPATHL, "%s%s", exp, p + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003696 var = NameBuff;
3697 /* Also set $HOME, it's needed for _viminfo. */
3698 vim_setenv((char_u *)"HOME", NameBuff);
3699 }
3700 }
3701 }
3702
3703 /*
3704 * Typically, $HOME is not defined on Windows, unless the user has
3705 * specifically defined it for Vim's sake. However, on Windows NT
3706 * platforms, $HOMEDRIVE and $HOMEPATH are automatically defined for
3707 * each user. Try constructing $HOME from these.
3708 */
3709 if (var == NULL)
3710 {
3711 char_u *homedrive, *homepath;
3712
3713 homedrive = mch_getenv((char_u *)"HOMEDRIVE");
3714 homepath = mch_getenv((char_u *)"HOMEPATH");
Bram Moolenaar6f977012010-01-06 17:53:38 +01003715 if (homepath == NULL || *homepath == NUL)
3716 homepath = "\\";
3717 if (homedrive != NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00003718 && STRLEN(homedrive) + STRLEN(homepath) < MAXPATHL)
3719 {
3720 sprintf((char *)NameBuff, "%s%s", homedrive, homepath);
3721 if (NameBuff[0] != NUL)
3722 {
3723 var = NameBuff;
3724 /* Also set $HOME, it's needed for _viminfo. */
3725 vim_setenv((char_u *)"HOME", NameBuff);
3726 }
3727 }
3728 }
Bram Moolenaar05159a02005-02-26 23:04:13 +00003729
3730# if defined(FEAT_MBYTE)
3731 if (enc_utf8 && var != NULL)
3732 {
3733 int len;
Bram Moolenaarb453a532011-04-28 17:48:44 +02003734 char_u *pp = NULL;
Bram Moolenaar05159a02005-02-26 23:04:13 +00003735
3736 /* Convert from active codepage to UTF-8. Other conversions are
3737 * not done, because they would fail for non-ASCII characters. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003738 acp_to_enc(var, (int)STRLEN(var), &pp, &len);
Bram Moolenaar05159a02005-02-26 23:04:13 +00003739 if (pp != NULL)
3740 {
3741 homedir = pp;
3742 return;
3743 }
3744 }
3745# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003746#endif
3747
3748#if defined(OS2) || defined(MSDOS) || defined(MSWIN)
3749 /*
3750 * Default home dir is C:/
3751 * Best assumption we can make in such a situation.
3752 */
3753 if (var == NULL)
3754 var = "C:/";
3755#endif
3756 if (var != NULL)
3757 {
3758#ifdef UNIX
3759 /*
3760 * Change to the directory and get the actual path. This resolves
3761 * links. Don't do it when we can't return.
3762 */
3763 if (mch_dirname(NameBuff, MAXPATHL) == OK
3764 && mch_chdir((char *)NameBuff) == 0)
3765 {
3766 if (!mch_chdir((char *)var) && mch_dirname(IObuff, IOSIZE) == OK)
3767 var = IObuff;
3768 if (mch_chdir((char *)NameBuff) != 0)
3769 EMSG(_(e_prev_dir));
3770 }
3771#endif
3772 homedir = vim_strsave(var);
3773 }
3774}
3775
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003776#if defined(EXITFREE) || defined(PROTO)
3777 void
3778free_homedir()
3779{
3780 vim_free(homedir);
3781}
3782#endif
3783
Bram Moolenaar071d4272004-06-13 20:20:40 +00003784/*
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003785 * Call expand_env() and store the result in an allocated string.
3786 * This is not very memory efficient, this expects the result to be freed
3787 * again soon.
3788 */
3789 char_u *
3790expand_env_save(src)
3791 char_u *src;
3792{
3793 return expand_env_save_opt(src, FALSE);
3794}
3795
3796/*
3797 * Idem, but when "one" is TRUE handle the string as one file name, only
3798 * expand "~" at the start.
3799 */
3800 char_u *
3801expand_env_save_opt(src, one)
3802 char_u *src;
3803 int one;
3804{
3805 char_u *p;
3806
3807 p = alloc(MAXPATHL);
3808 if (p != NULL)
3809 expand_env_esc(src, p, MAXPATHL, FALSE, one, NULL);
3810 return p;
3811}
3812
3813/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003814 * Expand environment variable with path name.
3815 * "~/" is also expanded, using $HOME. For Unix "~user/" is expanded.
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003816 * Skips over "\ ", "\~" and "\$" (not for Win32 though).
Bram Moolenaar071d4272004-06-13 20:20:40 +00003817 * If anything fails no expansion is done and dst equals src.
3818 */
3819 void
3820expand_env(src, dst, dstlen)
3821 char_u *src; /* input string e.g. "$HOME/vim.hlp" */
3822 char_u *dst; /* where to put the result */
3823 int dstlen; /* maximum length of the result */
3824{
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003825 expand_env_esc(src, dst, dstlen, FALSE, FALSE, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003826}
3827
3828 void
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003829expand_env_esc(srcp, dst, dstlen, esc, one, startstr)
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003830 char_u *srcp; /* input string e.g. "$HOME/vim.hlp" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003831 char_u *dst; /* where to put the result */
3832 int dstlen; /* maximum length of the result */
3833 int esc; /* escape spaces in expanded variables */
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003834 int one; /* "srcp" is one file name */
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003835 char_u *startstr; /* start again after this (can be NULL) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003836{
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003837 char_u *src;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003838 char_u *tail;
3839 int c;
3840 char_u *var;
3841 int copy_char;
3842 int mustfree; /* var was allocated, need to free it later */
3843 int at_start = TRUE; /* at start of a name */
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003844 int startstr_len = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003845
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003846 if (startstr != NULL)
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003847 startstr_len = (int)STRLEN(startstr);
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003848
3849 src = skipwhite(srcp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003850 --dstlen; /* leave one char space for "\," */
3851 while (*src && dstlen > 0)
3852 {
3853 copy_char = TRUE;
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003854 if ((*src == '$'
3855#ifdef VMS
3856 && at_start
3857#endif
3858 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003859#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3860 || *src == '%'
3861#endif
3862 || (*src == '~' && at_start))
3863 {
3864 mustfree = FALSE;
3865
3866 /*
3867 * The variable name is copied into dst temporarily, because it may
3868 * be a string in read-only memory and a NUL needs to be appended.
3869 */
3870 if (*src != '~') /* environment var */
3871 {
3872 tail = src + 1;
3873 var = dst;
3874 c = dstlen - 1;
3875
3876#ifdef UNIX
3877 /* Unix has ${var-name} type environment vars */
3878 if (*tail == '{' && !vim_isIDc('{'))
3879 {
3880 tail++; /* ignore '{' */
3881 while (c-- > 0 && *tail && *tail != '}')
3882 *var++ = *tail++;
3883 }
3884 else
3885#endif
3886 {
3887 while (c-- > 0 && *tail != NUL && ((vim_isIDc(*tail))
3888#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3889 || (*src == '%' && *tail != '%')
3890#endif
3891 ))
3892 {
3893#ifdef OS2 /* env vars only in uppercase */
3894 *var++ = TOUPPER_LOC(*tail);
3895 tail++; /* toupper() may be a macro! */
3896#else
3897 *var++ = *tail++;
3898#endif
3899 }
3900 }
3901
3902#if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
3903# ifdef UNIX
3904 if (src[1] == '{' && *tail != '}')
3905# else
3906 if (*src == '%' && *tail != '%')
3907# endif
3908 var = NULL;
3909 else
3910 {
3911# ifdef UNIX
3912 if (src[1] == '{')
3913# else
3914 if (*src == '%')
3915#endif
3916 ++tail;
3917#endif
3918 *var = NUL;
3919 var = vim_getenv(dst, &mustfree);
3920#if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
3921 }
3922#endif
3923 }
3924 /* home directory */
3925 else if ( src[1] == NUL
3926 || vim_ispathsep(src[1])
3927 || vim_strchr((char_u *)" ,\t\n", src[1]) != NULL)
3928 {
3929 var = homedir;
3930 tail = src + 1;
3931 }
3932 else /* user directory */
3933 {
3934#if defined(UNIX) || (defined(VMS) && defined(USER_HOME))
3935 /*
3936 * Copy ~user to dst[], so we can put a NUL after it.
3937 */
3938 tail = src;
3939 var = dst;
3940 c = dstlen - 1;
3941 while ( c-- > 0
3942 && *tail
3943 && vim_isfilec(*tail)
3944 && !vim_ispathsep(*tail))
3945 *var++ = *tail++;
3946 *var = NUL;
3947# ifdef UNIX
3948 /*
3949 * If the system supports getpwnam(), use it.
3950 * Otherwise, or if getpwnam() fails, the shell is used to
3951 * expand ~user. This is slower and may fail if the shell
3952 * does not support ~user (old versions of /bin/sh).
3953 */
3954# if defined(HAVE_GETPWNAM) && defined(HAVE_PWD_H)
3955 {
3956 struct passwd *pw;
3957
Bram Moolenaara40ceaf2006-01-13 22:35:40 +00003958 /* Note: memory allocated by getpwnam() is never freed.
3959 * Calling endpwent() apparently doesn't help. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003960 pw = getpwnam((char *)dst + 1);
3961 if (pw != NULL)
3962 var = (char_u *)pw->pw_dir;
3963 else
3964 var = NULL;
3965 }
3966 if (var == NULL)
3967# endif
3968 {
3969 expand_T xpc;
3970
3971 ExpandInit(&xpc);
3972 xpc.xp_context = EXPAND_FILES;
3973 var = ExpandOne(&xpc, dst, NULL,
3974 WILD_ADD_SLASH|WILD_SILENT, WILD_EXPAND_FREE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003975 mustfree = TRUE;
3976 }
3977
3978# else /* !UNIX, thus VMS */
3979 /*
3980 * USER_HOME is a comma-separated list of
3981 * directories to search for the user account in.
3982 */
3983 {
3984 char_u test[MAXPATHL], paths[MAXPATHL];
3985 char_u *path, *next_path, *ptr;
3986 struct stat st;
3987
3988 STRCPY(paths, USER_HOME);
3989 next_path = paths;
3990 while (*next_path)
3991 {
3992 for (path = next_path; *next_path && *next_path != ',';
3993 next_path++);
3994 if (*next_path)
3995 *next_path++ = NUL;
3996 STRCPY(test, path);
3997 STRCAT(test, "/");
3998 STRCAT(test, dst + 1);
3999 if (mch_stat(test, &st) == 0)
4000 {
4001 var = alloc(STRLEN(test) + 1);
4002 STRCPY(var, test);
4003 mustfree = TRUE;
4004 break;
4005 }
4006 }
4007 }
4008# endif /* UNIX */
4009#else
4010 /* cannot expand user's home directory, so don't try */
4011 var = NULL;
4012 tail = (char_u *)""; /* for gcc */
4013#endif /* UNIX || VMS */
4014 }
4015
4016#ifdef BACKSLASH_IN_FILENAME
4017 /* If 'shellslash' is set change backslashes to forward slashes.
4018 * Can't use slash_adjust(), p_ssl may be set temporarily. */
4019 if (p_ssl && var != NULL && vim_strchr(var, '\\') != NULL)
4020 {
4021 char_u *p = vim_strsave(var);
4022
4023 if (p != NULL)
4024 {
4025 if (mustfree)
4026 vim_free(var);
4027 var = p;
4028 mustfree = TRUE;
4029 forward_slash(var);
4030 }
4031 }
4032#endif
4033
4034 /* If "var" contains white space, escape it with a backslash.
4035 * Required for ":e ~/tt" when $HOME includes a space. */
4036 if (esc && var != NULL && vim_strpbrk(var, (char_u *)" \t") != NULL)
4037 {
4038 char_u *p = vim_strsave_escaped(var, (char_u *)" \t");
4039
4040 if (p != NULL)
4041 {
4042 if (mustfree)
4043 vim_free(var);
4044 var = p;
4045 mustfree = TRUE;
4046 }
4047 }
4048
4049 if (var != NULL && *var != NUL
4050 && (STRLEN(var) + STRLEN(tail) + 1 < (unsigned)dstlen))
4051 {
4052 STRCPY(dst, var);
4053 dstlen -= (int)STRLEN(var);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004054 c = (int)STRLEN(var);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004055 /* if var[] ends in a path separator and tail[] starts
4056 * with it, skip a character */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004057 if (*var != NUL && after_pathsep(dst, dst + c)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004058#if defined(BACKSLASH_IN_FILENAME) || defined(AMIGA)
4059 && dst[-1] != ':'
4060#endif
4061 && vim_ispathsep(*tail))
4062 ++tail;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004063 dst += c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004064 src = tail;
4065 copy_char = FALSE;
4066 }
4067 if (mustfree)
4068 vim_free(var);
4069 }
4070
4071 if (copy_char) /* copy at least one char */
4072 {
4073 /*
Bram Moolenaar25394022007-05-10 19:06:20 +00004074 * Recognize the start of a new name, for '~'.
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00004075 * Don't do this when "one" is TRUE, to avoid expanding "~" in
4076 * ":edit foo ~ foo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00004077 */
4078 at_start = FALSE;
4079 if (src[0] == '\\' && src[1] != NUL)
4080 {
4081 *dst++ = *src++;
4082 --dstlen;
4083 }
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00004084 else if ((src[0] == ' ' || src[0] == ',') && !one)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004085 at_start = TRUE;
4086 *dst++ = *src++;
4087 --dstlen;
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00004088
4089 if (startstr != NULL && src - startstr_len >= srcp
4090 && STRNCMP(src - startstr_len, startstr, startstr_len) == 0)
4091 at_start = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004092 }
4093 }
4094 *dst = NUL;
4095}
4096
4097/*
4098 * Vim's version of getenv().
4099 * Special handling of $HOME, $VIM and $VIMRUNTIME.
Bram Moolenaar2f6b0b82005-03-08 22:43:10 +00004100 * Also does ACP to 'enc' conversion for Win32.
Bram Moolenaarb453a532011-04-28 17:48:44 +02004101 * "mustfree" is set to TRUE when returned is allocated, it must be
4102 * initialized to FALSE by the caller.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004103 */
4104 char_u *
4105vim_getenv(name, mustfree)
4106 char_u *name;
Bram Moolenaarb453a532011-04-28 17:48:44 +02004107 int *mustfree;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004108{
4109 char_u *p;
4110 char_u *pend;
4111 int vimruntime;
4112
4113#if defined(OS2) || defined(MSDOS) || defined(MSWIN)
4114 /* use "C:/" when $HOME is not set */
4115 if (STRCMP(name, "HOME") == 0)
4116 return homedir;
4117#endif
4118
4119 p = mch_getenv(name);
4120 if (p != NULL && *p == NUL) /* empty is the same as not set */
4121 p = NULL;
4122
4123 if (p != NULL)
Bram Moolenaar05159a02005-02-26 23:04:13 +00004124 {
4125#if defined(FEAT_MBYTE) && defined(WIN3264)
4126 if (enc_utf8)
4127 {
4128 int len;
Bram Moolenaarb453a532011-04-28 17:48:44 +02004129 char_u *pp = NULL;
Bram Moolenaar05159a02005-02-26 23:04:13 +00004130
4131 /* Convert from active codepage to UTF-8. Other conversions are
4132 * not done, because they would fail for non-ASCII characters. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004133 acp_to_enc(p, (int)STRLEN(p), &pp, &len);
Bram Moolenaar05159a02005-02-26 23:04:13 +00004134 if (pp != NULL)
4135 {
4136 p = pp;
4137 *mustfree = TRUE;
4138 }
4139 }
4140#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004141 return p;
Bram Moolenaar05159a02005-02-26 23:04:13 +00004142 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004143
4144 vimruntime = (STRCMP(name, "VIMRUNTIME") == 0);
4145 if (!vimruntime && STRCMP(name, "VIM") != 0)
4146 return NULL;
4147
4148 /*
4149 * When expanding $VIMRUNTIME fails, try using $VIM/vim<version> or $VIM.
4150 * Don't do this when default_vimruntime_dir is non-empty.
4151 */
4152 if (vimruntime
4153#ifdef HAVE_PATHDEF
4154 && *default_vimruntime_dir == NUL
4155#endif
4156 )
4157 {
4158 p = mch_getenv((char_u *)"VIM");
4159 if (p != NULL && *p == NUL) /* empty is the same as not set */
4160 p = NULL;
4161 if (p != NULL)
4162 {
4163 p = vim_version_dir(p);
4164 if (p != NULL)
4165 *mustfree = TRUE;
4166 else
4167 p = mch_getenv((char_u *)"VIM");
Bram Moolenaar05159a02005-02-26 23:04:13 +00004168
4169#if defined(FEAT_MBYTE) && defined(WIN3264)
4170 if (enc_utf8)
4171 {
4172 int len;
Bram Moolenaarb453a532011-04-28 17:48:44 +02004173 char_u *pp = NULL;
Bram Moolenaar05159a02005-02-26 23:04:13 +00004174
4175 /* Convert from active codepage to UTF-8. Other conversions
4176 * are not done, because they would fail for non-ASCII
4177 * characters. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004178 acp_to_enc(p, (int)STRLEN(p), &pp, &len);
Bram Moolenaar05159a02005-02-26 23:04:13 +00004179 if (pp != NULL)
4180 {
Bram Moolenaarb453a532011-04-28 17:48:44 +02004181 if (*mustfree)
Bram Moolenaar05159a02005-02-26 23:04:13 +00004182 vim_free(p);
4183 p = pp;
4184 *mustfree = TRUE;
4185 }
4186 }
4187#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004188 }
4189 }
4190
4191 /*
4192 * When expanding $VIM or $VIMRUNTIME fails, try using:
4193 * - the directory name from 'helpfile' (unless it contains '$')
4194 * - the executable name from argv[0]
4195 */
4196 if (p == NULL)
4197 {
4198 if (p_hf != NULL && vim_strchr(p_hf, '$') == NULL)
4199 p = p_hf;
4200#ifdef USE_EXE_NAME
4201 /*
4202 * Use the name of the executable, obtained from argv[0].
4203 */
4204 else
4205 p = exe_name;
4206#endif
4207 if (p != NULL)
4208 {
4209 /* remove the file name */
4210 pend = gettail(p);
4211
4212 /* remove "doc/" from 'helpfile', if present */
4213 if (p == p_hf)
4214 pend = remove_tail(p, pend, (char_u *)"doc");
4215
4216#ifdef USE_EXE_NAME
4217# ifdef MACOS_X
Bram Moolenaar95e9b492006-03-15 23:04:43 +00004218 /* remove "MacOS" from exe_name and add "Resources/vim" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004219 if (p == exe_name)
4220 {
4221 char_u *pend1;
Bram Moolenaar95e9b492006-03-15 23:04:43 +00004222 char_u *pnew;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004223
Bram Moolenaar95e9b492006-03-15 23:04:43 +00004224 pend1 = remove_tail(p, pend, (char_u *)"MacOS");
4225 if (pend1 != pend)
4226 {
4227 pnew = alloc((unsigned)(pend1 - p) + 15);
4228 if (pnew != NULL)
4229 {
4230 STRNCPY(pnew, p, (pend1 - p));
4231 STRCPY(pnew + (pend1 - p), "Resources/vim");
4232 p = pnew;
4233 pend = p + STRLEN(p);
4234 }
4235 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004236 }
4237# endif
4238 /* remove "src/" from exe_name, if present */
4239 if (p == exe_name)
4240 pend = remove_tail(p, pend, (char_u *)"src");
4241#endif
4242
4243 /* for $VIM, remove "runtime/" or "vim54/", if present */
4244 if (!vimruntime)
4245 {
4246 pend = remove_tail(p, pend, (char_u *)RUNTIME_DIRNAME);
4247 pend = remove_tail(p, pend, (char_u *)VIM_VERSION_NODOT);
4248 }
4249
4250 /* remove trailing path separator */
4251#ifndef MACOS_CLASSIC
4252 /* With MacOS path (with colons) the final colon is required */
Bram Moolenaare21877a2008-02-13 09:58:14 +00004253 /* to avoid confusion between absolute and relative path */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004254 if (pend > p && after_pathsep(p, pend))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004255 --pend;
4256#endif
4257
Bram Moolenaar95e9b492006-03-15 23:04:43 +00004258#ifdef MACOS_X
4259 if (p == exe_name || p == p_hf)
4260#endif
4261 /* check that the result is a directory name */
4262 p = vim_strnsave(p, (int)(pend - p));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004263
4264 if (p != NULL && !mch_isdir(p))
4265 {
4266 vim_free(p);
4267 p = NULL;
4268 }
4269 else
4270 {
4271#ifdef USE_EXE_NAME
4272 /* may add "/vim54" or "/runtime" if it exists */
4273 if (vimruntime && (pend = vim_version_dir(p)) != NULL)
4274 {
4275 vim_free(p);
4276 p = pend;
4277 }
4278#endif
4279 *mustfree = TRUE;
4280 }
4281 }
4282 }
4283
4284#ifdef HAVE_PATHDEF
4285 /* When there is a pathdef.c file we can use default_vim_dir and
4286 * default_vimruntime_dir */
4287 if (p == NULL)
4288 {
4289 /* Only use default_vimruntime_dir when it is not empty */
4290 if (vimruntime && *default_vimruntime_dir != NUL)
4291 {
4292 p = default_vimruntime_dir;
4293 *mustfree = FALSE;
4294 }
4295 else if (*default_vim_dir != NUL)
4296 {
4297 if (vimruntime && (p = vim_version_dir(default_vim_dir)) != NULL)
4298 *mustfree = TRUE;
4299 else
4300 {
4301 p = default_vim_dir;
4302 *mustfree = FALSE;
4303 }
4304 }
4305 }
4306#endif
4307
4308 /*
4309 * Set the environment variable, so that the new value can be found fast
4310 * next time, and others can also use it (e.g. Perl).
4311 */
4312 if (p != NULL)
4313 {
4314 if (vimruntime)
4315 {
4316 vim_setenv((char_u *)"VIMRUNTIME", p);
4317 didset_vimruntime = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004318 }
4319 else
4320 {
4321 vim_setenv((char_u *)"VIM", p);
4322 didset_vim = TRUE;
4323 }
4324 }
4325 return p;
4326}
4327
4328/*
4329 * Check if the directory "vimdir/<version>" or "vimdir/runtime" exists.
4330 * Return NULL if not, return its name in allocated memory otherwise.
4331 */
4332 static char_u *
4333vim_version_dir(vimdir)
4334 char_u *vimdir;
4335{
4336 char_u *p;
4337
4338 if (vimdir == NULL || *vimdir == NUL)
4339 return NULL;
4340 p = concat_fnames(vimdir, (char_u *)VIM_VERSION_NODOT, TRUE);
4341 if (p != NULL && mch_isdir(p))
4342 return p;
4343 vim_free(p);
4344 p = concat_fnames(vimdir, (char_u *)RUNTIME_DIRNAME, TRUE);
4345 if (p != NULL && mch_isdir(p))
4346 return p;
4347 vim_free(p);
4348 return NULL;
4349}
4350
4351/*
4352 * If the string between "p" and "pend" ends in "name/", return "pend" minus
4353 * the length of "name/". Otherwise return "pend".
4354 */
4355 static char_u *
4356remove_tail(p, pend, name)
4357 char_u *p;
4358 char_u *pend;
4359 char_u *name;
4360{
4361 int len = (int)STRLEN(name) + 1;
4362 char_u *newend = pend - len;
4363
4364 if (newend >= p
4365 && fnamencmp(newend, name, len - 1) == 0
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004366 && (newend == p || after_pathsep(p, newend)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004367 return newend;
4368 return pend;
4369}
4370
Bram Moolenaar071d4272004-06-13 20:20:40 +00004371/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004372 * Our portable version of setenv.
4373 */
4374 void
4375vim_setenv(name, val)
4376 char_u *name;
4377 char_u *val;
4378{
4379#ifdef HAVE_SETENV
4380 mch_setenv((char *)name, (char *)val, 1);
4381#else
4382 char_u *envbuf;
4383
4384 /*
4385 * Putenv does not copy the string, it has to remain
4386 * valid. The allocated memory will never be freed.
4387 */
4388 envbuf = alloc((unsigned)(STRLEN(name) + STRLEN(val) + 2));
4389 if (envbuf != NULL)
4390 {
4391 sprintf((char *)envbuf, "%s=%s", name, val);
4392 putenv((char *)envbuf);
4393 }
4394#endif
Bram Moolenaar011a34d2012-02-29 13:49:09 +01004395#ifdef FEAT_GETTEXT
4396 /*
4397 * When setting $VIMRUNTIME adjust the directory to find message
4398 * translations to $VIMRUNTIME/lang.
4399 */
4400 if (*val != NUL && STRICMP(name, "VIMRUNTIME") == 0)
4401 {
4402 char_u *buf = concat_str(val, (char_u *)"/lang");
4403
4404 if (buf != NULL)
4405 {
4406 bindtextdomain(VIMPACKAGE, (char *)buf);
4407 vim_free(buf);
4408 }
4409 }
4410#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004411}
4412
4413#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
4414/*
4415 * Function given to ExpandGeneric() to obtain an environment variable name.
4416 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004417 char_u *
4418get_env_name(xp, idx)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00004419 expand_T *xp UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004420 int idx;
4421{
4422# if defined(AMIGA) || defined(__MRC__) || defined(__SC__)
4423 /*
4424 * No environ[] on the Amiga and on the Mac (using MPW).
4425 */
4426 return NULL;
4427# else
4428# ifndef __WIN32__
4429 /* Borland C++ 5.2 has this in a header file. */
4430 extern char **environ;
4431# endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00004432# define ENVNAMELEN 100
4433 static char_u name[ENVNAMELEN];
Bram Moolenaar071d4272004-06-13 20:20:40 +00004434 char_u *str;
4435 int n;
4436
4437 str = (char_u *)environ[idx];
4438 if (str == NULL)
4439 return NULL;
4440
Bram Moolenaar21cf8232004-07-16 20:18:37 +00004441 for (n = 0; n < ENVNAMELEN - 1; ++n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004442 {
4443 if (str[n] == '=' || str[n] == NUL)
4444 break;
4445 name[n] = str[n];
4446 }
4447 name[n] = NUL;
4448 return name;
4449# endif
4450}
4451#endif
4452
4453/*
4454 * Replace home directory by "~" in each space or comma separated file name in
4455 * 'src'.
4456 * If anything fails (except when out of space) dst equals src.
4457 */
4458 void
4459home_replace(buf, src, dst, dstlen, one)
4460 buf_T *buf; /* when not NULL, check for help files */
4461 char_u *src; /* input file name */
4462 char_u *dst; /* where to put the result */
4463 int dstlen; /* maximum length of the result */
4464 int one; /* if TRUE, only replace one file name, include
4465 spaces and commas in the file name. */
4466{
4467 size_t dirlen = 0, envlen = 0;
4468 size_t len;
Bram Moolenaar9158f9e2012-06-20 14:02:27 +02004469 char_u *homedir_env, *homedir_env_orig;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004470 char_u *p;
4471
4472 if (src == NULL)
4473 {
4474 *dst = NUL;
4475 return;
4476 }
4477
4478 /*
4479 * If the file is a help file, remove the path completely.
4480 */
4481 if (buf != NULL && buf->b_help)
4482 {
4483 STRCPY(dst, gettail(src));
4484 return;
4485 }
4486
4487 /*
4488 * We check both the value of the $HOME environment variable and the
4489 * "real" home directory.
4490 */
4491 if (homedir != NULL)
4492 dirlen = STRLEN(homedir);
4493
4494#ifdef VMS
Bram Moolenaar9158f9e2012-06-20 14:02:27 +02004495 homedir_env_orig = homedir_env = mch_getenv((char_u *)"SYS$LOGIN");
Bram Moolenaar071d4272004-06-13 20:20:40 +00004496#else
Bram Moolenaar9158f9e2012-06-20 14:02:27 +02004497 homedir_env_orig = homedir_env = mch_getenv((char_u *)"HOME");
4498#endif
4499#if defined(FEAT_MODIFY_FNAME) || defined(WIN3264)
4500 if (vim_strchr(homedir_env, '~') != NULL)
4501 {
4502 int usedlen = 0;
4503 int flen;
4504 char_u *fbuf = NULL;
4505
4506 flen = (int)STRLEN(homedir_env);
Bram Moolenaard12f8112012-06-20 17:56:09 +02004507 (void)modify_fname((char_u *)":p", &usedlen,
4508 &homedir_env, &fbuf, &flen);
Bram Moolenaar9158f9e2012-06-20 14:02:27 +02004509 flen = (int)STRLEN(homedir_env);
4510 if (flen > 0 && vim_ispathsep(homedir_env[flen - 1]))
4511 /* Remove the trailing / that is added to a directory. */
4512 homedir_env[flen - 1] = NUL;
4513 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004514#endif
4515
4516 if (homedir_env != NULL && *homedir_env == NUL)
4517 homedir_env = NULL;
4518 if (homedir_env != NULL)
4519 envlen = STRLEN(homedir_env);
4520
4521 if (!one)
4522 src = skipwhite(src);
4523 while (*src && dstlen > 0)
4524 {
4525 /*
4526 * Here we are at the beginning of a file name.
4527 * First, check to see if the beginning of the file name matches
4528 * $HOME or the "real" home directory. Check that there is a '/'
4529 * after the match (so that if e.g. the file is "/home/pieter/bla",
4530 * and the home directory is "/home/piet", the file does not end up
4531 * as "~er/bla" (which would seem to indicate the file "bla" in user
4532 * er's home directory)).
4533 */
4534 p = homedir;
4535 len = dirlen;
4536 for (;;)
4537 {
4538 if ( len
4539 && fnamencmp(src, p, len) == 0
4540 && (vim_ispathsep(src[len])
4541 || (!one && (src[len] == ',' || src[len] == ' '))
4542 || src[len] == NUL))
4543 {
4544 src += len;
4545 if (--dstlen > 0)
4546 *dst++ = '~';
4547
4548 /*
4549 * If it's just the home directory, add "/".
4550 */
4551 if (!vim_ispathsep(src[0]) && --dstlen > 0)
4552 *dst++ = '/';
4553 break;
4554 }
4555 if (p == homedir_env)
4556 break;
4557 p = homedir_env;
4558 len = envlen;
4559 }
4560
4561 /* if (!one) skip to separator: space or comma */
4562 while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
4563 *dst++ = *src++;
4564 /* skip separator */
4565 while ((*src == ' ' || *src == ',') && --dstlen > 0)
4566 *dst++ = *src++;
4567 }
4568 /* if (dstlen == 0) out of space, what to do??? */
4569
4570 *dst = NUL;
Bram Moolenaar9158f9e2012-06-20 14:02:27 +02004571
4572 if (homedir_env != homedir_env_orig)
4573 vim_free(homedir_env);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004574}
4575
4576/*
4577 * Like home_replace, store the replaced string in allocated memory.
4578 * When something fails, NULL is returned.
4579 */
4580 char_u *
4581home_replace_save(buf, src)
4582 buf_T *buf; /* when not NULL, check for help files */
4583 char_u *src; /* input file name */
4584{
4585 char_u *dst;
4586 unsigned len;
4587
4588 len = 3; /* space for "~/" and trailing NUL */
4589 if (src != NULL) /* just in case */
4590 len += (unsigned)STRLEN(src);
4591 dst = alloc(len);
4592 if (dst != NULL)
4593 home_replace(buf, src, dst, len, TRUE);
4594 return dst;
4595}
4596
4597/*
4598 * Compare two file names and return:
4599 * FPC_SAME if they both exist and are the same file.
4600 * FPC_SAMEX if they both don't exist and have the same file name.
4601 * FPC_DIFF if they both exist and are different files.
4602 * FPC_NOTX if they both don't exist.
4603 * FPC_DIFFX if one of them doesn't exist.
4604 * For the first name environment variables are expanded
4605 */
4606 int
4607fullpathcmp(s1, s2, checkname)
4608 char_u *s1, *s2;
4609 int checkname; /* when both don't exist, check file names */
4610{
4611#ifdef UNIX
4612 char_u exp1[MAXPATHL];
4613 char_u full1[MAXPATHL];
4614 char_u full2[MAXPATHL];
4615 struct stat st1, st2;
4616 int r1, r2;
4617
4618 expand_env(s1, exp1, MAXPATHL);
4619 r1 = mch_stat((char *)exp1, &st1);
4620 r2 = mch_stat((char *)s2, &st2);
4621 if (r1 != 0 && r2 != 0)
4622 {
4623 /* if mch_stat() doesn't work, may compare the names */
4624 if (checkname)
4625 {
4626 if (fnamecmp(exp1, s2) == 0)
4627 return FPC_SAMEX;
4628 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4629 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4630 if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
4631 return FPC_SAMEX;
4632 }
4633 return FPC_NOTX;
4634 }
4635 if (r1 != 0 || r2 != 0)
4636 return FPC_DIFFX;
4637 if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
4638 return FPC_SAME;
4639 return FPC_DIFF;
4640#else
4641 char_u *exp1; /* expanded s1 */
4642 char_u *full1; /* full path of s1 */
4643 char_u *full2; /* full path of s2 */
4644 int retval = FPC_DIFF;
4645 int r1, r2;
4646
4647 /* allocate one buffer to store three paths (alloc()/free() is slow!) */
4648 if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
4649 {
4650 full1 = exp1 + MAXPATHL;
4651 full2 = full1 + MAXPATHL;
4652
4653 expand_env(s1, exp1, MAXPATHL);
4654 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4655 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4656
4657 /* If vim_FullName() fails, the file probably doesn't exist. */
4658 if (r1 != OK && r2 != OK)
4659 {
4660 if (checkname && fnamecmp(exp1, s2) == 0)
4661 retval = FPC_SAMEX;
4662 else
4663 retval = FPC_NOTX;
4664 }
4665 else if (r1 != OK || r2 != OK)
4666 retval = FPC_DIFFX;
4667 else if (fnamecmp(full1, full2))
4668 retval = FPC_DIFF;
4669 else
4670 retval = FPC_SAME;
4671 vim_free(exp1);
4672 }
4673 return retval;
4674#endif
4675}
4676
4677/*
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004678 * Get the tail of a path: the file name.
Bram Moolenaar31710262010-08-13 13:36:15 +02004679 * When the path ends in a path separator the tail is the NUL after it.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004680 * Fail safe: never returns NULL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004681 */
4682 char_u *
4683gettail(fname)
4684 char_u *fname;
4685{
4686 char_u *p1, *p2;
4687
4688 if (fname == NULL)
4689 return (char_u *)"";
4690 for (p1 = p2 = fname; *p2; ) /* find last part of path */
4691 {
4692 if (vim_ispathsep(*p2))
4693 p1 = p2 + 1;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004694 mb_ptr_adv(p2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004695 }
4696 return p1;
4697}
4698
Bram Moolenaar31710262010-08-13 13:36:15 +02004699#if defined(FEAT_SEARCHPATH)
4700static char_u *gettail_dir __ARGS((char_u *fname));
4701
4702/*
4703 * Return the end of the directory name, on the first path
4704 * separator:
4705 * "/path/file", "/path/dir/", "/path//dir", "/file"
4706 * ^ ^ ^ ^
4707 */
4708 static char_u *
4709gettail_dir(fname)
4710 char_u *fname;
4711{
4712 char_u *dir_end = fname;
4713 char_u *next_dir_end = fname;
4714 int look_for_sep = TRUE;
4715 char_u *p;
4716
4717 for (p = fname; *p != NUL; )
4718 {
4719 if (vim_ispathsep(*p))
4720 {
4721 if (look_for_sep)
4722 {
4723 next_dir_end = p;
4724 look_for_sep = FALSE;
4725 }
4726 }
4727 else
4728 {
4729 if (!look_for_sep)
4730 dir_end = next_dir_end;
4731 look_for_sep = TRUE;
4732 }
4733 mb_ptr_adv(p);
4734 }
4735 return dir_end;
4736}
4737#endif
4738
Bram Moolenaar071d4272004-06-13 20:20:40 +00004739/*
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004740 * Get pointer to tail of "fname", including path separators. Putting a NUL
4741 * here leaves the directory name. Takes care of "c:/" and "//".
4742 * Always returns a valid pointer.
4743 */
4744 char_u *
4745gettail_sep(fname)
4746 char_u *fname;
4747{
4748 char_u *p;
4749 char_u *t;
4750
4751 p = get_past_head(fname); /* don't remove the '/' from "c:/file" */
4752 t = gettail(fname);
4753 while (t > p && after_pathsep(fname, t))
4754 --t;
4755#ifdef VMS
4756 /* path separator is part of the path */
4757 ++t;
4758#endif
4759 return t;
4760}
4761
4762/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004763 * get the next path component (just after the next path separator).
4764 */
4765 char_u *
4766getnextcomp(fname)
4767 char_u *fname;
4768{
4769 while (*fname && !vim_ispathsep(*fname))
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004770 mb_ptr_adv(fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004771 if (*fname)
4772 ++fname;
4773 return fname;
4774}
4775
Bram Moolenaar071d4272004-06-13 20:20:40 +00004776/*
4777 * Get a pointer to one character past the head of a path name.
4778 * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
4779 * If there is no head, path is returned.
4780 */
4781 char_u *
4782get_past_head(path)
4783 char_u *path;
4784{
4785 char_u *retval;
4786
4787#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
4788 /* may skip "c:" */
4789 if (isalpha(path[0]) && path[1] == ':')
4790 retval = path + 2;
4791 else
4792 retval = path;
4793#else
4794# if defined(AMIGA)
4795 /* may skip "label:" */
4796 retval = vim_strchr(path, ':');
4797 if (retval == NULL)
4798 retval = path;
4799# else /* Unix */
4800 retval = path;
4801# endif
4802#endif
4803
4804 while (vim_ispathsep(*retval))
4805 ++retval;
4806
4807 return retval;
4808}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004809
4810/*
4811 * return TRUE if 'c' is a path separator.
4812 */
4813 int
4814vim_ispathsep(c)
4815 int c;
4816{
Bram Moolenaare60acc12011-05-10 16:41:25 +02004817#ifdef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00004818 return (c == '/'); /* UNIX has ':' inside file names */
Bram Moolenaare60acc12011-05-10 16:41:25 +02004819#else
4820# ifdef BACKSLASH_IN_FILENAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00004821 return (c == ':' || c == '/' || c == '\\');
Bram Moolenaare60acc12011-05-10 16:41:25 +02004822# else
4823# ifdef VMS
Bram Moolenaar071d4272004-06-13 20:20:40 +00004824 /* server"user passwd"::device:[full.path.name]fname.extension;version" */
4825 return (c == ':' || c == '[' || c == ']' || c == '/'
4826 || c == '<' || c == '>' || c == '"' );
Bram Moolenaare60acc12011-05-10 16:41:25 +02004827# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004828 return (c == ':' || c == '/');
Bram Moolenaare60acc12011-05-10 16:41:25 +02004829# endif /* VMS */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004830# endif
Bram Moolenaare60acc12011-05-10 16:41:25 +02004831#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004832}
4833
4834#if defined(FEAT_SEARCHPATH) || defined(PROTO)
4835/*
4836 * return TRUE if 'c' is a path list separator.
4837 */
4838 int
4839vim_ispathlistsep(c)
4840 int c;
4841{
4842#ifdef UNIX
4843 return (c == ':');
4844#else
Bram Moolenaar25394022007-05-10 19:06:20 +00004845 return (c == ';'); /* might not be right for every system... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004846#endif
4847}
4848#endif
4849
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004850#if defined(FEAT_GUI_TABLINE) || defined(FEAT_WINDOWS) \
4851 || defined(FEAT_EVAL) || defined(PROTO)
4852/*
4853 * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
4854 * It's done in-place.
4855 */
4856 void
4857shorten_dir(str)
4858 char_u *str;
4859{
4860 char_u *tail, *s, *d;
4861 int skip = FALSE;
4862
4863 tail = gettail(str);
4864 d = str;
4865 for (s = str; ; ++s)
4866 {
4867 if (s >= tail) /* copy the whole tail */
4868 {
4869 *d++ = *s;
4870 if (*s == NUL)
4871 break;
4872 }
4873 else if (vim_ispathsep(*s)) /* copy '/' and next char */
4874 {
4875 *d++ = *s;
4876 skip = FALSE;
4877 }
4878 else if (!skip)
4879 {
4880 *d++ = *s; /* copy next char */
4881 if (*s != '~' && *s != '.') /* and leading "~" and "." */
4882 skip = TRUE;
4883# ifdef FEAT_MBYTE
4884 if (has_mbyte)
4885 {
4886 int l = mb_ptr2len(s);
4887
4888 while (--l > 0)
Bram Moolenaarb6baca52006-08-15 20:24:14 +00004889 *d++ = *++s;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004890 }
4891# endif
4892 }
4893 }
4894}
4895#endif
4896
Bram Moolenaar900b4d72005-12-12 22:05:50 +00004897/*
4898 * Return TRUE if the directory of "fname" exists, FALSE otherwise.
4899 * Also returns TRUE if there is no directory name.
4900 * "fname" must be writable!.
4901 */
4902 int
4903dir_of_file_exists(fname)
4904 char_u *fname;
4905{
4906 char_u *p;
4907 int c;
4908 int retval;
4909
4910 p = gettail_sep(fname);
4911 if (p == fname)
4912 return TRUE;
4913 c = *p;
4914 *p = NUL;
4915 retval = mch_isdir(fname);
4916 *p = c;
4917 return retval;
4918}
4919
Bram Moolenaar071d4272004-06-13 20:20:40 +00004920#if (defined(CASE_INSENSITIVE_FILENAME) && defined(BACKSLASH_IN_FILENAME)) \
4921 || defined(PROTO)
4922/*
4923 * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally.
4924 */
4925 int
4926vim_fnamecmp(x, y)
4927 char_u *x, *y;
4928{
4929 return vim_fnamencmp(x, y, MAXPATHL);
4930}
4931
4932 int
4933vim_fnamencmp(x, y, len)
4934 char_u *x, *y;
4935 size_t len;
4936{
4937 while (len > 0 && *x && *y)
4938 {
4939 if (TOLOWER_LOC(*x) != TOLOWER_LOC(*y)
4940 && !(*x == '/' && *y == '\\')
4941 && !(*x == '\\' && *y == '/'))
4942 break;
4943 ++x;
4944 ++y;
4945 --len;
4946 }
4947 if (len == 0)
4948 return 0;
4949 return (*x - *y);
4950}
4951#endif
4952
4953/*
4954 * Concatenate file names fname1 and fname2 into allocated memory.
Bram Moolenaar25394022007-05-10 19:06:20 +00004955 * Only add a '/' or '\\' when 'sep' is TRUE and it is necessary.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004956 */
4957 char_u *
4958concat_fnames(fname1, fname2, sep)
4959 char_u *fname1;
4960 char_u *fname2;
4961 int sep;
4962{
4963 char_u *dest;
4964
4965 dest = alloc((unsigned)(STRLEN(fname1) + STRLEN(fname2) + 3));
4966 if (dest != NULL)
4967 {
4968 STRCPY(dest, fname1);
4969 if (sep)
4970 add_pathsep(dest);
4971 STRCAT(dest, fname2);
4972 }
4973 return dest;
4974}
4975
Bram Moolenaard6754642005-01-17 22:18:45 +00004976/*
4977 * Concatenate two strings and return the result in allocated memory.
4978 * Returns NULL when out of memory.
4979 */
4980 char_u *
4981concat_str(str1, str2)
4982 char_u *str1;
4983 char_u *str2;
4984{
4985 char_u *dest;
4986 size_t l = STRLEN(str1);
4987
4988 dest = alloc((unsigned)(l + STRLEN(str2) + 1L));
4989 if (dest != NULL)
4990 {
4991 STRCPY(dest, str1);
4992 STRCPY(dest + l, str2);
4993 }
4994 return dest;
4995}
Bram Moolenaard6754642005-01-17 22:18:45 +00004996
Bram Moolenaar071d4272004-06-13 20:20:40 +00004997/*
4998 * Add a path separator to a file name, unless it already ends in a path
4999 * separator.
5000 */
5001 void
5002add_pathsep(p)
5003 char_u *p;
5004{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005005 if (*p != NUL && !after_pathsep(p, p + STRLEN(p)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005006 STRCAT(p, PATHSEPSTR);
5007}
5008
5009/*
5010 * FullName_save - Make an allocated copy of a full file name.
5011 * Returns NULL when out of memory.
5012 */
5013 char_u *
5014FullName_save(fname, force)
5015 char_u *fname;
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +02005016 int force; /* force expansion, even when it already looks
5017 * like a full path name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005018{
5019 char_u *buf;
5020 char_u *new_fname = NULL;
5021
5022 if (fname == NULL)
5023 return NULL;
5024
5025 buf = alloc((unsigned)MAXPATHL);
5026 if (buf != NULL)
5027 {
5028 if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
5029 new_fname = vim_strsave(buf);
5030 else
5031 new_fname = vim_strsave(fname);
5032 vim_free(buf);
5033 }
5034 return new_fname;
5035}
5036
5037#if defined(FEAT_CINDENT) || defined(FEAT_SYN_HL)
5038
5039static char_u *skip_string __ARGS((char_u *p));
5040
5041/*
5042 * Find the start of a comment, not knowing if we are in a comment right now.
5043 * Search starts at w_cursor.lnum and goes backwards.
5044 */
5045 pos_T *
5046find_start_comment(ind_maxcomment) /* XXX */
5047 int ind_maxcomment;
5048{
5049 pos_T *pos;
5050 char_u *line;
5051 char_u *p;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005052 int cur_maxcomment = ind_maxcomment;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005053
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005054 for (;;)
5055 {
5056 pos = findmatchlimit(NULL, '*', FM_BACKWARD, cur_maxcomment);
5057 if (pos == NULL)
5058 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005059
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005060 /*
5061 * Check if the comment start we found is inside a string.
5062 * If it is then restrict the search to below this line and try again.
5063 */
5064 line = ml_get(pos->lnum);
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00005065 for (p = line; *p && (colnr_T)(p - line) < pos->col; ++p)
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005066 p = skip_string(p);
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00005067 if ((colnr_T)(p - line) <= pos->col)
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005068 break;
5069 cur_maxcomment = curwin->w_cursor.lnum - pos->lnum - 1;
5070 if (cur_maxcomment <= 0)
5071 {
5072 pos = NULL;
5073 break;
5074 }
5075 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005076 return pos;
5077}
5078
5079/*
5080 * Skip to the end of a "string" and a 'c' character.
5081 * If there is no string or character, return argument unmodified.
5082 */
5083 static char_u *
5084skip_string(p)
5085 char_u *p;
5086{
5087 int i;
5088
5089 /*
5090 * We loop, because strings may be concatenated: "date""time".
5091 */
5092 for ( ; ; ++p)
5093 {
5094 if (p[0] == '\'') /* 'c' or '\n' or '\000' */
5095 {
5096 if (!p[1]) /* ' at end of line */
5097 break;
5098 i = 2;
5099 if (p[1] == '\\') /* '\n' or '\000' */
5100 {
5101 ++i;
5102 while (vim_isdigit(p[i - 1])) /* '\000' */
5103 ++i;
5104 }
5105 if (p[i] == '\'') /* check for trailing ' */
5106 {
5107 p += i;
5108 continue;
5109 }
5110 }
5111 else if (p[0] == '"') /* start of string */
5112 {
5113 for (++p; p[0]; ++p)
5114 {
5115 if (p[0] == '\\' && p[1] != NUL)
5116 ++p;
5117 else if (p[0] == '"') /* end of string */
5118 break;
5119 }
5120 if (p[0] == '"')
5121 continue;
5122 }
5123 break; /* no string found */
5124 }
5125 if (!*p)
5126 --p; /* backup from NUL */
5127 return p;
5128}
5129#endif /* FEAT_CINDENT || FEAT_SYN_HL */
5130
5131#if defined(FEAT_CINDENT) || defined(PROTO)
5132
5133/*
5134 * Do C or expression indenting on the current line.
5135 */
5136 void
5137do_c_expr_indent()
5138{
5139# ifdef FEAT_EVAL
5140 if (*curbuf->b_p_inde != NUL)
5141 fixthisline(get_expr_indent);
5142 else
5143# endif
5144 fixthisline(get_c_indent);
5145}
5146
5147/*
5148 * Functions for C-indenting.
5149 * Most of this originally comes from Eric Fischer.
5150 */
5151/*
5152 * Below "XXX" means that this function may unlock the current line.
5153 */
5154
5155static char_u *cin_skipcomment __ARGS((char_u *));
5156static int cin_nocode __ARGS((char_u *));
5157static pos_T *find_line_comment __ARGS((void));
5158static int cin_islabel_skip __ARGS((char_u **));
5159static int cin_isdefault __ARGS((char_u *));
5160static char_u *after_label __ARGS((char_u *l));
5161static int get_indent_nolabel __ARGS((linenr_T lnum));
5162static int skip_label __ARGS((linenr_T, char_u **pp, int ind_maxcomment));
5163static int cin_first_id_amount __ARGS((void));
5164static int cin_get_equal_amount __ARGS((linenr_T lnum));
5165static int cin_ispreproc __ARGS((char_u *));
5166static int cin_ispreproc_cont __ARGS((char_u **pp, linenr_T *lnump));
5167static int cin_iscomment __ARGS((char_u *));
5168static int cin_islinecomment __ARGS((char_u *));
5169static int cin_isterminated __ARGS((char_u *, int, int));
5170static int cin_isinit __ARGS((void));
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005171static int cin_isfuncdecl __ARGS((char_u **, linenr_T, linenr_T, int, int));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005172static int cin_isif __ARGS((char_u *));
5173static int cin_iselse __ARGS((char_u *));
5174static int cin_isdo __ARGS((char_u *));
5175static int cin_iswhileofdo __ARGS((char_u *, linenr_T, int));
Bram Moolenaarb345d492012-04-09 20:42:26 +02005176static int cin_is_if_for_while_before_offset __ARGS((char_u *line, int *poffset));
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005177static int cin_iswhileofdo_end __ARGS((int terminated, int ind_maxparen, int ind_maxcomment));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005178static int cin_isbreak __ARGS((char_u *));
Bram Moolenaare7c56862007-08-04 10:14:52 +00005179static int cin_is_cpp_baseclass __ARGS((colnr_T *col));
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005180static int get_baseclass_amount __ARGS((int col, int ind_maxparen, int ind_maxcomment, int ind_cpp_baseclass));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005181static int cin_ends_in __ARGS((char_u *, char_u *, char_u *));
5182static int cin_skip2pos __ARGS((pos_T *trypos));
5183static pos_T *find_start_brace __ARGS((int));
5184static pos_T *find_match_paren __ARGS((int, int));
5185static int corr_ind_maxparen __ARGS((int ind_maxparen, pos_T *startpos));
5186static int find_last_paren __ARGS((char_u *l, int start, int end));
5187static int find_match __ARGS((int lookfor, linenr_T ourscope, int ind_maxparen, int ind_maxcomment));
Bram Moolenaared38b0a2011-05-25 15:16:18 +02005188static int cin_is_cpp_namespace __ARGS((char_u *));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005189
Bram Moolenaar39353fd2007-03-27 09:02:11 +00005190static int ind_hash_comment = 0; /* # starts a comment */
5191
Bram Moolenaar071d4272004-06-13 20:20:40 +00005192/*
5193 * Skip over white space and C comments within the line.
Bram Moolenaar39353fd2007-03-27 09:02:11 +00005194 * Also skip over Perl/shell comments if desired.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005195 */
5196 static char_u *
5197cin_skipcomment(s)
5198 char_u *s;
5199{
5200 while (*s)
5201 {
Bram Moolenaar39353fd2007-03-27 09:02:11 +00005202 char_u *prev_s = s;
5203
Bram Moolenaar071d4272004-06-13 20:20:40 +00005204 s = skipwhite(s);
Bram Moolenaar39353fd2007-03-27 09:02:11 +00005205
5206 /* Perl/shell # comment comment continues until eol. Require a space
5207 * before # to avoid recognizing $#array. */
5208 if (ind_hash_comment != 0 && s != prev_s && *s == '#')
5209 {
5210 s += STRLEN(s);
5211 break;
5212 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005213 if (*s != '/')
5214 break;
5215 ++s;
5216 if (*s == '/') /* slash-slash comment continues till eol */
5217 {
5218 s += STRLEN(s);
5219 break;
5220 }
5221 if (*s != '*')
5222 break;
5223 for (++s; *s; ++s) /* skip slash-star comment */
5224 if (s[0] == '*' && s[1] == '/')
5225 {
5226 s += 2;
5227 break;
5228 }
5229 }
5230 return s;
5231}
5232
5233/*
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005234 * Return TRUE if there is no code at *s. White space and comments are
Bram Moolenaar071d4272004-06-13 20:20:40 +00005235 * not considered code.
5236 */
5237 static int
5238cin_nocode(s)
5239 char_u *s;
5240{
5241 return *cin_skipcomment(s) == NUL;
5242}
5243
5244/*
5245 * Check previous lines for a "//" line comment, skipping over blank lines.
5246 */
5247 static pos_T *
5248find_line_comment() /* XXX */
5249{
5250 static pos_T pos;
5251 char_u *line;
5252 char_u *p;
5253
5254 pos = curwin->w_cursor;
5255 while (--pos.lnum > 0)
5256 {
5257 line = ml_get(pos.lnum);
5258 p = skipwhite(line);
5259 if (cin_islinecomment(p))
5260 {
5261 pos.col = (int)(p - line);
5262 return &pos;
5263 }
5264 if (*p != NUL)
5265 break;
5266 }
5267 return NULL;
5268}
5269
5270/*
5271 * Check if string matches "label:"; move to character after ':' if true.
5272 */
5273 static int
5274cin_islabel_skip(s)
5275 char_u **s;
5276{
5277 if (!vim_isIDc(**s)) /* need at least one ID character */
5278 return FALSE;
5279
5280 while (vim_isIDc(**s))
5281 (*s)++;
5282
5283 *s = cin_skipcomment(*s);
5284
5285 /* "::" is not a label, it's C++ */
5286 return (**s == ':' && *++*s != ':');
5287}
5288
5289/*
5290 * Recognize a label: "label:".
5291 * Note: curwin->w_cursor must be where we are looking for the label.
5292 */
5293 int
5294cin_islabel(ind_maxcomment) /* XXX */
5295 int ind_maxcomment;
5296{
5297 char_u *s;
5298
5299 s = cin_skipcomment(ml_get_curline());
5300
5301 /*
5302 * Exclude "default" from labels, since it should be indented
5303 * like a switch label. Same for C++ scope declarations.
5304 */
5305 if (cin_isdefault(s))
5306 return FALSE;
5307 if (cin_isscopedecl(s))
5308 return FALSE;
5309
5310 if (cin_islabel_skip(&s))
5311 {
5312 /*
5313 * Only accept a label if the previous line is terminated or is a case
5314 * label.
5315 */
5316 pos_T cursor_save;
5317 pos_T *trypos;
5318 char_u *line;
5319
5320 cursor_save = curwin->w_cursor;
5321 while (curwin->w_cursor.lnum > 1)
5322 {
5323 --curwin->w_cursor.lnum;
5324
5325 /*
5326 * If we're in a comment now, skip to the start of the comment.
5327 */
5328 curwin->w_cursor.col = 0;
5329 if ((trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
5330 curwin->w_cursor = *trypos;
5331
5332 line = ml_get_curline();
5333 if (cin_ispreproc(line)) /* ignore #defines, #if, etc. */
5334 continue;
5335 if (*(line = cin_skipcomment(line)) == NUL)
5336 continue;
5337
5338 curwin->w_cursor = cursor_save;
5339 if (cin_isterminated(line, TRUE, FALSE)
5340 || cin_isscopedecl(line)
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005341 || cin_iscase(line, TRUE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005342 || (cin_islabel_skip(&line) && cin_nocode(line)))
5343 return TRUE;
5344 return FALSE;
5345 }
5346 curwin->w_cursor = cursor_save;
5347 return TRUE; /* label at start of file??? */
5348 }
5349 return FALSE;
5350}
5351
5352/*
5353 * Recognize structure initialization and enumerations.
5354 * Q&D-Implementation:
5355 * check for "=" at end or "[typedef] enum" at beginning of line.
5356 */
5357 static int
5358cin_isinit(void)
5359{
5360 char_u *s;
5361
5362 s = cin_skipcomment(ml_get_curline());
5363
5364 if (STRNCMP(s, "typedef", 7) == 0 && !vim_isIDc(s[7]))
5365 s = cin_skipcomment(s + 7);
5366
Bram Moolenaara5285652011-12-14 20:05:21 +01005367 if (STRNCMP(s, "static", 6) == 0 && !vim_isIDc(s[6]))
5368 s = cin_skipcomment(s + 6);
5369
Bram Moolenaar071d4272004-06-13 20:20:40 +00005370 if (STRNCMP(s, "enum", 4) == 0 && !vim_isIDc(s[4]))
5371 return TRUE;
5372
5373 if (cin_ends_in(s, (char_u *)"=", (char_u *)"{"))
5374 return TRUE;
5375
5376 return FALSE;
5377}
5378
5379/*
5380 * Recognize a switch label: "case .*:" or "default:".
5381 */
5382 int
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005383cin_iscase(s, strict)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005384 char_u *s;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005385 int strict; /* Allow relaxed check of case statement for JS */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005386{
5387 s = cin_skipcomment(s);
5388 if (STRNCMP(s, "case", 4) == 0 && !vim_isIDc(s[4]))
5389 {
5390 for (s += 4; *s; ++s)
5391 {
5392 s = cin_skipcomment(s);
5393 if (*s == ':')
5394 {
5395 if (s[1] == ':') /* skip over "::" for C++ */
5396 ++s;
5397 else
5398 return TRUE;
5399 }
5400 if (*s == '\'' && s[1] && s[2] == '\'')
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005401 s += 2; /* skip over ':' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005402 else if (*s == '/' && (s[1] == '*' || s[1] == '/'))
5403 return FALSE; /* stop at comment */
5404 else if (*s == '"')
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005405 {
5406 /* JS etc. */
5407 if (strict)
5408 return FALSE; /* stop at string */
5409 else
5410 return TRUE;
5411 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005412 }
5413 return FALSE;
5414 }
5415
5416 if (cin_isdefault(s))
5417 return TRUE;
5418 return FALSE;
5419}
5420
5421/*
5422 * Recognize a "default" switch label.
5423 */
5424 static int
5425cin_isdefault(s)
5426 char_u *s;
5427{
5428 return (STRNCMP(s, "default", 7) == 0
5429 && *(s = cin_skipcomment(s + 7)) == ':'
5430 && s[1] != ':');
5431}
5432
5433/*
Bram Moolenaar1a509df2010-08-01 17:59:57 +02005434 * Recognize a "public/private/protected" scope declaration label.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005435 */
5436 int
5437cin_isscopedecl(s)
5438 char_u *s;
5439{
5440 int i;
5441
5442 s = cin_skipcomment(s);
5443 if (STRNCMP(s, "public", 6) == 0)
5444 i = 6;
5445 else if (STRNCMP(s, "protected", 9) == 0)
5446 i = 9;
5447 else if (STRNCMP(s, "private", 7) == 0)
5448 i = 7;
5449 else
5450 return FALSE;
5451 return (*(s = cin_skipcomment(s + i)) == ':' && s[1] != ':');
5452}
5453
Bram Moolenaared38b0a2011-05-25 15:16:18 +02005454/* Maximum number of lines to search back for a "namespace" line. */
5455#define FIND_NAMESPACE_LIM 20
5456
5457/*
5458 * Recognize a "namespace" scope declaration.
5459 */
5460 static int
5461cin_is_cpp_namespace(s)
5462 char_u *s;
5463{
5464 char_u *p;
5465 int has_name = FALSE;
5466
5467 s = cin_skipcomment(s);
5468 if (STRNCMP(s, "namespace", 9) == 0 && (s[9] == NUL || !vim_iswordc(s[9])))
5469 {
5470 p = cin_skipcomment(skipwhite(s + 9));
5471 while (*p != NUL)
5472 {
5473 if (vim_iswhite(*p))
5474 {
5475 has_name = TRUE; /* found end of a name */
5476 p = cin_skipcomment(skipwhite(p));
5477 }
5478 else if (*p == '{')
5479 {
5480 break;
5481 }
5482 else if (vim_iswordc(*p))
5483 {
5484 if (has_name)
5485 return FALSE; /* word character after skipping past name */
5486 ++p;
5487 }
5488 else
5489 {
5490 return FALSE;
5491 }
5492 }
5493 return TRUE;
5494 }
5495 return FALSE;
5496}
5497
Bram Moolenaar071d4272004-06-13 20:20:40 +00005498/*
5499 * Return a pointer to the first non-empty non-comment character after a ':'.
5500 * Return NULL if not found.
5501 * case 234: a = b;
5502 * ^
5503 */
5504 static char_u *
5505after_label(l)
5506 char_u *l;
5507{
5508 for ( ; *l; ++l)
5509 {
5510 if (*l == ':')
5511 {
5512 if (l[1] == ':') /* skip over "::" for C++ */
5513 ++l;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005514 else if (!cin_iscase(l + 1, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005515 break;
5516 }
5517 else if (*l == '\'' && l[1] && l[2] == '\'')
5518 l += 2; /* skip over 'x' */
5519 }
5520 if (*l == NUL)
5521 return NULL;
5522 l = cin_skipcomment(l + 1);
5523 if (*l == NUL)
5524 return NULL;
5525 return l;
5526}
5527
5528/*
5529 * Get indent of line "lnum", skipping a label.
5530 * Return 0 if there is nothing after the label.
5531 */
5532 static int
5533get_indent_nolabel(lnum) /* XXX */
5534 linenr_T lnum;
5535{
5536 char_u *l;
5537 pos_T fp;
5538 colnr_T col;
5539 char_u *p;
5540
5541 l = ml_get(lnum);
5542 p = after_label(l);
5543 if (p == NULL)
5544 return 0;
5545
5546 fp.col = (colnr_T)(p - l);
5547 fp.lnum = lnum;
5548 getvcol(curwin, &fp, &col, NULL, NULL);
5549 return (int)col;
5550}
5551
5552/*
5553 * Find indent for line "lnum", ignoring any case or jump label.
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005554 * Also return a pointer to the text (after the label) in "pp".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005555 * label: if (asdf && asdfasdf)
5556 * ^
5557 */
5558 static int
5559skip_label(lnum, pp, ind_maxcomment)
5560 linenr_T lnum;
5561 char_u **pp;
5562 int ind_maxcomment;
5563{
5564 char_u *l;
5565 int amount;
5566 pos_T cursor_save;
5567
5568 cursor_save = curwin->w_cursor;
5569 curwin->w_cursor.lnum = lnum;
5570 l = ml_get_curline();
5571 /* XXX */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005572 if (cin_iscase(l, FALSE) || cin_isscopedecl(l)
5573 || cin_islabel(ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005574 {
5575 amount = get_indent_nolabel(lnum);
5576 l = after_label(ml_get_curline());
5577 if (l == NULL) /* just in case */
5578 l = ml_get_curline();
5579 }
5580 else
5581 {
5582 amount = get_indent();
5583 l = ml_get_curline();
5584 }
5585 *pp = l;
5586
5587 curwin->w_cursor = cursor_save;
5588 return amount;
5589}
5590
5591/*
5592 * Return the indent of the first variable name after a type in a declaration.
5593 * int a, indent of "a"
5594 * static struct foo b, indent of "b"
5595 * enum bla c, indent of "c"
5596 * Returns zero when it doesn't look like a declaration.
5597 */
5598 static int
5599cin_first_id_amount()
5600{
5601 char_u *line, *p, *s;
5602 int len;
5603 pos_T fp;
5604 colnr_T col;
5605
5606 line = ml_get_curline();
5607 p = skipwhite(line);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005608 len = (int)(skiptowhite(p) - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005609 if (len == 6 && STRNCMP(p, "static", 6) == 0)
5610 {
5611 p = skipwhite(p + 6);
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00005612 len = (int)(skiptowhite(p) - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005613 }
5614 if (len == 6 && STRNCMP(p, "struct", 6) == 0)
5615 p = skipwhite(p + 6);
5616 else if (len == 4 && STRNCMP(p, "enum", 4) == 0)
5617 p = skipwhite(p + 4);
5618 else if ((len == 8 && STRNCMP(p, "unsigned", 8) == 0)
5619 || (len == 6 && STRNCMP(p, "signed", 6) == 0))
5620 {
5621 s = skipwhite(p + len);
5622 if ((STRNCMP(s, "int", 3) == 0 && vim_iswhite(s[3]))
5623 || (STRNCMP(s, "long", 4) == 0 && vim_iswhite(s[4]))
5624 || (STRNCMP(s, "short", 5) == 0 && vim_iswhite(s[5]))
5625 || (STRNCMP(s, "char", 4) == 0 && vim_iswhite(s[4])))
5626 p = s;
5627 }
5628 for (len = 0; vim_isIDc(p[len]); ++len)
5629 ;
5630 if (len == 0 || !vim_iswhite(p[len]) || cin_nocode(p))
5631 return 0;
5632
5633 p = skipwhite(p + len);
5634 fp.lnum = curwin->w_cursor.lnum;
5635 fp.col = (colnr_T)(p - line);
5636 getvcol(curwin, &fp, &col, NULL, NULL);
5637 return (int)col;
5638}
5639
5640/*
5641 * Return the indent of the first non-blank after an equal sign.
5642 * char *foo = "here";
5643 * Return zero if no (useful) equal sign found.
5644 * Return -1 if the line above "lnum" ends in a backslash.
5645 * foo = "asdf\
5646 * asdf\
5647 * here";
5648 */
5649 static int
5650cin_get_equal_amount(lnum)
5651 linenr_T lnum;
5652{
5653 char_u *line;
5654 char_u *s;
5655 colnr_T col;
5656 pos_T fp;
5657
5658 if (lnum > 1)
5659 {
5660 line = ml_get(lnum - 1);
5661 if (*line != NUL && line[STRLEN(line) - 1] == '\\')
5662 return -1;
5663 }
5664
5665 line = s = ml_get(lnum);
5666 while (*s != NUL && vim_strchr((char_u *)"=;{}\"'", *s) == NULL)
5667 {
5668 if (cin_iscomment(s)) /* ignore comments */
5669 s = cin_skipcomment(s);
5670 else
5671 ++s;
5672 }
5673 if (*s != '=')
5674 return 0;
5675
5676 s = skipwhite(s + 1);
5677 if (cin_nocode(s))
5678 return 0;
5679
5680 if (*s == '"') /* nice alignment for continued strings */
5681 ++s;
5682
5683 fp.lnum = lnum;
5684 fp.col = (colnr_T)(s - line);
5685 getvcol(curwin, &fp, &col, NULL, NULL);
5686 return (int)col;
5687}
5688
5689/*
5690 * Recognize a preprocessor statement: Any line that starts with '#'.
5691 */
5692 static int
5693cin_ispreproc(s)
5694 char_u *s;
5695{
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005696 if (*skipwhite(s) == '#')
Bram Moolenaar071d4272004-06-13 20:20:40 +00005697 return TRUE;
5698 return FALSE;
5699}
5700
5701/*
5702 * Return TRUE if line "*pp" at "*lnump" is a preprocessor statement or a
5703 * continuation line of a preprocessor statement. Decrease "*lnump" to the
5704 * start and return the line in "*pp".
5705 */
5706 static int
5707cin_ispreproc_cont(pp, lnump)
5708 char_u **pp;
5709 linenr_T *lnump;
5710{
5711 char_u *line = *pp;
5712 linenr_T lnum = *lnump;
5713 int retval = FALSE;
5714
Bram Moolenaard8e9bb22005-07-09 21:14:46 +00005715 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005716 {
5717 if (cin_ispreproc(line))
5718 {
5719 retval = TRUE;
5720 *lnump = lnum;
5721 break;
5722 }
5723 if (lnum == 1)
5724 break;
5725 line = ml_get(--lnum);
5726 if (*line == NUL || line[STRLEN(line) - 1] != '\\')
5727 break;
5728 }
5729
5730 if (lnum != *lnump)
5731 *pp = ml_get(*lnump);
5732 return retval;
5733}
5734
5735/*
5736 * Recognize the start of a C or C++ comment.
5737 */
5738 static int
5739cin_iscomment(p)
5740 char_u *p;
5741{
5742 return (p[0] == '/' && (p[1] == '*' || p[1] == '/'));
5743}
5744
5745/*
5746 * Recognize the start of a "//" comment.
5747 */
5748 static int
5749cin_islinecomment(p)
5750 char_u *p;
5751{
5752 return (p[0] == '/' && p[1] == '/');
5753}
5754
5755/*
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005756 * Recognize a line that starts with '{' or '}', or ends with ';', ',', '{' or
5757 * '}'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005758 * Don't consider "} else" a terminated line.
Bram Moolenaar496f9512011-05-19 16:35:09 +02005759 * If a line begins with an "else", only consider it terminated if no unmatched
5760 * opening braces follow (handle "else { foo();" correctly).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005761 * Return the character terminating the line (ending char's have precedence if
5762 * both apply in order to determine initializations).
5763 */
5764 static int
5765cin_isterminated(s, incl_open, incl_comma)
5766 char_u *s;
5767 int incl_open; /* include '{' at the end as terminator */
5768 int incl_comma; /* recognize a trailing comma */
5769{
Bram Moolenaar496f9512011-05-19 16:35:09 +02005770 char_u found_start = 0;
5771 unsigned n_open = 0;
5772 int is_else = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005773
5774 s = cin_skipcomment(s);
5775
5776 if (*s == '{' || (*s == '}' && !cin_iselse(s)))
5777 found_start = *s;
5778
Bram Moolenaar496f9512011-05-19 16:35:09 +02005779 if (!found_start)
5780 is_else = cin_iselse(s);
5781
Bram Moolenaar071d4272004-06-13 20:20:40 +00005782 while (*s)
5783 {
5784 /* skip over comments, "" strings and 'c'haracters */
5785 s = skip_string(cin_skipcomment(s));
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005786 if (*s == '}' && n_open > 0)
5787 --n_open;
Bram Moolenaar496f9512011-05-19 16:35:09 +02005788 if ((!is_else || n_open == 0)
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005789 && (*s == ';' || *s == '}' || (incl_comma && *s == ','))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005790 && cin_nocode(s + 1))
5791 return *s;
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005792 else if (*s == '{')
5793 {
5794 if (incl_open && cin_nocode(s + 1))
5795 return *s;
5796 else
5797 ++n_open;
5798 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005799
5800 if (*s)
5801 s++;
5802 }
5803 return found_start;
5804}
5805
5806/*
5807 * Recognize the basic picture of a function declaration -- it needs to
5808 * have an open paren somewhere and a close paren at the end of the line and
5809 * no semicolons anywhere.
5810 * When a line ends in a comma we continue looking in the next line.
5811 * "sp" points to a string with the line. When looking at other lines it must
5812 * be restored to the line. When it's NULL fetch lines here.
5813 * "lnum" is where we start looking.
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005814 * "min_lnum" is the line before which we will not be looking.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005815 */
5816 static int
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005817cin_isfuncdecl(sp, first_lnum, min_lnum, ind_maxparen, ind_maxcomment)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005818 char_u **sp;
5819 linenr_T first_lnum;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005820 linenr_T min_lnum;
5821 int ind_maxparen;
5822 int ind_maxcomment;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005823{
5824 char_u *s;
5825 linenr_T lnum = first_lnum;
5826 int retval = FALSE;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005827 pos_T *trypos;
5828 int just_started = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005829
5830 if (sp == NULL)
5831 s = ml_get(lnum);
5832 else
5833 s = *sp;
5834
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005835 if (find_last_paren(s, '(', ')')
5836 && (trypos = find_match_paren(ind_maxparen, ind_maxcomment)) != NULL)
5837 {
5838 lnum = trypos->lnum;
5839 if (lnum < min_lnum)
5840 return FALSE;
5841
5842 s = ml_get(lnum);
5843 }
5844
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005845 /* Ignore line starting with #. */
5846 if (cin_ispreproc(s))
5847 return FALSE;
5848
Bram Moolenaar071d4272004-06-13 20:20:40 +00005849 while (*s && *s != '(' && *s != ';' && *s != '\'' && *s != '"')
5850 {
5851 if (cin_iscomment(s)) /* ignore comments */
5852 s = cin_skipcomment(s);
5853 else
5854 ++s;
5855 }
5856 if (*s != '(')
5857 return FALSE; /* ';', ' or " before any () or no '(' */
5858
5859 while (*s && *s != ';' && *s != '\'' && *s != '"')
5860 {
5861 if (*s == ')' && cin_nocode(s + 1))
5862 {
5863 /* ')' at the end: may have found a match
5864 * Check for he previous line not to end in a backslash:
5865 * #if defined(x) && \
5866 * defined(y)
5867 */
5868 lnum = first_lnum - 1;
5869 s = ml_get(lnum);
5870 if (*s == NUL || s[STRLEN(s) - 1] != '\\')
5871 retval = TRUE;
5872 goto done;
5873 }
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005874 if ((*s == ',' && cin_nocode(s + 1)) || s[1] == NUL || cin_nocode(s))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005875 {
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005876 int comma = (*s == ',');
5877
5878 /* ',' at the end: continue looking in the next line.
5879 * At the end: check for ',' in the next line, for this style:
5880 * func(arg1
5881 * , arg2) */
5882 for (;;)
5883 {
5884 if (lnum >= curbuf->b_ml.ml_line_count)
5885 break;
5886 s = ml_get(++lnum);
5887 if (!cin_ispreproc(s))
5888 break;
5889 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005890 if (lnum >= curbuf->b_ml.ml_line_count)
5891 break;
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005892 /* Require a comma at end of the line or a comma or ')' at the
5893 * start of next line. */
5894 s = skipwhite(s);
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005895 if (!just_started && (!comma && *s != ',' && *s != ')'))
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005896 break;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005897 just_started = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005898 }
5899 else if (cin_iscomment(s)) /* ignore comments */
5900 s = cin_skipcomment(s);
5901 else
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005902 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005903 ++s;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005904 just_started = FALSE;
5905 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005906 }
5907
5908done:
5909 if (lnum != first_lnum && sp != NULL)
5910 *sp = ml_get(first_lnum);
5911
5912 return retval;
5913}
5914
5915 static int
5916cin_isif(p)
5917 char_u *p;
5918{
5919 return (STRNCMP(p, "if", 2) == 0 && !vim_isIDc(p[2]));
5920}
5921
5922 static int
5923cin_iselse(p)
5924 char_u *p;
5925{
5926 if (*p == '}') /* accept "} else" */
5927 p = cin_skipcomment(p + 1);
5928 return (STRNCMP(p, "else", 4) == 0 && !vim_isIDc(p[4]));
5929}
5930
5931 static int
5932cin_isdo(p)
5933 char_u *p;
5934{
5935 return (STRNCMP(p, "do", 2) == 0 && !vim_isIDc(p[2]));
5936}
5937
5938/*
5939 * Check if this is a "while" that should have a matching "do".
5940 * We only accept a "while (condition) ;", with only white space between the
5941 * ')' and ';'. The condition may be spread over several lines.
5942 */
5943 static int
5944cin_iswhileofdo(p, lnum, ind_maxparen) /* XXX */
5945 char_u *p;
5946 linenr_T lnum;
5947 int ind_maxparen;
5948{
5949 pos_T cursor_save;
5950 pos_T *trypos;
5951 int retval = FALSE;
5952
5953 p = cin_skipcomment(p);
5954 if (*p == '}') /* accept "} while (cond);" */
5955 p = cin_skipcomment(p + 1);
5956 if (STRNCMP(p, "while", 5) == 0 && !vim_isIDc(p[5]))
5957 {
5958 cursor_save = curwin->w_cursor;
5959 curwin->w_cursor.lnum = lnum;
5960 curwin->w_cursor.col = 0;
5961 p = ml_get_curline();
5962 while (*p && *p != 'w') /* skip any '}', until the 'w' of the "while" */
5963 {
5964 ++p;
5965 ++curwin->w_cursor.col;
5966 }
5967 if ((trypos = findmatchlimit(NULL, 0, 0, ind_maxparen)) != NULL
5968 && *cin_skipcomment(ml_get_pos(trypos) + 1) == ';')
5969 retval = TRUE;
5970 curwin->w_cursor = cursor_save;
5971 }
5972 return retval;
5973}
5974
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005975/*
Bram Moolenaarb345d492012-04-09 20:42:26 +02005976 * Check whether in "p" there is an "if", "for" or "while" before "*poffset".
Bram Moolenaar3675fa02012-04-05 17:17:42 +02005977 * Return 0 if there is none.
5978 * Otherwise return !0 and update "*poffset" to point to the place where the
5979 * string was found.
5980 */
5981 static int
Bram Moolenaarb345d492012-04-09 20:42:26 +02005982cin_is_if_for_while_before_offset(line, poffset)
Bram Moolenaar3675fa02012-04-05 17:17:42 +02005983 char_u *line;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02005984 int *poffset;
5985{
Bram Moolenaarb345d492012-04-09 20:42:26 +02005986 int offset = *poffset;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02005987
5988 if (offset-- < 2)
5989 return 0;
5990 while (offset > 2 && vim_iswhite(line[offset]))
5991 --offset;
5992
5993 offset -= 1;
5994 if (!STRNCMP(line + offset, "if", 2))
5995 goto probablyFound;
5996
5997 if (offset >= 1)
5998 {
5999 offset -= 1;
6000 if (!STRNCMP(line + offset, "for", 3))
6001 goto probablyFound;
6002
6003 if (offset >= 2)
6004 {
6005 offset -= 2;
6006 if (!STRNCMP(line + offset, "while", 5))
6007 goto probablyFound;
6008 }
6009 }
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006010 return 0;
Bram Moolenaarb345d492012-04-09 20:42:26 +02006011
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006012probablyFound:
6013 if (!offset || !vim_isIDc(line[offset - 1]))
6014 {
6015 *poffset = offset;
6016 return 1;
6017 }
6018 return 0;
6019}
6020
6021/*
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006022 * Return TRUE if we are at the end of a do-while.
6023 * do
6024 * nothing;
6025 * while (foo
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00006026 * && bar); <-- here
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006027 * Adjust the cursor to the line with "while".
6028 */
6029 static int
6030cin_iswhileofdo_end(terminated, ind_maxparen, ind_maxcomment)
6031 int terminated;
6032 int ind_maxparen;
6033 int ind_maxcomment;
6034{
6035 char_u *line;
6036 char_u *p;
6037 char_u *s;
6038 pos_T *trypos;
6039 int i;
6040
6041 if (terminated != ';') /* there must be a ';' at the end */
6042 return FALSE;
6043
6044 p = line = ml_get_curline();
6045 while (*p != NUL)
6046 {
6047 p = cin_skipcomment(p);
6048 if (*p == ')')
6049 {
6050 s = skipwhite(p + 1);
6051 if (*s == ';' && cin_nocode(s + 1))
6052 {
6053 /* Found ");" at end of the line, now check there is "while"
6054 * before the matching '('. XXX */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006055 i = (int)(p - line);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006056 curwin->w_cursor.col = i;
6057 trypos = find_match_paren(ind_maxparen, ind_maxcomment);
6058 if (trypos != NULL)
6059 {
6060 s = cin_skipcomment(ml_get(trypos->lnum));
6061 if (*s == '}') /* accept "} while (cond);" */
6062 s = cin_skipcomment(s + 1);
6063 if (STRNCMP(s, "while", 5) == 0 && !vim_isIDc(s[5]))
6064 {
6065 curwin->w_cursor.lnum = trypos->lnum;
6066 return TRUE;
6067 }
6068 }
6069
6070 /* Searching may have made "line" invalid, get it again. */
6071 line = ml_get_curline();
6072 p = line + i;
6073 }
6074 }
6075 if (*p != NUL)
6076 ++p;
6077 }
6078 return FALSE;
6079}
6080
Bram Moolenaar071d4272004-06-13 20:20:40 +00006081 static int
6082cin_isbreak(p)
6083 char_u *p;
6084{
6085 return (STRNCMP(p, "break", 5) == 0 && !vim_isIDc(p[5]));
6086}
6087
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006088/*
6089 * Find the position of a C++ base-class declaration or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006090 * constructor-initialization. eg:
6091 *
6092 * class MyClass :
6093 * baseClass <-- here
6094 * class MyClass : public baseClass,
6095 * anotherBaseClass <-- here (should probably lineup ??)
6096 * MyClass::MyClass(...) :
6097 * baseClass(...) <-- here (constructor-initialization)
Bram Moolenaar18144c82006-04-12 21:52:12 +00006098 *
6099 * This is a lot of guessing. Watch out for "cond ? func() : foo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00006100 */
6101 static int
Bram Moolenaare7c56862007-08-04 10:14:52 +00006102cin_is_cpp_baseclass(col)
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006103 colnr_T *col; /* return: column to align with */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006104{
6105 char_u *s;
6106 int class_or_struct, lookfor_ctor_init, cpp_base_class;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006107 linenr_T lnum = curwin->w_cursor.lnum;
Bram Moolenaare7c56862007-08-04 10:14:52 +00006108 char_u *line = ml_get_curline();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006109
6110 *col = 0;
6111
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006112 s = skipwhite(line);
6113 if (*s == '#') /* skip #define FOO x ? (x) : x */
6114 return FALSE;
6115 s = cin_skipcomment(s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006116 if (*s == NUL)
6117 return FALSE;
6118
6119 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
6120
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006121 /* Search for a line starting with '#', empty, ending in ';' or containing
6122 * '{' or '}' and start below it. This handles the following situations:
6123 * a = cond ?
6124 * func() :
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00006125 * asdf;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006126 * func::foo()
6127 * : something
6128 * {}
6129 * Foo::Foo (int one, int two)
6130 * : something(4),
6131 * somethingelse(3)
6132 * {}
6133 */
6134 while (lnum > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006135 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00006136 line = ml_get(lnum - 1);
6137 s = skipwhite(line);
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006138 if (*s == '#' || *s == NUL)
6139 break;
6140 while (*s != NUL)
6141 {
6142 s = cin_skipcomment(s);
6143 if (*s == '{' || *s == '}'
6144 || (*s == ';' && cin_nocode(s + 1)))
6145 break;
6146 if (*s != NUL)
6147 ++s;
6148 }
6149 if (*s != NUL)
6150 break;
6151 --lnum;
6152 }
6153
Bram Moolenaare7c56862007-08-04 10:14:52 +00006154 line = ml_get(lnum);
6155 s = cin_skipcomment(line);
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006156 for (;;)
6157 {
6158 if (*s == NUL)
6159 {
6160 if (lnum == curwin->w_cursor.lnum)
6161 break;
6162 /* Continue in the cursor line. */
Bram Moolenaare7c56862007-08-04 10:14:52 +00006163 line = ml_get(++lnum);
6164 s = cin_skipcomment(line);
6165 if (*s == NUL)
6166 continue;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006167 }
6168
Bram Moolenaaraede6ce2011-05-10 11:56:30 +02006169 if (s[0] == '"')
6170 s = skip_string(s) + 1;
6171 else if (s[0] == ':')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006172 {
6173 if (s[1] == ':')
6174 {
6175 /* skip double colon. It can't be a constructor
6176 * initialization any more */
6177 lookfor_ctor_init = FALSE;
6178 s = cin_skipcomment(s + 2);
6179 }
6180 else if (lookfor_ctor_init || class_or_struct)
6181 {
6182 /* we have something found, that looks like the start of
Bram Moolenaare21877a2008-02-13 09:58:14 +00006183 * cpp-base-class-declaration or constructor-initialization */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006184 cpp_base_class = TRUE;
6185 lookfor_ctor_init = class_or_struct = FALSE;
6186 *col = 0;
6187 s = cin_skipcomment(s + 1);
6188 }
6189 else
6190 s = cin_skipcomment(s + 1);
6191 }
6192 else if ((STRNCMP(s, "class", 5) == 0 && !vim_isIDc(s[5]))
6193 || (STRNCMP(s, "struct", 6) == 0 && !vim_isIDc(s[6])))
6194 {
6195 class_or_struct = TRUE;
6196 lookfor_ctor_init = FALSE;
6197
6198 if (*s == 'c')
6199 s = cin_skipcomment(s + 5);
6200 else
6201 s = cin_skipcomment(s + 6);
6202 }
6203 else
6204 {
6205 if (s[0] == '{' || s[0] == '}' || s[0] == ';')
6206 {
6207 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
6208 }
6209 else if (s[0] == ')')
6210 {
6211 /* Constructor-initialization is assumed if we come across
6212 * something like "):" */
6213 class_or_struct = FALSE;
6214 lookfor_ctor_init = TRUE;
6215 }
Bram Moolenaar18144c82006-04-12 21:52:12 +00006216 else if (s[0] == '?')
6217 {
6218 /* Avoid seeing '() :' after '?' as constructor init. */
6219 return FALSE;
6220 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006221 else if (!vim_isIDc(s[0]))
6222 {
6223 /* if it is not an identifier, we are wrong */
6224 class_or_struct = FALSE;
6225 lookfor_ctor_init = FALSE;
6226 }
6227 else if (*col == 0)
6228 {
6229 /* it can't be a constructor-initialization any more */
6230 lookfor_ctor_init = FALSE;
6231
6232 /* the first statement starts here: lineup with this one... */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006233 if (cpp_base_class)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006234 *col = (colnr_T)(s - line);
6235 }
6236
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006237 /* When the line ends in a comma don't align with it. */
6238 if (lnum == curwin->w_cursor.lnum && *s == ',' && cin_nocode(s + 1))
6239 *col = 0;
6240
Bram Moolenaar071d4272004-06-13 20:20:40 +00006241 s = cin_skipcomment(s + 1);
6242 }
6243 }
6244
6245 return cpp_base_class;
6246}
6247
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006248 static int
6249get_baseclass_amount(col, ind_maxparen, ind_maxcomment, ind_cpp_baseclass)
6250 int col;
6251 int ind_maxparen;
6252 int ind_maxcomment;
6253 int ind_cpp_baseclass;
6254{
6255 int amount;
6256 colnr_T vcol;
6257 pos_T *trypos;
6258
6259 if (col == 0)
6260 {
6261 amount = get_indent();
6262 if (find_last_paren(ml_get_curline(), '(', ')')
6263 && (trypos = find_match_paren(ind_maxparen,
6264 ind_maxcomment)) != NULL)
6265 amount = get_indent_lnum(trypos->lnum); /* XXX */
6266 if (!cin_ends_in(ml_get_curline(), (char_u *)",", NULL))
6267 amount += ind_cpp_baseclass;
6268 }
6269 else
6270 {
6271 curwin->w_cursor.col = col;
6272 getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
6273 amount = (int)vcol;
6274 }
6275 if (amount < ind_cpp_baseclass)
6276 amount = ind_cpp_baseclass;
6277 return amount;
6278}
6279
Bram Moolenaar071d4272004-06-13 20:20:40 +00006280/*
6281 * Return TRUE if string "s" ends with the string "find", possibly followed by
6282 * white space and comments. Skip strings and comments.
6283 * Ignore "ignore" after "find" if it's not NULL.
6284 */
6285 static int
6286cin_ends_in(s, find, ignore)
6287 char_u *s;
6288 char_u *find;
6289 char_u *ignore;
6290{
6291 char_u *p = s;
6292 char_u *r;
6293 int len = (int)STRLEN(find);
6294
6295 while (*p != NUL)
6296 {
6297 p = cin_skipcomment(p);
6298 if (STRNCMP(p, find, len) == 0)
6299 {
6300 r = skipwhite(p + len);
6301 if (ignore != NULL && STRNCMP(r, ignore, STRLEN(ignore)) == 0)
6302 r = skipwhite(r + STRLEN(ignore));
6303 if (cin_nocode(r))
6304 return TRUE;
6305 }
6306 if (*p != NUL)
6307 ++p;
6308 }
6309 return FALSE;
6310}
6311
6312/*
6313 * Skip strings, chars and comments until at or past "trypos".
6314 * Return the column found.
6315 */
6316 static int
6317cin_skip2pos(trypos)
6318 pos_T *trypos;
6319{
6320 char_u *line;
6321 char_u *p;
6322
6323 p = line = ml_get(trypos->lnum);
6324 while (*p && (colnr_T)(p - line) < trypos->col)
6325 {
6326 if (cin_iscomment(p))
6327 p = cin_skipcomment(p);
6328 else
6329 {
6330 p = skip_string(p);
6331 ++p;
6332 }
6333 }
6334 return (int)(p - line);
6335}
6336
6337/*
6338 * Find the '{' at the start of the block we are in.
6339 * Return NULL if no match found.
6340 * Ignore a '{' that is in a comment, makes indenting the next three lines
6341 * work. */
6342/* foo() */
6343/* { */
6344/* } */
6345
6346 static pos_T *
6347find_start_brace(ind_maxcomment) /* XXX */
6348 int ind_maxcomment;
6349{
6350 pos_T cursor_save;
6351 pos_T *trypos;
6352 pos_T *pos;
6353 static pos_T pos_copy;
6354
6355 cursor_save = curwin->w_cursor;
6356 while ((trypos = findmatchlimit(NULL, '{', FM_BLOCKSTOP, 0)) != NULL)
6357 {
6358 pos_copy = *trypos; /* copy pos_T, next findmatch will change it */
6359 trypos = &pos_copy;
6360 curwin->w_cursor = *trypos;
6361 pos = NULL;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006362 /* ignore the { if it's in a // or / * * / comment */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006363 if ((colnr_T)cin_skip2pos(trypos) == trypos->col
6364 && (pos = find_start_comment(ind_maxcomment)) == NULL) /* XXX */
6365 break;
6366 if (pos != NULL)
6367 curwin->w_cursor.lnum = pos->lnum;
6368 }
6369 curwin->w_cursor = cursor_save;
6370 return trypos;
6371}
6372
6373/*
6374 * Find the matching '(', failing if it is in a comment.
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006375 * Return NULL if no match found.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006376 */
6377 static pos_T *
6378find_match_paren(ind_maxparen, ind_maxcomment) /* XXX */
6379 int ind_maxparen;
6380 int ind_maxcomment;
6381{
6382 pos_T cursor_save;
6383 pos_T *trypos;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006384 static pos_T pos_copy;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006385
6386 cursor_save = curwin->w_cursor;
6387 if ((trypos = findmatchlimit(NULL, '(', 0, ind_maxparen)) != NULL)
6388 {
6389 /* check if the ( is in a // comment */
6390 if ((colnr_T)cin_skip2pos(trypos) > trypos->col)
6391 trypos = NULL;
6392 else
6393 {
6394 pos_copy = *trypos; /* copy trypos, findmatch will change it */
6395 trypos = &pos_copy;
6396 curwin->w_cursor = *trypos;
6397 if (find_start_comment(ind_maxcomment) != NULL) /* XXX */
6398 trypos = NULL;
6399 }
6400 }
6401 curwin->w_cursor = cursor_save;
6402 return trypos;
6403}
6404
6405/*
6406 * Return ind_maxparen corrected for the difference in line number between the
6407 * cursor position and "startpos". This makes sure that searching for a
6408 * matching paren above the cursor line doesn't find a match because of
6409 * looking a few lines further.
6410 */
6411 static int
6412corr_ind_maxparen(ind_maxparen, startpos)
6413 int ind_maxparen;
6414 pos_T *startpos;
6415{
6416 long n = (long)startpos->lnum - (long)curwin->w_cursor.lnum;
6417
6418 if (n > 0 && n < ind_maxparen / 2)
6419 return ind_maxparen - (int)n;
6420 return ind_maxparen;
6421}
6422
6423/*
6424 * Set w_cursor.col to the column number of the last unmatched ')' or '{' in
Bram Moolenaar6d8f9c62011-11-30 13:03:28 +01006425 * line "l". "l" must point to the start of the line.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006426 */
6427 static int
6428find_last_paren(l, start, end)
6429 char_u *l;
6430 int start, end;
6431{
6432 int i;
6433 int retval = FALSE;
6434 int open_count = 0;
6435
6436 curwin->w_cursor.col = 0; /* default is start of line */
6437
Bram Moolenaar6d8f9c62011-11-30 13:03:28 +01006438 for (i = 0; l[i] != NUL; i++)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006439 {
6440 i = (int)(cin_skipcomment(l + i) - l); /* ignore parens in comments */
6441 i = (int)(skip_string(l + i) - l); /* ignore parens in quotes */
6442 if (l[i] == start)
6443 ++open_count;
6444 else if (l[i] == end)
6445 {
6446 if (open_count > 0)
6447 --open_count;
6448 else
6449 {
6450 curwin->w_cursor.col = i;
6451 retval = TRUE;
6452 }
6453 }
6454 }
6455 return retval;
6456}
6457
6458 int
6459get_c_indent()
6460{
6461 /*
6462 * spaces from a block's opening brace the prevailing indent for that
6463 * block should be
6464 */
6465 int ind_level = curbuf->b_p_sw;
6466
6467 /*
6468 * spaces from the edge of the line an open brace that's at the end of a
6469 * line is imagined to be.
6470 */
6471 int ind_open_imag = 0;
6472
6473 /*
Bram Moolenaar1a509df2010-08-01 17:59:57 +02006474 * spaces from the prevailing indent for a line that is not preceded by
Bram Moolenaar071d4272004-06-13 20:20:40 +00006475 * an opening brace.
6476 */
6477 int ind_no_brace = 0;
6478
6479 /*
6480 * column where the first { of a function should be located }
6481 */
6482 int ind_first_open = 0;
6483
6484 /*
6485 * spaces from the prevailing indent a leftmost open brace should be
6486 * located
6487 */
6488 int ind_open_extra = 0;
6489
6490 /*
6491 * spaces from the matching open brace (real location for one at the left
6492 * edge; imaginary location from one that ends a line) the matching close
6493 * brace should be located
6494 */
6495 int ind_close_extra = 0;
6496
6497 /*
6498 * spaces from the edge of the line an open brace sitting in the leftmost
6499 * column is imagined to be
6500 */
6501 int ind_open_left_imag = 0;
6502
6503 /*
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006504 * Spaces jump labels should be shifted to the left if N is non-negative,
6505 * otherwise the jump label will be put to column 1.
6506 */
6507 int ind_jump_label = -1;
6508
6509 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006510 * spaces from the switch() indent a "case xx" label should be located
6511 */
6512 int ind_case = curbuf->b_p_sw;
6513
6514 /*
6515 * spaces from the "case xx:" code after a switch() should be located
6516 */
6517 int ind_case_code = curbuf->b_p_sw;
6518
6519 /*
6520 * lineup break at end of case in switch() with case label
6521 */
6522 int ind_case_break = 0;
6523
6524 /*
6525 * spaces from the class declaration indent a scope declaration label
6526 * should be located
6527 */
6528 int ind_scopedecl = curbuf->b_p_sw;
6529
6530 /*
6531 * spaces from the scope declaration label code should be located
6532 */
6533 int ind_scopedecl_code = curbuf->b_p_sw;
6534
6535 /*
6536 * amount K&R-style parameters should be indented
6537 */
6538 int ind_param = curbuf->b_p_sw;
6539
6540 /*
6541 * amount a function type spec should be indented
6542 */
6543 int ind_func_type = curbuf->b_p_sw;
6544
6545 /*
6546 * amount a cpp base class declaration or constructor initialization
6547 * should be indented
6548 */
6549 int ind_cpp_baseclass = curbuf->b_p_sw;
6550
6551 /*
6552 * additional spaces beyond the prevailing indent a continuation line
6553 * should be located
6554 */
6555 int ind_continuation = curbuf->b_p_sw;
6556
6557 /*
6558 * spaces from the indent of the line with an unclosed parentheses
6559 */
6560 int ind_unclosed = curbuf->b_p_sw * 2;
6561
6562 /*
6563 * spaces from the indent of the line with an unclosed parentheses, which
6564 * itself is also unclosed
6565 */
6566 int ind_unclosed2 = curbuf->b_p_sw;
6567
6568 /*
6569 * suppress ignoring spaces from the indent of a line starting with an
6570 * unclosed parentheses.
6571 */
6572 int ind_unclosed_noignore = 0;
6573
6574 /*
6575 * If the opening paren is the last nonwhite character on the line, and
6576 * ind_unclosed_wrapped is nonzero, use this indent relative to the outer
6577 * context (for very long lines).
6578 */
6579 int ind_unclosed_wrapped = 0;
6580
6581 /*
6582 * suppress ignoring white space when lining up with the character after
6583 * an unclosed parentheses.
6584 */
6585 int ind_unclosed_whiteok = 0;
6586
6587 /*
6588 * indent a closing parentheses under the line start of the matching
6589 * opening parentheses.
6590 */
6591 int ind_matching_paren = 0;
6592
6593 /*
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006594 * indent a closing parentheses under the previous line.
6595 */
6596 int ind_paren_prev = 0;
6597
6598 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006599 * Extra indent for comments.
6600 */
6601 int ind_comment = 0;
6602
6603 /*
6604 * spaces from the comment opener when there is nothing after it.
6605 */
6606 int ind_in_comment = 3;
6607
6608 /*
6609 * boolean: if non-zero, use ind_in_comment even if there is something
6610 * after the comment opener.
6611 */
6612 int ind_in_comment2 = 0;
6613
6614 /*
6615 * max lines to search for an open paren
6616 */
6617 int ind_maxparen = 20;
6618
6619 /*
6620 * max lines to search for an open comment
6621 */
6622 int ind_maxcomment = 70;
6623
6624 /*
6625 * handle braces for java code
6626 */
6627 int ind_java = 0;
6628
6629 /*
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006630 * not to confuse JS object properties with labels
6631 */
6632 int ind_js = 0;
6633
6634 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006635 * handle blocked cases correctly
6636 */
6637 int ind_keep_case_label = 0;
6638
Bram Moolenaared38b0a2011-05-25 15:16:18 +02006639 /*
6640 * handle C++ namespace
6641 */
6642 int ind_cpp_namespace = 0;
6643
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006644 /*
6645 * handle continuation lines containing conditions of if(), for() and
6646 * while()
6647 */
6648 int ind_if_for_while = 0;
6649
Bram Moolenaar071d4272004-06-13 20:20:40 +00006650 pos_T cur_curpos;
6651 int amount;
6652 int scope_amount;
Bram Moolenaarb21e5842006-04-16 18:30:08 +00006653 int cur_amount = MAXCOL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006654 colnr_T col;
6655 char_u *theline;
6656 char_u *linecopy;
6657 pos_T *trypos;
6658 pos_T *tryposBrace = NULL;
6659 pos_T our_paren_pos;
6660 char_u *start;
6661 int start_brace;
Bram Moolenaare21877a2008-02-13 09:58:14 +00006662#define BRACE_IN_COL0 1 /* '{' is in column 0 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006663#define BRACE_AT_START 2 /* '{' is at start of line */
6664#define BRACE_AT_END 3 /* '{' is at end of line */
6665 linenr_T ourscope;
6666 char_u *l;
6667 char_u *look;
6668 char_u terminated;
6669 int lookfor;
6670#define LOOKFOR_INITIAL 0
6671#define LOOKFOR_IF 1
6672#define LOOKFOR_DO 2
6673#define LOOKFOR_CASE 3
6674#define LOOKFOR_ANY 4
6675#define LOOKFOR_TERM 5
6676#define LOOKFOR_UNTERM 6
6677#define LOOKFOR_SCOPEDECL 7
6678#define LOOKFOR_NOBREAK 8
6679#define LOOKFOR_CPP_BASECLASS 9
6680#define LOOKFOR_ENUM_OR_INIT 10
6681
6682 int whilelevel;
6683 linenr_T lnum;
6684 char_u *options;
Bram Moolenaar48d27922012-06-13 13:40:48 +02006685 char_u *digits;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006686 int fraction = 0; /* init for GCC */
6687 int divider;
6688 int n;
6689 int iscase;
6690 int lookfor_break;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02006691 int lookfor_cpp_namespace = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006692 int cont_amount = 0; /* amount for continuation line */
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006693 int original_line_islabel;
Bram Moolenaare79d1532011-10-04 18:03:47 +02006694 int added_to_amount = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006695
6696 for (options = curbuf->b_p_cino; *options; )
6697 {
6698 l = options++;
6699 if (*options == '-')
6700 ++options;
Bram Moolenaar48d27922012-06-13 13:40:48 +02006701 digits = options; /* remember where the digits start */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006702 n = getdigits(&options);
6703 divider = 0;
6704 if (*options == '.') /* ".5s" means a fraction */
6705 {
6706 fraction = atol((char *)++options);
6707 while (VIM_ISDIGIT(*options))
6708 {
6709 ++options;
6710 if (divider)
6711 divider *= 10;
6712 else
6713 divider = 10;
6714 }
6715 }
6716 if (*options == 's') /* "2s" means two times 'shiftwidth' */
6717 {
Bram Moolenaar48d27922012-06-13 13:40:48 +02006718 if (options == digits)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006719 n = curbuf->b_p_sw; /* just "s" is one 'shiftwidth' */
6720 else
6721 {
6722 n *= curbuf->b_p_sw;
6723 if (divider)
6724 n += (curbuf->b_p_sw * fraction + divider / 2) / divider;
6725 }
6726 ++options;
6727 }
6728 if (l[1] == '-')
6729 n = -n;
6730 /* When adding an entry here, also update the default 'cinoptions' in
Bram Moolenaar39353fd2007-03-27 09:02:11 +00006731 * doc/indent.txt, and add explanation for it! */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006732 switch (*l)
6733 {
6734 case '>': ind_level = n; break;
6735 case 'e': ind_open_imag = n; break;
6736 case 'n': ind_no_brace = n; break;
6737 case 'f': ind_first_open = n; break;
6738 case '{': ind_open_extra = n; break;
6739 case '}': ind_close_extra = n; break;
6740 case '^': ind_open_left_imag = n; break;
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006741 case 'L': ind_jump_label = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006742 case ':': ind_case = n; break;
6743 case '=': ind_case_code = n; break;
6744 case 'b': ind_case_break = n; break;
6745 case 'p': ind_param = n; break;
6746 case 't': ind_func_type = n; break;
6747 case '/': ind_comment = n; break;
6748 case 'c': ind_in_comment = n; break;
6749 case 'C': ind_in_comment2 = n; break;
6750 case 'i': ind_cpp_baseclass = n; break;
6751 case '+': ind_continuation = n; break;
6752 case '(': ind_unclosed = n; break;
6753 case 'u': ind_unclosed2 = n; break;
6754 case 'U': ind_unclosed_noignore = n; break;
6755 case 'W': ind_unclosed_wrapped = n; break;
6756 case 'w': ind_unclosed_whiteok = n; break;
6757 case 'm': ind_matching_paren = n; break;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006758 case 'M': ind_paren_prev = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006759 case ')': ind_maxparen = n; break;
6760 case '*': ind_maxcomment = n; break;
6761 case 'g': ind_scopedecl = n; break;
6762 case 'h': ind_scopedecl_code = n; break;
6763 case 'j': ind_java = n; break;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006764 case 'J': ind_js = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006765 case 'l': ind_keep_case_label = n; break;
Bram Moolenaar39353fd2007-03-27 09:02:11 +00006766 case '#': ind_hash_comment = n; break;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02006767 case 'N': ind_cpp_namespace = n; break;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006768 case 'k': ind_if_for_while = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006769 }
Bram Moolenaardfdf3c42010-03-23 18:22:46 +01006770 if (*options == ',')
6771 ++options;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006772 }
6773
6774 /* remember where the cursor was when we started */
6775 cur_curpos = curwin->w_cursor;
6776
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006777 /* if we are at line 1 0 is fine, right? */
6778 if (cur_curpos.lnum == 1)
6779 return 0;
6780
Bram Moolenaar071d4272004-06-13 20:20:40 +00006781 /* Get a copy of the current contents of the line.
6782 * This is required, because only the most recent line obtained with
6783 * ml_get is valid! */
6784 linecopy = vim_strsave(ml_get(cur_curpos.lnum));
6785 if (linecopy == NULL)
6786 return 0;
6787
6788 /*
6789 * In insert mode and the cursor is on a ')' truncate the line at the
6790 * cursor position. We don't want to line up with the matching '(' when
6791 * inserting new stuff.
6792 * For unknown reasons the cursor might be past the end of the line, thus
6793 * check for that.
6794 */
6795 if ((State & INSERT)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006796 && curwin->w_cursor.col < (colnr_T)STRLEN(linecopy)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006797 && linecopy[curwin->w_cursor.col] == ')')
6798 linecopy[curwin->w_cursor.col] = NUL;
6799
6800 theline = skipwhite(linecopy);
6801
6802 /* move the cursor to the start of the line */
6803
6804 curwin->w_cursor.col = 0;
6805
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006806 original_line_islabel = cin_islabel(ind_maxcomment); /* XXX */
6807
Bram Moolenaar071d4272004-06-13 20:20:40 +00006808 /*
6809 * #defines and so on always go at the left when included in 'cinkeys'.
6810 */
6811 if (*theline == '#' && (*linecopy == '#' || in_cinkeys('#', ' ', TRUE)))
6812 {
6813 amount = 0;
6814 }
6815
6816 /*
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006817 * Is it a non-case label? Then that goes at the left margin too unless:
6818 * - JS flag is set.
6819 * - 'L' item has a positive value.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006820 */
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006821 else if (original_line_islabel && !ind_js && ind_jump_label < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006822 {
6823 amount = 0;
6824 }
6825
6826 /*
6827 * If we're inside a "//" comment and there is a "//" comment in a
6828 * previous line, lineup with that one.
6829 */
6830 else if (cin_islinecomment(theline)
6831 && (trypos = find_line_comment()) != NULL) /* XXX */
6832 {
6833 /* find how indented the line beginning the comment is */
6834 getvcol(curwin, trypos, &col, NULL, NULL);
6835 amount = col;
6836 }
6837
6838 /*
6839 * If we're inside a comment and not looking at the start of the
6840 * comment, try using the 'comments' option.
6841 */
6842 else if (!cin_iscomment(theline)
6843 && (trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
6844 {
6845 int lead_start_len = 2;
6846 int lead_middle_len = 1;
6847 char_u lead_start[COM_MAX_LEN]; /* start-comment string */
6848 char_u lead_middle[COM_MAX_LEN]; /* middle-comment string */
6849 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
6850 char_u *p;
6851 int start_align = 0;
6852 int start_off = 0;
6853 int done = FALSE;
6854
6855 /* find how indented the line beginning the comment is */
6856 getvcol(curwin, trypos, &col, NULL, NULL);
6857 amount = col;
Bram Moolenaar4aa97422011-04-11 14:27:38 +02006858 *lead_start = NUL;
6859 *lead_middle = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006860
6861 p = curbuf->b_p_com;
6862 while (*p != NUL)
6863 {
6864 int align = 0;
6865 int off = 0;
6866 int what = 0;
6867
6868 while (*p != NUL && *p != ':')
6869 {
6870 if (*p == COM_START || *p == COM_END || *p == COM_MIDDLE)
6871 what = *p++;
6872 else if (*p == COM_LEFT || *p == COM_RIGHT)
6873 align = *p++;
6874 else if (VIM_ISDIGIT(*p) || *p == '-')
6875 off = getdigits(&p);
6876 else
6877 ++p;
6878 }
6879
6880 if (*p == ':')
6881 ++p;
6882 (void)copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
6883 if (what == COM_START)
6884 {
6885 STRCPY(lead_start, lead_end);
6886 lead_start_len = (int)STRLEN(lead_start);
6887 start_off = off;
6888 start_align = align;
6889 }
6890 else if (what == COM_MIDDLE)
6891 {
6892 STRCPY(lead_middle, lead_end);
6893 lead_middle_len = (int)STRLEN(lead_middle);
6894 }
6895 else if (what == COM_END)
6896 {
6897 /* If our line starts with the middle comment string, line it
6898 * up with the comment opener per the 'comments' option. */
6899 if (STRNCMP(theline, lead_middle, lead_middle_len) == 0
6900 && STRNCMP(theline, lead_end, STRLEN(lead_end)) != 0)
6901 {
6902 done = TRUE;
6903 if (curwin->w_cursor.lnum > 1)
6904 {
6905 /* If the start comment string matches in the previous
Bram Moolenaare21877a2008-02-13 09:58:14 +00006906 * line, use the indent of that line plus offset. If
Bram Moolenaar071d4272004-06-13 20:20:40 +00006907 * the middle comment string matches in the previous
6908 * line, use the indent of that line. XXX */
6909 look = skipwhite(ml_get(curwin->w_cursor.lnum - 1));
6910 if (STRNCMP(look, lead_start, lead_start_len) == 0)
6911 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6912 else if (STRNCMP(look, lead_middle,
6913 lead_middle_len) == 0)
6914 {
6915 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6916 break;
6917 }
6918 /* If the start comment string doesn't match with the
6919 * start of the comment, skip this entry. XXX */
6920 else if (STRNCMP(ml_get(trypos->lnum) + trypos->col,
6921 lead_start, lead_start_len) != 0)
6922 continue;
6923 }
6924 if (start_off != 0)
6925 amount += start_off;
6926 else if (start_align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006927 amount += vim_strsize(lead_start)
6928 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006929 break;
6930 }
6931
6932 /* If our line starts with the end comment string, line it up
6933 * with the middle comment */
6934 if (STRNCMP(theline, lead_middle, lead_middle_len) != 0
6935 && STRNCMP(theline, lead_end, STRLEN(lead_end)) == 0)
6936 {
6937 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6938 /* XXX */
6939 if (off != 0)
6940 amount += off;
6941 else if (align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006942 amount += vim_strsize(lead_start)
6943 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006944 done = TRUE;
6945 break;
6946 }
6947 }
6948 }
6949
6950 /* If our line starts with an asterisk, line up with the
6951 * asterisk in the comment opener; otherwise, line up
6952 * with the first character of the comment text.
6953 */
6954 if (done)
6955 ;
6956 else if (theline[0] == '*')
6957 amount += 1;
6958 else
6959 {
6960 /*
6961 * If we are more than one line away from the comment opener, take
6962 * the indent of the previous non-empty line. If 'cino' has "CO"
6963 * and we are just below the comment opener and there are any
6964 * white characters after it line up with the text after it;
6965 * otherwise, add the amount specified by "c" in 'cino'
6966 */
6967 amount = -1;
6968 for (lnum = cur_curpos.lnum - 1; lnum > trypos->lnum; --lnum)
6969 {
6970 if (linewhite(lnum)) /* skip blank lines */
6971 continue;
6972 amount = get_indent_lnum(lnum); /* XXX */
6973 break;
6974 }
6975 if (amount == -1) /* use the comment opener */
6976 {
6977 if (!ind_in_comment2)
6978 {
6979 start = ml_get(trypos->lnum);
6980 look = start + trypos->col + 2; /* skip / and * */
6981 if (*look != NUL) /* if something after it */
6982 trypos->col = (colnr_T)(skipwhite(look) - start);
6983 }
6984 getvcol(curwin, trypos, &col, NULL, NULL);
6985 amount = col;
6986 if (ind_in_comment2 || *look == NUL)
6987 amount += ind_in_comment;
6988 }
6989 }
6990 }
6991
6992 /*
6993 * Are we inside parentheses or braces?
6994 */ /* XXX */
6995 else if (((trypos = find_match_paren(ind_maxparen, ind_maxcomment)) != NULL
6996 && ind_java == 0)
6997 || (tryposBrace = find_start_brace(ind_maxcomment)) != NULL
6998 || trypos != NULL)
6999 {
7000 if (trypos != NULL && tryposBrace != NULL)
7001 {
7002 /* Both an unmatched '(' and '{' is found. Use the one which is
7003 * closer to the current cursor position, set the other to NULL. */
7004 if (trypos->lnum != tryposBrace->lnum
7005 ? trypos->lnum < tryposBrace->lnum
7006 : trypos->col < tryposBrace->col)
7007 trypos = NULL;
7008 else
7009 tryposBrace = NULL;
7010 }
7011
7012 if (trypos != NULL)
7013 {
7014 /*
7015 * If the matching paren is more than one line away, use the indent of
7016 * a previous non-empty line that matches the same paren.
7017 */
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007018 if (theline[0] == ')' && ind_paren_prev)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007019 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007020 /* Line up with the start of the matching paren line. */
7021 amount = get_indent_lnum(curwin->w_cursor.lnum - 1); /* XXX */
7022 }
7023 else
7024 {
7025 amount = -1;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007026 our_paren_pos = *trypos;
7027 for (lnum = cur_curpos.lnum - 1; lnum > our_paren_pos.lnum; --lnum)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007028 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007029 l = skipwhite(ml_get(lnum));
7030 if (cin_nocode(l)) /* skip comment lines */
7031 continue;
7032 if (cin_ispreproc_cont(&l, &lnum))
7033 continue; /* ignore #define, #if, etc. */
7034 curwin->w_cursor.lnum = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007035
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007036 /* Skip a comment. XXX */
7037 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
7038 {
7039 lnum = trypos->lnum + 1;
7040 continue;
7041 }
7042
7043 /* XXX */
7044 if ((trypos = find_match_paren(
7045 corr_ind_maxparen(ind_maxparen, &cur_curpos),
Bram Moolenaar071d4272004-06-13 20:20:40 +00007046 ind_maxcomment)) != NULL
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007047 && trypos->lnum == our_paren_pos.lnum
7048 && trypos->col == our_paren_pos.col)
7049 {
7050 amount = get_indent_lnum(lnum); /* XXX */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007051
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007052 if (theline[0] == ')')
7053 {
7054 if (our_paren_pos.lnum != lnum
7055 && cur_amount > amount)
7056 cur_amount = amount;
7057 amount = -1;
7058 }
7059 break;
7060 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007061 }
7062 }
7063
7064 /*
7065 * Line up with line where the matching paren is. XXX
7066 * If the line starts with a '(' or the indent for unclosed
7067 * parentheses is zero, line up with the unclosed parentheses.
7068 */
7069 if (amount == -1)
7070 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007071 int ignore_paren_col = 0;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007072 int is_if_for_while = 0;
7073
7074 if (ind_if_for_while)
7075 {
7076 /* Look for the outermost opening parenthesis on this line
7077 * and check whether it belongs to an "if", "for" or "while". */
7078
7079 pos_T cursor_save = curwin->w_cursor;
7080 pos_T outermost;
7081 char_u *line;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007082
7083 trypos = &our_paren_pos;
7084 do {
7085 outermost = *trypos;
7086 curwin->w_cursor.lnum = outermost.lnum;
7087 curwin->w_cursor.col = outermost.col;
7088
7089 trypos = find_match_paren(ind_maxparen, ind_maxcomment);
7090 } while (trypos && trypos->lnum == outermost.lnum);
7091
7092 curwin->w_cursor = cursor_save;
7093
7094 line = ml_get(outermost.lnum);
7095
7096 is_if_for_while =
Bram Moolenaarb345d492012-04-09 20:42:26 +02007097 cin_is_if_for_while_before_offset(line, &outermost.col);
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007098 }
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007099
Bram Moolenaar071d4272004-06-13 20:20:40 +00007100 amount = skip_label(our_paren_pos.lnum, &look, ind_maxcomment);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007101 look = skipwhite(look);
7102 if (*look == '(')
7103 {
7104 linenr_T save_lnum = curwin->w_cursor.lnum;
7105 char_u *line;
7106 int look_col;
7107
7108 /* Ignore a '(' in front of the line that has a match before
7109 * our matching '('. */
7110 curwin->w_cursor.lnum = our_paren_pos.lnum;
7111 line = ml_get_curline();
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007112 look_col = (int)(look - line);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007113 curwin->w_cursor.col = look_col + 1;
7114 if ((trypos = findmatchlimit(NULL, ')', 0, ind_maxparen))
7115 != NULL
7116 && trypos->lnum == our_paren_pos.lnum
7117 && trypos->col < our_paren_pos.col)
7118 ignore_paren_col = trypos->col + 1;
7119
7120 curwin->w_cursor.lnum = save_lnum;
7121 look = ml_get(our_paren_pos.lnum) + look_col;
7122 }
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007123 if (theline[0] == ')' || (ind_unclosed == 0 && is_if_for_while == 0)
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007124 || (!ind_unclosed_noignore && *look == '('
7125 && ignore_paren_col == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007126 {
7127 /*
7128 * If we're looking at a close paren, line up right there;
7129 * otherwise, line up with the next (non-white) character.
7130 * When ind_unclosed_wrapped is set and the matching paren is
7131 * the last nonwhite character of the line, use either the
7132 * indent of the current line or the indentation of the next
7133 * outer paren and add ind_unclosed_wrapped (for very long
7134 * lines).
7135 */
7136 if (theline[0] != ')')
7137 {
7138 cur_amount = MAXCOL;
7139 l = ml_get(our_paren_pos.lnum);
7140 if (ind_unclosed_wrapped
7141 && cin_ends_in(l, (char_u *)"(", NULL))
7142 {
7143 /* look for opening unmatched paren, indent one level
7144 * for each additional level */
7145 n = 1;
7146 for (col = 0; col < our_paren_pos.col; ++col)
7147 {
7148 switch (l[col])
7149 {
7150 case '(':
7151 case '{': ++n;
7152 break;
7153
7154 case ')':
7155 case '}': if (n > 1)
7156 --n;
7157 break;
7158 }
7159 }
7160
7161 our_paren_pos.col = 0;
7162 amount += n * ind_unclosed_wrapped;
7163 }
7164 else if (ind_unclosed_whiteok)
7165 our_paren_pos.col++;
7166 else
7167 {
7168 col = our_paren_pos.col + 1;
7169 while (vim_iswhite(l[col]))
7170 col++;
7171 if (l[col] != NUL) /* In case of trailing space */
7172 our_paren_pos.col = col;
7173 else
7174 our_paren_pos.col++;
7175 }
7176 }
7177
7178 /*
7179 * Find how indented the paren is, or the character after it
7180 * if we did the above "if".
7181 */
7182 if (our_paren_pos.col > 0)
7183 {
7184 getvcol(curwin, &our_paren_pos, &col, NULL, NULL);
7185 if (cur_amount > (int)col)
7186 cur_amount = col;
7187 }
7188 }
7189
7190 if (theline[0] == ')' && ind_matching_paren)
7191 {
7192 /* Line up with the start of the matching paren line. */
7193 }
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007194 else if ((ind_unclosed == 0 && is_if_for_while == 0)
7195 || (!ind_unclosed_noignore
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007196 && *look == '(' && ignore_paren_col == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007197 {
7198 if (cur_amount != MAXCOL)
7199 amount = cur_amount;
7200 }
7201 else
7202 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007203 /* Add ind_unclosed2 for each '(' before our matching one, but
7204 * ignore (void) before the line (ignore_paren_col). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007205 col = our_paren_pos.col;
Bram Moolenaarb21e5842006-04-16 18:30:08 +00007206 while ((int)our_paren_pos.col > ignore_paren_col)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007207 {
7208 --our_paren_pos.col;
7209 switch (*ml_get_pos(&our_paren_pos))
7210 {
7211 case '(': amount += ind_unclosed2;
7212 col = our_paren_pos.col;
7213 break;
7214 case ')': amount -= ind_unclosed2;
7215 col = MAXCOL;
7216 break;
7217 }
7218 }
7219
7220 /* Use ind_unclosed once, when the first '(' is not inside
7221 * braces */
7222 if (col == MAXCOL)
7223 amount += ind_unclosed;
7224 else
7225 {
7226 curwin->w_cursor.lnum = our_paren_pos.lnum;
7227 curwin->w_cursor.col = col;
Bram Moolenaar367bec82011-04-11 14:26:19 +02007228 if (find_match_paren(ind_maxparen, ind_maxcomment) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007229 amount += ind_unclosed2;
7230 else
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007231 {
7232 if (is_if_for_while)
7233 amount += ind_if_for_while;
7234 else
7235 amount += ind_unclosed;
7236 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007237 }
7238 /*
7239 * For a line starting with ')' use the minimum of the two
7240 * positions, to avoid giving it more indent than the previous
7241 * lines:
7242 * func_long_name( if (x
7243 * arg && yy
7244 * ) ^ not here ) ^ not here
7245 */
7246 if (cur_amount < amount)
7247 amount = cur_amount;
7248 }
7249 }
7250
7251 /* add extra indent for a comment */
7252 if (cin_iscomment(theline))
7253 amount += ind_comment;
7254 }
7255
7256 /*
7257 * Are we at least inside braces, then?
7258 */
7259 else
7260 {
7261 trypos = tryposBrace;
7262
7263 ourscope = trypos->lnum;
7264 start = ml_get(ourscope);
7265
7266 /*
7267 * Now figure out how indented the line is in general.
7268 * If the brace was at the start of the line, we use that;
7269 * otherwise, check out the indentation of the line as
7270 * a whole and then add the "imaginary indent" to that.
7271 */
7272 look = skipwhite(start);
7273 if (*look == '{')
7274 {
7275 getvcol(curwin, trypos, &col, NULL, NULL);
7276 amount = col;
7277 if (*start == '{')
7278 start_brace = BRACE_IN_COL0;
7279 else
7280 start_brace = BRACE_AT_START;
7281 }
7282 else
7283 {
7284 /*
7285 * that opening brace might have been on a continuation
7286 * line. if so, find the start of the line.
7287 */
7288 curwin->w_cursor.lnum = ourscope;
7289
7290 /*
7291 * position the cursor over the rightmost paren, so that
7292 * matching it will take us back to the start of the line.
7293 */
7294 lnum = ourscope;
7295 if (find_last_paren(start, '(', ')')
7296 && (trypos = find_match_paren(ind_maxparen,
7297 ind_maxcomment)) != NULL)
7298 lnum = trypos->lnum;
7299
7300 /*
7301 * It could have been something like
7302 * case 1: if (asdf &&
7303 * ldfd) {
7304 * }
7305 */
Bram Moolenaar6ec154b2011-06-12 21:51:08 +02007306 if (ind_js || (ind_keep_case_label
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007307 && cin_iscase(skipwhite(ml_get_curline()), FALSE)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007308 amount = get_indent();
7309 else
7310 amount = skip_label(lnum, &l, ind_maxcomment);
7311
7312 start_brace = BRACE_AT_END;
7313 }
7314
7315 /*
7316 * if we're looking at a closing brace, that's where
7317 * we want to be. otherwise, add the amount of room
7318 * that an indent is supposed to be.
7319 */
7320 if (theline[0] == '}')
7321 {
7322 /*
7323 * they may want closing braces to line up with something
7324 * other than the open brace. indulge them, if so.
7325 */
7326 amount += ind_close_extra;
7327 }
7328 else
7329 {
7330 /*
7331 * If we're looking at an "else", try to find an "if"
7332 * to match it with.
7333 * If we're looking at a "while", try to find a "do"
7334 * to match it with.
7335 */
7336 lookfor = LOOKFOR_INITIAL;
7337 if (cin_iselse(theline))
7338 lookfor = LOOKFOR_IF;
7339 else if (cin_iswhileofdo(theline, cur_curpos.lnum, ind_maxparen))
7340 /* XXX */
7341 lookfor = LOOKFOR_DO;
7342 if (lookfor != LOOKFOR_INITIAL)
7343 {
7344 curwin->w_cursor.lnum = cur_curpos.lnum;
7345 if (find_match(lookfor, ourscope, ind_maxparen,
7346 ind_maxcomment) == OK)
7347 {
7348 amount = get_indent(); /* XXX */
7349 goto theend;
7350 }
7351 }
7352
7353 /*
7354 * We get here if we are not on an "while-of-do" or "else" (or
7355 * failed to find a matching "if").
7356 * Search backwards for something to line up with.
7357 * First set amount for when we don't find anything.
7358 */
7359
7360 /*
7361 * if the '{' is _really_ at the left margin, use the imaginary
7362 * location of a left-margin brace. Otherwise, correct the
7363 * location for ind_open_extra.
7364 */
7365
7366 if (start_brace == BRACE_IN_COL0) /* '{' is in column 0 */
7367 {
7368 amount = ind_open_left_imag;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007369 lookfor_cpp_namespace = TRUE;
7370 }
7371 else if (start_brace == BRACE_AT_START &&
7372 lookfor_cpp_namespace) /* '{' is at start */
7373 {
7374
7375 lookfor_cpp_namespace = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007376 }
7377 else
7378 {
7379 if (start_brace == BRACE_AT_END) /* '{' is at end of line */
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007380 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007381 amount += ind_open_imag;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007382
7383 l = skipwhite(ml_get_curline());
7384 if (cin_is_cpp_namespace(l))
7385 amount += ind_cpp_namespace;
7386 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007387 else
7388 {
7389 /* Compensate for adding ind_open_extra later. */
7390 amount -= ind_open_extra;
7391 if (amount < 0)
7392 amount = 0;
7393 }
7394 }
7395
7396 lookfor_break = FALSE;
7397
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007398 if (cin_iscase(theline, FALSE)) /* it's a switch() label */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007399 {
7400 lookfor = LOOKFOR_CASE; /* find a previous switch() label */
7401 amount += ind_case;
7402 }
7403 else if (cin_isscopedecl(theline)) /* private:, ... */
7404 {
7405 lookfor = LOOKFOR_SCOPEDECL; /* class decl is this block */
7406 amount += ind_scopedecl;
7407 }
7408 else
7409 {
7410 if (ind_case_break && cin_isbreak(theline)) /* break; ... */
7411 lookfor_break = TRUE;
7412
7413 lookfor = LOOKFOR_INITIAL;
7414 amount += ind_level; /* ind_level from start of block */
7415 }
7416 scope_amount = amount;
7417 whilelevel = 0;
7418
7419 /*
7420 * Search backwards. If we find something we recognize, line up
7421 * with that.
7422 *
7423 * if we're looking at an open brace, indent
7424 * the usual amount relative to the conditional
7425 * that opens the block.
7426 */
7427 curwin->w_cursor = cur_curpos;
7428 for (;;)
7429 {
7430 curwin->w_cursor.lnum--;
7431 curwin->w_cursor.col = 0;
7432
7433 /*
7434 * If we went all the way back to the start of our scope, line
7435 * up with it.
7436 */
7437 if (curwin->w_cursor.lnum <= ourscope)
7438 {
7439 /* we reached end of scope:
7440 * if looking for a enum or structure initialization
7441 * go further back:
7442 * if it is an initializer (enum xxx or xxx =), then
7443 * don't add ind_continuation, otherwise it is a variable
7444 * declaration:
7445 * int x,
7446 * here; <-- add ind_continuation
7447 */
7448 if (lookfor == LOOKFOR_ENUM_OR_INIT)
7449 {
7450 if (curwin->w_cursor.lnum == 0
7451 || curwin->w_cursor.lnum
7452 < ourscope - ind_maxparen)
7453 {
7454 /* nothing found (abuse ind_maxparen as limit)
7455 * assume terminated line (i.e. a variable
7456 * initialization) */
7457 if (cont_amount > 0)
7458 amount = cont_amount;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007459 else if (!ind_js)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007460 amount += ind_continuation;
7461 break;
7462 }
7463
7464 l = ml_get_curline();
7465
7466 /*
7467 * If we're in a comment now, skip to the start of the
7468 * comment.
7469 */
7470 trypos = find_start_comment(ind_maxcomment);
7471 if (trypos != NULL)
7472 {
7473 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007474 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007475 continue;
7476 }
7477
7478 /*
7479 * Skip preprocessor directives and blank lines.
7480 */
7481 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7482 continue;
7483
7484 if (cin_nocode(l))
7485 continue;
7486
7487 terminated = cin_isterminated(l, FALSE, TRUE);
7488
7489 /*
7490 * If we are at top level and the line looks like a
7491 * function declaration, we are done
7492 * (it's a variable declaration).
7493 */
7494 if (start_brace != BRACE_IN_COL0
Bram Moolenaarc367faa2011-12-14 20:21:35 +01007495 || !cin_isfuncdecl(&l, curwin->w_cursor.lnum,
7496 0, ind_maxparen, ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007497 {
7498 /* if the line is terminated with another ','
7499 * it is a continued variable initialization.
7500 * don't add extra indent.
7501 * TODO: does not work, if a function
7502 * declaration is split over multiple lines:
7503 * cin_isfuncdecl returns FALSE then.
7504 */
7505 if (terminated == ',')
7506 break;
7507
7508 /* if it es a enum declaration or an assignment,
7509 * we are done.
7510 */
7511 if (terminated != ';' && cin_isinit())
7512 break;
7513
7514 /* nothing useful found */
7515 if (terminated == 0 || terminated == '{')
7516 continue;
7517 }
7518
7519 if (terminated != ';')
7520 {
7521 /* Skip parens and braces. Position the cursor
7522 * over the rightmost paren, so that matching it
7523 * will take us back to the start of the line.
7524 */ /* XXX */
7525 trypos = NULL;
7526 if (find_last_paren(l, '(', ')'))
7527 trypos = find_match_paren(ind_maxparen,
7528 ind_maxcomment);
7529
7530 if (trypos == NULL && find_last_paren(l, '{', '}'))
7531 trypos = find_start_brace(ind_maxcomment);
7532
7533 if (trypos != NULL)
7534 {
7535 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007536 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007537 continue;
7538 }
7539 }
7540
7541 /* it's a variable declaration, add indentation
7542 * like in
7543 * int a,
7544 * b;
7545 */
7546 if (cont_amount > 0)
7547 amount = cont_amount;
7548 else
7549 amount += ind_continuation;
7550 }
7551 else if (lookfor == LOOKFOR_UNTERM)
7552 {
7553 if (cont_amount > 0)
7554 amount = cont_amount;
7555 else
7556 amount += ind_continuation;
7557 }
Bram Moolenaare79d1532011-10-04 18:03:47 +02007558 else
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007559 {
Bram Moolenaare79d1532011-10-04 18:03:47 +02007560 if (lookfor != LOOKFOR_TERM
Bram Moolenaar071d4272004-06-13 20:20:40 +00007561 && lookfor != LOOKFOR_CPP_BASECLASS)
Bram Moolenaare79d1532011-10-04 18:03:47 +02007562 {
7563 amount = scope_amount;
7564 if (theline[0] == '{')
7565 {
7566 amount += ind_open_extra;
7567 added_to_amount = ind_open_extra;
7568 }
7569 }
7570
7571 if (lookfor_cpp_namespace)
7572 {
7573 /*
7574 * Looking for C++ namespace, need to look further
7575 * back.
7576 */
7577 if (curwin->w_cursor.lnum == ourscope)
7578 continue;
7579
7580 if (curwin->w_cursor.lnum == 0
7581 || curwin->w_cursor.lnum
7582 < ourscope - FIND_NAMESPACE_LIM)
7583 break;
7584
7585 l = ml_get_curline();
7586
7587 /* If we're in a comment now, skip to the start of
7588 * the comment. */
7589 trypos = find_start_comment(ind_maxcomment);
7590 if (trypos != NULL)
7591 {
7592 curwin->w_cursor.lnum = trypos->lnum + 1;
7593 curwin->w_cursor.col = 0;
7594 continue;
7595 }
7596
7597 /* Skip preprocessor directives and blank lines. */
7598 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7599 continue;
7600
7601 /* Finally the actual check for "namespace". */
7602 if (cin_is_cpp_namespace(l))
7603 {
7604 amount += ind_cpp_namespace - added_to_amount;
7605 break;
7606 }
7607
7608 if (cin_nocode(l))
7609 continue;
7610 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007611 }
7612 break;
7613 }
7614
7615 /*
7616 * If we're in a comment now, skip to the start of the comment.
7617 */ /* XXX */
7618 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
7619 {
7620 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007621 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007622 continue;
7623 }
7624
7625 l = ml_get_curline();
7626
7627 /*
7628 * If this is a switch() label, may line up relative to that.
Bram Moolenaar18144c82006-04-12 21:52:12 +00007629 * If this is a C++ scope declaration, do the same.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007630 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007631 iscase = cin_iscase(l, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007632 if (iscase || cin_isscopedecl(l))
7633 {
7634 /* we are only looking for cpp base class
7635 * declaration/initialization any longer */
7636 if (lookfor == LOOKFOR_CPP_BASECLASS)
7637 break;
7638
7639 /* When looking for a "do" we are not interested in
7640 * labels. */
7641 if (whilelevel > 0)
7642 continue;
7643
7644 /*
7645 * case xx:
7646 * c = 99 + <- this indent plus continuation
7647 *-> here;
7648 */
7649 if (lookfor == LOOKFOR_UNTERM
7650 || lookfor == LOOKFOR_ENUM_OR_INIT)
7651 {
7652 if (cont_amount > 0)
7653 amount = cont_amount;
7654 else
7655 amount += ind_continuation;
7656 break;
7657 }
7658
7659 /*
7660 * case xx: <- line up with this case
7661 * x = 333;
7662 * case yy:
7663 */
7664 if ( (iscase && lookfor == LOOKFOR_CASE)
7665 || (iscase && lookfor_break)
7666 || (!iscase && lookfor == LOOKFOR_SCOPEDECL))
7667 {
7668 /*
7669 * Check that this case label is not for another
7670 * switch()
7671 */ /* XXX */
7672 if ((trypos = find_start_brace(ind_maxcomment)) ==
7673 NULL || trypos->lnum == ourscope)
7674 {
7675 amount = get_indent(); /* XXX */
7676 break;
7677 }
7678 continue;
7679 }
7680
7681 n = get_indent_nolabel(curwin->w_cursor.lnum); /* XXX */
7682
7683 /*
7684 * case xx: if (cond) <- line up with this if
7685 * y = y + 1;
7686 * -> s = 99;
7687 *
7688 * case xx:
7689 * if (cond) <- line up with this line
7690 * y = y + 1;
7691 * -> s = 99;
7692 */
7693 if (lookfor == LOOKFOR_TERM)
7694 {
7695 if (n)
7696 amount = n;
7697
7698 if (!lookfor_break)
7699 break;
7700 }
7701
7702 /*
7703 * case xx: x = x + 1; <- line up with this x
7704 * -> y = y + 1;
7705 *
7706 * case xx: if (cond) <- line up with this if
7707 * -> y = y + 1;
7708 */
7709 if (n)
7710 {
7711 amount = n;
7712 l = after_label(ml_get_curline());
7713 if (l != NULL && cin_is_cinword(l))
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007714 {
7715 if (theline[0] == '{')
7716 amount += ind_open_extra;
7717 else
7718 amount += ind_level + ind_no_brace;
7719 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007720 break;
7721 }
7722
7723 /*
7724 * Try to get the indent of a statement before the switch
7725 * label. If nothing is found, line up relative to the
7726 * switch label.
7727 * break; <- may line up with this line
7728 * case xx:
7729 * -> y = 1;
7730 */
7731 scope_amount = get_indent() + (iscase /* XXX */
7732 ? ind_case_code : ind_scopedecl_code);
7733 lookfor = ind_case_break ? LOOKFOR_NOBREAK : LOOKFOR_ANY;
7734 continue;
7735 }
7736
7737 /*
7738 * Looking for a switch() label or C++ scope declaration,
7739 * ignore other lines, skip {}-blocks.
7740 */
7741 if (lookfor == LOOKFOR_CASE || lookfor == LOOKFOR_SCOPEDECL)
7742 {
7743 if (find_last_paren(l, '{', '}') && (trypos =
7744 find_start_brace(ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007745 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007746 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007747 curwin->w_cursor.col = 0;
7748 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007749 continue;
7750 }
7751
7752 /*
7753 * Ignore jump labels with nothing after them.
7754 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007755 if (!ind_js && cin_islabel(ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007756 {
7757 l = after_label(ml_get_curline());
7758 if (l == NULL || cin_nocode(l))
7759 continue;
7760 }
7761
7762 /*
7763 * Ignore #defines, #if, etc.
7764 * Ignore comment and empty lines.
7765 * (need to get the line again, cin_islabel() may have
7766 * unlocked it)
7767 */
7768 l = ml_get_curline();
7769 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum)
7770 || cin_nocode(l))
7771 continue;
7772
7773 /*
7774 * Are we at the start of a cpp base class declaration or
7775 * constructor initialization?
7776 */ /* XXX */
Bram Moolenaar18144c82006-04-12 21:52:12 +00007777 n = FALSE;
7778 if (lookfor != LOOKFOR_TERM && ind_cpp_baseclass > 0)
7779 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00007780 n = cin_is_cpp_baseclass(&col);
Bram Moolenaar18144c82006-04-12 21:52:12 +00007781 l = ml_get_curline();
7782 }
7783 if (n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007784 {
7785 if (lookfor == LOOKFOR_UNTERM)
7786 {
7787 if (cont_amount > 0)
7788 amount = cont_amount;
7789 else
7790 amount += ind_continuation;
7791 }
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007792 else if (theline[0] == '{')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007793 {
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007794 /* Need to find start of the declaration. */
7795 lookfor = LOOKFOR_UNTERM;
7796 ind_continuation = 0;
7797 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007798 }
7799 else
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007800 /* XXX */
7801 amount = get_baseclass_amount(col, ind_maxparen,
7802 ind_maxcomment, ind_cpp_baseclass);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007803 break;
7804 }
7805 else if (lookfor == LOOKFOR_CPP_BASECLASS)
7806 {
7807 /* only look, whether there is a cpp base class
Bram Moolenaar18144c82006-04-12 21:52:12 +00007808 * declaration or initialization before the opening brace.
7809 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007810 if (cin_isterminated(l, TRUE, FALSE))
7811 break;
7812 else
7813 continue;
7814 }
7815
7816 /*
7817 * What happens next depends on the line being terminated.
7818 * If terminated with a ',' only consider it terminating if
Bram Moolenaar25394022007-05-10 19:06:20 +00007819 * there is another unterminated statement behind, eg:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007820 * 123,
7821 * sizeof
7822 * here
7823 * Otherwise check whether it is a enumeration or structure
7824 * initialisation (not indented) or a variable declaration
7825 * (indented).
7826 */
7827 terminated = cin_isterminated(l, FALSE, TRUE);
7828
7829 if (terminated == 0 || (lookfor != LOOKFOR_UNTERM
7830 && terminated == ','))
7831 {
7832 /*
7833 * if we're in the middle of a paren thing,
7834 * go back to the line that starts it so
7835 * we can get the right prevailing indent
7836 * if ( foo &&
7837 * bar )
7838 */
7839 /*
7840 * position the cursor over the rightmost paren, so that
7841 * matching it will take us back to the start of the line.
7842 */
7843 (void)find_last_paren(l, '(', ')');
7844 trypos = find_match_paren(
7845 corr_ind_maxparen(ind_maxparen, &cur_curpos),
7846 ind_maxcomment);
7847
7848 /*
7849 * If we are looking for ',', we also look for matching
7850 * braces.
7851 */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007852 if (trypos == NULL && terminated == ','
7853 && find_last_paren(l, '{', '}'))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007854 trypos = find_start_brace(ind_maxcomment);
7855
7856 if (trypos != NULL)
7857 {
7858 /*
7859 * Check if we are on a case label now. This is
7860 * handled above.
7861 * case xx: if ( asdf &&
7862 * asdf)
7863 */
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007864 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007865 l = ml_get_curline();
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007866 if (cin_iscase(l, FALSE) || cin_isscopedecl(l))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007867 {
7868 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007869 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007870 continue;
7871 }
7872 }
7873
7874 /*
7875 * Skip over continuation lines to find the one to get the
7876 * indent from
7877 * char *usethis = "bla\
7878 * bla",
7879 * here;
7880 */
7881 if (terminated == ',')
7882 {
7883 while (curwin->w_cursor.lnum > 1)
7884 {
7885 l = ml_get(curwin->w_cursor.lnum - 1);
7886 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
7887 break;
7888 --curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007889 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007890 }
7891 }
7892
7893 /*
7894 * Get indent and pointer to text for current line,
7895 * ignoring any jump label. XXX
7896 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007897 if (!ind_js)
7898 cur_amount = skip_label(curwin->w_cursor.lnum,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007899 &l, ind_maxcomment);
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007900 else
7901 cur_amount = get_indent();
Bram Moolenaar071d4272004-06-13 20:20:40 +00007902 /*
7903 * If this is just above the line we are indenting, and it
7904 * starts with a '{', line it up with this line.
7905 * while (not)
7906 * -> {
7907 * }
7908 */
7909 if (terminated != ',' && lookfor != LOOKFOR_TERM
7910 && theline[0] == '{')
7911 {
7912 amount = cur_amount;
7913 /*
7914 * Only add ind_open_extra when the current line
7915 * doesn't start with a '{', which must have a match
7916 * in the same line (scope is the same). Probably:
7917 * { 1, 2 },
7918 * -> { 3, 4 }
7919 */
7920 if (*skipwhite(l) != '{')
7921 amount += ind_open_extra;
7922
7923 if (ind_cpp_baseclass)
7924 {
7925 /* have to look back, whether it is a cpp base
7926 * class declaration or initialization */
7927 lookfor = LOOKFOR_CPP_BASECLASS;
7928 continue;
7929 }
7930 break;
7931 }
7932
7933 /*
7934 * Check if we are after an "if", "while", etc.
7935 * Also allow " } else".
7936 */
7937 if (cin_is_cinword(l) || cin_iselse(skipwhite(l)))
7938 {
7939 /*
7940 * Found an unterminated line after an if (), line up
7941 * with the last one.
7942 * if (cond)
7943 * 100 +
7944 * -> here;
7945 */
7946 if (lookfor == LOOKFOR_UNTERM
7947 || lookfor == LOOKFOR_ENUM_OR_INIT)
7948 {
7949 if (cont_amount > 0)
7950 amount = cont_amount;
7951 else
7952 amount += ind_continuation;
7953 break;
7954 }
7955
7956 /*
7957 * If this is just above the line we are indenting, we
7958 * are finished.
7959 * while (not)
7960 * -> here;
7961 * Otherwise this indent can be used when the line
7962 * before this is terminated.
7963 * yyy;
7964 * if (stat)
7965 * while (not)
7966 * xxx;
7967 * -> here;
7968 */
7969 amount = cur_amount;
7970 if (theline[0] == '{')
7971 amount += ind_open_extra;
7972 if (lookfor != LOOKFOR_TERM)
7973 {
7974 amount += ind_level + ind_no_brace;
7975 break;
7976 }
7977
7978 /*
7979 * Special trick: when expecting the while () after a
7980 * do, line up with the while()
7981 * do
7982 * x = 1;
7983 * -> here
7984 */
7985 l = skipwhite(ml_get_curline());
7986 if (cin_isdo(l))
7987 {
7988 if (whilelevel == 0)
7989 break;
7990 --whilelevel;
7991 }
7992
7993 /*
7994 * When searching for a terminated line, don't use the
Bram Moolenaar334adf02011-05-25 13:34:04 +02007995 * one between the "if" and the matching "else".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007996 * Need to use the scope of this "else". XXX
7997 * If whilelevel != 0 continue looking for a "do {".
7998 */
Bram Moolenaar334adf02011-05-25 13:34:04 +02007999 if (cin_iselse(l) && whilelevel == 0)
8000 {
8001 /* If we're looking at "} else", let's make sure we
8002 * find the opening brace of the enclosing scope,
8003 * not the one from "if () {". */
8004 if (*l == '}')
8005 curwin->w_cursor.col =
Bram Moolenaar9b83c2f2011-05-25 17:29:44 +02008006 (colnr_T)(l - ml_get_curline()) + 1;
Bram Moolenaar334adf02011-05-25 13:34:04 +02008007
8008 if ((trypos = find_start_brace(ind_maxcomment))
8009 == NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00008010 || find_match(LOOKFOR_IF, trypos->lnum,
Bram Moolenaar334adf02011-05-25 13:34:04 +02008011 ind_maxparen, ind_maxcomment) == FAIL)
8012 break;
8013 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008014 }
8015
8016 /*
8017 * If we're below an unterminated line that is not an
8018 * "if" or something, we may line up with this line or
Bram Moolenaar25394022007-05-10 19:06:20 +00008019 * add something for a continuation line, depending on
Bram Moolenaar071d4272004-06-13 20:20:40 +00008020 * the line before this one.
8021 */
8022 else
8023 {
8024 /*
8025 * Found two unterminated lines on a row, line up with
8026 * the last one.
8027 * c = 99 +
8028 * 100 +
8029 * -> here;
8030 */
8031 if (lookfor == LOOKFOR_UNTERM)
8032 {
8033 /* When line ends in a comma add extra indent */
8034 if (terminated == ',')
8035 amount += ind_continuation;
8036 break;
8037 }
8038
8039 if (lookfor == LOOKFOR_ENUM_OR_INIT)
8040 {
8041 /* Found two lines ending in ',', lineup with the
8042 * lowest one, but check for cpp base class
8043 * declaration/initialization, if it is an
8044 * opening brace or we are looking just for
8045 * enumerations/initializations. */
8046 if (terminated == ',')
8047 {
8048 if (ind_cpp_baseclass == 0)
8049 break;
8050
8051 lookfor = LOOKFOR_CPP_BASECLASS;
8052 continue;
8053 }
8054
8055 /* Ignore unterminated lines in between, but
8056 * reduce indent. */
8057 if (amount > cur_amount)
8058 amount = cur_amount;
8059 }
8060 else
8061 {
8062 /*
8063 * Found first unterminated line on a row, may
8064 * line up with this line, remember its indent
8065 * 100 +
8066 * -> here;
8067 */
8068 amount = cur_amount;
8069
8070 /*
8071 * If previous line ends in ',', check whether we
8072 * are in an initialization or enum
8073 * struct xxx =
8074 * {
8075 * sizeof a,
8076 * 124 };
8077 * or a normal possible continuation line.
8078 * but only, of no other statement has been found
8079 * yet.
8080 */
8081 if (lookfor == LOOKFOR_INITIAL && terminated == ',')
8082 {
8083 lookfor = LOOKFOR_ENUM_OR_INIT;
8084 cont_amount = cin_first_id_amount();
8085 }
8086 else
8087 {
8088 if (lookfor == LOOKFOR_INITIAL
8089 && *l != NUL
8090 && l[STRLEN(l) - 1] == '\\')
8091 /* XXX */
8092 cont_amount = cin_get_equal_amount(
8093 curwin->w_cursor.lnum);
8094 if (lookfor != LOOKFOR_TERM)
8095 lookfor = LOOKFOR_UNTERM;
8096 }
8097 }
8098 }
8099 }
8100
8101 /*
8102 * Check if we are after a while (cond);
8103 * If so: Ignore until the matching "do".
8104 */
8105 /* XXX */
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00008106 else if (cin_iswhileofdo_end(terminated, ind_maxparen,
8107 ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008108 {
8109 /*
8110 * Found an unterminated line after a while ();, line up
8111 * with the last one.
8112 * while (cond);
8113 * 100 + <- line up with this one
8114 * -> here;
8115 */
8116 if (lookfor == LOOKFOR_UNTERM
8117 || lookfor == LOOKFOR_ENUM_OR_INIT)
8118 {
8119 if (cont_amount > 0)
8120 amount = cont_amount;
8121 else
8122 amount += ind_continuation;
8123 break;
8124 }
8125
8126 if (whilelevel == 0)
8127 {
8128 lookfor = LOOKFOR_TERM;
8129 amount = get_indent(); /* XXX */
8130 if (theline[0] == '{')
8131 amount += ind_open_extra;
8132 }
8133 ++whilelevel;
8134 }
8135
8136 /*
8137 * We are after a "normal" statement.
8138 * If we had another statement we can stop now and use the
8139 * indent of that other statement.
8140 * Otherwise the indent of the current statement may be used,
8141 * search backwards for the next "normal" statement.
8142 */
8143 else
8144 {
8145 /*
8146 * Skip single break line, if before a switch label. It
8147 * may be lined up with the case label.
8148 */
8149 if (lookfor == LOOKFOR_NOBREAK
8150 && cin_isbreak(skipwhite(ml_get_curline())))
8151 {
8152 lookfor = LOOKFOR_ANY;
8153 continue;
8154 }
8155
8156 /*
8157 * Handle "do {" line.
8158 */
8159 if (whilelevel > 0)
8160 {
8161 l = cin_skipcomment(ml_get_curline());
8162 if (cin_isdo(l))
8163 {
8164 amount = get_indent(); /* XXX */
8165 --whilelevel;
8166 continue;
8167 }
8168 }
8169
8170 /*
8171 * Found a terminated line above an unterminated line. Add
8172 * the amount for a continuation line.
8173 * x = 1;
8174 * y = foo +
8175 * -> here;
8176 * or
8177 * int x = 1;
8178 * int foo,
8179 * -> here;
8180 */
8181 if (lookfor == LOOKFOR_UNTERM
8182 || lookfor == LOOKFOR_ENUM_OR_INIT)
8183 {
8184 if (cont_amount > 0)
8185 amount = cont_amount;
8186 else
8187 amount += ind_continuation;
8188 break;
8189 }
8190
8191 /*
8192 * Found a terminated line above a terminated line or "if"
8193 * etc. line. Use the amount of the line below us.
8194 * x = 1; x = 1;
8195 * if (asdf) y = 2;
8196 * while (asdf) ->here;
8197 * here;
8198 * ->foo;
8199 */
8200 if (lookfor == LOOKFOR_TERM)
8201 {
8202 if (!lookfor_break && whilelevel == 0)
8203 break;
8204 }
8205
8206 /*
8207 * First line above the one we're indenting is terminated.
8208 * To know what needs to be done look further backward for
8209 * a terminated line.
8210 */
8211 else
8212 {
8213 /*
8214 * position the cursor over the rightmost paren, so
8215 * that matching it will take us back to the start of
8216 * the line. Helps for:
8217 * func(asdr,
8218 * asdfasdf);
8219 * here;
8220 */
8221term_again:
8222 l = ml_get_curline();
8223 if (find_last_paren(l, '(', ')')
8224 && (trypos = find_match_paren(ind_maxparen,
8225 ind_maxcomment)) != NULL)
8226 {
8227 /*
8228 * Check if we are on a case label now. This is
8229 * handled above.
8230 * case xx: if ( asdf &&
8231 * asdf)
8232 */
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008233 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008234 l = ml_get_curline();
Bram Moolenaar3acfc302010-07-11 17:23:02 +02008235 if (cin_iscase(l, FALSE) || cin_isscopedecl(l))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008236 {
8237 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008238 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008239 continue;
8240 }
8241 }
8242
8243 /* When aligning with the case statement, don't align
8244 * with a statement after it.
8245 * case 1: { <-- don't use this { position
8246 * stat;
8247 * }
8248 * case 2:
8249 * stat;
8250 * }
8251 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02008252 iscase = (ind_keep_case_label && cin_iscase(l, FALSE));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008253
8254 /*
8255 * Get indent and pointer to text for current line,
8256 * ignoring any jump label.
8257 */
8258 amount = skip_label(curwin->w_cursor.lnum,
8259 &l, ind_maxcomment);
8260
8261 if (theline[0] == '{')
8262 amount += ind_open_extra;
8263 /* See remark above: "Only add ind_open_extra.." */
Bram Moolenaar18144c82006-04-12 21:52:12 +00008264 l = skipwhite(l);
8265 if (*l == '{')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008266 amount -= ind_open_extra;
8267 lookfor = iscase ? LOOKFOR_ANY : LOOKFOR_TERM;
8268
8269 /*
Bram Moolenaar18144c82006-04-12 21:52:12 +00008270 * When a terminated line starts with "else" skip to
8271 * the matching "if":
8272 * else 3;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008273 * indent this;
Bram Moolenaar18144c82006-04-12 21:52:12 +00008274 * Need to use the scope of this "else". XXX
8275 * If whilelevel != 0 continue looking for a "do {".
8276 */
8277 if (lookfor == LOOKFOR_TERM
8278 && *l != '}'
8279 && cin_iselse(l)
8280 && whilelevel == 0)
8281 {
8282 if ((trypos = find_start_brace(ind_maxcomment))
8283 == NULL
8284 || find_match(LOOKFOR_IF, trypos->lnum,
8285 ind_maxparen, ind_maxcomment) == FAIL)
8286 break;
8287 continue;
8288 }
8289
8290 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008291 * If we're at the end of a block, skip to the start of
8292 * that block.
8293 */
Bram Moolenaar6d8f9c62011-11-30 13:03:28 +01008294 l = ml_get_curline();
Bram Moolenaar50f42ca2011-07-15 14:12:30 +02008295 if (find_last_paren(l, '{', '}')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008296 && (trypos = find_start_brace(ind_maxcomment))
8297 != NULL) /* XXX */
8298 {
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008299 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008300 /* if not "else {" check for terminated again */
8301 /* but skip block for "} else {" */
8302 l = cin_skipcomment(ml_get_curline());
8303 if (*l == '}' || !cin_iselse(l))
8304 goto term_again;
8305 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008306 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008307 }
8308 }
8309 }
8310 }
8311 }
8312 }
8313
8314 /* add extra indent for a comment */
8315 if (cin_iscomment(theline))
8316 amount += ind_comment;
Bram Moolenaar02c707a2010-07-17 17:12:06 +02008317
8318 /* subtract extra left-shift for jump labels */
8319 if (ind_jump_label > 0 && original_line_islabel)
8320 amount -= ind_jump_label;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008321 }
8322
8323 /*
8324 * ok -- we're not inside any sort of structure at all!
8325 *
8326 * this means we're at the top level, and everything should
8327 * basically just match where the previous line is, except
8328 * for the lines immediately following a function declaration,
8329 * which are K&R-style parameters and need to be indented.
8330 */
8331 else
8332 {
8333 /*
8334 * if our line starts with an open brace, forget about any
8335 * prevailing indent and make sure it looks like the start
8336 * of a function
8337 */
8338
8339 if (theline[0] == '{')
8340 {
8341 amount = ind_first_open;
8342 }
8343
8344 /*
8345 * If the NEXT line is a function declaration, the current
8346 * line needs to be indented as a function type spec.
Bram Moolenaar1a89bbe2010-03-02 12:38:22 +01008347 * Don't do this if the current line looks like a comment or if the
8348 * current line is terminated, ie. ends in ';', or if the current line
8349 * contains { or }: "void f() {\n if (1)"
Bram Moolenaar071d4272004-06-13 20:20:40 +00008350 */
8351 else if (cur_curpos.lnum < curbuf->b_ml.ml_line_count
8352 && !cin_nocode(theline)
Bram Moolenaar1a89bbe2010-03-02 12:38:22 +01008353 && vim_strchr(theline, '{') == NULL
8354 && vim_strchr(theline, '}') == NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00008355 && !cin_ends_in(theline, (char_u *)":", NULL)
8356 && !cin_ends_in(theline, (char_u *)",", NULL)
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008357 && cin_isfuncdecl(NULL, cur_curpos.lnum + 1,
8358 cur_curpos.lnum + 1,
8359 ind_maxparen, ind_maxcomment)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008360 && !cin_isterminated(theline, FALSE, TRUE))
8361 {
8362 amount = ind_func_type;
8363 }
8364 else
8365 {
8366 amount = 0;
8367 curwin->w_cursor = cur_curpos;
8368
8369 /* search backwards until we find something we recognize */
8370
8371 while (curwin->w_cursor.lnum > 1)
8372 {
8373 curwin->w_cursor.lnum--;
8374 curwin->w_cursor.col = 0;
8375
8376 l = ml_get_curline();
8377
8378 /*
8379 * If we're in a comment now, skip to the start of the comment.
8380 */ /* XXX */
8381 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
8382 {
8383 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008384 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008385 continue;
8386 }
8387
8388 /*
Bram Moolenaar18144c82006-04-12 21:52:12 +00008389 * Are we at the start of a cpp base class declaration or
8390 * constructor initialization?
Bram Moolenaar071d4272004-06-13 20:20:40 +00008391 */ /* XXX */
Bram Moolenaar18144c82006-04-12 21:52:12 +00008392 n = FALSE;
8393 if (ind_cpp_baseclass != 0 && theline[0] != '{')
8394 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00008395 n = cin_is_cpp_baseclass(&col);
Bram Moolenaar18144c82006-04-12 21:52:12 +00008396 l = ml_get_curline();
8397 }
8398 if (n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008399 {
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00008400 /* XXX */
8401 amount = get_baseclass_amount(col, ind_maxparen,
8402 ind_maxcomment, ind_cpp_baseclass);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008403 break;
8404 }
8405
8406 /*
8407 * Skip preprocessor directives and blank lines.
8408 */
8409 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
8410 continue;
8411
8412 if (cin_nocode(l))
8413 continue;
8414
8415 /*
8416 * If the previous line ends in ',', use one level of
8417 * indentation:
8418 * int foo,
8419 * bar;
8420 * do this before checking for '}' in case of eg.
8421 * enum foobar
8422 * {
8423 * ...
8424 * } foo,
8425 * bar;
8426 */
8427 n = 0;
8428 if (cin_ends_in(l, (char_u *)",", NULL)
8429 || (*l != NUL && (n = l[STRLEN(l) - 1]) == '\\'))
8430 {
8431 /* take us back to opening paren */
8432 if (find_last_paren(l, '(', ')')
8433 && (trypos = find_match_paren(ind_maxparen,
8434 ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008435 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008436
8437 /* For a line ending in ',' that is a continuation line go
8438 * back to the first line with a backslash:
8439 * char *foo = "bla\
8440 * bla",
8441 * here;
8442 */
8443 while (n == 0 && curwin->w_cursor.lnum > 1)
8444 {
8445 l = ml_get(curwin->w_cursor.lnum - 1);
8446 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
8447 break;
8448 --curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008449 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008450 }
8451
8452 amount = get_indent(); /* XXX */
8453
8454 if (amount == 0)
8455 amount = cin_first_id_amount();
8456 if (amount == 0)
8457 amount = ind_continuation;
8458 break;
8459 }
8460
8461 /*
8462 * If the line looks like a function declaration, and we're
8463 * not in a comment, put it the left margin.
8464 */
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008465 if (cin_isfuncdecl(NULL, cur_curpos.lnum, 0,
8466 ind_maxparen, ind_maxcomment)) /* XXX */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008467 break;
8468 l = ml_get_curline();
8469
8470 /*
8471 * Finding the closing '}' of a previous function. Put
8472 * current line at the left margin. For when 'cino' has "fs".
8473 */
8474 if (*skipwhite(l) == '}')
8475 break;
8476
8477 /* (matching {)
8478 * If the previous line ends on '};' (maybe followed by
8479 * comments) align at column 0. For example:
8480 * char *string_array[] = { "foo",
8481 * / * x * / "b};ar" }; / * foobar * /
8482 */
8483 if (cin_ends_in(l, (char_u *)"};", NULL))
8484 break;
8485
8486 /*
Bram Moolenaar3388bb42011-11-30 17:20:23 +01008487 * Find a line only has a semicolon that belongs to a previous
8488 * line ending in '}', e.g. before an #endif. Don't increase
8489 * indent then.
8490 */
8491 if (*(look = skipwhite(l)) == ';' && cin_nocode(look + 1))
8492 {
8493 pos_T curpos_save = curwin->w_cursor;
8494
8495 while (curwin->w_cursor.lnum > 1)
8496 {
8497 look = ml_get(--curwin->w_cursor.lnum);
8498 if (!(cin_nocode(look) || cin_ispreproc_cont(
8499 &look, &curwin->w_cursor.lnum)))
8500 break;
8501 }
8502 if (curwin->w_cursor.lnum > 0
8503 && cin_ends_in(look, (char_u *)"}", NULL))
8504 break;
8505
8506 curwin->w_cursor = curpos_save;
8507 }
8508
8509 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008510 * If the PREVIOUS line is a function declaration, the current
8511 * line (and the ones that follow) needs to be indented as
8512 * parameters.
8513 */
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008514 if (cin_isfuncdecl(&l, curwin->w_cursor.lnum, 0,
8515 ind_maxparen, ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008516 {
8517 amount = ind_param;
8518 break;
8519 }
8520
8521 /*
8522 * If the previous line ends in ';' and the line before the
8523 * previous line ends in ',' or '\', ident to column zero:
8524 * int foo,
8525 * bar;
8526 * indent_to_0 here;
8527 */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00008528 if (cin_ends_in(l, (char_u *)";", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008529 {
8530 l = ml_get(curwin->w_cursor.lnum - 1);
8531 if (cin_ends_in(l, (char_u *)",", NULL)
8532 || (*l != NUL && l[STRLEN(l) - 1] == '\\'))
8533 break;
8534 l = ml_get_curline();
8535 }
8536
8537 /*
8538 * Doesn't look like anything interesting -- so just
8539 * use the indent of this line.
8540 *
8541 * Position the cursor over the rightmost paren, so that
8542 * matching it will take us back to the start of the line.
8543 */
8544 find_last_paren(l, '(', ')');
8545
8546 if ((trypos = find_match_paren(ind_maxparen,
8547 ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008548 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008549 amount = get_indent(); /* XXX */
8550 break;
8551 }
8552
8553 /* add extra indent for a comment */
8554 if (cin_iscomment(theline))
8555 amount += ind_comment;
8556
8557 /* add extra indent if the previous line ended in a backslash:
8558 * "asdfasdf\
8559 * here";
8560 * char *foo = "asdf\
8561 * here";
8562 */
8563 if (cur_curpos.lnum > 1)
8564 {
8565 l = ml_get(cur_curpos.lnum - 1);
8566 if (*l != NUL && l[STRLEN(l) - 1] == '\\')
8567 {
8568 cur_amount = cin_get_equal_amount(cur_curpos.lnum - 1);
8569 if (cur_amount > 0)
8570 amount = cur_amount;
8571 else if (cur_amount == 0)
8572 amount += ind_continuation;
8573 }
8574 }
8575 }
8576 }
8577
8578theend:
8579 /* put the cursor back where it belongs */
8580 curwin->w_cursor = cur_curpos;
8581
8582 vim_free(linecopy);
8583
8584 if (amount < 0)
8585 return 0;
8586 return amount;
8587}
8588
8589 static int
8590find_match(lookfor, ourscope, ind_maxparen, ind_maxcomment)
8591 int lookfor;
8592 linenr_T ourscope;
8593 int ind_maxparen;
8594 int ind_maxcomment;
8595{
8596 char_u *look;
8597 pos_T *theirscope;
8598 char_u *mightbeif;
8599 int elselevel;
8600 int whilelevel;
8601
8602 if (lookfor == LOOKFOR_IF)
8603 {
8604 elselevel = 1;
8605 whilelevel = 0;
8606 }
8607 else
8608 {
8609 elselevel = 0;
8610 whilelevel = 1;
8611 }
8612
8613 curwin->w_cursor.col = 0;
8614
8615 while (curwin->w_cursor.lnum > ourscope + 1)
8616 {
8617 curwin->w_cursor.lnum--;
8618 curwin->w_cursor.col = 0;
8619
8620 look = cin_skipcomment(ml_get_curline());
8621 if (cin_iselse(look)
8622 || cin_isif(look)
8623 || cin_isdo(look) /* XXX */
8624 || cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
8625 {
8626 /*
8627 * if we've gone outside the braces entirely,
8628 * we must be out of scope...
8629 */
8630 theirscope = find_start_brace(ind_maxcomment); /* XXX */
8631 if (theirscope == NULL)
8632 break;
8633
8634 /*
8635 * and if the brace enclosing this is further
8636 * back than the one enclosing the else, we're
8637 * out of luck too.
8638 */
8639 if (theirscope->lnum < ourscope)
8640 break;
8641
8642 /*
8643 * and if they're enclosed in a *deeper* brace,
8644 * then we can ignore it because it's in a
8645 * different scope...
8646 */
8647 if (theirscope->lnum > ourscope)
8648 continue;
8649
8650 /*
8651 * if it was an "else" (that's not an "else if")
8652 * then we need to go back to another if, so
8653 * increment elselevel
8654 */
8655 look = cin_skipcomment(ml_get_curline());
8656 if (cin_iselse(look))
8657 {
8658 mightbeif = cin_skipcomment(look + 4);
8659 if (!cin_isif(mightbeif))
8660 ++elselevel;
8661 continue;
8662 }
8663
8664 /*
8665 * if it was a "while" then we need to go back to
8666 * another "do", so increment whilelevel. XXX
8667 */
8668 if (cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
8669 {
8670 ++whilelevel;
8671 continue;
8672 }
8673
8674 /* If it's an "if" decrement elselevel */
8675 look = cin_skipcomment(ml_get_curline());
8676 if (cin_isif(look))
8677 {
8678 elselevel--;
8679 /*
8680 * When looking for an "if" ignore "while"s that
8681 * get in the way.
8682 */
8683 if (elselevel == 0 && lookfor == LOOKFOR_IF)
8684 whilelevel = 0;
8685 }
8686
8687 /* If it's a "do" decrement whilelevel */
8688 if (cin_isdo(look))
8689 whilelevel--;
8690
8691 /*
8692 * if we've used up all the elses, then
8693 * this must be the if that we want!
8694 * match the indent level of that if.
8695 */
8696 if (elselevel <= 0 && whilelevel <= 0)
8697 {
8698 return OK;
8699 }
8700 }
8701 }
8702 return FAIL;
8703}
8704
8705# if defined(FEAT_EVAL) || defined(PROTO)
8706/*
8707 * Get indent level from 'indentexpr'.
8708 */
8709 int
8710get_expr_indent()
8711{
8712 int indent;
8713 pos_T pos;
8714 int save_State;
Bram Moolenaard1f56e62006-02-22 21:25:37 +00008715 int use_sandbox = was_set_insecurely((char_u *)"indentexpr",
8716 OPT_LOCAL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008717
8718 pos = curwin->w_cursor;
8719 set_vim_var_nr(VV_LNUM, curwin->w_cursor.lnum);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00008720 if (use_sandbox)
8721 ++sandbox;
8722 ++textlock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008723 indent = eval_to_number(curbuf->b_p_inde);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00008724 if (use_sandbox)
8725 --sandbox;
8726 --textlock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008727
8728 /* Restore the cursor position so that 'indentexpr' doesn't need to.
8729 * Pretend to be in Insert mode, allow cursor past end of line for "o"
8730 * command. */
8731 save_State = State;
8732 State = INSERT;
8733 curwin->w_cursor = pos;
8734 check_cursor();
8735 State = save_State;
8736
8737 /* If there is an error, just keep the current indent. */
8738 if (indent < 0)
8739 indent = get_indent();
8740
8741 return indent;
8742}
8743# endif
8744
8745#endif /* FEAT_CINDENT */
8746
8747#if defined(FEAT_LISP) || defined(PROTO)
8748
8749static int lisp_match __ARGS((char_u *p));
8750
8751 static int
8752lisp_match(p)
8753 char_u *p;
8754{
8755 char_u buf[LSIZE];
8756 int len;
8757 char_u *word = p_lispwords;
8758
8759 while (*word != NUL)
8760 {
8761 (void)copy_option_part(&word, buf, LSIZE, ",");
8762 len = (int)STRLEN(buf);
8763 if (STRNCMP(buf, p, len) == 0 && p[len] == ' ')
8764 return TRUE;
8765 }
8766 return FALSE;
8767}
8768
8769/*
8770 * When 'p' is present in 'cpoptions, a Vi compatible method is used.
8771 * The incompatible newer method is quite a bit better at indenting
8772 * code in lisp-like languages than the traditional one; it's still
8773 * mostly heuristics however -- Dirk van Deun, dirk@rave.org
8774 *
8775 * TODO:
8776 * Findmatch() should be adapted for lisp, also to make showmatch
8777 * work correctly: now (v5.3) it seems all C/C++ oriented:
8778 * - it does not recognize the #\( and #\) notations as character literals
8779 * - it doesn't know about comments starting with a semicolon
8780 * - it incorrectly interprets '(' as a character literal
8781 * All this messes up get_lisp_indent in some rare cases.
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008782 * Update from Sergey Khorev:
8783 * I tried to fix the first two issues.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008784 */
8785 int
8786get_lisp_indent()
8787{
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008788 pos_T *pos, realpos, paren;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008789 int amount;
8790 char_u *that;
8791 colnr_T col;
8792 colnr_T firsttry;
8793 int parencount, quotecount;
8794 int vi_lisp;
8795
8796 /* Set vi_lisp to use the vi-compatible method */
8797 vi_lisp = (vim_strchr(p_cpo, CPO_LISP) != NULL);
8798
8799 realpos = curwin->w_cursor;
8800 curwin->w_cursor.col = 0;
8801
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008802 if ((pos = findmatch(NULL, '(')) == NULL)
8803 pos = findmatch(NULL, '[');
8804 else
8805 {
8806 paren = *pos;
8807 pos = findmatch(NULL, '[');
8808 if (pos == NULL || ltp(pos, &paren))
8809 pos = &paren;
8810 }
8811 if (pos != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008812 {
8813 /* Extra trick: Take the indent of the first previous non-white
8814 * line that is at the same () level. */
8815 amount = -1;
8816 parencount = 0;
8817
8818 while (--curwin->w_cursor.lnum >= pos->lnum)
8819 {
8820 if (linewhite(curwin->w_cursor.lnum))
8821 continue;
8822 for (that = ml_get_curline(); *that != NUL; ++that)
8823 {
8824 if (*that == ';')
8825 {
8826 while (*(that + 1) != NUL)
8827 ++that;
8828 continue;
8829 }
8830 if (*that == '\\')
8831 {
8832 if (*(that + 1) != NUL)
8833 ++that;
8834 continue;
8835 }
8836 if (*that == '"' && *(that + 1) != NUL)
8837 {
Bram Moolenaar15ff6c12006-09-15 18:18:09 +00008838 while (*++that && *that != '"')
8839 {
8840 /* skipping escaped characters in the string */
8841 if (*that == '\\')
8842 {
8843 if (*++that == NUL)
8844 break;
8845 if (that[1] == NUL)
8846 {
8847 ++that;
8848 break;
8849 }
8850 }
8851 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008852 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008853 if (*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008854 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008855 else if (*that == ')' || *that == ']')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008856 --parencount;
8857 }
8858 if (parencount == 0)
8859 {
8860 amount = get_indent();
8861 break;
8862 }
8863 }
8864
8865 if (amount == -1)
8866 {
8867 curwin->w_cursor.lnum = pos->lnum;
8868 curwin->w_cursor.col = pos->col;
8869 col = pos->col;
8870
8871 that = ml_get_curline();
8872
8873 if (vi_lisp && get_indent() == 0)
8874 amount = 2;
8875 else
8876 {
8877 amount = 0;
8878 while (*that && col)
8879 {
8880 amount += lbr_chartabsize_adv(&that, (colnr_T)amount);
8881 col--;
8882 }
8883
8884 /*
8885 * Some keywords require "body" indenting rules (the
8886 * non-standard-lisp ones are Scheme special forms):
8887 *
8888 * (let ((a 1)) instead (let ((a 1))
8889 * (...)) of (...))
8890 */
8891
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008892 if (!vi_lisp && (*that == '(' || *that == '[')
8893 && lisp_match(that + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008894 amount += 2;
8895 else
8896 {
8897 that++;
8898 amount++;
8899 firsttry = amount;
8900
8901 while (vim_iswhite(*that))
8902 {
8903 amount += lbr_chartabsize(that, (colnr_T)amount);
8904 ++that;
8905 }
8906
8907 if (*that && *that != ';') /* not a comment line */
8908 {
Bram Moolenaare21877a2008-02-13 09:58:14 +00008909 /* test *that != '(' to accommodate first let/do
Bram Moolenaar071d4272004-06-13 20:20:40 +00008910 * argument if it is more than one line */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008911 if (!vi_lisp && *that != '(' && *that != '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008912 firsttry++;
8913
8914 parencount = 0;
8915 quotecount = 0;
8916
8917 if (vi_lisp
8918 || (*that != '"'
8919 && *that != '\''
8920 && *that != '#'
8921 && (*that < '0' || *that > '9')))
8922 {
8923 while (*that
8924 && (!vim_iswhite(*that)
8925 || quotecount
8926 || parencount)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008927 && (!((*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008928 && !quotecount
8929 && !parencount
8930 && vi_lisp)))
8931 {
8932 if (*that == '"')
8933 quotecount = !quotecount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008934 if ((*that == '(' || *that == '[')
8935 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008936 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008937 if ((*that == ')' || *that == ']')
8938 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008939 --parencount;
8940 if (*that == '\\' && *(that+1) != NUL)
8941 amount += lbr_chartabsize_adv(&that,
8942 (colnr_T)amount);
8943 amount += lbr_chartabsize_adv(&that,
8944 (colnr_T)amount);
8945 }
8946 }
8947 while (vim_iswhite(*that))
8948 {
8949 amount += lbr_chartabsize(that, (colnr_T)amount);
8950 that++;
8951 }
8952 if (!*that || *that == ';')
8953 amount = firsttry;
8954 }
8955 }
8956 }
8957 }
8958 }
8959 else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008960 amount = 0; /* no matching '(' or '[' found, use zero indent */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008961
8962 curwin->w_cursor = realpos;
8963
8964 return amount;
8965}
8966#endif /* FEAT_LISP */
8967
8968 void
8969prepare_to_exit()
8970{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00008971#if defined(SIGHUP) && defined(SIG_IGN)
8972 /* Ignore SIGHUP, because a dropped connection causes a read error, which
8973 * makes Vim exit and then handling SIGHUP causes various reentrance
8974 * problems. */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00008975 signal(SIGHUP, SIG_IGN);
8976#endif
8977
Bram Moolenaar071d4272004-06-13 20:20:40 +00008978#ifdef FEAT_GUI
8979 if (gui.in_use)
8980 {
8981 gui.dying = TRUE;
8982 out_trash(); /* trash any pending output */
8983 }
8984 else
8985#endif
8986 {
8987 windgoto((int)Rows - 1, 0);
8988
8989 /*
8990 * Switch terminal mode back now, so messages end up on the "normal"
8991 * screen (if there are two screens).
8992 */
8993 settmode(TMODE_COOK);
8994#ifdef WIN3264
8995 if (can_end_termcap_mode(FALSE) == TRUE)
8996#endif
8997 stoptermcap();
8998 out_flush();
8999 }
9000}
9001
9002/*
9003 * Preserve files and exit.
9004 * When called IObuff must contain a message.
9005 */
9006 void
9007preserve_exit()
9008{
9009 buf_T *buf;
9010
9011 prepare_to_exit();
9012
Bram Moolenaar4770d092006-01-12 23:22:24 +00009013 /* Setting this will prevent free() calls. That avoids calling free()
9014 * recursively when free() was invoked with a bad pointer. */
9015 really_exiting = TRUE;
9016
Bram Moolenaar071d4272004-06-13 20:20:40 +00009017 out_str(IObuff);
9018 screen_start(); /* don't know where cursor is now */
9019 out_flush();
9020
9021 ml_close_notmod(); /* close all not-modified buffers */
9022
9023 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
9024 {
9025 if (buf->b_ml.ml_mfp != NULL && buf->b_ml.ml_mfp->mf_fname != NULL)
9026 {
9027 OUT_STR(_("Vim: preserving files...\n"));
9028 screen_start(); /* don't know where cursor is now */
9029 out_flush();
9030 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
9031 break;
9032 }
9033 }
9034
9035 ml_close_all(FALSE); /* close all memfiles, without deleting */
9036
9037 OUT_STR(_("Vim: Finished.\n"));
9038
9039 getout(1);
9040}
9041
9042/*
9043 * return TRUE if "fname" exists.
9044 */
9045 int
9046vim_fexists(fname)
9047 char_u *fname;
9048{
9049 struct stat st;
9050
9051 if (mch_stat((char *)fname, &st))
9052 return FALSE;
9053 return TRUE;
9054}
9055
9056/*
9057 * Check for CTRL-C pressed, but only once in a while.
9058 * Should be used instead of ui_breakcheck() for functions that check for
9059 * each line in the file. Calling ui_breakcheck() each time takes too much
9060 * time, because it can be a system call.
9061 */
9062
9063#ifndef BREAKCHECK_SKIP
9064# ifdef FEAT_GUI /* assume the GUI only runs on fast computers */
9065# define BREAKCHECK_SKIP 200
9066# else
9067# define BREAKCHECK_SKIP 32
9068# endif
9069#endif
9070
9071static int breakcheck_count = 0;
9072
9073 void
9074line_breakcheck()
9075{
9076 if (++breakcheck_count >= BREAKCHECK_SKIP)
9077 {
9078 breakcheck_count = 0;
9079 ui_breakcheck();
9080 }
9081}
9082
9083/*
9084 * Like line_breakcheck() but check 10 times less often.
9085 */
9086 void
9087fast_breakcheck()
9088{
9089 if (++breakcheck_count >= BREAKCHECK_SKIP * 10)
9090 {
9091 breakcheck_count = 0;
9092 ui_breakcheck();
9093 }
9094}
9095
9096/*
Bram Moolenaard7834d32009-12-02 16:14:36 +00009097 * Invoke expand_wildcards() for one pattern.
9098 * Expand items like "%:h" before the expansion.
9099 * Returns OK or FAIL.
9100 */
9101 int
9102expand_wildcards_eval(pat, num_file, file, flags)
9103 char_u **pat; /* pointer to input pattern */
9104 int *num_file; /* resulting number of files */
9105 char_u ***file; /* array of resulting files */
9106 int flags; /* EW_DIR, etc. */
9107{
9108 int ret = FAIL;
9109 char_u *eval_pat = NULL;
9110 char_u *exp_pat = *pat;
9111 char_u *ignored_msg;
9112 int usedlen;
9113
9114 if (*exp_pat == '%' || *exp_pat == '#' || *exp_pat == '<')
9115 {
9116 ++emsg_off;
9117 eval_pat = eval_vars(exp_pat, exp_pat, &usedlen,
9118 NULL, &ignored_msg, NULL);
9119 --emsg_off;
9120 if (eval_pat != NULL)
9121 exp_pat = concat_str(eval_pat, exp_pat + usedlen);
9122 }
9123
9124 if (exp_pat != NULL)
9125 ret = expand_wildcards(1, &exp_pat, num_file, file, flags);
9126
9127 if (eval_pat != NULL)
9128 {
9129 vim_free(exp_pat);
9130 vim_free(eval_pat);
9131 }
9132
9133 return ret;
9134}
9135
9136/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00009137 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching
9138 * 'wildignore'.
Bram Moolenaar9e193ac2010-07-19 23:11:27 +02009139 * Returns OK or FAIL. When FAIL then "num_file" won't be set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009140 */
9141 int
9142expand_wildcards(num_pat, pat, num_file, file, flags)
9143 int num_pat; /* number of input patterns */
9144 char_u **pat; /* array of input patterns */
9145 int *num_file; /* resulting number of files */
9146 char_u ***file; /* array of resulting files */
9147 int flags; /* EW_DIR, etc. */
9148{
9149 int retval;
9150 int i, j;
9151 char_u *p;
9152 int non_suf_match; /* number without matching suffix */
9153
9154 retval = gen_expand_wildcards(num_pat, pat, num_file, file, flags);
9155
9156 /* When keeping all matches, return here */
Bram Moolenaar9e193ac2010-07-19 23:11:27 +02009157 if ((flags & EW_KEEPALL) || retval == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009158 return retval;
9159
9160#ifdef FEAT_WILDIGN
9161 /*
9162 * Remove names that match 'wildignore'.
9163 */
9164 if (*p_wig)
9165 {
9166 char_u *ffname;
9167
9168 /* check all files in (*file)[] */
9169 for (i = 0; i < *num_file; ++i)
9170 {
9171 ffname = FullName_save((*file)[i], FALSE);
9172 if (ffname == NULL) /* out of memory */
9173 break;
9174# ifdef VMS
9175 vms_remove_version(ffname);
9176# endif
9177 if (match_file_list(p_wig, (*file)[i], ffname))
9178 {
9179 /* remove this matching file from the list */
9180 vim_free((*file)[i]);
9181 for (j = i; j + 1 < *num_file; ++j)
9182 (*file)[j] = (*file)[j + 1];
9183 --*num_file;
9184 --i;
9185 }
9186 vim_free(ffname);
9187 }
9188 }
9189#endif
9190
9191 /*
9192 * Move the names where 'suffixes' match to the end.
9193 */
9194 if (*num_file > 1)
9195 {
9196 non_suf_match = 0;
9197 for (i = 0; i < *num_file; ++i)
9198 {
9199 if (!match_suffix((*file)[i]))
9200 {
9201 /*
9202 * Move the name without matching suffix to the front
9203 * of the list.
9204 */
9205 p = (*file)[i];
9206 for (j = i; j > non_suf_match; --j)
9207 (*file)[j] = (*file)[j - 1];
9208 (*file)[non_suf_match++] = p;
9209 }
9210 }
9211 }
9212
9213 return retval;
9214}
9215
9216/*
9217 * Return TRUE if "fname" matches with an entry in 'suffixes'.
9218 */
9219 int
9220match_suffix(fname)
9221 char_u *fname;
9222{
9223 int fnamelen, setsuflen;
9224 char_u *setsuf;
9225#define MAXSUFLEN 30 /* maximum length of a file suffix */
9226 char_u suf_buf[MAXSUFLEN];
9227
9228 fnamelen = (int)STRLEN(fname);
9229 setsuflen = 0;
9230 for (setsuf = p_su; *setsuf; )
9231 {
9232 setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
Bram Moolenaar055a2ba2009-07-14 19:40:21 +00009233 if (setsuflen == 0)
9234 {
9235 char_u *tail = gettail(fname);
9236
9237 /* empty entry: match name without a '.' */
9238 if (vim_strchr(tail, '.') == NULL)
9239 {
9240 setsuflen = 1;
9241 break;
9242 }
9243 }
9244 else
9245 {
9246 if (fnamelen >= setsuflen
9247 && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
9248 (size_t)setsuflen) == 0)
9249 break;
9250 setsuflen = 0;
9251 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009252 }
9253 return (setsuflen != 0);
9254}
9255
9256#if !defined(NO_EXPANDPATH) || defined(PROTO)
9257
9258# ifdef VIM_BACKTICK
9259static int vim_backtick __ARGS((char_u *p));
9260static int expand_backtick __ARGS((garray_T *gap, char_u *pat, int flags));
9261# endif
9262
9263# if defined(MSDOS) || defined(FEAT_GUI_W16) || defined(WIN3264)
9264/*
9265 * File name expansion code for MS-DOS, Win16 and Win32. It's here because
9266 * it's shared between these systems.
9267 */
9268# if defined(DJGPP) || defined(PROTO)
9269# define _cdecl /* DJGPP doesn't have this */
9270# else
9271# ifdef __BORLANDC__
9272# define _cdecl _RTLENTRYF
9273# endif
9274# endif
9275
9276/*
9277 * comparison function for qsort in dos_expandpath()
9278 */
9279 static int _cdecl
9280pstrcmp(const void *a, const void *b)
9281{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00009282 return (pathcmp(*(char **)a, *(char **)b, -1));
Bram Moolenaar071d4272004-06-13 20:20:40 +00009283}
9284
9285# ifndef WIN3264
9286 static void
9287namelowcpy(
9288 char_u *d,
9289 char_u *s)
9290{
9291# ifdef DJGPP
9292 if (USE_LONG_FNAME) /* don't lower case on Windows 95/NT systems */
9293 while (*s)
9294 *d++ = *s++;
9295 else
9296# endif
9297 while (*s)
9298 *d++ = TOLOWER_LOC(*s++);
9299 *d = NUL;
9300}
9301# endif
9302
9303/*
Bram Moolenaar231334e2005-07-25 20:46:57 +00009304 * Recursively expand one path component into all matching files and/or
9305 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009306 * Return the number of matches found.
9307 * "path" has backslashes before chars that are not to be expanded, starting
9308 * at "path[wildoff]".
Bram Moolenaar231334e2005-07-25 20:46:57 +00009309 * Return the number of matches found.
9310 * NOTE: much of this is identical to unix_expandpath(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00009311 */
9312 static int
9313dos_expandpath(
9314 garray_T *gap,
9315 char_u *path,
9316 int wildoff,
Bram Moolenaar231334e2005-07-25 20:46:57 +00009317 int flags, /* EW_* flags */
Bram Moolenaar25394022007-05-10 19:06:20 +00009318 int didstar) /* expanded "**" once already */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009319{
Bram Moolenaar231334e2005-07-25 20:46:57 +00009320 char_u *buf;
9321 char_u *path_end;
9322 char_u *p, *s, *e;
9323 int start_len = gap->ga_len;
9324 char_u *pat;
9325 regmatch_T regmatch;
9326 int starts_with_dot;
9327 int matches;
9328 int len;
9329 int starstar = FALSE;
9330 static int stardepth = 0; /* depth for "**" expansion */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009331#ifdef WIN3264
9332 WIN32_FIND_DATA fb;
9333 HANDLE hFind = (HANDLE)0;
9334# ifdef FEAT_MBYTE
9335 WIN32_FIND_DATAW wfb;
9336 WCHAR *wn = NULL; /* UCS-2 name, NULL when not used. */
9337# endif
9338#else
9339 struct ffblk fb;
9340#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009341 char_u *matchname;
Bram Moolenaar231334e2005-07-25 20:46:57 +00009342 int ok;
9343
9344 /* Expanding "**" may take a long time, check for CTRL-C. */
9345 if (stardepth > 0)
9346 {
9347 ui_breakcheck();
9348 if (got_int)
9349 return 0;
9350 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009351
9352 /* make room for file name */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009353 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009354 if (buf == NULL)
9355 return 0;
9356
9357 /*
9358 * Find the first part in the path name that contains a wildcard or a ~1.
9359 * Copy it into buf, including the preceding characters.
9360 */
9361 p = buf;
9362 s = buf;
9363 e = NULL;
9364 path_end = path;
9365 while (*path_end != NUL)
9366 {
9367 /* May ignore a wildcard that has a backslash before it; it will
9368 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
9369 if (path_end >= path + wildoff && rem_backslash(path_end))
9370 *p++ = *path_end++;
9371 else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
9372 {
9373 if (e != NULL)
9374 break;
9375 s = p + 1;
9376 }
9377 else if (path_end >= path + wildoff
9378 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
9379 e = p;
9380#ifdef FEAT_MBYTE
9381 if (has_mbyte)
9382 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00009383 len = (*mb_ptr2len)(path_end);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009384 STRNCPY(p, path_end, len);
9385 p += len;
9386 path_end += len;
9387 }
9388 else
9389#endif
9390 *p++ = *path_end++;
9391 }
9392 e = p;
9393 *e = NUL;
9394
9395 /* now we have one wildcard component between s and e */
9396 /* Remove backslashes between "wildoff" and the start of the wildcard
9397 * component. */
9398 for (p = buf + wildoff; p < s; ++p)
9399 if (rem_backslash(p))
9400 {
Bram Moolenaar8c8de832008-06-24 22:58:06 +00009401 STRMOVE(p, p + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009402 --e;
9403 --s;
9404 }
9405
Bram Moolenaar231334e2005-07-25 20:46:57 +00009406 /* Check for "**" between "s" and "e". */
9407 for (p = s; p < e; ++p)
9408 if (p[0] == '*' && p[1] == '*')
9409 starstar = TRUE;
9410
Bram Moolenaar071d4272004-06-13 20:20:40 +00009411 starts_with_dot = (*s == '.');
9412 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
9413 if (pat == NULL)
9414 {
9415 vim_free(buf);
9416 return 0;
9417 }
9418
9419 /* compile the regexp into a program */
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009420 if (flags & (EW_NOERROR | EW_NOTWILD))
Bram Moolenaarb5609832011-07-20 15:04:58 +02009421 ++emsg_silent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009422 regmatch.rm_ic = TRUE; /* Always ignore case */
9423 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009424 if (flags & (EW_NOERROR | EW_NOTWILD))
Bram Moolenaarb5609832011-07-20 15:04:58 +02009425 --emsg_silent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009426 vim_free(pat);
9427
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009428 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009429 {
9430 vim_free(buf);
9431 return 0;
9432 }
9433
9434 /* remember the pattern or file name being looked for */
9435 matchname = vim_strsave(s);
9436
Bram Moolenaar231334e2005-07-25 20:46:57 +00009437 /* If "**" is by itself, this is the first time we encounter it and more
9438 * is following then find matches without any directory. */
9439 if (!didstar && stardepth < 100 && starstar && e - s == 2
9440 && *path_end == '/')
9441 {
9442 STRCPY(s, path_end + 1);
9443 ++stardepth;
9444 (void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
9445 --stardepth;
9446 }
9447
Bram Moolenaar071d4272004-06-13 20:20:40 +00009448 /* Scan all files in the directory with "dir/ *.*" */
9449 STRCPY(s, "*.*");
9450#ifdef WIN3264
9451# ifdef FEAT_MBYTE
9452 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
9453 {
9454 /* The active codepage differs from 'encoding'. Attempt using the
9455 * wide function. If it fails because it is not implemented fall back
9456 * to the non-wide version (for Windows 98) */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009457 wn = enc_to_utf16(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009458 if (wn != NULL)
9459 {
9460 hFind = FindFirstFileW(wn, &wfb);
9461 if (hFind == INVALID_HANDLE_VALUE
9462 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
9463 {
9464 vim_free(wn);
9465 wn = NULL;
9466 }
9467 }
9468 }
9469
9470 if (wn == NULL)
9471# endif
9472 hFind = FindFirstFile(buf, &fb);
9473 ok = (hFind != INVALID_HANDLE_VALUE);
9474#else
9475 /* If we are expanding wildcards we try both files and directories */
9476 ok = (findfirst((char *)buf, &fb,
9477 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
9478#endif
9479
9480 while (ok)
9481 {
9482#ifdef WIN3264
9483# ifdef FEAT_MBYTE
9484 if (wn != NULL)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009485 p = utf16_to_enc(wfb.cFileName, NULL); /* p is allocated here */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009486 else
9487# endif
9488 p = (char_u *)fb.cFileName;
9489#else
9490 p = (char_u *)fb.ff_name;
9491#endif
9492 /* Ignore entries starting with a dot, unless when asked for. Accept
9493 * all entries found with "matchname". */
9494 if ((p[0] != '.' || starts_with_dot)
9495 && (matchname == NULL
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009496 || (regmatch.regprog != NULL
9497 && vim_regexec(&regmatch, p, (colnr_T)0))
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009498 || ((flags & EW_NOTWILD)
9499 && fnamencmp(path + (s - buf), p, e - s) == 0)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009500 {
9501#ifdef WIN3264
9502 STRCPY(s, p);
9503#else
9504 namelowcpy(s, p);
9505#endif
9506 len = (int)STRLEN(buf);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009507
9508 if (starstar && stardepth < 100)
9509 {
9510 /* For "**" in the pattern first go deeper in the tree to
9511 * find matches. */
9512 STRCPY(buf + len, "/**");
9513 STRCPY(buf + len + 3, path_end);
9514 ++stardepth;
9515 (void)dos_expandpath(gap, buf, len + 1, flags, TRUE);
9516 --stardepth;
9517 }
9518
Bram Moolenaar071d4272004-06-13 20:20:40 +00009519 STRCPY(buf + len, path_end);
9520 if (mch_has_exp_wildcard(path_end))
9521 {
9522 /* need to expand another component of the path */
9523 /* remove backslashes for the remaining components only */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009524 (void)dos_expandpath(gap, buf, len + 1, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009525 }
9526 else
9527 {
9528 /* no more wildcards, check if there is a match */
9529 /* remove backslashes for the remaining components only */
9530 if (*path_end != 0)
9531 backslash_halve(buf + len + 1);
9532 if (mch_getperm(buf) >= 0) /* add existing file */
9533 addfile(gap, buf, flags);
9534 }
9535 }
9536
9537#ifdef WIN3264
9538# ifdef FEAT_MBYTE
9539 if (wn != NULL)
9540 {
9541 vim_free(p);
9542 ok = FindNextFileW(hFind, &wfb);
9543 }
9544 else
9545# endif
9546 ok = FindNextFile(hFind, &fb);
9547#else
9548 ok = (findnext(&fb) == 0);
9549#endif
9550
9551 /* If no more matches and no match was used, try expanding the name
9552 * itself. Finds the long name of a short filename. */
9553 if (!ok && matchname != NULL && gap->ga_len == start_len)
9554 {
9555 STRCPY(s, matchname);
9556#ifdef WIN3264
9557 FindClose(hFind);
9558# ifdef FEAT_MBYTE
9559 if (wn != NULL)
9560 {
9561 vim_free(wn);
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009562 wn = enc_to_utf16(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009563 if (wn != NULL)
9564 hFind = FindFirstFileW(wn, &wfb);
9565 }
9566 if (wn == NULL)
9567# endif
9568 hFind = FindFirstFile(buf, &fb);
9569 ok = (hFind != INVALID_HANDLE_VALUE);
9570#else
9571 ok = (findfirst((char *)buf, &fb,
9572 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
9573#endif
9574 vim_free(matchname);
9575 matchname = NULL;
9576 }
9577 }
9578
9579#ifdef WIN3264
9580 FindClose(hFind);
9581# ifdef FEAT_MBYTE
9582 vim_free(wn);
9583# endif
9584#endif
9585 vim_free(buf);
9586 vim_free(regmatch.regprog);
9587 vim_free(matchname);
9588
9589 matches = gap->ga_len - start_len;
9590 if (matches > 0)
9591 qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
9592 sizeof(char_u *), pstrcmp);
9593 return matches;
9594}
9595
9596 int
9597mch_expandpath(
9598 garray_T *gap,
9599 char_u *path,
9600 int flags) /* EW_* flags */
9601{
Bram Moolenaar231334e2005-07-25 20:46:57 +00009602 return dos_expandpath(gap, path, 0, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009603}
9604# endif /* MSDOS || FEAT_GUI_W16 || WIN3264 */
9605
Bram Moolenaar231334e2005-07-25 20:46:57 +00009606#if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
9607 || defined(PROTO)
9608/*
9609 * Unix style wildcard expansion code.
9610 * It's here because it's used both for Unix and Mac.
9611 */
9612static int pstrcmp __ARGS((const void *, const void *));
9613
9614 static int
9615pstrcmp(a, b)
9616 const void *a, *b;
9617{
9618 return (pathcmp(*(char **)a, *(char **)b, -1));
9619}
9620
9621/*
9622 * Recursively expand one path component into all matching files and/or
9623 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
9624 * "path" has backslashes before chars that are not to be expanded, starting
9625 * at "path + wildoff".
9626 * Return the number of matches found.
9627 * NOTE: much of this is identical to dos_expandpath(), keep in sync!
9628 */
9629 int
9630unix_expandpath(gap, path, wildoff, flags, didstar)
9631 garray_T *gap;
9632 char_u *path;
9633 int wildoff;
9634 int flags; /* EW_* flags */
9635 int didstar; /* expanded "**" once already */
9636{
9637 char_u *buf;
9638 char_u *path_end;
9639 char_u *p, *s, *e;
9640 int start_len = gap->ga_len;
9641 char_u *pat;
9642 regmatch_T regmatch;
9643 int starts_with_dot;
9644 int matches;
9645 int len;
9646 int starstar = FALSE;
9647 static int stardepth = 0; /* depth for "**" expansion */
9648
9649 DIR *dirp;
9650 struct dirent *dp;
9651
9652 /* Expanding "**" may take a long time, check for CTRL-C. */
9653 if (stardepth > 0)
9654 {
9655 ui_breakcheck();
9656 if (got_int)
9657 return 0;
9658 }
9659
9660 /* make room for file name */
9661 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
9662 if (buf == NULL)
9663 return 0;
9664
9665 /*
9666 * Find the first part in the path name that contains a wildcard.
Bram Moolenaar2d0b92f2012-04-30 21:09:43 +02009667 * When EW_ICASE is set every letter is considered to be a wildcard.
Bram Moolenaar231334e2005-07-25 20:46:57 +00009668 * Copy it into "buf", including the preceding characters.
9669 */
9670 p = buf;
9671 s = buf;
9672 e = NULL;
9673 path_end = path;
9674 while (*path_end != NUL)
9675 {
9676 /* May ignore a wildcard that has a backslash before it; it will
9677 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
9678 if (path_end >= path + wildoff && rem_backslash(path_end))
9679 *p++ = *path_end++;
9680 else if (*path_end == '/')
9681 {
9682 if (e != NULL)
9683 break;
9684 s = p + 1;
9685 }
9686 else if (path_end >= path + wildoff
Bram Moolenaar2d0b92f2012-04-30 21:09:43 +02009687 && (vim_strchr((char_u *)"*?[{~$", *path_end) != NULL
9688#ifndef CASE_INSENSITIVE_FILENAME
9689 || ((flags & EW_ICASE)
9690 && isalpha(PTR2CHAR(path_end)))
9691#endif
9692 ))
Bram Moolenaar231334e2005-07-25 20:46:57 +00009693 e = p;
9694#ifdef FEAT_MBYTE
9695 if (has_mbyte)
9696 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00009697 len = (*mb_ptr2len)(path_end);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009698 STRNCPY(p, path_end, len);
9699 p += len;
9700 path_end += len;
9701 }
9702 else
9703#endif
9704 *p++ = *path_end++;
9705 }
9706 e = p;
9707 *e = NUL;
9708
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009709 /* Now we have one wildcard component between "s" and "e". */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009710 /* Remove backslashes between "wildoff" and the start of the wildcard
9711 * component. */
9712 for (p = buf + wildoff; p < s; ++p)
9713 if (rem_backslash(p))
9714 {
Bram Moolenaar8c8de832008-06-24 22:58:06 +00009715 STRMOVE(p, p + 1);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009716 --e;
9717 --s;
9718 }
9719
9720 /* Check for "**" between "s" and "e". */
9721 for (p = s; p < e; ++p)
9722 if (p[0] == '*' && p[1] == '*')
9723 starstar = TRUE;
9724
9725 /* convert the file pattern to a regexp pattern */
9726 starts_with_dot = (*s == '.');
9727 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
9728 if (pat == NULL)
9729 {
9730 vim_free(buf);
9731 return 0;
9732 }
9733
9734 /* compile the regexp into a program */
Bram Moolenaarcc016f52005-12-10 20:23:46 +00009735#ifdef CASE_INSENSITIVE_FILENAME
Bram Moolenaar231334e2005-07-25 20:46:57 +00009736 regmatch.rm_ic = TRUE; /* Behave like Terminal.app */
9737#else
Bram Moolenaar94950a92010-12-02 16:01:29 +01009738 if (flags & EW_ICASE)
9739 regmatch.rm_ic = TRUE; /* 'wildignorecase' set */
9740 else
9741 regmatch.rm_ic = FALSE; /* Don't ignore case */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009742#endif
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009743 if (flags & (EW_NOERROR | EW_NOTWILD))
9744 ++emsg_silent;
Bram Moolenaar231334e2005-07-25 20:46:57 +00009745 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009746 if (flags & (EW_NOERROR | EW_NOTWILD))
9747 --emsg_silent;
Bram Moolenaar231334e2005-07-25 20:46:57 +00009748 vim_free(pat);
9749
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009750 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
Bram Moolenaar231334e2005-07-25 20:46:57 +00009751 {
9752 vim_free(buf);
9753 return 0;
9754 }
9755
9756 /* If "**" is by itself, this is the first time we encounter it and more
9757 * is following then find matches without any directory. */
9758 if (!didstar && stardepth < 100 && starstar && e - s == 2
9759 && *path_end == '/')
9760 {
9761 STRCPY(s, path_end + 1);
9762 ++stardepth;
9763 (void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
9764 --stardepth;
9765 }
9766
9767 /* open the directory for scanning */
9768 *s = NUL;
9769 dirp = opendir(*buf == NUL ? "." : (char *)buf);
9770
9771 /* Find all matching entries */
9772 if (dirp != NULL)
9773 {
9774 for (;;)
9775 {
9776 dp = readdir(dirp);
9777 if (dp == NULL)
9778 break;
9779 if ((dp->d_name[0] != '.' || starts_with_dot)
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009780 && ((regmatch.regprog != NULL && vim_regexec(&regmatch,
9781 (char_u *)dp->d_name, (colnr_T)0))
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009782 || ((flags & EW_NOTWILD)
9783 && fnamencmp(path + (s - buf), dp->d_name, e - s) == 0)))
Bram Moolenaar231334e2005-07-25 20:46:57 +00009784 {
9785 STRCPY(s, dp->d_name);
9786 len = STRLEN(buf);
9787
9788 if (starstar && stardepth < 100)
9789 {
9790 /* For "**" in the pattern first go deeper in the tree to
9791 * find matches. */
9792 STRCPY(buf + len, "/**");
9793 STRCPY(buf + len + 3, path_end);
9794 ++stardepth;
9795 (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
9796 --stardepth;
9797 }
9798
9799 STRCPY(buf + len, path_end);
9800 if (mch_has_exp_wildcard(path_end)) /* handle more wildcards */
9801 {
9802 /* need to expand another component of the path */
9803 /* remove backslashes for the remaining components only */
9804 (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
9805 }
9806 else
9807 {
9808 /* no more wildcards, check if there is a match */
9809 /* remove backslashes for the remaining components only */
9810 if (*path_end != NUL)
9811 backslash_halve(buf + len + 1);
9812 if (mch_getperm(buf) >= 0) /* add existing file */
9813 {
Bram Moolenaar95e9b492006-03-15 23:04:43 +00009814#ifdef MACOS_CONVERT
Bram Moolenaar231334e2005-07-25 20:46:57 +00009815 size_t precomp_len = STRLEN(buf)+1;
9816 char_u *precomp_buf =
9817 mac_precompose_path(buf, precomp_len, &precomp_len);
Bram Moolenaar95e9b492006-03-15 23:04:43 +00009818
Bram Moolenaar231334e2005-07-25 20:46:57 +00009819 if (precomp_buf)
9820 {
9821 mch_memmove(buf, precomp_buf, precomp_len);
9822 vim_free(precomp_buf);
9823 }
9824#endif
9825 addfile(gap, buf, flags);
9826 }
9827 }
9828 }
9829 }
9830
9831 closedir(dirp);
9832 }
9833
9834 vim_free(buf);
9835 vim_free(regmatch.regprog);
9836
9837 matches = gap->ga_len - start_len;
9838 if (matches > 0)
9839 qsort(((char_u **)gap->ga_data) + start_len, matches,
9840 sizeof(char_u *), pstrcmp);
9841 return matches;
9842}
9843#endif
9844
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009845#if defined(FEAT_SEARCHPATH)
9846static int find_previous_pathsep __ARGS((char_u *path, char_u **psep));
9847static int is_unique __ARGS((char_u *maybe_unique, garray_T *gap, int i));
Bram Moolenaar162bd912010-07-28 22:29:10 +02009848static void expand_path_option __ARGS((char_u *curdir, garray_T *gap));
9849static char_u *get_path_cutoff __ARGS((char_u *fname, garray_T *gap));
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009850static void uniquefy_paths __ARGS((garray_T *gap, char_u *pattern));
9851static int expand_in_path __ARGS((garray_T *gap, char_u *pattern, int flags));
9852
9853/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009854 * Moves "*psep" back to the previous path separator in "path".
9855 * Returns FAIL is "*psep" ends up at the beginning of "path".
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009856 */
9857 static int
9858find_previous_pathsep(path, psep)
9859 char_u *path;
9860 char_u **psep;
9861{
9862 /* skip the current separator */
9863 if (*psep > path && vim_ispathsep(**psep))
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009864 --*psep;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009865
9866 /* find the previous separator */
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009867 while (*psep > path)
9868 {
9869 if (vim_ispathsep(**psep))
9870 return OK;
9871 mb_ptr_back(path, *psep);
9872 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009873
9874 return FAIL;
9875}
9876
9877/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009878 * Returns TRUE if "maybe_unique" is unique wrt other_paths in "gap".
9879 * "maybe_unique" is the end portion of "((char_u **)gap->ga_data)[i]".
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009880 */
9881 static int
9882is_unique(maybe_unique, gap, i)
9883 char_u *maybe_unique;
9884 garray_T *gap;
9885 int i;
9886{
9887 int j;
9888 int candidate_len;
9889 int other_path_len;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009890 char_u **other_paths = (char_u **)gap->ga_data;
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009891 char_u *rival;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009892
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009893 for (j = 0; j < gap->ga_len; j++)
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009894 {
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009895 if (j == i)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009896 continue; /* don't compare it with itself */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009897
Bram Moolenaar624c7aa2010-07-16 20:38:52 +02009898 candidate_len = (int)STRLEN(maybe_unique);
9899 other_path_len = (int)STRLEN(other_paths[j]);
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009900 if (other_path_len < candidate_len)
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009901 continue; /* it's different when it's shorter */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009902
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009903 rival = other_paths[j] + other_path_len - candidate_len;
Bram Moolenaarda9836c2010-08-16 21:53:27 +02009904 if (fnamecmp(maybe_unique, rival) == 0
9905 && (rival == other_paths[j] || vim_ispathsep(*(rival - 1))))
Bram Moolenaar162bd912010-07-28 22:29:10 +02009906 return FALSE; /* match */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009907 }
9908
Bram Moolenaar162bd912010-07-28 22:29:10 +02009909 return TRUE; /* no match found */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009910}
9911
9912/*
Bram Moolenaar1a509df2010-08-01 17:59:57 +02009913 * Split the 'path' option into an array of strings in garray_T. Relative
Bram Moolenaar162bd912010-07-28 22:29:10 +02009914 * paths are expanded to their equivalent fullpath. This includes the "."
9915 * (relative to current buffer directory) and empty path (relative to current
9916 * directory) notations.
9917 *
9918 * TODO: handle upward search (;) and path limiter (**N) notations by
9919 * expanding each into their equivalent path(s).
9920 */
9921 static void
9922expand_path_option(curdir, gap)
9923 char_u *curdir;
9924 garray_T *gap;
9925{
9926 char_u *path_option = *curbuf->b_p_path == NUL
9927 ? p_path : curbuf->b_p_path;
9928 char_u *buf;
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009929 char_u *p;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009930 int len;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009931
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +02009932 if ((buf = alloc((int)MAXPATHL)) == NULL)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009933 return;
9934
9935 while (*path_option != NUL)
9936 {
9937 copy_option_part(&path_option, buf, MAXPATHL, " ,");
9938
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009939 if (buf[0] == '.' && (buf[1] == NUL || vim_ispathsep(buf[1])))
Bram Moolenaar162bd912010-07-28 22:29:10 +02009940 {
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009941 /* Relative to current buffer:
9942 * "/path/file" + "." -> "/path/"
9943 * "/path/file" + "./subdir" -> "/path/subdir" */
Bram Moolenaar162bd912010-07-28 22:29:10 +02009944 if (curbuf->b_ffname == NULL)
9945 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009946 p = gettail(curbuf->b_ffname);
9947 len = (int)(p - curbuf->b_ffname);
9948 if (len + (int)STRLEN(buf) >= MAXPATHL)
9949 continue;
9950 if (buf[1] == NUL)
9951 buf[len] = NUL;
9952 else
9953 STRMOVE(buf + len, buf + 2);
9954 mch_memmove(buf, curbuf->b_ffname, len);
9955 simplify_filename(buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009956 }
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009957 else if (buf[0] == NUL)
9958 /* relative to current directory */
Bram Moolenaar162bd912010-07-28 22:29:10 +02009959 STRCPY(buf, curdir);
Bram Moolenaar84f888a2010-08-05 21:40:16 +02009960 else if (path_with_url(buf))
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009961 /* URL can't be used here */
Bram Moolenaar84f888a2010-08-05 21:40:16 +02009962 continue;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009963 else if (!mch_isFullName(buf))
9964 {
9965 /* Expand relative path to their full path equivalent */
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009966 len = (int)STRLEN(curdir);
9967 if (len + (int)STRLEN(buf) + 3 > MAXPATHL)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009968 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009969 STRMOVE(buf + len + 1, buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009970 STRCPY(buf, curdir);
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009971 buf[len] = PATHSEP;
Bram Moolenaar57adda12010-08-03 22:11:29 +02009972 simplify_filename(buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009973 }
9974
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009975 if (ga_grow(gap, 1) == FAIL)
9976 break;
9977 p = vim_strsave(buf);
9978 if (p == NULL)
9979 break;
9980 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009981 }
9982
9983 vim_free(buf);
9984}
9985
9986/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009987 * Returns a pointer to the file or directory name in "fname" that matches the
9988 * longest path in "ga"p, or NULL if there is no match. For example:
Bram Moolenaar162bd912010-07-28 22:29:10 +02009989 *
9990 * path: /foo/bar/baz
9991 * fname: /foo/bar/baz/quux.txt
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009992 * returns: ^this
Bram Moolenaar162bd912010-07-28 22:29:10 +02009993 */
9994 static char_u *
9995get_path_cutoff(fname, gap)
9996 char_u *fname;
9997 garray_T *gap;
9998{
9999 int i;
10000 int maxlen = 0;
10001 char_u **path_part = (char_u **)gap->ga_data;
10002 char_u *cutoff = NULL;
10003
10004 for (i = 0; i < gap->ga_len; i++)
10005 {
10006 int j = 0;
10007
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010008 while ((fname[j] == path_part[i][j]
Bram Moolenaar2d7c47d2010-08-10 19:50:26 +020010009# if defined(MSWIN) || defined(MSDOS)
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010010 || (vim_ispathsep(fname[j]) && vim_ispathsep(path_part[i][j]))
10011#endif
10012 ) && fname[j] != NUL && path_part[i][j] != NUL)
Bram Moolenaar162bd912010-07-28 22:29:10 +020010013 j++;
10014 if (j > maxlen)
10015 {
10016 maxlen = j;
10017 cutoff = &fname[j];
10018 }
10019 }
10020
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010021 /* skip to the file or directory name */
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010022 if (cutoff != NULL)
Bram Moolenaar31710262010-08-13 13:36:15 +020010023 while (vim_ispathsep(*cutoff))
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010024 mb_ptr_adv(cutoff);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010025
10026 return cutoff;
10027}
10028
10029/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010030 * Sorts, removes duplicates and modifies all the fullpath names in "gap" so
10031 * that they are unique with respect to each other while conserving the part
10032 * that matches the pattern. Beware, this is at least O(n^2) wrt "gap->ga_len".
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010033 */
10034 static void
10035uniquefy_paths(gap, pattern)
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +020010036 garray_T *gap;
10037 char_u *pattern;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010038{
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +020010039 int i;
10040 int len;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010041 char_u **fnames = (char_u **)gap->ga_data;
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010042 int sort_again = FALSE;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010043 char_u *pat;
10044 char_u *file_pattern;
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010045 char_u *curdir;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010046 regmatch_T regmatch;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010047 garray_T path_ga;
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010048 char_u **in_curdir = NULL;
10049 char_u *short_name;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010050
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +020010051 remove_duplicates(gap);
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010052 ga_init2(&path_ga, (int)sizeof(char_u *), 1);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010053
10054 /*
10055 * We need to prepend a '*' at the beginning of file_pattern so that the
10056 * regex matches anywhere in the path. FIXME: is this valid for all
Bram Moolenaarb31e4382010-07-24 16:01:56 +020010057 * possible patterns?
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010058 */
Bram Moolenaar624c7aa2010-07-16 20:38:52 +020010059 len = (int)STRLEN(pattern);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010060 file_pattern = alloc(len + 2);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010061 if (file_pattern == NULL)
10062 return;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010063 file_pattern[0] = '*';
Bram Moolenaar162bd912010-07-28 22:29:10 +020010064 file_pattern[1] = NUL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010065 STRCAT(file_pattern, pattern);
10066 pat = file_pat_to_reg_pat(file_pattern, NULL, NULL, TRUE);
10067 vim_free(file_pattern);
Bram Moolenaarb31e4382010-07-24 16:01:56 +020010068 if (pat == NULL)
10069 return;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010070
Bram Moolenaarb31e4382010-07-24 16:01:56 +020010071 regmatch.rm_ic = TRUE; /* always ignore case */
10072 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
10073 vim_free(pat);
10074 if (regmatch.regprog == NULL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010075 return;
10076
Bram Moolenaar162bd912010-07-28 22:29:10 +020010077 if ((curdir = alloc((int)(MAXPATHL))) == NULL)
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010078 goto theend;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010079 mch_dirname(curdir, MAXPATHL);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010080 expand_path_option(curdir, &path_ga);
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010081
10082 in_curdir = (char_u **)alloc_clear(gap->ga_len * sizeof(char_u *));
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010083 if (in_curdir == NULL)
10084 goto theend;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010085
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010086 for (i = 0; i < gap->ga_len && !got_int; i++)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010087 {
Bram Moolenaar162bd912010-07-28 22:29:10 +020010088 char_u *path = fnames[i];
10089 int is_in_curdir;
Bram Moolenaar31710262010-08-13 13:36:15 +020010090 char_u *dir_end = gettail_dir(path);
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010091 char_u *pathsep_p;
10092 char_u *path_cutoff;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010093
Bram Moolenaar624c7aa2010-07-16 20:38:52 +020010094 len = (int)STRLEN(path);
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010095 is_in_curdir = fnamencmp(curdir, path, dir_end - path) == 0
Bram Moolenaar162bd912010-07-28 22:29:10 +020010096 && curdir[dir_end - path] == NUL;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010097 if (is_in_curdir)
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010098 in_curdir[i] = vim_strsave(path);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010099
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010100 /* Shorten the filename while maintaining its uniqueness */
10101 path_cutoff = get_path_cutoff(path, &path_ga);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010102
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010103 /* we start at the end of the path */
10104 pathsep_p = path + len - 1;
10105
10106 while (find_previous_pathsep(path, &pathsep_p))
10107 if (vim_regexec(&regmatch, pathsep_p + 1, (colnr_T)0)
10108 && is_unique(pathsep_p + 1, gap, i)
10109 && path_cutoff != NULL && pathsep_p + 1 >= path_cutoff)
10110 {
10111 sort_again = TRUE;
10112 mch_memmove(path, pathsep_p + 1, STRLEN(pathsep_p));
10113 break;
10114 }
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010115
10116 if (mch_isFullName(path))
10117 {
10118 /*
10119 * Last resort: shorten relative to curdir if possible.
10120 * 'possible' means:
10121 * 1. It is under the current directory.
10122 * 2. The result is actually shorter than the original.
10123 *
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010124 * Before curdir After
10125 * /foo/bar/file.txt /foo/bar ./file.txt
10126 * c:\foo\bar\file.txt c:\foo\bar .\file.txt
10127 * /file.txt / /file.txt
10128 * c:\file.txt c:\ .\file.txt
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010129 */
10130 short_name = shorten_fname(path, curdir);
Bram Moolenaar31710262010-08-13 13:36:15 +020010131 if (short_name != NULL && short_name > path + 1
10132#if defined(MSWIN) || defined(MSDOS)
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010133 /* On windows,
Bram Moolenaar31710262010-08-13 13:36:15 +020010134 * shorten_fname("c:\a\a.txt", "c:\a\b")
Bram Moolenaar31710262010-08-13 13:36:15 +020010135 * returns "\a\a.txt", which is not really the short
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010136 * name, hence: */
Bram Moolenaar31710262010-08-13 13:36:15 +020010137 && !vim_ispathsep(*short_name)
10138#endif
10139 )
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010140 {
10141 STRCPY(path, ".");
10142 add_pathsep(path);
Bram Moolenaarcda000e2010-08-14 13:34:39 +020010143 STRMOVE(path + STRLEN(path), short_name);
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010144 }
10145 }
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010146 ui_breakcheck();
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010147 }
10148
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010149 /* Shorten filenames in /in/current/directory/{filename} */
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010150 for (i = 0; i < gap->ga_len && !got_int; i++)
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010151 {
10152 char_u *rel_path;
10153 char_u *path = in_curdir[i];
10154
10155 if (path == NULL)
10156 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010157
10158 /* If the {filename} is not unique, change it to ./{filename}.
10159 * Else reduce it to {filename} */
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010160 short_name = shorten_fname(path, curdir);
10161 if (short_name == NULL)
10162 short_name = path;
10163 if (is_unique(short_name, gap, i))
10164 {
10165 STRCPY(fnames[i], short_name);
10166 continue;
10167 }
10168
10169 rel_path = alloc((int)(STRLEN(short_name) + STRLEN(PATHSEPSTR) + 2));
10170 if (rel_path == NULL)
10171 goto theend;
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010172 STRCPY(rel_path, ".");
10173 add_pathsep(rel_path);
10174 STRCAT(rel_path, short_name);
10175
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010176 vim_free(fnames[i]);
10177 fnames[i] = rel_path;
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010178 sort_again = TRUE;
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010179 ui_breakcheck();
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010180 }
10181
Bram Moolenaar162bd912010-07-28 22:29:10 +020010182theend:
10183 vim_free(curdir);
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010184 if (in_curdir != NULL)
10185 {
10186 for (i = 0; i < gap->ga_len; i++)
10187 vim_free(in_curdir[i]);
10188 vim_free(in_curdir);
10189 }
Bram Moolenaar162bd912010-07-28 22:29:10 +020010190 ga_clear_strings(&path_ga);
Bram Moolenaarb31e4382010-07-24 16:01:56 +020010191 vim_free(regmatch.regprog);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010192
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010193 if (sort_again)
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +020010194 remove_duplicates(gap);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010195}
10196
10197/*
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010198 * Calls globpath() with 'path' values for the given pattern and stores the
10199 * result in "gap".
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010200 * Returns the total number of matches.
10201 */
10202 static int
10203expand_in_path(gap, pattern, flags)
10204 garray_T *gap;
10205 char_u *pattern;
10206 int flags; /* EW_* flags */
10207{
Bram Moolenaar162bd912010-07-28 22:29:10 +020010208 char_u *curdir;
10209 garray_T path_ga;
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010210 char_u *files = NULL;
10211 char_u *s; /* start */
10212 char_u *e; /* end */
10213 char_u *paths = NULL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010214
Bram Moolenaar7f0f6212010-08-03 22:21:00 +020010215 if ((curdir = alloc((unsigned)MAXPATHL)) == NULL)
Bram Moolenaar162bd912010-07-28 22:29:10 +020010216 return 0;
10217 mch_dirname(curdir, MAXPATHL);
10218
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010219 ga_init2(&path_ga, (int)sizeof(char_u *), 1);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010220 expand_path_option(curdir, &path_ga);
10221 vim_free(curdir);
Bram Moolenaar006d2b02010-08-04 12:39:44 +020010222 if (path_ga.ga_len == 0)
10223 return 0;
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010224
10225 paths = ga_concat_strings(&path_ga);
10226 ga_clear_strings(&path_ga);
10227 if (paths == NULL)
Bram Moolenaar7f0f6212010-08-03 22:21:00 +020010228 return 0;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010229
Bram Moolenaar94950a92010-12-02 16:01:29 +010010230 files = globpath(paths, pattern, (flags & EW_ICASE) ? WILD_ICASE : 0);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010231 vim_free(paths);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010232 if (files == NULL)
10233 return 0;
10234
10235 /* Copy each path in files into gap */
10236 s = e = files;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010237 while (*s != NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010238 {
Bram Moolenaar162bd912010-07-28 22:29:10 +020010239 while (*e != '\n' && *e != NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010240 e++;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010241 if (*e == NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010242 {
10243 addfile(gap, s, flags);
10244 break;
10245 }
10246 else
10247 {
10248 /* *e is '\n' */
Bram Moolenaar162bd912010-07-28 22:29:10 +020010249 *e = NUL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010250 addfile(gap, s, flags);
10251 e++;
10252 s = e;
10253 }
10254 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010255 vim_free(files);
10256
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010257 return gap->ga_len;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010258}
10259#endif
10260
Bram Moolenaar1587a1e2010-07-29 20:59:59 +020010261#if defined(FEAT_SEARCHPATH) || defined(FEAT_CMDL_COMPL) || defined(PROTO)
10262/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010263 * Sort "gap" and remove duplicate entries. "gap" is expected to contain a
10264 * list of file names in allocated memory.
Bram Moolenaar1587a1e2010-07-29 20:59:59 +020010265 */
10266 void
10267remove_duplicates(gap)
10268 garray_T *gap;
10269{
10270 int i;
10271 int j;
10272 char_u **fnames = (char_u **)gap->ga_data;
10273
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010274 sort_strings(fnames, gap->ga_len);
Bram Moolenaar1587a1e2010-07-29 20:59:59 +020010275 for (i = gap->ga_len - 1; i > 0; --i)
10276 if (fnamecmp(fnames[i - 1], fnames[i]) == 0)
10277 {
10278 vim_free(fnames[i]);
10279 for (j = i + 1; j < gap->ga_len; ++j)
10280 fnames[j - 1] = fnames[j];
10281 --gap->ga_len;
10282 }
10283}
10284#endif
10285
Bram Moolenaar071d4272004-06-13 20:20:40 +000010286/*
10287 * Generic wildcard expansion code.
10288 *
10289 * Characters in "pat" that should not be expanded must be preceded with a
10290 * backslash. E.g., "/path\ with\ spaces/my\*star*"
10291 *
10292 * Return FAIL when no single file was found. In this case "num_file" is not
10293 * set, and "file" may contain an error message.
10294 * Return OK when some files found. "num_file" is set to the number of
10295 * matches, "file" to the array of matches. Call FreeWild() later.
10296 */
10297 int
10298gen_expand_wildcards(num_pat, pat, num_file, file, flags)
10299 int num_pat; /* number of input patterns */
10300 char_u **pat; /* array of input patterns */
10301 int *num_file; /* resulting number of files */
10302 char_u ***file; /* array of resulting files */
10303 int flags; /* EW_* flags */
10304{
10305 int i;
10306 garray_T ga;
10307 char_u *p;
10308 static int recursive = FALSE;
10309 int add_pat;
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010310#if defined(FEAT_SEARCHPATH)
10311 int did_expand_in_path = FALSE;
10312#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000010313
10314 /*
10315 * expand_env() is called to expand things like "~user". If this fails,
10316 * it calls ExpandOne(), which brings us back here. In this case, always
10317 * call the machine specific expansion function, if possible. Otherwise,
10318 * return FAIL.
10319 */
10320 if (recursive)
10321#ifdef SPECIAL_WILDCHAR
10322 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
10323#else
10324 return FAIL;
10325#endif
10326
10327#ifdef SPECIAL_WILDCHAR
10328 /*
10329 * If there are any special wildcard characters which we cannot handle
10330 * here, call machine specific function for all the expansion. This
10331 * avoids starting the shell for each argument separately.
10332 * For `=expr` do use the internal function.
10333 */
10334 for (i = 0; i < num_pat; i++)
10335 {
10336 if (vim_strpbrk(pat[i], (char_u *)SPECIAL_WILDCHAR) != NULL
10337# ifdef VIM_BACKTICK
10338 && !(vim_backtick(pat[i]) && pat[i][1] == '=')
10339# endif
10340 )
10341 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
10342 }
10343#endif
10344
10345 recursive = TRUE;
10346
10347 /*
10348 * The matching file names are stored in a growarray. Init it empty.
10349 */
10350 ga_init2(&ga, (int)sizeof(char_u *), 30);
10351
10352 for (i = 0; i < num_pat; ++i)
10353 {
10354 add_pat = -1;
10355 p = pat[i];
10356
10357#ifdef VIM_BACKTICK
10358 if (vim_backtick(p))
10359 add_pat = expand_backtick(&ga, p, flags);
10360 else
10361#endif
10362 {
10363 /*
10364 * First expand environment variables, "~/" and "~user/".
10365 */
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010366 if (vim_strchr(p, '$') != NULL || *p == '~')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010367 {
Bram Moolenaar9f0545d2007-09-26 20:36:32 +000010368 p = expand_env_save_opt(p, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010369 if (p == NULL)
10370 p = pat[i];
10371#ifdef UNIX
10372 /*
10373 * On Unix, if expand_env() can't expand an environment
10374 * variable, use the shell to do that. Discard previously
10375 * found file names and start all over again.
10376 */
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010377 else if (vim_strchr(p, '$') != NULL || *p == '~')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010378 {
10379 vim_free(p);
Bram Moolenaar782027e2009-06-24 14:25:49 +000010380 ga_clear_strings(&ga);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010381 i = mch_expand_wildcards(num_pat, pat, num_file, file,
10382 flags);
10383 recursive = FALSE;
10384 return i;
10385 }
10386#endif
10387 }
10388
10389 /*
10390 * If there are wildcards: Expand file names and add each match to
10391 * the list. If there is no match, and EW_NOTFOUND is given, add
10392 * the pattern.
10393 * If there are no wildcards: Add the file name if it exists or
10394 * when EW_NOTFOUND is given.
10395 */
10396 if (mch_has_exp_wildcard(p))
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010397 {
10398#if defined(FEAT_SEARCHPATH)
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010399 if ((flags & EW_PATH)
10400 && !mch_isFullName(p)
10401 && !(p[0] == '.'
10402 && (vim_ispathsep(p[1])
10403 || (p[1] == '.' && vim_ispathsep(p[2]))))
10404 )
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010405 {
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010406 /* :find completion where 'path' is used.
10407 * Recursiveness is OK here. */
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010408 recursive = FALSE;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010409 add_pat = expand_in_path(&ga, p, flags);
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010410 recursive = TRUE;
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010411 did_expand_in_path = TRUE;
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010412 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010413 else
10414#endif
10415 add_pat = mch_expandpath(&ga, p, flags);
10416 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010417 }
10418
10419 if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
10420 {
10421 char_u *t = backslash_halve_save(p);
10422
10423#if defined(MACOS_CLASSIC)
10424 slash_to_colon(t);
10425#endif
10426 /* When EW_NOTFOUND is used, always add files and dirs. Makes
10427 * "vim c:/" work. */
10428 if (flags & EW_NOTFOUND)
10429 addfile(&ga, t, flags | EW_DIR | EW_FILE);
10430 else if (mch_getperm(t) >= 0)
10431 addfile(&ga, t, flags);
10432 vim_free(t);
10433 }
10434
Bram Moolenaarb28ebbc2010-07-14 16:59:57 +020010435#if defined(FEAT_SEARCHPATH)
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010436 if (did_expand_in_path && ga.ga_len > 0 && (flags & EW_PATH))
Bram Moolenaarb28ebbc2010-07-14 16:59:57 +020010437 uniquefy_paths(&ga, p);
10438#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000010439 if (p != pat[i])
10440 vim_free(p);
10441 }
10442
10443 *num_file = ga.ga_len;
10444 *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data : (char_u **)"";
10445
10446 recursive = FALSE;
10447
10448 return (ga.ga_data != NULL) ? OK : FAIL;
10449}
10450
10451# ifdef VIM_BACKTICK
10452
10453/*
10454 * Return TRUE if we can expand this backtick thing here.
10455 */
10456 static int
10457vim_backtick(p)
10458 char_u *p;
10459{
10460 return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
10461}
10462
10463/*
10464 * Expand an item in `backticks` by executing it as a command.
10465 * Currently only works when pat[] starts and ends with a `.
10466 * Returns number of file names found.
10467 */
10468 static int
10469expand_backtick(gap, pat, flags)
10470 garray_T *gap;
10471 char_u *pat;
10472 int flags; /* EW_* flags */
10473{
10474 char_u *p;
10475 char_u *cmd;
10476 char_u *buffer;
10477 int cnt = 0;
10478 int i;
10479
10480 /* Create the command: lop off the backticks. */
10481 cmd = vim_strnsave(pat + 1, (int)STRLEN(pat) - 2);
10482 if (cmd == NULL)
10483 return 0;
10484
10485#ifdef FEAT_EVAL
10486 if (*cmd == '=') /* `={expr}`: Expand expression */
Bram Moolenaar362e1a32006-03-06 23:29:24 +000010487 buffer = eval_to_string(cmd + 1, &p, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010488 else
10489#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010490 buffer = get_cmd_output(cmd, NULL,
10491 (flags & EW_SILENT) ? SHELL_SILENT : 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010492 vim_free(cmd);
10493 if (buffer == NULL)
10494 return 0;
10495
10496 cmd = buffer;
10497 while (*cmd != NUL)
10498 {
10499 cmd = skipwhite(cmd); /* skip over white space */
10500 p = cmd;
10501 while (*p != NUL && *p != '\r' && *p != '\n') /* skip over entry */
10502 ++p;
10503 /* add an entry if it is not empty */
10504 if (p > cmd)
10505 {
10506 i = *p;
10507 *p = NUL;
10508 addfile(gap, cmd, flags);
10509 *p = i;
10510 ++cnt;
10511 }
10512 cmd = p;
10513 while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
10514 ++cmd;
10515 }
10516
10517 vim_free(buffer);
10518 return cnt;
10519}
10520# endif /* VIM_BACKTICK */
10521
10522/*
10523 * Add a file to a file list. Accepted flags:
10524 * EW_DIR add directories
10525 * EW_FILE add files
Bram Moolenaar1f35bf92006-03-07 22:38:47 +000010526 * EW_EXEC add executable files
Bram Moolenaar071d4272004-06-13 20:20:40 +000010527 * EW_NOTFOUND add even when it doesn't exist
10528 * EW_ADDSLASH add slash after directory name
10529 */
10530 void
10531addfile(gap, f, flags)
10532 garray_T *gap;
10533 char_u *f; /* filename */
10534 int flags;
10535{
10536 char_u *p;
10537 int isdir;
10538
10539 /* if the file/dir doesn't exist, may not add it */
10540 if (!(flags & EW_NOTFOUND) && mch_getperm(f) < 0)
10541 return;
10542
10543#ifdef FNAME_ILLEGAL
10544 /* if the file/dir contains illegal characters, don't add it */
10545 if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
10546 return;
10547#endif
10548
10549 isdir = mch_isdir(f);
10550 if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
10551 return;
10552
Bram Moolenaar1f35bf92006-03-07 22:38:47 +000010553 /* If the file isn't executable, may not add it. Do accept directories. */
10554 if (!isdir && (flags & EW_EXEC) && !mch_can_exe(f))
10555 return;
10556
Bram Moolenaar071d4272004-06-13 20:20:40 +000010557 /* Make room for another item in the file list. */
10558 if (ga_grow(gap, 1) == FAIL)
10559 return;
10560
10561 p = alloc((unsigned)(STRLEN(f) + 1 + isdir));
10562 if (p == NULL)
10563 return;
10564
10565 STRCPY(p, f);
10566#ifdef BACKSLASH_IN_FILENAME
10567 slash_adjust(p);
10568#endif
10569 /*
10570 * Append a slash or backslash after directory names if none is present.
10571 */
10572#ifndef DONT_ADD_PATHSEP_TO_DIR
10573 if (isdir && (flags & EW_ADDSLASH))
10574 add_pathsep(p);
10575#endif
10576 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010577}
10578#endif /* !NO_EXPANDPATH */
10579
10580#if defined(VIM_BACKTICK) || defined(FEAT_EVAL) || defined(PROTO)
10581
10582#ifndef SEEK_SET
10583# define SEEK_SET 0
10584#endif
10585#ifndef SEEK_END
10586# define SEEK_END 2
10587#endif
10588
10589/*
10590 * Get the stdout of an external command.
10591 * Returns an allocated string, or NULL for error.
10592 */
10593 char_u *
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010594get_cmd_output(cmd, infile, flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010595 char_u *cmd;
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010596 char_u *infile; /* optional input file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010597 int flags; /* can be SHELL_SILENT */
10598{
10599 char_u *tempname;
10600 char_u *command;
10601 char_u *buffer = NULL;
10602 int len;
10603 int i = 0;
10604 FILE *fd;
10605
10606 if (check_restricted() || check_secure())
10607 return NULL;
10608
10609 /* get a name for the temp file */
10610 if ((tempname = vim_tempname('o')) == NULL)
10611 {
10612 EMSG(_(e_notmp));
10613 return NULL;
10614 }
10615
10616 /* Add the redirection stuff */
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010617 command = make_filter_cmd(cmd, infile, tempname);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010618 if (command == NULL)
10619 goto done;
10620
10621 /*
10622 * Call the shell to execute the command (errors are ignored).
10623 * Don't check timestamps here.
10624 */
10625 ++no_check_timestamps;
10626 call_shell(command, SHELL_DOOUT | SHELL_EXPAND | flags);
10627 --no_check_timestamps;
10628
10629 vim_free(command);
10630
10631 /*
10632 * read the names from the file into memory
10633 */
10634# ifdef VMS
Bram Moolenaar25394022007-05-10 19:06:20 +000010635 /* created temporary file is not always readable as binary */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010636 fd = mch_fopen((char *)tempname, "r");
10637# else
10638 fd = mch_fopen((char *)tempname, READBIN);
10639# endif
10640
10641 if (fd == NULL)
10642 {
10643 EMSG2(_(e_notopen), tempname);
10644 goto done;
10645 }
10646
10647 fseek(fd, 0L, SEEK_END);
10648 len = ftell(fd); /* get size of temp file */
10649 fseek(fd, 0L, SEEK_SET);
10650
10651 buffer = alloc(len + 1);
10652 if (buffer != NULL)
10653 i = (int)fread((char *)buffer, (size_t)1, (size_t)len, fd);
10654 fclose(fd);
10655 mch_remove(tempname);
10656 if (buffer == NULL)
10657 goto done;
10658#ifdef VMS
10659 len = i; /* VMS doesn't give us what we asked for... */
10660#endif
10661 if (i != len)
10662 {
10663 EMSG2(_(e_notread), tempname);
10664 vim_free(buffer);
10665 buffer = NULL;
10666 }
10667 else
Bram Moolenaar162bd912010-07-28 22:29:10 +020010668 buffer[len] = NUL; /* make sure the buffer is terminated */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010669
10670done:
10671 vim_free(tempname);
10672 return buffer;
10673}
10674#endif
10675
10676/*
10677 * Free the list of files returned by expand_wildcards() or other expansion
10678 * functions.
10679 */
10680 void
10681FreeWild(count, files)
10682 int count;
10683 char_u **files;
10684{
Bram Moolenaarfc1421e2006-04-20 22:17:20 +000010685 if (count <= 0 || files == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010686 return;
10687#if defined(__EMX__) && defined(__ALWAYS_HAS_TRAILING_NULL_POINTER) /* XXX */
10688 /*
10689 * Is this still OK for when other functions than expand_wildcards() have
10690 * been used???
10691 */
10692 _fnexplodefree((char **)files);
10693#else
10694 while (count--)
10695 vim_free(files[count]);
10696 vim_free(files);
10697#endif
10698}
10699
10700/*
Bram Moolenaara9dc3752010-07-11 20:46:53 +020010701 * Return TRUE when need to go to Insert mode because of 'insertmode'.
Bram Moolenaar071d4272004-06-13 20:20:40 +000010702 * Don't do this when still processing a command or a mapping.
10703 * Don't do this when inside a ":normal" command.
10704 */
10705 int
10706goto_im()
10707{
10708 return (p_im && stuff_empty() && typebuf_typed());
10709}