blob: 34822720600ec7c56433b78d04aac52182c15d2a [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
Bram Moolenaarbef47902012-07-06 16:49:40 +02004499 /* Empty is the same as not set. */
4500 if (homedir_env != NULL && *homedir_env == NUL)
4501 homedir_env = NULL;
4502
Bram Moolenaar9158f9e2012-06-20 14:02:27 +02004503#if defined(FEAT_MODIFY_FNAME) || defined(WIN3264)
Bram Moolenaarbef47902012-07-06 16:49:40 +02004504 if (homedir_env != NULL && vim_strchr(homedir_env, '~') != NULL)
Bram Moolenaar9158f9e2012-06-20 14:02:27 +02004505 {
4506 int usedlen = 0;
4507 int flen;
4508 char_u *fbuf = NULL;
4509
4510 flen = (int)STRLEN(homedir_env);
Bram Moolenaard12f8112012-06-20 17:56:09 +02004511 (void)modify_fname((char_u *)":p", &usedlen,
4512 &homedir_env, &fbuf, &flen);
Bram Moolenaar9158f9e2012-06-20 14:02:27 +02004513 flen = (int)STRLEN(homedir_env);
4514 if (flen > 0 && vim_ispathsep(homedir_env[flen - 1]))
4515 /* Remove the trailing / that is added to a directory. */
4516 homedir_env[flen - 1] = NUL;
4517 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004518#endif
4519
Bram Moolenaar071d4272004-06-13 20:20:40 +00004520 if (homedir_env != NULL)
4521 envlen = STRLEN(homedir_env);
4522
4523 if (!one)
4524 src = skipwhite(src);
4525 while (*src && dstlen > 0)
4526 {
4527 /*
4528 * Here we are at the beginning of a file name.
4529 * First, check to see if the beginning of the file name matches
4530 * $HOME or the "real" home directory. Check that there is a '/'
4531 * after the match (so that if e.g. the file is "/home/pieter/bla",
4532 * and the home directory is "/home/piet", the file does not end up
4533 * as "~er/bla" (which would seem to indicate the file "bla" in user
4534 * er's home directory)).
4535 */
4536 p = homedir;
4537 len = dirlen;
4538 for (;;)
4539 {
4540 if ( len
4541 && fnamencmp(src, p, len) == 0
4542 && (vim_ispathsep(src[len])
4543 || (!one && (src[len] == ',' || src[len] == ' '))
4544 || src[len] == NUL))
4545 {
4546 src += len;
4547 if (--dstlen > 0)
4548 *dst++ = '~';
4549
4550 /*
4551 * If it's just the home directory, add "/".
4552 */
4553 if (!vim_ispathsep(src[0]) && --dstlen > 0)
4554 *dst++ = '/';
4555 break;
4556 }
4557 if (p == homedir_env)
4558 break;
4559 p = homedir_env;
4560 len = envlen;
4561 }
4562
4563 /* if (!one) skip to separator: space or comma */
4564 while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
4565 *dst++ = *src++;
4566 /* skip separator */
4567 while ((*src == ' ' || *src == ',') && --dstlen > 0)
4568 *dst++ = *src++;
4569 }
4570 /* if (dstlen == 0) out of space, what to do??? */
4571
4572 *dst = NUL;
Bram Moolenaar9158f9e2012-06-20 14:02:27 +02004573
4574 if (homedir_env != homedir_env_orig)
4575 vim_free(homedir_env);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004576}
4577
4578/*
4579 * Like home_replace, store the replaced string in allocated memory.
4580 * When something fails, NULL is returned.
4581 */
4582 char_u *
4583home_replace_save(buf, src)
4584 buf_T *buf; /* when not NULL, check for help files */
4585 char_u *src; /* input file name */
4586{
4587 char_u *dst;
4588 unsigned len;
4589
4590 len = 3; /* space for "~/" and trailing NUL */
4591 if (src != NULL) /* just in case */
4592 len += (unsigned)STRLEN(src);
4593 dst = alloc(len);
4594 if (dst != NULL)
4595 home_replace(buf, src, dst, len, TRUE);
4596 return dst;
4597}
4598
4599/*
4600 * Compare two file names and return:
4601 * FPC_SAME if they both exist and are the same file.
4602 * FPC_SAMEX if they both don't exist and have the same file name.
4603 * FPC_DIFF if they both exist and are different files.
4604 * FPC_NOTX if they both don't exist.
4605 * FPC_DIFFX if one of them doesn't exist.
4606 * For the first name environment variables are expanded
4607 */
4608 int
4609fullpathcmp(s1, s2, checkname)
4610 char_u *s1, *s2;
4611 int checkname; /* when both don't exist, check file names */
4612{
4613#ifdef UNIX
4614 char_u exp1[MAXPATHL];
4615 char_u full1[MAXPATHL];
4616 char_u full2[MAXPATHL];
4617 struct stat st1, st2;
4618 int r1, r2;
4619
4620 expand_env(s1, exp1, MAXPATHL);
4621 r1 = mch_stat((char *)exp1, &st1);
4622 r2 = mch_stat((char *)s2, &st2);
4623 if (r1 != 0 && r2 != 0)
4624 {
4625 /* if mch_stat() doesn't work, may compare the names */
4626 if (checkname)
4627 {
4628 if (fnamecmp(exp1, s2) == 0)
4629 return FPC_SAMEX;
4630 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4631 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4632 if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
4633 return FPC_SAMEX;
4634 }
4635 return FPC_NOTX;
4636 }
4637 if (r1 != 0 || r2 != 0)
4638 return FPC_DIFFX;
4639 if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
4640 return FPC_SAME;
4641 return FPC_DIFF;
4642#else
4643 char_u *exp1; /* expanded s1 */
4644 char_u *full1; /* full path of s1 */
4645 char_u *full2; /* full path of s2 */
4646 int retval = FPC_DIFF;
4647 int r1, r2;
4648
4649 /* allocate one buffer to store three paths (alloc()/free() is slow!) */
4650 if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
4651 {
4652 full1 = exp1 + MAXPATHL;
4653 full2 = full1 + MAXPATHL;
4654
4655 expand_env(s1, exp1, MAXPATHL);
4656 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4657 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4658
4659 /* If vim_FullName() fails, the file probably doesn't exist. */
4660 if (r1 != OK && r2 != OK)
4661 {
4662 if (checkname && fnamecmp(exp1, s2) == 0)
4663 retval = FPC_SAMEX;
4664 else
4665 retval = FPC_NOTX;
4666 }
4667 else if (r1 != OK || r2 != OK)
4668 retval = FPC_DIFFX;
4669 else if (fnamecmp(full1, full2))
4670 retval = FPC_DIFF;
4671 else
4672 retval = FPC_SAME;
4673 vim_free(exp1);
4674 }
4675 return retval;
4676#endif
4677}
4678
4679/*
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004680 * Get the tail of a path: the file name.
Bram Moolenaar31710262010-08-13 13:36:15 +02004681 * When the path ends in a path separator the tail is the NUL after it.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004682 * Fail safe: never returns NULL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004683 */
4684 char_u *
4685gettail(fname)
4686 char_u *fname;
4687{
4688 char_u *p1, *p2;
4689
4690 if (fname == NULL)
4691 return (char_u *)"";
4692 for (p1 = p2 = fname; *p2; ) /* find last part of path */
4693 {
4694 if (vim_ispathsep(*p2))
4695 p1 = p2 + 1;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004696 mb_ptr_adv(p2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004697 }
4698 return p1;
4699}
4700
Bram Moolenaar31710262010-08-13 13:36:15 +02004701#if defined(FEAT_SEARCHPATH)
4702static char_u *gettail_dir __ARGS((char_u *fname));
4703
4704/*
4705 * Return the end of the directory name, on the first path
4706 * separator:
4707 * "/path/file", "/path/dir/", "/path//dir", "/file"
4708 * ^ ^ ^ ^
4709 */
4710 static char_u *
4711gettail_dir(fname)
4712 char_u *fname;
4713{
4714 char_u *dir_end = fname;
4715 char_u *next_dir_end = fname;
4716 int look_for_sep = TRUE;
4717 char_u *p;
4718
4719 for (p = fname; *p != NUL; )
4720 {
4721 if (vim_ispathsep(*p))
4722 {
4723 if (look_for_sep)
4724 {
4725 next_dir_end = p;
4726 look_for_sep = FALSE;
4727 }
4728 }
4729 else
4730 {
4731 if (!look_for_sep)
4732 dir_end = next_dir_end;
4733 look_for_sep = TRUE;
4734 }
4735 mb_ptr_adv(p);
4736 }
4737 return dir_end;
4738}
4739#endif
4740
Bram Moolenaar071d4272004-06-13 20:20:40 +00004741/*
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004742 * Get pointer to tail of "fname", including path separators. Putting a NUL
4743 * here leaves the directory name. Takes care of "c:/" and "//".
4744 * Always returns a valid pointer.
4745 */
4746 char_u *
4747gettail_sep(fname)
4748 char_u *fname;
4749{
4750 char_u *p;
4751 char_u *t;
4752
4753 p = get_past_head(fname); /* don't remove the '/' from "c:/file" */
4754 t = gettail(fname);
4755 while (t > p && after_pathsep(fname, t))
4756 --t;
4757#ifdef VMS
4758 /* path separator is part of the path */
4759 ++t;
4760#endif
4761 return t;
4762}
4763
4764/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004765 * get the next path component (just after the next path separator).
4766 */
4767 char_u *
4768getnextcomp(fname)
4769 char_u *fname;
4770{
4771 while (*fname && !vim_ispathsep(*fname))
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004772 mb_ptr_adv(fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004773 if (*fname)
4774 ++fname;
4775 return fname;
4776}
4777
Bram Moolenaar071d4272004-06-13 20:20:40 +00004778/*
4779 * Get a pointer to one character past the head of a path name.
4780 * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
4781 * If there is no head, path is returned.
4782 */
4783 char_u *
4784get_past_head(path)
4785 char_u *path;
4786{
4787 char_u *retval;
4788
4789#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
4790 /* may skip "c:" */
4791 if (isalpha(path[0]) && path[1] == ':')
4792 retval = path + 2;
4793 else
4794 retval = path;
4795#else
4796# if defined(AMIGA)
4797 /* may skip "label:" */
4798 retval = vim_strchr(path, ':');
4799 if (retval == NULL)
4800 retval = path;
4801# else /* Unix */
4802 retval = path;
4803# endif
4804#endif
4805
4806 while (vim_ispathsep(*retval))
4807 ++retval;
4808
4809 return retval;
4810}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004811
4812/*
4813 * return TRUE if 'c' is a path separator.
4814 */
4815 int
4816vim_ispathsep(c)
4817 int c;
4818{
Bram Moolenaare60acc12011-05-10 16:41:25 +02004819#ifdef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00004820 return (c == '/'); /* UNIX has ':' inside file names */
Bram Moolenaare60acc12011-05-10 16:41:25 +02004821#else
4822# ifdef BACKSLASH_IN_FILENAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00004823 return (c == ':' || c == '/' || c == '\\');
Bram Moolenaare60acc12011-05-10 16:41:25 +02004824# else
4825# ifdef VMS
Bram Moolenaar071d4272004-06-13 20:20:40 +00004826 /* server"user passwd"::device:[full.path.name]fname.extension;version" */
4827 return (c == ':' || c == '[' || c == ']' || c == '/'
4828 || c == '<' || c == '>' || c == '"' );
Bram Moolenaare60acc12011-05-10 16:41:25 +02004829# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004830 return (c == ':' || c == '/');
Bram Moolenaare60acc12011-05-10 16:41:25 +02004831# endif /* VMS */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004832# endif
Bram Moolenaare60acc12011-05-10 16:41:25 +02004833#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004834}
4835
4836#if defined(FEAT_SEARCHPATH) || defined(PROTO)
4837/*
4838 * return TRUE if 'c' is a path list separator.
4839 */
4840 int
4841vim_ispathlistsep(c)
4842 int c;
4843{
4844#ifdef UNIX
4845 return (c == ':');
4846#else
Bram Moolenaar25394022007-05-10 19:06:20 +00004847 return (c == ';'); /* might not be right for every system... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004848#endif
4849}
4850#endif
4851
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004852#if defined(FEAT_GUI_TABLINE) || defined(FEAT_WINDOWS) \
4853 || defined(FEAT_EVAL) || defined(PROTO)
4854/*
4855 * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
4856 * It's done in-place.
4857 */
4858 void
4859shorten_dir(str)
4860 char_u *str;
4861{
4862 char_u *tail, *s, *d;
4863 int skip = FALSE;
4864
4865 tail = gettail(str);
4866 d = str;
4867 for (s = str; ; ++s)
4868 {
4869 if (s >= tail) /* copy the whole tail */
4870 {
4871 *d++ = *s;
4872 if (*s == NUL)
4873 break;
4874 }
4875 else if (vim_ispathsep(*s)) /* copy '/' and next char */
4876 {
4877 *d++ = *s;
4878 skip = FALSE;
4879 }
4880 else if (!skip)
4881 {
4882 *d++ = *s; /* copy next char */
4883 if (*s != '~' && *s != '.') /* and leading "~" and "." */
4884 skip = TRUE;
4885# ifdef FEAT_MBYTE
4886 if (has_mbyte)
4887 {
4888 int l = mb_ptr2len(s);
4889
4890 while (--l > 0)
Bram Moolenaarb6baca52006-08-15 20:24:14 +00004891 *d++ = *++s;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004892 }
4893# endif
4894 }
4895 }
4896}
4897#endif
4898
Bram Moolenaar900b4d72005-12-12 22:05:50 +00004899/*
4900 * Return TRUE if the directory of "fname" exists, FALSE otherwise.
4901 * Also returns TRUE if there is no directory name.
4902 * "fname" must be writable!.
4903 */
4904 int
4905dir_of_file_exists(fname)
4906 char_u *fname;
4907{
4908 char_u *p;
4909 int c;
4910 int retval;
4911
4912 p = gettail_sep(fname);
4913 if (p == fname)
4914 return TRUE;
4915 c = *p;
4916 *p = NUL;
4917 retval = mch_isdir(fname);
4918 *p = c;
4919 return retval;
4920}
4921
Bram Moolenaar071d4272004-06-13 20:20:40 +00004922#if (defined(CASE_INSENSITIVE_FILENAME) && defined(BACKSLASH_IN_FILENAME)) \
4923 || defined(PROTO)
4924/*
4925 * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally.
4926 */
4927 int
4928vim_fnamecmp(x, y)
4929 char_u *x, *y;
4930{
4931 return vim_fnamencmp(x, y, MAXPATHL);
4932}
4933
4934 int
4935vim_fnamencmp(x, y, len)
4936 char_u *x, *y;
4937 size_t len;
4938{
4939 while (len > 0 && *x && *y)
4940 {
4941 if (TOLOWER_LOC(*x) != TOLOWER_LOC(*y)
4942 && !(*x == '/' && *y == '\\')
4943 && !(*x == '\\' && *y == '/'))
4944 break;
4945 ++x;
4946 ++y;
4947 --len;
4948 }
4949 if (len == 0)
4950 return 0;
4951 return (*x - *y);
4952}
4953#endif
4954
4955/*
4956 * Concatenate file names fname1 and fname2 into allocated memory.
Bram Moolenaar25394022007-05-10 19:06:20 +00004957 * Only add a '/' or '\\' when 'sep' is TRUE and it is necessary.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004958 */
4959 char_u *
4960concat_fnames(fname1, fname2, sep)
4961 char_u *fname1;
4962 char_u *fname2;
4963 int sep;
4964{
4965 char_u *dest;
4966
4967 dest = alloc((unsigned)(STRLEN(fname1) + STRLEN(fname2) + 3));
4968 if (dest != NULL)
4969 {
4970 STRCPY(dest, fname1);
4971 if (sep)
4972 add_pathsep(dest);
4973 STRCAT(dest, fname2);
4974 }
4975 return dest;
4976}
4977
Bram Moolenaard6754642005-01-17 22:18:45 +00004978/*
4979 * Concatenate two strings and return the result in allocated memory.
4980 * Returns NULL when out of memory.
4981 */
4982 char_u *
4983concat_str(str1, str2)
4984 char_u *str1;
4985 char_u *str2;
4986{
4987 char_u *dest;
4988 size_t l = STRLEN(str1);
4989
4990 dest = alloc((unsigned)(l + STRLEN(str2) + 1L));
4991 if (dest != NULL)
4992 {
4993 STRCPY(dest, str1);
4994 STRCPY(dest + l, str2);
4995 }
4996 return dest;
4997}
Bram Moolenaard6754642005-01-17 22:18:45 +00004998
Bram Moolenaar071d4272004-06-13 20:20:40 +00004999/*
5000 * Add a path separator to a file name, unless it already ends in a path
5001 * separator.
5002 */
5003 void
5004add_pathsep(p)
5005 char_u *p;
5006{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005007 if (*p != NUL && !after_pathsep(p, p + STRLEN(p)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005008 STRCAT(p, PATHSEPSTR);
5009}
5010
5011/*
5012 * FullName_save - Make an allocated copy of a full file name.
5013 * Returns NULL when out of memory.
5014 */
5015 char_u *
5016FullName_save(fname, force)
5017 char_u *fname;
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +02005018 int force; /* force expansion, even when it already looks
5019 * like a full path name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005020{
5021 char_u *buf;
5022 char_u *new_fname = NULL;
5023
5024 if (fname == NULL)
5025 return NULL;
5026
5027 buf = alloc((unsigned)MAXPATHL);
5028 if (buf != NULL)
5029 {
5030 if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
5031 new_fname = vim_strsave(buf);
5032 else
5033 new_fname = vim_strsave(fname);
5034 vim_free(buf);
5035 }
5036 return new_fname;
5037}
5038
5039#if defined(FEAT_CINDENT) || defined(FEAT_SYN_HL)
5040
5041static char_u *skip_string __ARGS((char_u *p));
5042
5043/*
5044 * Find the start of a comment, not knowing if we are in a comment right now.
5045 * Search starts at w_cursor.lnum and goes backwards.
5046 */
5047 pos_T *
5048find_start_comment(ind_maxcomment) /* XXX */
5049 int ind_maxcomment;
5050{
5051 pos_T *pos;
5052 char_u *line;
5053 char_u *p;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005054 int cur_maxcomment = ind_maxcomment;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005055
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005056 for (;;)
5057 {
5058 pos = findmatchlimit(NULL, '*', FM_BACKWARD, cur_maxcomment);
5059 if (pos == NULL)
5060 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005061
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005062 /*
5063 * Check if the comment start we found is inside a string.
5064 * If it is then restrict the search to below this line and try again.
5065 */
5066 line = ml_get(pos->lnum);
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00005067 for (p = line; *p && (colnr_T)(p - line) < pos->col; ++p)
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005068 p = skip_string(p);
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00005069 if ((colnr_T)(p - line) <= pos->col)
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005070 break;
5071 cur_maxcomment = curwin->w_cursor.lnum - pos->lnum - 1;
5072 if (cur_maxcomment <= 0)
5073 {
5074 pos = NULL;
5075 break;
5076 }
5077 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005078 return pos;
5079}
5080
5081/*
5082 * Skip to the end of a "string" and a 'c' character.
5083 * If there is no string or character, return argument unmodified.
5084 */
5085 static char_u *
5086skip_string(p)
5087 char_u *p;
5088{
5089 int i;
5090
5091 /*
5092 * We loop, because strings may be concatenated: "date""time".
5093 */
5094 for ( ; ; ++p)
5095 {
5096 if (p[0] == '\'') /* 'c' or '\n' or '\000' */
5097 {
5098 if (!p[1]) /* ' at end of line */
5099 break;
5100 i = 2;
5101 if (p[1] == '\\') /* '\n' or '\000' */
5102 {
5103 ++i;
5104 while (vim_isdigit(p[i - 1])) /* '\000' */
5105 ++i;
5106 }
5107 if (p[i] == '\'') /* check for trailing ' */
5108 {
5109 p += i;
5110 continue;
5111 }
5112 }
5113 else if (p[0] == '"') /* start of string */
5114 {
5115 for (++p; p[0]; ++p)
5116 {
5117 if (p[0] == '\\' && p[1] != NUL)
5118 ++p;
5119 else if (p[0] == '"') /* end of string */
5120 break;
5121 }
5122 if (p[0] == '"')
5123 continue;
5124 }
5125 break; /* no string found */
5126 }
5127 if (!*p)
5128 --p; /* backup from NUL */
5129 return p;
5130}
5131#endif /* FEAT_CINDENT || FEAT_SYN_HL */
5132
5133#if defined(FEAT_CINDENT) || defined(PROTO)
5134
5135/*
5136 * Do C or expression indenting on the current line.
5137 */
5138 void
5139do_c_expr_indent()
5140{
5141# ifdef FEAT_EVAL
5142 if (*curbuf->b_p_inde != NUL)
5143 fixthisline(get_expr_indent);
5144 else
5145# endif
5146 fixthisline(get_c_indent);
5147}
5148
5149/*
5150 * Functions for C-indenting.
5151 * Most of this originally comes from Eric Fischer.
5152 */
5153/*
5154 * Below "XXX" means that this function may unlock the current line.
5155 */
5156
5157static char_u *cin_skipcomment __ARGS((char_u *));
5158static int cin_nocode __ARGS((char_u *));
5159static pos_T *find_line_comment __ARGS((void));
5160static int cin_islabel_skip __ARGS((char_u **));
5161static int cin_isdefault __ARGS((char_u *));
5162static char_u *after_label __ARGS((char_u *l));
5163static int get_indent_nolabel __ARGS((linenr_T lnum));
5164static int skip_label __ARGS((linenr_T, char_u **pp, int ind_maxcomment));
5165static int cin_first_id_amount __ARGS((void));
5166static int cin_get_equal_amount __ARGS((linenr_T lnum));
5167static int cin_ispreproc __ARGS((char_u *));
5168static int cin_ispreproc_cont __ARGS((char_u **pp, linenr_T *lnump));
5169static int cin_iscomment __ARGS((char_u *));
5170static int cin_islinecomment __ARGS((char_u *));
5171static int cin_isterminated __ARGS((char_u *, int, int));
5172static int cin_isinit __ARGS((void));
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005173static int cin_isfuncdecl __ARGS((char_u **, linenr_T, linenr_T, int, int));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005174static int cin_isif __ARGS((char_u *));
5175static int cin_iselse __ARGS((char_u *));
5176static int cin_isdo __ARGS((char_u *));
5177static int cin_iswhileofdo __ARGS((char_u *, linenr_T, int));
Bram Moolenaarb345d492012-04-09 20:42:26 +02005178static int cin_is_if_for_while_before_offset __ARGS((char_u *line, int *poffset));
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005179static int cin_iswhileofdo_end __ARGS((int terminated, int ind_maxparen, int ind_maxcomment));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005180static int cin_isbreak __ARGS((char_u *));
Bram Moolenaare7c56862007-08-04 10:14:52 +00005181static int cin_is_cpp_baseclass __ARGS((colnr_T *col));
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005182static int get_baseclass_amount __ARGS((int col, int ind_maxparen, int ind_maxcomment, int ind_cpp_baseclass));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005183static int cin_ends_in __ARGS((char_u *, char_u *, char_u *));
5184static int cin_skip2pos __ARGS((pos_T *trypos));
5185static pos_T *find_start_brace __ARGS((int));
5186static pos_T *find_match_paren __ARGS((int, int));
5187static int corr_ind_maxparen __ARGS((int ind_maxparen, pos_T *startpos));
5188static int find_last_paren __ARGS((char_u *l, int start, int end));
5189static int find_match __ARGS((int lookfor, linenr_T ourscope, int ind_maxparen, int ind_maxcomment));
Bram Moolenaared38b0a2011-05-25 15:16:18 +02005190static int cin_is_cpp_namespace __ARGS((char_u *));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005191
Bram Moolenaar39353fd2007-03-27 09:02:11 +00005192static int ind_hash_comment = 0; /* # starts a comment */
5193
Bram Moolenaar071d4272004-06-13 20:20:40 +00005194/*
5195 * Skip over white space and C comments within the line.
Bram Moolenaar39353fd2007-03-27 09:02:11 +00005196 * Also skip over Perl/shell comments if desired.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005197 */
5198 static char_u *
5199cin_skipcomment(s)
5200 char_u *s;
5201{
5202 while (*s)
5203 {
Bram Moolenaar39353fd2007-03-27 09:02:11 +00005204 char_u *prev_s = s;
5205
Bram Moolenaar071d4272004-06-13 20:20:40 +00005206 s = skipwhite(s);
Bram Moolenaar39353fd2007-03-27 09:02:11 +00005207
5208 /* Perl/shell # comment comment continues until eol. Require a space
5209 * before # to avoid recognizing $#array. */
5210 if (ind_hash_comment != 0 && s != prev_s && *s == '#')
5211 {
5212 s += STRLEN(s);
5213 break;
5214 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005215 if (*s != '/')
5216 break;
5217 ++s;
5218 if (*s == '/') /* slash-slash comment continues till eol */
5219 {
5220 s += STRLEN(s);
5221 break;
5222 }
5223 if (*s != '*')
5224 break;
5225 for (++s; *s; ++s) /* skip slash-star comment */
5226 if (s[0] == '*' && s[1] == '/')
5227 {
5228 s += 2;
5229 break;
5230 }
5231 }
5232 return s;
5233}
5234
5235/*
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005236 * Return TRUE if there is no code at *s. White space and comments are
Bram Moolenaar071d4272004-06-13 20:20:40 +00005237 * not considered code.
5238 */
5239 static int
5240cin_nocode(s)
5241 char_u *s;
5242{
5243 return *cin_skipcomment(s) == NUL;
5244}
5245
5246/*
5247 * Check previous lines for a "//" line comment, skipping over blank lines.
5248 */
5249 static pos_T *
5250find_line_comment() /* XXX */
5251{
5252 static pos_T pos;
5253 char_u *line;
5254 char_u *p;
5255
5256 pos = curwin->w_cursor;
5257 while (--pos.lnum > 0)
5258 {
5259 line = ml_get(pos.lnum);
5260 p = skipwhite(line);
5261 if (cin_islinecomment(p))
5262 {
5263 pos.col = (int)(p - line);
5264 return &pos;
5265 }
5266 if (*p != NUL)
5267 break;
5268 }
5269 return NULL;
5270}
5271
5272/*
5273 * Check if string matches "label:"; move to character after ':' if true.
5274 */
5275 static int
5276cin_islabel_skip(s)
5277 char_u **s;
5278{
5279 if (!vim_isIDc(**s)) /* need at least one ID character */
5280 return FALSE;
5281
5282 while (vim_isIDc(**s))
5283 (*s)++;
5284
5285 *s = cin_skipcomment(*s);
5286
5287 /* "::" is not a label, it's C++ */
5288 return (**s == ':' && *++*s != ':');
5289}
5290
5291/*
5292 * Recognize a label: "label:".
5293 * Note: curwin->w_cursor must be where we are looking for the label.
5294 */
5295 int
5296cin_islabel(ind_maxcomment) /* XXX */
5297 int ind_maxcomment;
5298{
5299 char_u *s;
5300
5301 s = cin_skipcomment(ml_get_curline());
5302
5303 /*
5304 * Exclude "default" from labels, since it should be indented
5305 * like a switch label. Same for C++ scope declarations.
5306 */
5307 if (cin_isdefault(s))
5308 return FALSE;
5309 if (cin_isscopedecl(s))
5310 return FALSE;
5311
5312 if (cin_islabel_skip(&s))
5313 {
5314 /*
5315 * Only accept a label if the previous line is terminated or is a case
5316 * label.
5317 */
5318 pos_T cursor_save;
5319 pos_T *trypos;
5320 char_u *line;
5321
5322 cursor_save = curwin->w_cursor;
5323 while (curwin->w_cursor.lnum > 1)
5324 {
5325 --curwin->w_cursor.lnum;
5326
5327 /*
5328 * If we're in a comment now, skip to the start of the comment.
5329 */
5330 curwin->w_cursor.col = 0;
5331 if ((trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
5332 curwin->w_cursor = *trypos;
5333
5334 line = ml_get_curline();
5335 if (cin_ispreproc(line)) /* ignore #defines, #if, etc. */
5336 continue;
5337 if (*(line = cin_skipcomment(line)) == NUL)
5338 continue;
5339
5340 curwin->w_cursor = cursor_save;
5341 if (cin_isterminated(line, TRUE, FALSE)
5342 || cin_isscopedecl(line)
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005343 || cin_iscase(line, TRUE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005344 || (cin_islabel_skip(&line) && cin_nocode(line)))
5345 return TRUE;
5346 return FALSE;
5347 }
5348 curwin->w_cursor = cursor_save;
5349 return TRUE; /* label at start of file??? */
5350 }
5351 return FALSE;
5352}
5353
5354/*
5355 * Recognize structure initialization and enumerations.
5356 * Q&D-Implementation:
5357 * check for "=" at end or "[typedef] enum" at beginning of line.
5358 */
5359 static int
5360cin_isinit(void)
5361{
5362 char_u *s;
5363
5364 s = cin_skipcomment(ml_get_curline());
5365
5366 if (STRNCMP(s, "typedef", 7) == 0 && !vim_isIDc(s[7]))
5367 s = cin_skipcomment(s + 7);
5368
Bram Moolenaara5285652011-12-14 20:05:21 +01005369 if (STRNCMP(s, "static", 6) == 0 && !vim_isIDc(s[6]))
5370 s = cin_skipcomment(s + 6);
5371
Bram Moolenaar071d4272004-06-13 20:20:40 +00005372 if (STRNCMP(s, "enum", 4) == 0 && !vim_isIDc(s[4]))
5373 return TRUE;
5374
5375 if (cin_ends_in(s, (char_u *)"=", (char_u *)"{"))
5376 return TRUE;
5377
5378 return FALSE;
5379}
5380
5381/*
5382 * Recognize a switch label: "case .*:" or "default:".
5383 */
5384 int
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005385cin_iscase(s, strict)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005386 char_u *s;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005387 int strict; /* Allow relaxed check of case statement for JS */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005388{
5389 s = cin_skipcomment(s);
5390 if (STRNCMP(s, "case", 4) == 0 && !vim_isIDc(s[4]))
5391 {
5392 for (s += 4; *s; ++s)
5393 {
5394 s = cin_skipcomment(s);
5395 if (*s == ':')
5396 {
5397 if (s[1] == ':') /* skip over "::" for C++ */
5398 ++s;
5399 else
5400 return TRUE;
5401 }
5402 if (*s == '\'' && s[1] && s[2] == '\'')
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005403 s += 2; /* skip over ':' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005404 else if (*s == '/' && (s[1] == '*' || s[1] == '/'))
5405 return FALSE; /* stop at comment */
5406 else if (*s == '"')
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005407 {
5408 /* JS etc. */
5409 if (strict)
5410 return FALSE; /* stop at string */
5411 else
5412 return TRUE;
5413 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005414 }
5415 return FALSE;
5416 }
5417
5418 if (cin_isdefault(s))
5419 return TRUE;
5420 return FALSE;
5421}
5422
5423/*
5424 * Recognize a "default" switch label.
5425 */
5426 static int
5427cin_isdefault(s)
5428 char_u *s;
5429{
5430 return (STRNCMP(s, "default", 7) == 0
5431 && *(s = cin_skipcomment(s + 7)) == ':'
5432 && s[1] != ':');
5433}
5434
5435/*
Bram Moolenaar1a509df2010-08-01 17:59:57 +02005436 * Recognize a "public/private/protected" scope declaration label.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005437 */
5438 int
5439cin_isscopedecl(s)
5440 char_u *s;
5441{
5442 int i;
5443
5444 s = cin_skipcomment(s);
5445 if (STRNCMP(s, "public", 6) == 0)
5446 i = 6;
5447 else if (STRNCMP(s, "protected", 9) == 0)
5448 i = 9;
5449 else if (STRNCMP(s, "private", 7) == 0)
5450 i = 7;
5451 else
5452 return FALSE;
5453 return (*(s = cin_skipcomment(s + i)) == ':' && s[1] != ':');
5454}
5455
Bram Moolenaared38b0a2011-05-25 15:16:18 +02005456/* Maximum number of lines to search back for a "namespace" line. */
5457#define FIND_NAMESPACE_LIM 20
5458
5459/*
5460 * Recognize a "namespace" scope declaration.
5461 */
5462 static int
5463cin_is_cpp_namespace(s)
5464 char_u *s;
5465{
5466 char_u *p;
5467 int has_name = FALSE;
5468
5469 s = cin_skipcomment(s);
5470 if (STRNCMP(s, "namespace", 9) == 0 && (s[9] == NUL || !vim_iswordc(s[9])))
5471 {
5472 p = cin_skipcomment(skipwhite(s + 9));
5473 while (*p != NUL)
5474 {
5475 if (vim_iswhite(*p))
5476 {
5477 has_name = TRUE; /* found end of a name */
5478 p = cin_skipcomment(skipwhite(p));
5479 }
5480 else if (*p == '{')
5481 {
5482 break;
5483 }
5484 else if (vim_iswordc(*p))
5485 {
5486 if (has_name)
5487 return FALSE; /* word character after skipping past name */
5488 ++p;
5489 }
5490 else
5491 {
5492 return FALSE;
5493 }
5494 }
5495 return TRUE;
5496 }
5497 return FALSE;
5498}
5499
Bram Moolenaar071d4272004-06-13 20:20:40 +00005500/*
5501 * Return a pointer to the first non-empty non-comment character after a ':'.
5502 * Return NULL if not found.
5503 * case 234: a = b;
5504 * ^
5505 */
5506 static char_u *
5507after_label(l)
5508 char_u *l;
5509{
5510 for ( ; *l; ++l)
5511 {
5512 if (*l == ':')
5513 {
5514 if (l[1] == ':') /* skip over "::" for C++ */
5515 ++l;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005516 else if (!cin_iscase(l + 1, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005517 break;
5518 }
5519 else if (*l == '\'' && l[1] && l[2] == '\'')
5520 l += 2; /* skip over 'x' */
5521 }
5522 if (*l == NUL)
5523 return NULL;
5524 l = cin_skipcomment(l + 1);
5525 if (*l == NUL)
5526 return NULL;
5527 return l;
5528}
5529
5530/*
5531 * Get indent of line "lnum", skipping a label.
5532 * Return 0 if there is nothing after the label.
5533 */
5534 static int
5535get_indent_nolabel(lnum) /* XXX */
5536 linenr_T lnum;
5537{
5538 char_u *l;
5539 pos_T fp;
5540 colnr_T col;
5541 char_u *p;
5542
5543 l = ml_get(lnum);
5544 p = after_label(l);
5545 if (p == NULL)
5546 return 0;
5547
5548 fp.col = (colnr_T)(p - l);
5549 fp.lnum = lnum;
5550 getvcol(curwin, &fp, &col, NULL, NULL);
5551 return (int)col;
5552}
5553
5554/*
5555 * Find indent for line "lnum", ignoring any case or jump label.
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005556 * Also return a pointer to the text (after the label) in "pp".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005557 * label: if (asdf && asdfasdf)
5558 * ^
5559 */
5560 static int
5561skip_label(lnum, pp, ind_maxcomment)
5562 linenr_T lnum;
5563 char_u **pp;
5564 int ind_maxcomment;
5565{
5566 char_u *l;
5567 int amount;
5568 pos_T cursor_save;
5569
5570 cursor_save = curwin->w_cursor;
5571 curwin->w_cursor.lnum = lnum;
5572 l = ml_get_curline();
5573 /* XXX */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005574 if (cin_iscase(l, FALSE) || cin_isscopedecl(l)
5575 || cin_islabel(ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005576 {
5577 amount = get_indent_nolabel(lnum);
5578 l = after_label(ml_get_curline());
5579 if (l == NULL) /* just in case */
5580 l = ml_get_curline();
5581 }
5582 else
5583 {
5584 amount = get_indent();
5585 l = ml_get_curline();
5586 }
5587 *pp = l;
5588
5589 curwin->w_cursor = cursor_save;
5590 return amount;
5591}
5592
5593/*
5594 * Return the indent of the first variable name after a type in a declaration.
5595 * int a, indent of "a"
5596 * static struct foo b, indent of "b"
5597 * enum bla c, indent of "c"
5598 * Returns zero when it doesn't look like a declaration.
5599 */
5600 static int
5601cin_first_id_amount()
5602{
5603 char_u *line, *p, *s;
5604 int len;
5605 pos_T fp;
5606 colnr_T col;
5607
5608 line = ml_get_curline();
5609 p = skipwhite(line);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005610 len = (int)(skiptowhite(p) - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005611 if (len == 6 && STRNCMP(p, "static", 6) == 0)
5612 {
5613 p = skipwhite(p + 6);
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00005614 len = (int)(skiptowhite(p) - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005615 }
5616 if (len == 6 && STRNCMP(p, "struct", 6) == 0)
5617 p = skipwhite(p + 6);
5618 else if (len == 4 && STRNCMP(p, "enum", 4) == 0)
5619 p = skipwhite(p + 4);
5620 else if ((len == 8 && STRNCMP(p, "unsigned", 8) == 0)
5621 || (len == 6 && STRNCMP(p, "signed", 6) == 0))
5622 {
5623 s = skipwhite(p + len);
5624 if ((STRNCMP(s, "int", 3) == 0 && vim_iswhite(s[3]))
5625 || (STRNCMP(s, "long", 4) == 0 && vim_iswhite(s[4]))
5626 || (STRNCMP(s, "short", 5) == 0 && vim_iswhite(s[5]))
5627 || (STRNCMP(s, "char", 4) == 0 && vim_iswhite(s[4])))
5628 p = s;
5629 }
5630 for (len = 0; vim_isIDc(p[len]); ++len)
5631 ;
5632 if (len == 0 || !vim_iswhite(p[len]) || cin_nocode(p))
5633 return 0;
5634
5635 p = skipwhite(p + len);
5636 fp.lnum = curwin->w_cursor.lnum;
5637 fp.col = (colnr_T)(p - line);
5638 getvcol(curwin, &fp, &col, NULL, NULL);
5639 return (int)col;
5640}
5641
5642/*
5643 * Return the indent of the first non-blank after an equal sign.
5644 * char *foo = "here";
5645 * Return zero if no (useful) equal sign found.
5646 * Return -1 if the line above "lnum" ends in a backslash.
5647 * foo = "asdf\
5648 * asdf\
5649 * here";
5650 */
5651 static int
5652cin_get_equal_amount(lnum)
5653 linenr_T lnum;
5654{
5655 char_u *line;
5656 char_u *s;
5657 colnr_T col;
5658 pos_T fp;
5659
5660 if (lnum > 1)
5661 {
5662 line = ml_get(lnum - 1);
5663 if (*line != NUL && line[STRLEN(line) - 1] == '\\')
5664 return -1;
5665 }
5666
5667 line = s = ml_get(lnum);
5668 while (*s != NUL && vim_strchr((char_u *)"=;{}\"'", *s) == NULL)
5669 {
5670 if (cin_iscomment(s)) /* ignore comments */
5671 s = cin_skipcomment(s);
5672 else
5673 ++s;
5674 }
5675 if (*s != '=')
5676 return 0;
5677
5678 s = skipwhite(s + 1);
5679 if (cin_nocode(s))
5680 return 0;
5681
5682 if (*s == '"') /* nice alignment for continued strings */
5683 ++s;
5684
5685 fp.lnum = lnum;
5686 fp.col = (colnr_T)(s - line);
5687 getvcol(curwin, &fp, &col, NULL, NULL);
5688 return (int)col;
5689}
5690
5691/*
5692 * Recognize a preprocessor statement: Any line that starts with '#'.
5693 */
5694 static int
5695cin_ispreproc(s)
5696 char_u *s;
5697{
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005698 if (*skipwhite(s) == '#')
Bram Moolenaar071d4272004-06-13 20:20:40 +00005699 return TRUE;
5700 return FALSE;
5701}
5702
5703/*
5704 * Return TRUE if line "*pp" at "*lnump" is a preprocessor statement or a
5705 * continuation line of a preprocessor statement. Decrease "*lnump" to the
5706 * start and return the line in "*pp".
5707 */
5708 static int
5709cin_ispreproc_cont(pp, lnump)
5710 char_u **pp;
5711 linenr_T *lnump;
5712{
5713 char_u *line = *pp;
5714 linenr_T lnum = *lnump;
5715 int retval = FALSE;
5716
Bram Moolenaard8e9bb22005-07-09 21:14:46 +00005717 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005718 {
5719 if (cin_ispreproc(line))
5720 {
5721 retval = TRUE;
5722 *lnump = lnum;
5723 break;
5724 }
5725 if (lnum == 1)
5726 break;
5727 line = ml_get(--lnum);
5728 if (*line == NUL || line[STRLEN(line) - 1] != '\\')
5729 break;
5730 }
5731
5732 if (lnum != *lnump)
5733 *pp = ml_get(*lnump);
5734 return retval;
5735}
5736
5737/*
5738 * Recognize the start of a C or C++ comment.
5739 */
5740 static int
5741cin_iscomment(p)
5742 char_u *p;
5743{
5744 return (p[0] == '/' && (p[1] == '*' || p[1] == '/'));
5745}
5746
5747/*
5748 * Recognize the start of a "//" comment.
5749 */
5750 static int
5751cin_islinecomment(p)
5752 char_u *p;
5753{
5754 return (p[0] == '/' && p[1] == '/');
5755}
5756
5757/*
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005758 * Recognize a line that starts with '{' or '}', or ends with ';', ',', '{' or
5759 * '}'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005760 * Don't consider "} else" a terminated line.
Bram Moolenaar496f9512011-05-19 16:35:09 +02005761 * If a line begins with an "else", only consider it terminated if no unmatched
5762 * opening braces follow (handle "else { foo();" correctly).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005763 * Return the character terminating the line (ending char's have precedence if
5764 * both apply in order to determine initializations).
5765 */
5766 static int
5767cin_isterminated(s, incl_open, incl_comma)
5768 char_u *s;
5769 int incl_open; /* include '{' at the end as terminator */
5770 int incl_comma; /* recognize a trailing comma */
5771{
Bram Moolenaar496f9512011-05-19 16:35:09 +02005772 char_u found_start = 0;
5773 unsigned n_open = 0;
5774 int is_else = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005775
5776 s = cin_skipcomment(s);
5777
5778 if (*s == '{' || (*s == '}' && !cin_iselse(s)))
5779 found_start = *s;
5780
Bram Moolenaar496f9512011-05-19 16:35:09 +02005781 if (!found_start)
5782 is_else = cin_iselse(s);
5783
Bram Moolenaar071d4272004-06-13 20:20:40 +00005784 while (*s)
5785 {
5786 /* skip over comments, "" strings and 'c'haracters */
5787 s = skip_string(cin_skipcomment(s));
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005788 if (*s == '}' && n_open > 0)
5789 --n_open;
Bram Moolenaar496f9512011-05-19 16:35:09 +02005790 if ((!is_else || n_open == 0)
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005791 && (*s == ';' || *s == '}' || (incl_comma && *s == ','))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005792 && cin_nocode(s + 1))
5793 return *s;
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005794 else if (*s == '{')
5795 {
5796 if (incl_open && cin_nocode(s + 1))
5797 return *s;
5798 else
5799 ++n_open;
5800 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005801
5802 if (*s)
5803 s++;
5804 }
5805 return found_start;
5806}
5807
5808/*
5809 * Recognize the basic picture of a function declaration -- it needs to
5810 * have an open paren somewhere and a close paren at the end of the line and
5811 * no semicolons anywhere.
5812 * When a line ends in a comma we continue looking in the next line.
5813 * "sp" points to a string with the line. When looking at other lines it must
5814 * be restored to the line. When it's NULL fetch lines here.
5815 * "lnum" is where we start looking.
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005816 * "min_lnum" is the line before which we will not be looking.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005817 */
5818 static int
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005819cin_isfuncdecl(sp, first_lnum, min_lnum, ind_maxparen, ind_maxcomment)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005820 char_u **sp;
5821 linenr_T first_lnum;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005822 linenr_T min_lnum;
5823 int ind_maxparen;
5824 int ind_maxcomment;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005825{
5826 char_u *s;
5827 linenr_T lnum = first_lnum;
5828 int retval = FALSE;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005829 pos_T *trypos;
5830 int just_started = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005831
5832 if (sp == NULL)
5833 s = ml_get(lnum);
5834 else
5835 s = *sp;
5836
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005837 if (find_last_paren(s, '(', ')')
5838 && (trypos = find_match_paren(ind_maxparen, ind_maxcomment)) != NULL)
5839 {
5840 lnum = trypos->lnum;
5841 if (lnum < min_lnum)
5842 return FALSE;
5843
5844 s = ml_get(lnum);
5845 }
5846
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005847 /* Ignore line starting with #. */
5848 if (cin_ispreproc(s))
5849 return FALSE;
5850
Bram Moolenaar071d4272004-06-13 20:20:40 +00005851 while (*s && *s != '(' && *s != ';' && *s != '\'' && *s != '"')
5852 {
5853 if (cin_iscomment(s)) /* ignore comments */
5854 s = cin_skipcomment(s);
5855 else
5856 ++s;
5857 }
5858 if (*s != '(')
5859 return FALSE; /* ';', ' or " before any () or no '(' */
5860
5861 while (*s && *s != ';' && *s != '\'' && *s != '"')
5862 {
5863 if (*s == ')' && cin_nocode(s + 1))
5864 {
5865 /* ')' at the end: may have found a match
5866 * Check for he previous line not to end in a backslash:
5867 * #if defined(x) && \
5868 * defined(y)
5869 */
5870 lnum = first_lnum - 1;
5871 s = ml_get(lnum);
5872 if (*s == NUL || s[STRLEN(s) - 1] != '\\')
5873 retval = TRUE;
5874 goto done;
5875 }
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005876 if ((*s == ',' && cin_nocode(s + 1)) || s[1] == NUL || cin_nocode(s))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005877 {
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005878 int comma = (*s == ',');
5879
5880 /* ',' at the end: continue looking in the next line.
5881 * At the end: check for ',' in the next line, for this style:
5882 * func(arg1
5883 * , arg2) */
5884 for (;;)
5885 {
5886 if (lnum >= curbuf->b_ml.ml_line_count)
5887 break;
5888 s = ml_get(++lnum);
5889 if (!cin_ispreproc(s))
5890 break;
5891 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005892 if (lnum >= curbuf->b_ml.ml_line_count)
5893 break;
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005894 /* Require a comma at end of the line or a comma or ')' at the
5895 * start of next line. */
5896 s = skipwhite(s);
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005897 if (!just_started && (!comma && *s != ',' && *s != ')'))
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005898 break;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005899 just_started = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005900 }
5901 else if (cin_iscomment(s)) /* ignore comments */
5902 s = cin_skipcomment(s);
5903 else
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005904 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005905 ++s;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005906 just_started = FALSE;
5907 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005908 }
5909
5910done:
5911 if (lnum != first_lnum && sp != NULL)
5912 *sp = ml_get(first_lnum);
5913
5914 return retval;
5915}
5916
5917 static int
5918cin_isif(p)
5919 char_u *p;
5920{
5921 return (STRNCMP(p, "if", 2) == 0 && !vim_isIDc(p[2]));
5922}
5923
5924 static int
5925cin_iselse(p)
5926 char_u *p;
5927{
5928 if (*p == '}') /* accept "} else" */
5929 p = cin_skipcomment(p + 1);
5930 return (STRNCMP(p, "else", 4) == 0 && !vim_isIDc(p[4]));
5931}
5932
5933 static int
5934cin_isdo(p)
5935 char_u *p;
5936{
5937 return (STRNCMP(p, "do", 2) == 0 && !vim_isIDc(p[2]));
5938}
5939
5940/*
5941 * Check if this is a "while" that should have a matching "do".
5942 * We only accept a "while (condition) ;", with only white space between the
5943 * ')' and ';'. The condition may be spread over several lines.
5944 */
5945 static int
5946cin_iswhileofdo(p, lnum, ind_maxparen) /* XXX */
5947 char_u *p;
5948 linenr_T lnum;
5949 int ind_maxparen;
5950{
5951 pos_T cursor_save;
5952 pos_T *trypos;
5953 int retval = FALSE;
5954
5955 p = cin_skipcomment(p);
5956 if (*p == '}') /* accept "} while (cond);" */
5957 p = cin_skipcomment(p + 1);
5958 if (STRNCMP(p, "while", 5) == 0 && !vim_isIDc(p[5]))
5959 {
5960 cursor_save = curwin->w_cursor;
5961 curwin->w_cursor.lnum = lnum;
5962 curwin->w_cursor.col = 0;
5963 p = ml_get_curline();
5964 while (*p && *p != 'w') /* skip any '}', until the 'w' of the "while" */
5965 {
5966 ++p;
5967 ++curwin->w_cursor.col;
5968 }
5969 if ((trypos = findmatchlimit(NULL, 0, 0, ind_maxparen)) != NULL
5970 && *cin_skipcomment(ml_get_pos(trypos) + 1) == ';')
5971 retval = TRUE;
5972 curwin->w_cursor = cursor_save;
5973 }
5974 return retval;
5975}
5976
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005977/*
Bram Moolenaarb345d492012-04-09 20:42:26 +02005978 * Check whether in "p" there is an "if", "for" or "while" before "*poffset".
Bram Moolenaar3675fa02012-04-05 17:17:42 +02005979 * Return 0 if there is none.
5980 * Otherwise return !0 and update "*poffset" to point to the place where the
5981 * string was found.
5982 */
5983 static int
Bram Moolenaarb345d492012-04-09 20:42:26 +02005984cin_is_if_for_while_before_offset(line, poffset)
Bram Moolenaar3675fa02012-04-05 17:17:42 +02005985 char_u *line;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02005986 int *poffset;
5987{
Bram Moolenaarb345d492012-04-09 20:42:26 +02005988 int offset = *poffset;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02005989
5990 if (offset-- < 2)
5991 return 0;
5992 while (offset > 2 && vim_iswhite(line[offset]))
5993 --offset;
5994
5995 offset -= 1;
5996 if (!STRNCMP(line + offset, "if", 2))
5997 goto probablyFound;
5998
5999 if (offset >= 1)
6000 {
6001 offset -= 1;
6002 if (!STRNCMP(line + offset, "for", 3))
6003 goto probablyFound;
6004
6005 if (offset >= 2)
6006 {
6007 offset -= 2;
6008 if (!STRNCMP(line + offset, "while", 5))
6009 goto probablyFound;
6010 }
6011 }
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006012 return 0;
Bram Moolenaarb345d492012-04-09 20:42:26 +02006013
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006014probablyFound:
6015 if (!offset || !vim_isIDc(line[offset - 1]))
6016 {
6017 *poffset = offset;
6018 return 1;
6019 }
6020 return 0;
6021}
6022
6023/*
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006024 * Return TRUE if we are at the end of a do-while.
6025 * do
6026 * nothing;
6027 * while (foo
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00006028 * && bar); <-- here
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006029 * Adjust the cursor to the line with "while".
6030 */
6031 static int
6032cin_iswhileofdo_end(terminated, ind_maxparen, ind_maxcomment)
6033 int terminated;
6034 int ind_maxparen;
6035 int ind_maxcomment;
6036{
6037 char_u *line;
6038 char_u *p;
6039 char_u *s;
6040 pos_T *trypos;
6041 int i;
6042
6043 if (terminated != ';') /* there must be a ';' at the end */
6044 return FALSE;
6045
6046 p = line = ml_get_curline();
6047 while (*p != NUL)
6048 {
6049 p = cin_skipcomment(p);
6050 if (*p == ')')
6051 {
6052 s = skipwhite(p + 1);
6053 if (*s == ';' && cin_nocode(s + 1))
6054 {
6055 /* Found ");" at end of the line, now check there is "while"
6056 * before the matching '('. XXX */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006057 i = (int)(p - line);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006058 curwin->w_cursor.col = i;
6059 trypos = find_match_paren(ind_maxparen, ind_maxcomment);
6060 if (trypos != NULL)
6061 {
6062 s = cin_skipcomment(ml_get(trypos->lnum));
6063 if (*s == '}') /* accept "} while (cond);" */
6064 s = cin_skipcomment(s + 1);
6065 if (STRNCMP(s, "while", 5) == 0 && !vim_isIDc(s[5]))
6066 {
6067 curwin->w_cursor.lnum = trypos->lnum;
6068 return TRUE;
6069 }
6070 }
6071
6072 /* Searching may have made "line" invalid, get it again. */
6073 line = ml_get_curline();
6074 p = line + i;
6075 }
6076 }
6077 if (*p != NUL)
6078 ++p;
6079 }
6080 return FALSE;
6081}
6082
Bram Moolenaar071d4272004-06-13 20:20:40 +00006083 static int
6084cin_isbreak(p)
6085 char_u *p;
6086{
6087 return (STRNCMP(p, "break", 5) == 0 && !vim_isIDc(p[5]));
6088}
6089
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006090/*
6091 * Find the position of a C++ base-class declaration or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006092 * constructor-initialization. eg:
6093 *
6094 * class MyClass :
6095 * baseClass <-- here
6096 * class MyClass : public baseClass,
6097 * anotherBaseClass <-- here (should probably lineup ??)
6098 * MyClass::MyClass(...) :
6099 * baseClass(...) <-- here (constructor-initialization)
Bram Moolenaar18144c82006-04-12 21:52:12 +00006100 *
6101 * This is a lot of guessing. Watch out for "cond ? func() : foo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00006102 */
6103 static int
Bram Moolenaare7c56862007-08-04 10:14:52 +00006104cin_is_cpp_baseclass(col)
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006105 colnr_T *col; /* return: column to align with */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006106{
6107 char_u *s;
6108 int class_or_struct, lookfor_ctor_init, cpp_base_class;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006109 linenr_T lnum = curwin->w_cursor.lnum;
Bram Moolenaare7c56862007-08-04 10:14:52 +00006110 char_u *line = ml_get_curline();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006111
6112 *col = 0;
6113
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006114 s = skipwhite(line);
6115 if (*s == '#') /* skip #define FOO x ? (x) : x */
6116 return FALSE;
6117 s = cin_skipcomment(s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006118 if (*s == NUL)
6119 return FALSE;
6120
6121 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
6122
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006123 /* Search for a line starting with '#', empty, ending in ';' or containing
6124 * '{' or '}' and start below it. This handles the following situations:
6125 * a = cond ?
6126 * func() :
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00006127 * asdf;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006128 * func::foo()
6129 * : something
6130 * {}
6131 * Foo::Foo (int one, int two)
6132 * : something(4),
6133 * somethingelse(3)
6134 * {}
6135 */
6136 while (lnum > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006137 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00006138 line = ml_get(lnum - 1);
6139 s = skipwhite(line);
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006140 if (*s == '#' || *s == NUL)
6141 break;
6142 while (*s != NUL)
6143 {
6144 s = cin_skipcomment(s);
6145 if (*s == '{' || *s == '}'
6146 || (*s == ';' && cin_nocode(s + 1)))
6147 break;
6148 if (*s != NUL)
6149 ++s;
6150 }
6151 if (*s != NUL)
6152 break;
6153 --lnum;
6154 }
6155
Bram Moolenaare7c56862007-08-04 10:14:52 +00006156 line = ml_get(lnum);
6157 s = cin_skipcomment(line);
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006158 for (;;)
6159 {
6160 if (*s == NUL)
6161 {
6162 if (lnum == curwin->w_cursor.lnum)
6163 break;
6164 /* Continue in the cursor line. */
Bram Moolenaare7c56862007-08-04 10:14:52 +00006165 line = ml_get(++lnum);
6166 s = cin_skipcomment(line);
6167 if (*s == NUL)
6168 continue;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006169 }
6170
Bram Moolenaaraede6ce2011-05-10 11:56:30 +02006171 if (s[0] == '"')
6172 s = skip_string(s) + 1;
6173 else if (s[0] == ':')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006174 {
6175 if (s[1] == ':')
6176 {
6177 /* skip double colon. It can't be a constructor
6178 * initialization any more */
6179 lookfor_ctor_init = FALSE;
6180 s = cin_skipcomment(s + 2);
6181 }
6182 else if (lookfor_ctor_init || class_or_struct)
6183 {
6184 /* we have something found, that looks like the start of
Bram Moolenaare21877a2008-02-13 09:58:14 +00006185 * cpp-base-class-declaration or constructor-initialization */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006186 cpp_base_class = TRUE;
6187 lookfor_ctor_init = class_or_struct = FALSE;
6188 *col = 0;
6189 s = cin_skipcomment(s + 1);
6190 }
6191 else
6192 s = cin_skipcomment(s + 1);
6193 }
6194 else if ((STRNCMP(s, "class", 5) == 0 && !vim_isIDc(s[5]))
6195 || (STRNCMP(s, "struct", 6) == 0 && !vim_isIDc(s[6])))
6196 {
6197 class_or_struct = TRUE;
6198 lookfor_ctor_init = FALSE;
6199
6200 if (*s == 'c')
6201 s = cin_skipcomment(s + 5);
6202 else
6203 s = cin_skipcomment(s + 6);
6204 }
6205 else
6206 {
6207 if (s[0] == '{' || s[0] == '}' || s[0] == ';')
6208 {
6209 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
6210 }
6211 else if (s[0] == ')')
6212 {
6213 /* Constructor-initialization is assumed if we come across
6214 * something like "):" */
6215 class_or_struct = FALSE;
6216 lookfor_ctor_init = TRUE;
6217 }
Bram Moolenaar18144c82006-04-12 21:52:12 +00006218 else if (s[0] == '?')
6219 {
6220 /* Avoid seeing '() :' after '?' as constructor init. */
6221 return FALSE;
6222 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006223 else if (!vim_isIDc(s[0]))
6224 {
6225 /* if it is not an identifier, we are wrong */
6226 class_or_struct = FALSE;
6227 lookfor_ctor_init = FALSE;
6228 }
6229 else if (*col == 0)
6230 {
6231 /* it can't be a constructor-initialization any more */
6232 lookfor_ctor_init = FALSE;
6233
6234 /* the first statement starts here: lineup with this one... */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006235 if (cpp_base_class)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006236 *col = (colnr_T)(s - line);
6237 }
6238
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006239 /* When the line ends in a comma don't align with it. */
6240 if (lnum == curwin->w_cursor.lnum && *s == ',' && cin_nocode(s + 1))
6241 *col = 0;
6242
Bram Moolenaar071d4272004-06-13 20:20:40 +00006243 s = cin_skipcomment(s + 1);
6244 }
6245 }
6246
6247 return cpp_base_class;
6248}
6249
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006250 static int
6251get_baseclass_amount(col, ind_maxparen, ind_maxcomment, ind_cpp_baseclass)
6252 int col;
6253 int ind_maxparen;
6254 int ind_maxcomment;
6255 int ind_cpp_baseclass;
6256{
6257 int amount;
6258 colnr_T vcol;
6259 pos_T *trypos;
6260
6261 if (col == 0)
6262 {
6263 amount = get_indent();
6264 if (find_last_paren(ml_get_curline(), '(', ')')
6265 && (trypos = find_match_paren(ind_maxparen,
6266 ind_maxcomment)) != NULL)
6267 amount = get_indent_lnum(trypos->lnum); /* XXX */
6268 if (!cin_ends_in(ml_get_curline(), (char_u *)",", NULL))
6269 amount += ind_cpp_baseclass;
6270 }
6271 else
6272 {
6273 curwin->w_cursor.col = col;
6274 getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
6275 amount = (int)vcol;
6276 }
6277 if (amount < ind_cpp_baseclass)
6278 amount = ind_cpp_baseclass;
6279 return amount;
6280}
6281
Bram Moolenaar071d4272004-06-13 20:20:40 +00006282/*
6283 * Return TRUE if string "s" ends with the string "find", possibly followed by
6284 * white space and comments. Skip strings and comments.
6285 * Ignore "ignore" after "find" if it's not NULL.
6286 */
6287 static int
6288cin_ends_in(s, find, ignore)
6289 char_u *s;
6290 char_u *find;
6291 char_u *ignore;
6292{
6293 char_u *p = s;
6294 char_u *r;
6295 int len = (int)STRLEN(find);
6296
6297 while (*p != NUL)
6298 {
6299 p = cin_skipcomment(p);
6300 if (STRNCMP(p, find, len) == 0)
6301 {
6302 r = skipwhite(p + len);
6303 if (ignore != NULL && STRNCMP(r, ignore, STRLEN(ignore)) == 0)
6304 r = skipwhite(r + STRLEN(ignore));
6305 if (cin_nocode(r))
6306 return TRUE;
6307 }
6308 if (*p != NUL)
6309 ++p;
6310 }
6311 return FALSE;
6312}
6313
6314/*
6315 * Skip strings, chars and comments until at or past "trypos".
6316 * Return the column found.
6317 */
6318 static int
6319cin_skip2pos(trypos)
6320 pos_T *trypos;
6321{
6322 char_u *line;
6323 char_u *p;
6324
6325 p = line = ml_get(trypos->lnum);
6326 while (*p && (colnr_T)(p - line) < trypos->col)
6327 {
6328 if (cin_iscomment(p))
6329 p = cin_skipcomment(p);
6330 else
6331 {
6332 p = skip_string(p);
6333 ++p;
6334 }
6335 }
6336 return (int)(p - line);
6337}
6338
6339/*
6340 * Find the '{' at the start of the block we are in.
6341 * Return NULL if no match found.
6342 * Ignore a '{' that is in a comment, makes indenting the next three lines
6343 * work. */
6344/* foo() */
6345/* { */
6346/* } */
6347
6348 static pos_T *
6349find_start_brace(ind_maxcomment) /* XXX */
6350 int ind_maxcomment;
6351{
6352 pos_T cursor_save;
6353 pos_T *trypos;
6354 pos_T *pos;
6355 static pos_T pos_copy;
6356
6357 cursor_save = curwin->w_cursor;
6358 while ((trypos = findmatchlimit(NULL, '{', FM_BLOCKSTOP, 0)) != NULL)
6359 {
6360 pos_copy = *trypos; /* copy pos_T, next findmatch will change it */
6361 trypos = &pos_copy;
6362 curwin->w_cursor = *trypos;
6363 pos = NULL;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006364 /* ignore the { if it's in a // or / * * / comment */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006365 if ((colnr_T)cin_skip2pos(trypos) == trypos->col
6366 && (pos = find_start_comment(ind_maxcomment)) == NULL) /* XXX */
6367 break;
6368 if (pos != NULL)
6369 curwin->w_cursor.lnum = pos->lnum;
6370 }
6371 curwin->w_cursor = cursor_save;
6372 return trypos;
6373}
6374
6375/*
6376 * Find the matching '(', failing if it is in a comment.
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006377 * Return NULL if no match found.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006378 */
6379 static pos_T *
6380find_match_paren(ind_maxparen, ind_maxcomment) /* XXX */
6381 int ind_maxparen;
6382 int ind_maxcomment;
6383{
6384 pos_T cursor_save;
6385 pos_T *trypos;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006386 static pos_T pos_copy;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006387
6388 cursor_save = curwin->w_cursor;
6389 if ((trypos = findmatchlimit(NULL, '(', 0, ind_maxparen)) != NULL)
6390 {
6391 /* check if the ( is in a // comment */
6392 if ((colnr_T)cin_skip2pos(trypos) > trypos->col)
6393 trypos = NULL;
6394 else
6395 {
6396 pos_copy = *trypos; /* copy trypos, findmatch will change it */
6397 trypos = &pos_copy;
6398 curwin->w_cursor = *trypos;
6399 if (find_start_comment(ind_maxcomment) != NULL) /* XXX */
6400 trypos = NULL;
6401 }
6402 }
6403 curwin->w_cursor = cursor_save;
6404 return trypos;
6405}
6406
6407/*
6408 * Return ind_maxparen corrected for the difference in line number between the
6409 * cursor position and "startpos". This makes sure that searching for a
6410 * matching paren above the cursor line doesn't find a match because of
6411 * looking a few lines further.
6412 */
6413 static int
6414corr_ind_maxparen(ind_maxparen, startpos)
6415 int ind_maxparen;
6416 pos_T *startpos;
6417{
6418 long n = (long)startpos->lnum - (long)curwin->w_cursor.lnum;
6419
6420 if (n > 0 && n < ind_maxparen / 2)
6421 return ind_maxparen - (int)n;
6422 return ind_maxparen;
6423}
6424
6425/*
6426 * Set w_cursor.col to the column number of the last unmatched ')' or '{' in
Bram Moolenaar6d8f9c62011-11-30 13:03:28 +01006427 * line "l". "l" must point to the start of the line.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006428 */
6429 static int
6430find_last_paren(l, start, end)
6431 char_u *l;
6432 int start, end;
6433{
6434 int i;
6435 int retval = FALSE;
6436 int open_count = 0;
6437
6438 curwin->w_cursor.col = 0; /* default is start of line */
6439
Bram Moolenaar6d8f9c62011-11-30 13:03:28 +01006440 for (i = 0; l[i] != NUL; i++)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006441 {
6442 i = (int)(cin_skipcomment(l + i) - l); /* ignore parens in comments */
6443 i = (int)(skip_string(l + i) - l); /* ignore parens in quotes */
6444 if (l[i] == start)
6445 ++open_count;
6446 else if (l[i] == end)
6447 {
6448 if (open_count > 0)
6449 --open_count;
6450 else
6451 {
6452 curwin->w_cursor.col = i;
6453 retval = TRUE;
6454 }
6455 }
6456 }
6457 return retval;
6458}
6459
6460 int
6461get_c_indent()
6462{
6463 /*
6464 * spaces from a block's opening brace the prevailing indent for that
6465 * block should be
6466 */
6467 int ind_level = curbuf->b_p_sw;
6468
6469 /*
6470 * spaces from the edge of the line an open brace that's at the end of a
6471 * line is imagined to be.
6472 */
6473 int ind_open_imag = 0;
6474
6475 /*
Bram Moolenaar1a509df2010-08-01 17:59:57 +02006476 * spaces from the prevailing indent for a line that is not preceded by
Bram Moolenaar071d4272004-06-13 20:20:40 +00006477 * an opening brace.
6478 */
6479 int ind_no_brace = 0;
6480
6481 /*
6482 * column where the first { of a function should be located }
6483 */
6484 int ind_first_open = 0;
6485
6486 /*
6487 * spaces from the prevailing indent a leftmost open brace should be
6488 * located
6489 */
6490 int ind_open_extra = 0;
6491
6492 /*
6493 * spaces from the matching open brace (real location for one at the left
6494 * edge; imaginary location from one that ends a line) the matching close
6495 * brace should be located
6496 */
6497 int ind_close_extra = 0;
6498
6499 /*
6500 * spaces from the edge of the line an open brace sitting in the leftmost
6501 * column is imagined to be
6502 */
6503 int ind_open_left_imag = 0;
6504
6505 /*
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006506 * Spaces jump labels should be shifted to the left if N is non-negative,
6507 * otherwise the jump label will be put to column 1.
6508 */
6509 int ind_jump_label = -1;
6510
6511 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006512 * spaces from the switch() indent a "case xx" label should be located
6513 */
6514 int ind_case = curbuf->b_p_sw;
6515
6516 /*
6517 * spaces from the "case xx:" code after a switch() should be located
6518 */
6519 int ind_case_code = curbuf->b_p_sw;
6520
6521 /*
6522 * lineup break at end of case in switch() with case label
6523 */
6524 int ind_case_break = 0;
6525
6526 /*
6527 * spaces from the class declaration indent a scope declaration label
6528 * should be located
6529 */
6530 int ind_scopedecl = curbuf->b_p_sw;
6531
6532 /*
6533 * spaces from the scope declaration label code should be located
6534 */
6535 int ind_scopedecl_code = curbuf->b_p_sw;
6536
6537 /*
6538 * amount K&R-style parameters should be indented
6539 */
6540 int ind_param = curbuf->b_p_sw;
6541
6542 /*
6543 * amount a function type spec should be indented
6544 */
6545 int ind_func_type = curbuf->b_p_sw;
6546
6547 /*
6548 * amount a cpp base class declaration or constructor initialization
6549 * should be indented
6550 */
6551 int ind_cpp_baseclass = curbuf->b_p_sw;
6552
6553 /*
6554 * additional spaces beyond the prevailing indent a continuation line
6555 * should be located
6556 */
6557 int ind_continuation = curbuf->b_p_sw;
6558
6559 /*
6560 * spaces from the indent of the line with an unclosed parentheses
6561 */
6562 int ind_unclosed = curbuf->b_p_sw * 2;
6563
6564 /*
6565 * spaces from the indent of the line with an unclosed parentheses, which
6566 * itself is also unclosed
6567 */
6568 int ind_unclosed2 = curbuf->b_p_sw;
6569
6570 /*
6571 * suppress ignoring spaces from the indent of a line starting with an
6572 * unclosed parentheses.
6573 */
6574 int ind_unclosed_noignore = 0;
6575
6576 /*
6577 * If the opening paren is the last nonwhite character on the line, and
6578 * ind_unclosed_wrapped is nonzero, use this indent relative to the outer
6579 * context (for very long lines).
6580 */
6581 int ind_unclosed_wrapped = 0;
6582
6583 /*
6584 * suppress ignoring white space when lining up with the character after
6585 * an unclosed parentheses.
6586 */
6587 int ind_unclosed_whiteok = 0;
6588
6589 /*
6590 * indent a closing parentheses under the line start of the matching
6591 * opening parentheses.
6592 */
6593 int ind_matching_paren = 0;
6594
6595 /*
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006596 * indent a closing parentheses under the previous line.
6597 */
6598 int ind_paren_prev = 0;
6599
6600 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006601 * Extra indent for comments.
6602 */
6603 int ind_comment = 0;
6604
6605 /*
6606 * spaces from the comment opener when there is nothing after it.
6607 */
6608 int ind_in_comment = 3;
6609
6610 /*
6611 * boolean: if non-zero, use ind_in_comment even if there is something
6612 * after the comment opener.
6613 */
6614 int ind_in_comment2 = 0;
6615
6616 /*
6617 * max lines to search for an open paren
6618 */
6619 int ind_maxparen = 20;
6620
6621 /*
6622 * max lines to search for an open comment
6623 */
6624 int ind_maxcomment = 70;
6625
6626 /*
6627 * handle braces for java code
6628 */
6629 int ind_java = 0;
6630
6631 /*
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006632 * not to confuse JS object properties with labels
6633 */
6634 int ind_js = 0;
6635
6636 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006637 * handle blocked cases correctly
6638 */
6639 int ind_keep_case_label = 0;
6640
Bram Moolenaared38b0a2011-05-25 15:16:18 +02006641 /*
6642 * handle C++ namespace
6643 */
6644 int ind_cpp_namespace = 0;
6645
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006646 /*
6647 * handle continuation lines containing conditions of if(), for() and
6648 * while()
6649 */
6650 int ind_if_for_while = 0;
6651
Bram Moolenaar071d4272004-06-13 20:20:40 +00006652 pos_T cur_curpos;
6653 int amount;
6654 int scope_amount;
Bram Moolenaarb21e5842006-04-16 18:30:08 +00006655 int cur_amount = MAXCOL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006656 colnr_T col;
6657 char_u *theline;
6658 char_u *linecopy;
6659 pos_T *trypos;
6660 pos_T *tryposBrace = NULL;
6661 pos_T our_paren_pos;
6662 char_u *start;
6663 int start_brace;
Bram Moolenaare21877a2008-02-13 09:58:14 +00006664#define BRACE_IN_COL0 1 /* '{' is in column 0 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006665#define BRACE_AT_START 2 /* '{' is at start of line */
6666#define BRACE_AT_END 3 /* '{' is at end of line */
6667 linenr_T ourscope;
6668 char_u *l;
6669 char_u *look;
6670 char_u terminated;
6671 int lookfor;
6672#define LOOKFOR_INITIAL 0
6673#define LOOKFOR_IF 1
6674#define LOOKFOR_DO 2
6675#define LOOKFOR_CASE 3
6676#define LOOKFOR_ANY 4
6677#define LOOKFOR_TERM 5
6678#define LOOKFOR_UNTERM 6
6679#define LOOKFOR_SCOPEDECL 7
6680#define LOOKFOR_NOBREAK 8
6681#define LOOKFOR_CPP_BASECLASS 9
6682#define LOOKFOR_ENUM_OR_INIT 10
6683
6684 int whilelevel;
6685 linenr_T lnum;
6686 char_u *options;
Bram Moolenaar48d27922012-06-13 13:40:48 +02006687 char_u *digits;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006688 int fraction = 0; /* init for GCC */
6689 int divider;
6690 int n;
6691 int iscase;
6692 int lookfor_break;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02006693 int lookfor_cpp_namespace = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006694 int cont_amount = 0; /* amount for continuation line */
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006695 int original_line_islabel;
Bram Moolenaare79d1532011-10-04 18:03:47 +02006696 int added_to_amount = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006697
6698 for (options = curbuf->b_p_cino; *options; )
6699 {
6700 l = options++;
6701 if (*options == '-')
6702 ++options;
Bram Moolenaar48d27922012-06-13 13:40:48 +02006703 digits = options; /* remember where the digits start */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006704 n = getdigits(&options);
6705 divider = 0;
6706 if (*options == '.') /* ".5s" means a fraction */
6707 {
6708 fraction = atol((char *)++options);
6709 while (VIM_ISDIGIT(*options))
6710 {
6711 ++options;
6712 if (divider)
6713 divider *= 10;
6714 else
6715 divider = 10;
6716 }
6717 }
6718 if (*options == 's') /* "2s" means two times 'shiftwidth' */
6719 {
Bram Moolenaar48d27922012-06-13 13:40:48 +02006720 if (options == digits)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006721 n = curbuf->b_p_sw; /* just "s" is one 'shiftwidth' */
6722 else
6723 {
6724 n *= curbuf->b_p_sw;
6725 if (divider)
6726 n += (curbuf->b_p_sw * fraction + divider / 2) / divider;
6727 }
6728 ++options;
6729 }
6730 if (l[1] == '-')
6731 n = -n;
6732 /* When adding an entry here, also update the default 'cinoptions' in
Bram Moolenaar39353fd2007-03-27 09:02:11 +00006733 * doc/indent.txt, and add explanation for it! */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006734 switch (*l)
6735 {
6736 case '>': ind_level = n; break;
6737 case 'e': ind_open_imag = n; break;
6738 case 'n': ind_no_brace = n; break;
6739 case 'f': ind_first_open = n; break;
6740 case '{': ind_open_extra = n; break;
6741 case '}': ind_close_extra = n; break;
6742 case '^': ind_open_left_imag = n; break;
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006743 case 'L': ind_jump_label = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006744 case ':': ind_case = n; break;
6745 case '=': ind_case_code = n; break;
6746 case 'b': ind_case_break = n; break;
6747 case 'p': ind_param = n; break;
6748 case 't': ind_func_type = n; break;
6749 case '/': ind_comment = n; break;
6750 case 'c': ind_in_comment = n; break;
6751 case 'C': ind_in_comment2 = n; break;
6752 case 'i': ind_cpp_baseclass = n; break;
6753 case '+': ind_continuation = n; break;
6754 case '(': ind_unclosed = n; break;
6755 case 'u': ind_unclosed2 = n; break;
6756 case 'U': ind_unclosed_noignore = n; break;
6757 case 'W': ind_unclosed_wrapped = n; break;
6758 case 'w': ind_unclosed_whiteok = n; break;
6759 case 'm': ind_matching_paren = n; break;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006760 case 'M': ind_paren_prev = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006761 case ')': ind_maxparen = n; break;
6762 case '*': ind_maxcomment = n; break;
6763 case 'g': ind_scopedecl = n; break;
6764 case 'h': ind_scopedecl_code = n; break;
6765 case 'j': ind_java = n; break;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006766 case 'J': ind_js = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006767 case 'l': ind_keep_case_label = n; break;
Bram Moolenaar39353fd2007-03-27 09:02:11 +00006768 case '#': ind_hash_comment = n; break;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02006769 case 'N': ind_cpp_namespace = n; break;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006770 case 'k': ind_if_for_while = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006771 }
Bram Moolenaardfdf3c42010-03-23 18:22:46 +01006772 if (*options == ',')
6773 ++options;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006774 }
6775
6776 /* remember where the cursor was when we started */
6777 cur_curpos = curwin->w_cursor;
6778
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006779 /* if we are at line 1 0 is fine, right? */
6780 if (cur_curpos.lnum == 1)
6781 return 0;
6782
Bram Moolenaar071d4272004-06-13 20:20:40 +00006783 /* Get a copy of the current contents of the line.
6784 * This is required, because only the most recent line obtained with
6785 * ml_get is valid! */
6786 linecopy = vim_strsave(ml_get(cur_curpos.lnum));
6787 if (linecopy == NULL)
6788 return 0;
6789
6790 /*
6791 * In insert mode and the cursor is on a ')' truncate the line at the
6792 * cursor position. We don't want to line up with the matching '(' when
6793 * inserting new stuff.
6794 * For unknown reasons the cursor might be past the end of the line, thus
6795 * check for that.
6796 */
6797 if ((State & INSERT)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006798 && curwin->w_cursor.col < (colnr_T)STRLEN(linecopy)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006799 && linecopy[curwin->w_cursor.col] == ')')
6800 linecopy[curwin->w_cursor.col] = NUL;
6801
6802 theline = skipwhite(linecopy);
6803
6804 /* move the cursor to the start of the line */
6805
6806 curwin->w_cursor.col = 0;
6807
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006808 original_line_islabel = cin_islabel(ind_maxcomment); /* XXX */
6809
Bram Moolenaar071d4272004-06-13 20:20:40 +00006810 /*
6811 * #defines and so on always go at the left when included in 'cinkeys'.
6812 */
6813 if (*theline == '#' && (*linecopy == '#' || in_cinkeys('#', ' ', TRUE)))
6814 {
6815 amount = 0;
6816 }
6817
6818 /*
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006819 * Is it a non-case label? Then that goes at the left margin too unless:
6820 * - JS flag is set.
6821 * - 'L' item has a positive value.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006822 */
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006823 else if (original_line_islabel && !ind_js && ind_jump_label < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006824 {
6825 amount = 0;
6826 }
6827
6828 /*
6829 * If we're inside a "//" comment and there is a "//" comment in a
6830 * previous line, lineup with that one.
6831 */
6832 else if (cin_islinecomment(theline)
6833 && (trypos = find_line_comment()) != NULL) /* XXX */
6834 {
6835 /* find how indented the line beginning the comment is */
6836 getvcol(curwin, trypos, &col, NULL, NULL);
6837 amount = col;
6838 }
6839
6840 /*
6841 * If we're inside a comment and not looking at the start of the
6842 * comment, try using the 'comments' option.
6843 */
6844 else if (!cin_iscomment(theline)
6845 && (trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
6846 {
6847 int lead_start_len = 2;
6848 int lead_middle_len = 1;
6849 char_u lead_start[COM_MAX_LEN]; /* start-comment string */
6850 char_u lead_middle[COM_MAX_LEN]; /* middle-comment string */
6851 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
6852 char_u *p;
6853 int start_align = 0;
6854 int start_off = 0;
6855 int done = FALSE;
6856
6857 /* find how indented the line beginning the comment is */
6858 getvcol(curwin, trypos, &col, NULL, NULL);
6859 amount = col;
Bram Moolenaar4aa97422011-04-11 14:27:38 +02006860 *lead_start = NUL;
6861 *lead_middle = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006862
6863 p = curbuf->b_p_com;
6864 while (*p != NUL)
6865 {
6866 int align = 0;
6867 int off = 0;
6868 int what = 0;
6869
6870 while (*p != NUL && *p != ':')
6871 {
6872 if (*p == COM_START || *p == COM_END || *p == COM_MIDDLE)
6873 what = *p++;
6874 else if (*p == COM_LEFT || *p == COM_RIGHT)
6875 align = *p++;
6876 else if (VIM_ISDIGIT(*p) || *p == '-')
6877 off = getdigits(&p);
6878 else
6879 ++p;
6880 }
6881
6882 if (*p == ':')
6883 ++p;
6884 (void)copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
6885 if (what == COM_START)
6886 {
6887 STRCPY(lead_start, lead_end);
6888 lead_start_len = (int)STRLEN(lead_start);
6889 start_off = off;
6890 start_align = align;
6891 }
6892 else if (what == COM_MIDDLE)
6893 {
6894 STRCPY(lead_middle, lead_end);
6895 lead_middle_len = (int)STRLEN(lead_middle);
6896 }
6897 else if (what == COM_END)
6898 {
6899 /* If our line starts with the middle comment string, line it
6900 * up with the comment opener per the 'comments' option. */
6901 if (STRNCMP(theline, lead_middle, lead_middle_len) == 0
6902 && STRNCMP(theline, lead_end, STRLEN(lead_end)) != 0)
6903 {
6904 done = TRUE;
6905 if (curwin->w_cursor.lnum > 1)
6906 {
6907 /* If the start comment string matches in the previous
Bram Moolenaare21877a2008-02-13 09:58:14 +00006908 * line, use the indent of that line plus offset. If
Bram Moolenaar071d4272004-06-13 20:20:40 +00006909 * the middle comment string matches in the previous
6910 * line, use the indent of that line. XXX */
6911 look = skipwhite(ml_get(curwin->w_cursor.lnum - 1));
6912 if (STRNCMP(look, lead_start, lead_start_len) == 0)
6913 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6914 else if (STRNCMP(look, lead_middle,
6915 lead_middle_len) == 0)
6916 {
6917 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6918 break;
6919 }
6920 /* If the start comment string doesn't match with the
6921 * start of the comment, skip this entry. XXX */
6922 else if (STRNCMP(ml_get(trypos->lnum) + trypos->col,
6923 lead_start, lead_start_len) != 0)
6924 continue;
6925 }
6926 if (start_off != 0)
6927 amount += start_off;
6928 else if (start_align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006929 amount += vim_strsize(lead_start)
6930 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006931 break;
6932 }
6933
6934 /* If our line starts with the end comment string, line it up
6935 * with the middle comment */
6936 if (STRNCMP(theline, lead_middle, lead_middle_len) != 0
6937 && STRNCMP(theline, lead_end, STRLEN(lead_end)) == 0)
6938 {
6939 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6940 /* XXX */
6941 if (off != 0)
6942 amount += off;
6943 else if (align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006944 amount += vim_strsize(lead_start)
6945 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006946 done = TRUE;
6947 break;
6948 }
6949 }
6950 }
6951
6952 /* If our line starts with an asterisk, line up with the
6953 * asterisk in the comment opener; otherwise, line up
6954 * with the first character of the comment text.
6955 */
6956 if (done)
6957 ;
6958 else if (theline[0] == '*')
6959 amount += 1;
6960 else
6961 {
6962 /*
6963 * If we are more than one line away from the comment opener, take
6964 * the indent of the previous non-empty line. If 'cino' has "CO"
6965 * and we are just below the comment opener and there are any
6966 * white characters after it line up with the text after it;
6967 * otherwise, add the amount specified by "c" in 'cino'
6968 */
6969 amount = -1;
6970 for (lnum = cur_curpos.lnum - 1; lnum > trypos->lnum; --lnum)
6971 {
6972 if (linewhite(lnum)) /* skip blank lines */
6973 continue;
6974 amount = get_indent_lnum(lnum); /* XXX */
6975 break;
6976 }
6977 if (amount == -1) /* use the comment opener */
6978 {
6979 if (!ind_in_comment2)
6980 {
6981 start = ml_get(trypos->lnum);
6982 look = start + trypos->col + 2; /* skip / and * */
6983 if (*look != NUL) /* if something after it */
6984 trypos->col = (colnr_T)(skipwhite(look) - start);
6985 }
6986 getvcol(curwin, trypos, &col, NULL, NULL);
6987 amount = col;
6988 if (ind_in_comment2 || *look == NUL)
6989 amount += ind_in_comment;
6990 }
6991 }
6992 }
6993
6994 /*
6995 * Are we inside parentheses or braces?
6996 */ /* XXX */
6997 else if (((trypos = find_match_paren(ind_maxparen, ind_maxcomment)) != NULL
6998 && ind_java == 0)
6999 || (tryposBrace = find_start_brace(ind_maxcomment)) != NULL
7000 || trypos != NULL)
7001 {
7002 if (trypos != NULL && tryposBrace != NULL)
7003 {
7004 /* Both an unmatched '(' and '{' is found. Use the one which is
7005 * closer to the current cursor position, set the other to NULL. */
7006 if (trypos->lnum != tryposBrace->lnum
7007 ? trypos->lnum < tryposBrace->lnum
7008 : trypos->col < tryposBrace->col)
7009 trypos = NULL;
7010 else
7011 tryposBrace = NULL;
7012 }
7013
7014 if (trypos != NULL)
7015 {
7016 /*
7017 * If the matching paren is more than one line away, use the indent of
7018 * a previous non-empty line that matches the same paren.
7019 */
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007020 if (theline[0] == ')' && ind_paren_prev)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007021 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007022 /* Line up with the start of the matching paren line. */
7023 amount = get_indent_lnum(curwin->w_cursor.lnum - 1); /* XXX */
7024 }
7025 else
7026 {
7027 amount = -1;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007028 our_paren_pos = *trypos;
7029 for (lnum = cur_curpos.lnum - 1; lnum > our_paren_pos.lnum; --lnum)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007030 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007031 l = skipwhite(ml_get(lnum));
7032 if (cin_nocode(l)) /* skip comment lines */
7033 continue;
7034 if (cin_ispreproc_cont(&l, &lnum))
7035 continue; /* ignore #define, #if, etc. */
7036 curwin->w_cursor.lnum = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007037
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007038 /* Skip a comment. XXX */
7039 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
7040 {
7041 lnum = trypos->lnum + 1;
7042 continue;
7043 }
7044
7045 /* XXX */
7046 if ((trypos = find_match_paren(
7047 corr_ind_maxparen(ind_maxparen, &cur_curpos),
Bram Moolenaar071d4272004-06-13 20:20:40 +00007048 ind_maxcomment)) != NULL
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007049 && trypos->lnum == our_paren_pos.lnum
7050 && trypos->col == our_paren_pos.col)
7051 {
7052 amount = get_indent_lnum(lnum); /* XXX */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007053
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007054 if (theline[0] == ')')
7055 {
7056 if (our_paren_pos.lnum != lnum
7057 && cur_amount > amount)
7058 cur_amount = amount;
7059 amount = -1;
7060 }
7061 break;
7062 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007063 }
7064 }
7065
7066 /*
7067 * Line up with line where the matching paren is. XXX
7068 * If the line starts with a '(' or the indent for unclosed
7069 * parentheses is zero, line up with the unclosed parentheses.
7070 */
7071 if (amount == -1)
7072 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007073 int ignore_paren_col = 0;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007074 int is_if_for_while = 0;
7075
7076 if (ind_if_for_while)
7077 {
7078 /* Look for the outermost opening parenthesis on this line
7079 * and check whether it belongs to an "if", "for" or "while". */
7080
7081 pos_T cursor_save = curwin->w_cursor;
7082 pos_T outermost;
7083 char_u *line;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007084
7085 trypos = &our_paren_pos;
7086 do {
7087 outermost = *trypos;
7088 curwin->w_cursor.lnum = outermost.lnum;
7089 curwin->w_cursor.col = outermost.col;
7090
7091 trypos = find_match_paren(ind_maxparen, ind_maxcomment);
7092 } while (trypos && trypos->lnum == outermost.lnum);
7093
7094 curwin->w_cursor = cursor_save;
7095
7096 line = ml_get(outermost.lnum);
7097
7098 is_if_for_while =
Bram Moolenaarb345d492012-04-09 20:42:26 +02007099 cin_is_if_for_while_before_offset(line, &outermost.col);
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007100 }
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007101
Bram Moolenaar071d4272004-06-13 20:20:40 +00007102 amount = skip_label(our_paren_pos.lnum, &look, ind_maxcomment);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007103 look = skipwhite(look);
7104 if (*look == '(')
7105 {
7106 linenr_T save_lnum = curwin->w_cursor.lnum;
7107 char_u *line;
7108 int look_col;
7109
7110 /* Ignore a '(' in front of the line that has a match before
7111 * our matching '('. */
7112 curwin->w_cursor.lnum = our_paren_pos.lnum;
7113 line = ml_get_curline();
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007114 look_col = (int)(look - line);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007115 curwin->w_cursor.col = look_col + 1;
7116 if ((trypos = findmatchlimit(NULL, ')', 0, ind_maxparen))
7117 != NULL
7118 && trypos->lnum == our_paren_pos.lnum
7119 && trypos->col < our_paren_pos.col)
7120 ignore_paren_col = trypos->col + 1;
7121
7122 curwin->w_cursor.lnum = save_lnum;
7123 look = ml_get(our_paren_pos.lnum) + look_col;
7124 }
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007125 if (theline[0] == ')' || (ind_unclosed == 0 && is_if_for_while == 0)
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007126 || (!ind_unclosed_noignore && *look == '('
7127 && ignore_paren_col == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007128 {
7129 /*
7130 * If we're looking at a close paren, line up right there;
7131 * otherwise, line up with the next (non-white) character.
7132 * When ind_unclosed_wrapped is set and the matching paren is
7133 * the last nonwhite character of the line, use either the
7134 * indent of the current line or the indentation of the next
7135 * outer paren and add ind_unclosed_wrapped (for very long
7136 * lines).
7137 */
7138 if (theline[0] != ')')
7139 {
7140 cur_amount = MAXCOL;
7141 l = ml_get(our_paren_pos.lnum);
7142 if (ind_unclosed_wrapped
7143 && cin_ends_in(l, (char_u *)"(", NULL))
7144 {
7145 /* look for opening unmatched paren, indent one level
7146 * for each additional level */
7147 n = 1;
7148 for (col = 0; col < our_paren_pos.col; ++col)
7149 {
7150 switch (l[col])
7151 {
7152 case '(':
7153 case '{': ++n;
7154 break;
7155
7156 case ')':
7157 case '}': if (n > 1)
7158 --n;
7159 break;
7160 }
7161 }
7162
7163 our_paren_pos.col = 0;
7164 amount += n * ind_unclosed_wrapped;
7165 }
7166 else if (ind_unclosed_whiteok)
7167 our_paren_pos.col++;
7168 else
7169 {
7170 col = our_paren_pos.col + 1;
7171 while (vim_iswhite(l[col]))
7172 col++;
7173 if (l[col] != NUL) /* In case of trailing space */
7174 our_paren_pos.col = col;
7175 else
7176 our_paren_pos.col++;
7177 }
7178 }
7179
7180 /*
7181 * Find how indented the paren is, or the character after it
7182 * if we did the above "if".
7183 */
7184 if (our_paren_pos.col > 0)
7185 {
7186 getvcol(curwin, &our_paren_pos, &col, NULL, NULL);
7187 if (cur_amount > (int)col)
7188 cur_amount = col;
7189 }
7190 }
7191
7192 if (theline[0] == ')' && ind_matching_paren)
7193 {
7194 /* Line up with the start of the matching paren line. */
7195 }
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007196 else if ((ind_unclosed == 0 && is_if_for_while == 0)
7197 || (!ind_unclosed_noignore
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007198 && *look == '(' && ignore_paren_col == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007199 {
7200 if (cur_amount != MAXCOL)
7201 amount = cur_amount;
7202 }
7203 else
7204 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007205 /* Add ind_unclosed2 for each '(' before our matching one, but
7206 * ignore (void) before the line (ignore_paren_col). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007207 col = our_paren_pos.col;
Bram Moolenaarb21e5842006-04-16 18:30:08 +00007208 while ((int)our_paren_pos.col > ignore_paren_col)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007209 {
7210 --our_paren_pos.col;
7211 switch (*ml_get_pos(&our_paren_pos))
7212 {
7213 case '(': amount += ind_unclosed2;
7214 col = our_paren_pos.col;
7215 break;
7216 case ')': amount -= ind_unclosed2;
7217 col = MAXCOL;
7218 break;
7219 }
7220 }
7221
7222 /* Use ind_unclosed once, when the first '(' is not inside
7223 * braces */
7224 if (col == MAXCOL)
7225 amount += ind_unclosed;
7226 else
7227 {
7228 curwin->w_cursor.lnum = our_paren_pos.lnum;
7229 curwin->w_cursor.col = col;
Bram Moolenaar367bec82011-04-11 14:26:19 +02007230 if (find_match_paren(ind_maxparen, ind_maxcomment) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007231 amount += ind_unclosed2;
7232 else
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007233 {
7234 if (is_if_for_while)
7235 amount += ind_if_for_while;
7236 else
7237 amount += ind_unclosed;
7238 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007239 }
7240 /*
7241 * For a line starting with ')' use the minimum of the two
7242 * positions, to avoid giving it more indent than the previous
7243 * lines:
7244 * func_long_name( if (x
7245 * arg && yy
7246 * ) ^ not here ) ^ not here
7247 */
7248 if (cur_amount < amount)
7249 amount = cur_amount;
7250 }
7251 }
7252
7253 /* add extra indent for a comment */
7254 if (cin_iscomment(theline))
7255 amount += ind_comment;
7256 }
7257
7258 /*
7259 * Are we at least inside braces, then?
7260 */
7261 else
7262 {
7263 trypos = tryposBrace;
7264
7265 ourscope = trypos->lnum;
7266 start = ml_get(ourscope);
7267
7268 /*
7269 * Now figure out how indented the line is in general.
7270 * If the brace was at the start of the line, we use that;
7271 * otherwise, check out the indentation of the line as
7272 * a whole and then add the "imaginary indent" to that.
7273 */
7274 look = skipwhite(start);
7275 if (*look == '{')
7276 {
7277 getvcol(curwin, trypos, &col, NULL, NULL);
7278 amount = col;
7279 if (*start == '{')
7280 start_brace = BRACE_IN_COL0;
7281 else
7282 start_brace = BRACE_AT_START;
7283 }
7284 else
7285 {
7286 /*
7287 * that opening brace might have been on a continuation
7288 * line. if so, find the start of the line.
7289 */
7290 curwin->w_cursor.lnum = ourscope;
7291
7292 /*
7293 * position the cursor over the rightmost paren, so that
7294 * matching it will take us back to the start of the line.
7295 */
7296 lnum = ourscope;
7297 if (find_last_paren(start, '(', ')')
7298 && (trypos = find_match_paren(ind_maxparen,
7299 ind_maxcomment)) != NULL)
7300 lnum = trypos->lnum;
7301
7302 /*
7303 * It could have been something like
7304 * case 1: if (asdf &&
7305 * ldfd) {
7306 * }
7307 */
Bram Moolenaar6ec154b2011-06-12 21:51:08 +02007308 if (ind_js || (ind_keep_case_label
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007309 && cin_iscase(skipwhite(ml_get_curline()), FALSE)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007310 amount = get_indent();
7311 else
7312 amount = skip_label(lnum, &l, ind_maxcomment);
7313
7314 start_brace = BRACE_AT_END;
7315 }
7316
7317 /*
7318 * if we're looking at a closing brace, that's where
7319 * we want to be. otherwise, add the amount of room
7320 * that an indent is supposed to be.
7321 */
7322 if (theline[0] == '}')
7323 {
7324 /*
7325 * they may want closing braces to line up with something
7326 * other than the open brace. indulge them, if so.
7327 */
7328 amount += ind_close_extra;
7329 }
7330 else
7331 {
7332 /*
7333 * If we're looking at an "else", try to find an "if"
7334 * to match it with.
7335 * If we're looking at a "while", try to find a "do"
7336 * to match it with.
7337 */
7338 lookfor = LOOKFOR_INITIAL;
7339 if (cin_iselse(theline))
7340 lookfor = LOOKFOR_IF;
7341 else if (cin_iswhileofdo(theline, cur_curpos.lnum, ind_maxparen))
7342 /* XXX */
7343 lookfor = LOOKFOR_DO;
7344 if (lookfor != LOOKFOR_INITIAL)
7345 {
7346 curwin->w_cursor.lnum = cur_curpos.lnum;
7347 if (find_match(lookfor, ourscope, ind_maxparen,
7348 ind_maxcomment) == OK)
7349 {
7350 amount = get_indent(); /* XXX */
7351 goto theend;
7352 }
7353 }
7354
7355 /*
7356 * We get here if we are not on an "while-of-do" or "else" (or
7357 * failed to find a matching "if").
7358 * Search backwards for something to line up with.
7359 * First set amount for when we don't find anything.
7360 */
7361
7362 /*
7363 * if the '{' is _really_ at the left margin, use the imaginary
7364 * location of a left-margin brace. Otherwise, correct the
7365 * location for ind_open_extra.
7366 */
7367
7368 if (start_brace == BRACE_IN_COL0) /* '{' is in column 0 */
7369 {
7370 amount = ind_open_left_imag;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007371 lookfor_cpp_namespace = TRUE;
7372 }
7373 else if (start_brace == BRACE_AT_START &&
7374 lookfor_cpp_namespace) /* '{' is at start */
7375 {
7376
7377 lookfor_cpp_namespace = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007378 }
7379 else
7380 {
7381 if (start_brace == BRACE_AT_END) /* '{' is at end of line */
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007382 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007383 amount += ind_open_imag;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007384
7385 l = skipwhite(ml_get_curline());
7386 if (cin_is_cpp_namespace(l))
7387 amount += ind_cpp_namespace;
7388 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007389 else
7390 {
7391 /* Compensate for adding ind_open_extra later. */
7392 amount -= ind_open_extra;
7393 if (amount < 0)
7394 amount = 0;
7395 }
7396 }
7397
7398 lookfor_break = FALSE;
7399
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007400 if (cin_iscase(theline, FALSE)) /* it's a switch() label */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007401 {
7402 lookfor = LOOKFOR_CASE; /* find a previous switch() label */
7403 amount += ind_case;
7404 }
7405 else if (cin_isscopedecl(theline)) /* private:, ... */
7406 {
7407 lookfor = LOOKFOR_SCOPEDECL; /* class decl is this block */
7408 amount += ind_scopedecl;
7409 }
7410 else
7411 {
7412 if (ind_case_break && cin_isbreak(theline)) /* break; ... */
7413 lookfor_break = TRUE;
7414
7415 lookfor = LOOKFOR_INITIAL;
7416 amount += ind_level; /* ind_level from start of block */
7417 }
7418 scope_amount = amount;
7419 whilelevel = 0;
7420
7421 /*
7422 * Search backwards. If we find something we recognize, line up
7423 * with that.
7424 *
7425 * if we're looking at an open brace, indent
7426 * the usual amount relative to the conditional
7427 * that opens the block.
7428 */
7429 curwin->w_cursor = cur_curpos;
7430 for (;;)
7431 {
7432 curwin->w_cursor.lnum--;
7433 curwin->w_cursor.col = 0;
7434
7435 /*
7436 * If we went all the way back to the start of our scope, line
7437 * up with it.
7438 */
7439 if (curwin->w_cursor.lnum <= ourscope)
7440 {
7441 /* we reached end of scope:
7442 * if looking for a enum or structure initialization
7443 * go further back:
7444 * if it is an initializer (enum xxx or xxx =), then
7445 * don't add ind_continuation, otherwise it is a variable
7446 * declaration:
7447 * int x,
7448 * here; <-- add ind_continuation
7449 */
7450 if (lookfor == LOOKFOR_ENUM_OR_INIT)
7451 {
7452 if (curwin->w_cursor.lnum == 0
7453 || curwin->w_cursor.lnum
7454 < ourscope - ind_maxparen)
7455 {
7456 /* nothing found (abuse ind_maxparen as limit)
7457 * assume terminated line (i.e. a variable
7458 * initialization) */
7459 if (cont_amount > 0)
7460 amount = cont_amount;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007461 else if (!ind_js)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007462 amount += ind_continuation;
7463 break;
7464 }
7465
7466 l = ml_get_curline();
7467
7468 /*
7469 * If we're in a comment now, skip to the start of the
7470 * comment.
7471 */
7472 trypos = find_start_comment(ind_maxcomment);
7473 if (trypos != NULL)
7474 {
7475 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007476 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007477 continue;
7478 }
7479
7480 /*
7481 * Skip preprocessor directives and blank lines.
7482 */
7483 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7484 continue;
7485
7486 if (cin_nocode(l))
7487 continue;
7488
7489 terminated = cin_isterminated(l, FALSE, TRUE);
7490
7491 /*
7492 * If we are at top level and the line looks like a
7493 * function declaration, we are done
7494 * (it's a variable declaration).
7495 */
7496 if (start_brace != BRACE_IN_COL0
Bram Moolenaarc367faa2011-12-14 20:21:35 +01007497 || !cin_isfuncdecl(&l, curwin->w_cursor.lnum,
7498 0, ind_maxparen, ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007499 {
7500 /* if the line is terminated with another ','
7501 * it is a continued variable initialization.
7502 * don't add extra indent.
7503 * TODO: does not work, if a function
7504 * declaration is split over multiple lines:
7505 * cin_isfuncdecl returns FALSE then.
7506 */
7507 if (terminated == ',')
7508 break;
7509
7510 /* if it es a enum declaration or an assignment,
7511 * we are done.
7512 */
7513 if (terminated != ';' && cin_isinit())
7514 break;
7515
7516 /* nothing useful found */
7517 if (terminated == 0 || terminated == '{')
7518 continue;
7519 }
7520
7521 if (terminated != ';')
7522 {
7523 /* Skip parens and braces. Position the cursor
7524 * over the rightmost paren, so that matching it
7525 * will take us back to the start of the line.
7526 */ /* XXX */
7527 trypos = NULL;
7528 if (find_last_paren(l, '(', ')'))
7529 trypos = find_match_paren(ind_maxparen,
7530 ind_maxcomment);
7531
7532 if (trypos == NULL && find_last_paren(l, '{', '}'))
7533 trypos = find_start_brace(ind_maxcomment);
7534
7535 if (trypos != NULL)
7536 {
7537 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007538 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007539 continue;
7540 }
7541 }
7542
7543 /* it's a variable declaration, add indentation
7544 * like in
7545 * int a,
7546 * b;
7547 */
7548 if (cont_amount > 0)
7549 amount = cont_amount;
7550 else
7551 amount += ind_continuation;
7552 }
7553 else if (lookfor == LOOKFOR_UNTERM)
7554 {
7555 if (cont_amount > 0)
7556 amount = cont_amount;
7557 else
7558 amount += ind_continuation;
7559 }
Bram Moolenaare79d1532011-10-04 18:03:47 +02007560 else
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007561 {
Bram Moolenaare79d1532011-10-04 18:03:47 +02007562 if (lookfor != LOOKFOR_TERM
Bram Moolenaar071d4272004-06-13 20:20:40 +00007563 && lookfor != LOOKFOR_CPP_BASECLASS)
Bram Moolenaare79d1532011-10-04 18:03:47 +02007564 {
7565 amount = scope_amount;
7566 if (theline[0] == '{')
7567 {
7568 amount += ind_open_extra;
7569 added_to_amount = ind_open_extra;
7570 }
7571 }
7572
7573 if (lookfor_cpp_namespace)
7574 {
7575 /*
7576 * Looking for C++ namespace, need to look further
7577 * back.
7578 */
7579 if (curwin->w_cursor.lnum == ourscope)
7580 continue;
7581
7582 if (curwin->w_cursor.lnum == 0
7583 || curwin->w_cursor.lnum
7584 < ourscope - FIND_NAMESPACE_LIM)
7585 break;
7586
7587 l = ml_get_curline();
7588
7589 /* If we're in a comment now, skip to the start of
7590 * the comment. */
7591 trypos = find_start_comment(ind_maxcomment);
7592 if (trypos != NULL)
7593 {
7594 curwin->w_cursor.lnum = trypos->lnum + 1;
7595 curwin->w_cursor.col = 0;
7596 continue;
7597 }
7598
7599 /* Skip preprocessor directives and blank lines. */
7600 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7601 continue;
7602
7603 /* Finally the actual check for "namespace". */
7604 if (cin_is_cpp_namespace(l))
7605 {
7606 amount += ind_cpp_namespace - added_to_amount;
7607 break;
7608 }
7609
7610 if (cin_nocode(l))
7611 continue;
7612 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007613 }
7614 break;
7615 }
7616
7617 /*
7618 * If we're in a comment now, skip to the start of the comment.
7619 */ /* XXX */
7620 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
7621 {
7622 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007623 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007624 continue;
7625 }
7626
7627 l = ml_get_curline();
7628
7629 /*
7630 * If this is a switch() label, may line up relative to that.
Bram Moolenaar18144c82006-04-12 21:52:12 +00007631 * If this is a C++ scope declaration, do the same.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007632 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007633 iscase = cin_iscase(l, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007634 if (iscase || cin_isscopedecl(l))
7635 {
7636 /* we are only looking for cpp base class
7637 * declaration/initialization any longer */
7638 if (lookfor == LOOKFOR_CPP_BASECLASS)
7639 break;
7640
7641 /* When looking for a "do" we are not interested in
7642 * labels. */
7643 if (whilelevel > 0)
7644 continue;
7645
7646 /*
7647 * case xx:
7648 * c = 99 + <- this indent plus continuation
7649 *-> here;
7650 */
7651 if (lookfor == LOOKFOR_UNTERM
7652 || lookfor == LOOKFOR_ENUM_OR_INIT)
7653 {
7654 if (cont_amount > 0)
7655 amount = cont_amount;
7656 else
7657 amount += ind_continuation;
7658 break;
7659 }
7660
7661 /*
7662 * case xx: <- line up with this case
7663 * x = 333;
7664 * case yy:
7665 */
7666 if ( (iscase && lookfor == LOOKFOR_CASE)
7667 || (iscase && lookfor_break)
7668 || (!iscase && lookfor == LOOKFOR_SCOPEDECL))
7669 {
7670 /*
7671 * Check that this case label is not for another
7672 * switch()
7673 */ /* XXX */
7674 if ((trypos = find_start_brace(ind_maxcomment)) ==
7675 NULL || trypos->lnum == ourscope)
7676 {
7677 amount = get_indent(); /* XXX */
7678 break;
7679 }
7680 continue;
7681 }
7682
7683 n = get_indent_nolabel(curwin->w_cursor.lnum); /* XXX */
7684
7685 /*
7686 * case xx: if (cond) <- line up with this if
7687 * y = y + 1;
7688 * -> s = 99;
7689 *
7690 * case xx:
7691 * if (cond) <- line up with this line
7692 * y = y + 1;
7693 * -> s = 99;
7694 */
7695 if (lookfor == LOOKFOR_TERM)
7696 {
7697 if (n)
7698 amount = n;
7699
7700 if (!lookfor_break)
7701 break;
7702 }
7703
7704 /*
7705 * case xx: x = x + 1; <- line up with this x
7706 * -> y = y + 1;
7707 *
7708 * case xx: if (cond) <- line up with this if
7709 * -> y = y + 1;
7710 */
7711 if (n)
7712 {
7713 amount = n;
7714 l = after_label(ml_get_curline());
7715 if (l != NULL && cin_is_cinword(l))
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007716 {
7717 if (theline[0] == '{')
7718 amount += ind_open_extra;
7719 else
7720 amount += ind_level + ind_no_brace;
7721 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007722 break;
7723 }
7724
7725 /*
7726 * Try to get the indent of a statement before the switch
7727 * label. If nothing is found, line up relative to the
7728 * switch label.
7729 * break; <- may line up with this line
7730 * case xx:
7731 * -> y = 1;
7732 */
7733 scope_amount = get_indent() + (iscase /* XXX */
7734 ? ind_case_code : ind_scopedecl_code);
7735 lookfor = ind_case_break ? LOOKFOR_NOBREAK : LOOKFOR_ANY;
7736 continue;
7737 }
7738
7739 /*
7740 * Looking for a switch() label or C++ scope declaration,
7741 * ignore other lines, skip {}-blocks.
7742 */
7743 if (lookfor == LOOKFOR_CASE || lookfor == LOOKFOR_SCOPEDECL)
7744 {
7745 if (find_last_paren(l, '{', '}') && (trypos =
7746 find_start_brace(ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007747 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007748 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007749 curwin->w_cursor.col = 0;
7750 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007751 continue;
7752 }
7753
7754 /*
7755 * Ignore jump labels with nothing after them.
7756 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007757 if (!ind_js && cin_islabel(ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007758 {
7759 l = after_label(ml_get_curline());
7760 if (l == NULL || cin_nocode(l))
7761 continue;
7762 }
7763
7764 /*
7765 * Ignore #defines, #if, etc.
7766 * Ignore comment and empty lines.
7767 * (need to get the line again, cin_islabel() may have
7768 * unlocked it)
7769 */
7770 l = ml_get_curline();
7771 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum)
7772 || cin_nocode(l))
7773 continue;
7774
7775 /*
7776 * Are we at the start of a cpp base class declaration or
7777 * constructor initialization?
7778 */ /* XXX */
Bram Moolenaar18144c82006-04-12 21:52:12 +00007779 n = FALSE;
7780 if (lookfor != LOOKFOR_TERM && ind_cpp_baseclass > 0)
7781 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00007782 n = cin_is_cpp_baseclass(&col);
Bram Moolenaar18144c82006-04-12 21:52:12 +00007783 l = ml_get_curline();
7784 }
7785 if (n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007786 {
7787 if (lookfor == LOOKFOR_UNTERM)
7788 {
7789 if (cont_amount > 0)
7790 amount = cont_amount;
7791 else
7792 amount += ind_continuation;
7793 }
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007794 else if (theline[0] == '{')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007795 {
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007796 /* Need to find start of the declaration. */
7797 lookfor = LOOKFOR_UNTERM;
7798 ind_continuation = 0;
7799 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007800 }
7801 else
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007802 /* XXX */
7803 amount = get_baseclass_amount(col, ind_maxparen,
7804 ind_maxcomment, ind_cpp_baseclass);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007805 break;
7806 }
7807 else if (lookfor == LOOKFOR_CPP_BASECLASS)
7808 {
7809 /* only look, whether there is a cpp base class
Bram Moolenaar18144c82006-04-12 21:52:12 +00007810 * declaration or initialization before the opening brace.
7811 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007812 if (cin_isterminated(l, TRUE, FALSE))
7813 break;
7814 else
7815 continue;
7816 }
7817
7818 /*
7819 * What happens next depends on the line being terminated.
7820 * If terminated with a ',' only consider it terminating if
Bram Moolenaar25394022007-05-10 19:06:20 +00007821 * there is another unterminated statement behind, eg:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007822 * 123,
7823 * sizeof
7824 * here
7825 * Otherwise check whether it is a enumeration or structure
7826 * initialisation (not indented) or a variable declaration
7827 * (indented).
7828 */
7829 terminated = cin_isterminated(l, FALSE, TRUE);
7830
7831 if (terminated == 0 || (lookfor != LOOKFOR_UNTERM
7832 && terminated == ','))
7833 {
7834 /*
7835 * if we're in the middle of a paren thing,
7836 * go back to the line that starts it so
7837 * we can get the right prevailing indent
7838 * if ( foo &&
7839 * bar )
7840 */
7841 /*
7842 * position the cursor over the rightmost paren, so that
7843 * matching it will take us back to the start of the line.
7844 */
7845 (void)find_last_paren(l, '(', ')');
7846 trypos = find_match_paren(
7847 corr_ind_maxparen(ind_maxparen, &cur_curpos),
7848 ind_maxcomment);
7849
7850 /*
7851 * If we are looking for ',', we also look for matching
7852 * braces.
7853 */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007854 if (trypos == NULL && terminated == ','
7855 && find_last_paren(l, '{', '}'))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007856 trypos = find_start_brace(ind_maxcomment);
7857
7858 if (trypos != NULL)
7859 {
7860 /*
7861 * Check if we are on a case label now. This is
7862 * handled above.
7863 * case xx: if ( asdf &&
7864 * asdf)
7865 */
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007866 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007867 l = ml_get_curline();
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007868 if (cin_iscase(l, FALSE) || cin_isscopedecl(l))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007869 {
7870 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007871 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007872 continue;
7873 }
7874 }
7875
7876 /*
7877 * Skip over continuation lines to find the one to get the
7878 * indent from
7879 * char *usethis = "bla\
7880 * bla",
7881 * here;
7882 */
7883 if (terminated == ',')
7884 {
7885 while (curwin->w_cursor.lnum > 1)
7886 {
7887 l = ml_get(curwin->w_cursor.lnum - 1);
7888 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
7889 break;
7890 --curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007891 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007892 }
7893 }
7894
7895 /*
7896 * Get indent and pointer to text for current line,
7897 * ignoring any jump label. XXX
7898 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007899 if (!ind_js)
7900 cur_amount = skip_label(curwin->w_cursor.lnum,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007901 &l, ind_maxcomment);
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007902 else
7903 cur_amount = get_indent();
Bram Moolenaar071d4272004-06-13 20:20:40 +00007904 /*
7905 * If this is just above the line we are indenting, and it
7906 * starts with a '{', line it up with this line.
7907 * while (not)
7908 * -> {
7909 * }
7910 */
7911 if (terminated != ',' && lookfor != LOOKFOR_TERM
7912 && theline[0] == '{')
7913 {
7914 amount = cur_amount;
7915 /*
7916 * Only add ind_open_extra when the current line
7917 * doesn't start with a '{', which must have a match
7918 * in the same line (scope is the same). Probably:
7919 * { 1, 2 },
7920 * -> { 3, 4 }
7921 */
7922 if (*skipwhite(l) != '{')
7923 amount += ind_open_extra;
7924
7925 if (ind_cpp_baseclass)
7926 {
7927 /* have to look back, whether it is a cpp base
7928 * class declaration or initialization */
7929 lookfor = LOOKFOR_CPP_BASECLASS;
7930 continue;
7931 }
7932 break;
7933 }
7934
7935 /*
7936 * Check if we are after an "if", "while", etc.
7937 * Also allow " } else".
7938 */
7939 if (cin_is_cinword(l) || cin_iselse(skipwhite(l)))
7940 {
7941 /*
7942 * Found an unterminated line after an if (), line up
7943 * with the last one.
7944 * if (cond)
7945 * 100 +
7946 * -> here;
7947 */
7948 if (lookfor == LOOKFOR_UNTERM
7949 || lookfor == LOOKFOR_ENUM_OR_INIT)
7950 {
7951 if (cont_amount > 0)
7952 amount = cont_amount;
7953 else
7954 amount += ind_continuation;
7955 break;
7956 }
7957
7958 /*
7959 * If this is just above the line we are indenting, we
7960 * are finished.
7961 * while (not)
7962 * -> here;
7963 * Otherwise this indent can be used when the line
7964 * before this is terminated.
7965 * yyy;
7966 * if (stat)
7967 * while (not)
7968 * xxx;
7969 * -> here;
7970 */
7971 amount = cur_amount;
7972 if (theline[0] == '{')
7973 amount += ind_open_extra;
7974 if (lookfor != LOOKFOR_TERM)
7975 {
7976 amount += ind_level + ind_no_brace;
7977 break;
7978 }
7979
7980 /*
7981 * Special trick: when expecting the while () after a
7982 * do, line up with the while()
7983 * do
7984 * x = 1;
7985 * -> here
7986 */
7987 l = skipwhite(ml_get_curline());
7988 if (cin_isdo(l))
7989 {
7990 if (whilelevel == 0)
7991 break;
7992 --whilelevel;
7993 }
7994
7995 /*
7996 * When searching for a terminated line, don't use the
Bram Moolenaar334adf02011-05-25 13:34:04 +02007997 * one between the "if" and the matching "else".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007998 * Need to use the scope of this "else". XXX
7999 * If whilelevel != 0 continue looking for a "do {".
8000 */
Bram Moolenaar334adf02011-05-25 13:34:04 +02008001 if (cin_iselse(l) && whilelevel == 0)
8002 {
8003 /* If we're looking at "} else", let's make sure we
8004 * find the opening brace of the enclosing scope,
8005 * not the one from "if () {". */
8006 if (*l == '}')
8007 curwin->w_cursor.col =
Bram Moolenaar9b83c2f2011-05-25 17:29:44 +02008008 (colnr_T)(l - ml_get_curline()) + 1;
Bram Moolenaar334adf02011-05-25 13:34:04 +02008009
8010 if ((trypos = find_start_brace(ind_maxcomment))
8011 == NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00008012 || find_match(LOOKFOR_IF, trypos->lnum,
Bram Moolenaar334adf02011-05-25 13:34:04 +02008013 ind_maxparen, ind_maxcomment) == FAIL)
8014 break;
8015 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008016 }
8017
8018 /*
8019 * If we're below an unterminated line that is not an
8020 * "if" or something, we may line up with this line or
Bram Moolenaar25394022007-05-10 19:06:20 +00008021 * add something for a continuation line, depending on
Bram Moolenaar071d4272004-06-13 20:20:40 +00008022 * the line before this one.
8023 */
8024 else
8025 {
8026 /*
8027 * Found two unterminated lines on a row, line up with
8028 * the last one.
8029 * c = 99 +
8030 * 100 +
8031 * -> here;
8032 */
8033 if (lookfor == LOOKFOR_UNTERM)
8034 {
8035 /* When line ends in a comma add extra indent */
8036 if (terminated == ',')
8037 amount += ind_continuation;
8038 break;
8039 }
8040
8041 if (lookfor == LOOKFOR_ENUM_OR_INIT)
8042 {
8043 /* Found two lines ending in ',', lineup with the
8044 * lowest one, but check for cpp base class
8045 * declaration/initialization, if it is an
8046 * opening brace or we are looking just for
8047 * enumerations/initializations. */
8048 if (terminated == ',')
8049 {
8050 if (ind_cpp_baseclass == 0)
8051 break;
8052
8053 lookfor = LOOKFOR_CPP_BASECLASS;
8054 continue;
8055 }
8056
8057 /* Ignore unterminated lines in between, but
8058 * reduce indent. */
8059 if (amount > cur_amount)
8060 amount = cur_amount;
8061 }
8062 else
8063 {
8064 /*
8065 * Found first unterminated line on a row, may
8066 * line up with this line, remember its indent
8067 * 100 +
8068 * -> here;
8069 */
8070 amount = cur_amount;
8071
8072 /*
8073 * If previous line ends in ',', check whether we
8074 * are in an initialization or enum
8075 * struct xxx =
8076 * {
8077 * sizeof a,
8078 * 124 };
8079 * or a normal possible continuation line.
8080 * but only, of no other statement has been found
8081 * yet.
8082 */
8083 if (lookfor == LOOKFOR_INITIAL && terminated == ',')
8084 {
8085 lookfor = LOOKFOR_ENUM_OR_INIT;
8086 cont_amount = cin_first_id_amount();
8087 }
8088 else
8089 {
8090 if (lookfor == LOOKFOR_INITIAL
8091 && *l != NUL
8092 && l[STRLEN(l) - 1] == '\\')
8093 /* XXX */
8094 cont_amount = cin_get_equal_amount(
8095 curwin->w_cursor.lnum);
8096 if (lookfor != LOOKFOR_TERM)
8097 lookfor = LOOKFOR_UNTERM;
8098 }
8099 }
8100 }
8101 }
8102
8103 /*
8104 * Check if we are after a while (cond);
8105 * If so: Ignore until the matching "do".
8106 */
8107 /* XXX */
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00008108 else if (cin_iswhileofdo_end(terminated, ind_maxparen,
8109 ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008110 {
8111 /*
8112 * Found an unterminated line after a while ();, line up
8113 * with the last one.
8114 * while (cond);
8115 * 100 + <- line up with this one
8116 * -> here;
8117 */
8118 if (lookfor == LOOKFOR_UNTERM
8119 || lookfor == LOOKFOR_ENUM_OR_INIT)
8120 {
8121 if (cont_amount > 0)
8122 amount = cont_amount;
8123 else
8124 amount += ind_continuation;
8125 break;
8126 }
8127
8128 if (whilelevel == 0)
8129 {
8130 lookfor = LOOKFOR_TERM;
8131 amount = get_indent(); /* XXX */
8132 if (theline[0] == '{')
8133 amount += ind_open_extra;
8134 }
8135 ++whilelevel;
8136 }
8137
8138 /*
8139 * We are after a "normal" statement.
8140 * If we had another statement we can stop now and use the
8141 * indent of that other statement.
8142 * Otherwise the indent of the current statement may be used,
8143 * search backwards for the next "normal" statement.
8144 */
8145 else
8146 {
8147 /*
8148 * Skip single break line, if before a switch label. It
8149 * may be lined up with the case label.
8150 */
8151 if (lookfor == LOOKFOR_NOBREAK
8152 && cin_isbreak(skipwhite(ml_get_curline())))
8153 {
8154 lookfor = LOOKFOR_ANY;
8155 continue;
8156 }
8157
8158 /*
8159 * Handle "do {" line.
8160 */
8161 if (whilelevel > 0)
8162 {
8163 l = cin_skipcomment(ml_get_curline());
8164 if (cin_isdo(l))
8165 {
8166 amount = get_indent(); /* XXX */
8167 --whilelevel;
8168 continue;
8169 }
8170 }
8171
8172 /*
8173 * Found a terminated line above an unterminated line. Add
8174 * the amount for a continuation line.
8175 * x = 1;
8176 * y = foo +
8177 * -> here;
8178 * or
8179 * int x = 1;
8180 * int foo,
8181 * -> here;
8182 */
8183 if (lookfor == LOOKFOR_UNTERM
8184 || lookfor == LOOKFOR_ENUM_OR_INIT)
8185 {
8186 if (cont_amount > 0)
8187 amount = cont_amount;
8188 else
8189 amount += ind_continuation;
8190 break;
8191 }
8192
8193 /*
8194 * Found a terminated line above a terminated line or "if"
8195 * etc. line. Use the amount of the line below us.
8196 * x = 1; x = 1;
8197 * if (asdf) y = 2;
8198 * while (asdf) ->here;
8199 * here;
8200 * ->foo;
8201 */
8202 if (lookfor == LOOKFOR_TERM)
8203 {
8204 if (!lookfor_break && whilelevel == 0)
8205 break;
8206 }
8207
8208 /*
8209 * First line above the one we're indenting is terminated.
8210 * To know what needs to be done look further backward for
8211 * a terminated line.
8212 */
8213 else
8214 {
8215 /*
8216 * position the cursor over the rightmost paren, so
8217 * that matching it will take us back to the start of
8218 * the line. Helps for:
8219 * func(asdr,
8220 * asdfasdf);
8221 * here;
8222 */
8223term_again:
8224 l = ml_get_curline();
8225 if (find_last_paren(l, '(', ')')
8226 && (trypos = find_match_paren(ind_maxparen,
8227 ind_maxcomment)) != NULL)
8228 {
8229 /*
8230 * Check if we are on a case label now. This is
8231 * handled above.
8232 * case xx: if ( asdf &&
8233 * asdf)
8234 */
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008235 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008236 l = ml_get_curline();
Bram Moolenaar3acfc302010-07-11 17:23:02 +02008237 if (cin_iscase(l, FALSE) || cin_isscopedecl(l))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008238 {
8239 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008240 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008241 continue;
8242 }
8243 }
8244
8245 /* When aligning with the case statement, don't align
8246 * with a statement after it.
8247 * case 1: { <-- don't use this { position
8248 * stat;
8249 * }
8250 * case 2:
8251 * stat;
8252 * }
8253 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02008254 iscase = (ind_keep_case_label && cin_iscase(l, FALSE));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008255
8256 /*
8257 * Get indent and pointer to text for current line,
8258 * ignoring any jump label.
8259 */
8260 amount = skip_label(curwin->w_cursor.lnum,
8261 &l, ind_maxcomment);
8262
8263 if (theline[0] == '{')
8264 amount += ind_open_extra;
8265 /* See remark above: "Only add ind_open_extra.." */
Bram Moolenaar18144c82006-04-12 21:52:12 +00008266 l = skipwhite(l);
8267 if (*l == '{')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008268 amount -= ind_open_extra;
8269 lookfor = iscase ? LOOKFOR_ANY : LOOKFOR_TERM;
8270
8271 /*
Bram Moolenaar18144c82006-04-12 21:52:12 +00008272 * When a terminated line starts with "else" skip to
8273 * the matching "if":
8274 * else 3;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008275 * indent this;
Bram Moolenaar18144c82006-04-12 21:52:12 +00008276 * Need to use the scope of this "else". XXX
8277 * If whilelevel != 0 continue looking for a "do {".
8278 */
8279 if (lookfor == LOOKFOR_TERM
8280 && *l != '}'
8281 && cin_iselse(l)
8282 && whilelevel == 0)
8283 {
8284 if ((trypos = find_start_brace(ind_maxcomment))
8285 == NULL
8286 || find_match(LOOKFOR_IF, trypos->lnum,
8287 ind_maxparen, ind_maxcomment) == FAIL)
8288 break;
8289 continue;
8290 }
8291
8292 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008293 * If we're at the end of a block, skip to the start of
8294 * that block.
8295 */
Bram Moolenaar6d8f9c62011-11-30 13:03:28 +01008296 l = ml_get_curline();
Bram Moolenaar50f42ca2011-07-15 14:12:30 +02008297 if (find_last_paren(l, '{', '}')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008298 && (trypos = find_start_brace(ind_maxcomment))
8299 != NULL) /* XXX */
8300 {
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008301 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008302 /* if not "else {" check for terminated again */
8303 /* but skip block for "} else {" */
8304 l = cin_skipcomment(ml_get_curline());
8305 if (*l == '}' || !cin_iselse(l))
8306 goto term_again;
8307 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008308 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008309 }
8310 }
8311 }
8312 }
8313 }
8314 }
8315
8316 /* add extra indent for a comment */
8317 if (cin_iscomment(theline))
8318 amount += ind_comment;
Bram Moolenaar02c707a2010-07-17 17:12:06 +02008319
8320 /* subtract extra left-shift for jump labels */
8321 if (ind_jump_label > 0 && original_line_islabel)
8322 amount -= ind_jump_label;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008323 }
8324
8325 /*
8326 * ok -- we're not inside any sort of structure at all!
8327 *
8328 * this means we're at the top level, and everything should
8329 * basically just match where the previous line is, except
8330 * for the lines immediately following a function declaration,
8331 * which are K&R-style parameters and need to be indented.
8332 */
8333 else
8334 {
8335 /*
8336 * if our line starts with an open brace, forget about any
8337 * prevailing indent and make sure it looks like the start
8338 * of a function
8339 */
8340
8341 if (theline[0] == '{')
8342 {
8343 amount = ind_first_open;
8344 }
8345
8346 /*
8347 * If the NEXT line is a function declaration, the current
8348 * line needs to be indented as a function type spec.
Bram Moolenaar1a89bbe2010-03-02 12:38:22 +01008349 * Don't do this if the current line looks like a comment or if the
8350 * current line is terminated, ie. ends in ';', or if the current line
8351 * contains { or }: "void f() {\n if (1)"
Bram Moolenaar071d4272004-06-13 20:20:40 +00008352 */
8353 else if (cur_curpos.lnum < curbuf->b_ml.ml_line_count
8354 && !cin_nocode(theline)
Bram Moolenaar1a89bbe2010-03-02 12:38:22 +01008355 && vim_strchr(theline, '{') == NULL
8356 && vim_strchr(theline, '}') == NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00008357 && !cin_ends_in(theline, (char_u *)":", NULL)
8358 && !cin_ends_in(theline, (char_u *)",", NULL)
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008359 && cin_isfuncdecl(NULL, cur_curpos.lnum + 1,
8360 cur_curpos.lnum + 1,
8361 ind_maxparen, ind_maxcomment)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008362 && !cin_isterminated(theline, FALSE, TRUE))
8363 {
8364 amount = ind_func_type;
8365 }
8366 else
8367 {
8368 amount = 0;
8369 curwin->w_cursor = cur_curpos;
8370
8371 /* search backwards until we find something we recognize */
8372
8373 while (curwin->w_cursor.lnum > 1)
8374 {
8375 curwin->w_cursor.lnum--;
8376 curwin->w_cursor.col = 0;
8377
8378 l = ml_get_curline();
8379
8380 /*
8381 * If we're in a comment now, skip to the start of the comment.
8382 */ /* XXX */
8383 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
8384 {
8385 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008386 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008387 continue;
8388 }
8389
8390 /*
Bram Moolenaar18144c82006-04-12 21:52:12 +00008391 * Are we at the start of a cpp base class declaration or
8392 * constructor initialization?
Bram Moolenaar071d4272004-06-13 20:20:40 +00008393 */ /* XXX */
Bram Moolenaar18144c82006-04-12 21:52:12 +00008394 n = FALSE;
8395 if (ind_cpp_baseclass != 0 && theline[0] != '{')
8396 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00008397 n = cin_is_cpp_baseclass(&col);
Bram Moolenaar18144c82006-04-12 21:52:12 +00008398 l = ml_get_curline();
8399 }
8400 if (n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008401 {
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00008402 /* XXX */
8403 amount = get_baseclass_amount(col, ind_maxparen,
8404 ind_maxcomment, ind_cpp_baseclass);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008405 break;
8406 }
8407
8408 /*
8409 * Skip preprocessor directives and blank lines.
8410 */
8411 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
8412 continue;
8413
8414 if (cin_nocode(l))
8415 continue;
8416
8417 /*
8418 * If the previous line ends in ',', use one level of
8419 * indentation:
8420 * int foo,
8421 * bar;
8422 * do this before checking for '}' in case of eg.
8423 * enum foobar
8424 * {
8425 * ...
8426 * } foo,
8427 * bar;
8428 */
8429 n = 0;
8430 if (cin_ends_in(l, (char_u *)",", NULL)
8431 || (*l != NUL && (n = l[STRLEN(l) - 1]) == '\\'))
8432 {
8433 /* take us back to opening paren */
8434 if (find_last_paren(l, '(', ')')
8435 && (trypos = find_match_paren(ind_maxparen,
8436 ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008437 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008438
8439 /* For a line ending in ',' that is a continuation line go
8440 * back to the first line with a backslash:
8441 * char *foo = "bla\
8442 * bla",
8443 * here;
8444 */
8445 while (n == 0 && curwin->w_cursor.lnum > 1)
8446 {
8447 l = ml_get(curwin->w_cursor.lnum - 1);
8448 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
8449 break;
8450 --curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008451 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008452 }
8453
8454 amount = get_indent(); /* XXX */
8455
8456 if (amount == 0)
8457 amount = cin_first_id_amount();
8458 if (amount == 0)
8459 amount = ind_continuation;
8460 break;
8461 }
8462
8463 /*
8464 * If the line looks like a function declaration, and we're
8465 * not in a comment, put it the left margin.
8466 */
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008467 if (cin_isfuncdecl(NULL, cur_curpos.lnum, 0,
8468 ind_maxparen, ind_maxcomment)) /* XXX */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008469 break;
8470 l = ml_get_curline();
8471
8472 /*
8473 * Finding the closing '}' of a previous function. Put
8474 * current line at the left margin. For when 'cino' has "fs".
8475 */
8476 if (*skipwhite(l) == '}')
8477 break;
8478
8479 /* (matching {)
8480 * If the previous line ends on '};' (maybe followed by
8481 * comments) align at column 0. For example:
8482 * char *string_array[] = { "foo",
8483 * / * x * / "b};ar" }; / * foobar * /
8484 */
8485 if (cin_ends_in(l, (char_u *)"};", NULL))
8486 break;
8487
8488 /*
Bram Moolenaar3388bb42011-11-30 17:20:23 +01008489 * Find a line only has a semicolon that belongs to a previous
8490 * line ending in '}', e.g. before an #endif. Don't increase
8491 * indent then.
8492 */
8493 if (*(look = skipwhite(l)) == ';' && cin_nocode(look + 1))
8494 {
8495 pos_T curpos_save = curwin->w_cursor;
8496
8497 while (curwin->w_cursor.lnum > 1)
8498 {
8499 look = ml_get(--curwin->w_cursor.lnum);
8500 if (!(cin_nocode(look) || cin_ispreproc_cont(
8501 &look, &curwin->w_cursor.lnum)))
8502 break;
8503 }
8504 if (curwin->w_cursor.lnum > 0
8505 && cin_ends_in(look, (char_u *)"}", NULL))
8506 break;
8507
8508 curwin->w_cursor = curpos_save;
8509 }
8510
8511 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008512 * If the PREVIOUS line is a function declaration, the current
8513 * line (and the ones that follow) needs to be indented as
8514 * parameters.
8515 */
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008516 if (cin_isfuncdecl(&l, curwin->w_cursor.lnum, 0,
8517 ind_maxparen, ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008518 {
8519 amount = ind_param;
8520 break;
8521 }
8522
8523 /*
8524 * If the previous line ends in ';' and the line before the
8525 * previous line ends in ',' or '\', ident to column zero:
8526 * int foo,
8527 * bar;
8528 * indent_to_0 here;
8529 */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00008530 if (cin_ends_in(l, (char_u *)";", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008531 {
8532 l = ml_get(curwin->w_cursor.lnum - 1);
8533 if (cin_ends_in(l, (char_u *)",", NULL)
8534 || (*l != NUL && l[STRLEN(l) - 1] == '\\'))
8535 break;
8536 l = ml_get_curline();
8537 }
8538
8539 /*
8540 * Doesn't look like anything interesting -- so just
8541 * use the indent of this line.
8542 *
8543 * Position the cursor over the rightmost paren, so that
8544 * matching it will take us back to the start of the line.
8545 */
8546 find_last_paren(l, '(', ')');
8547
8548 if ((trypos = find_match_paren(ind_maxparen,
8549 ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008550 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008551 amount = get_indent(); /* XXX */
8552 break;
8553 }
8554
8555 /* add extra indent for a comment */
8556 if (cin_iscomment(theline))
8557 amount += ind_comment;
8558
8559 /* add extra indent if the previous line ended in a backslash:
8560 * "asdfasdf\
8561 * here";
8562 * char *foo = "asdf\
8563 * here";
8564 */
8565 if (cur_curpos.lnum > 1)
8566 {
8567 l = ml_get(cur_curpos.lnum - 1);
8568 if (*l != NUL && l[STRLEN(l) - 1] == '\\')
8569 {
8570 cur_amount = cin_get_equal_amount(cur_curpos.lnum - 1);
8571 if (cur_amount > 0)
8572 amount = cur_amount;
8573 else if (cur_amount == 0)
8574 amount += ind_continuation;
8575 }
8576 }
8577 }
8578 }
8579
8580theend:
8581 /* put the cursor back where it belongs */
8582 curwin->w_cursor = cur_curpos;
8583
8584 vim_free(linecopy);
8585
8586 if (amount < 0)
8587 return 0;
8588 return amount;
8589}
8590
8591 static int
8592find_match(lookfor, ourscope, ind_maxparen, ind_maxcomment)
8593 int lookfor;
8594 linenr_T ourscope;
8595 int ind_maxparen;
8596 int ind_maxcomment;
8597{
8598 char_u *look;
8599 pos_T *theirscope;
8600 char_u *mightbeif;
8601 int elselevel;
8602 int whilelevel;
8603
8604 if (lookfor == LOOKFOR_IF)
8605 {
8606 elselevel = 1;
8607 whilelevel = 0;
8608 }
8609 else
8610 {
8611 elselevel = 0;
8612 whilelevel = 1;
8613 }
8614
8615 curwin->w_cursor.col = 0;
8616
8617 while (curwin->w_cursor.lnum > ourscope + 1)
8618 {
8619 curwin->w_cursor.lnum--;
8620 curwin->w_cursor.col = 0;
8621
8622 look = cin_skipcomment(ml_get_curline());
8623 if (cin_iselse(look)
8624 || cin_isif(look)
8625 || cin_isdo(look) /* XXX */
8626 || cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
8627 {
8628 /*
8629 * if we've gone outside the braces entirely,
8630 * we must be out of scope...
8631 */
8632 theirscope = find_start_brace(ind_maxcomment); /* XXX */
8633 if (theirscope == NULL)
8634 break;
8635
8636 /*
8637 * and if the brace enclosing this is further
8638 * back than the one enclosing the else, we're
8639 * out of luck too.
8640 */
8641 if (theirscope->lnum < ourscope)
8642 break;
8643
8644 /*
8645 * and if they're enclosed in a *deeper* brace,
8646 * then we can ignore it because it's in a
8647 * different scope...
8648 */
8649 if (theirscope->lnum > ourscope)
8650 continue;
8651
8652 /*
8653 * if it was an "else" (that's not an "else if")
8654 * then we need to go back to another if, so
8655 * increment elselevel
8656 */
8657 look = cin_skipcomment(ml_get_curline());
8658 if (cin_iselse(look))
8659 {
8660 mightbeif = cin_skipcomment(look + 4);
8661 if (!cin_isif(mightbeif))
8662 ++elselevel;
8663 continue;
8664 }
8665
8666 /*
8667 * if it was a "while" then we need to go back to
8668 * another "do", so increment whilelevel. XXX
8669 */
8670 if (cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
8671 {
8672 ++whilelevel;
8673 continue;
8674 }
8675
8676 /* If it's an "if" decrement elselevel */
8677 look = cin_skipcomment(ml_get_curline());
8678 if (cin_isif(look))
8679 {
8680 elselevel--;
8681 /*
8682 * When looking for an "if" ignore "while"s that
8683 * get in the way.
8684 */
8685 if (elselevel == 0 && lookfor == LOOKFOR_IF)
8686 whilelevel = 0;
8687 }
8688
8689 /* If it's a "do" decrement whilelevel */
8690 if (cin_isdo(look))
8691 whilelevel--;
8692
8693 /*
8694 * if we've used up all the elses, then
8695 * this must be the if that we want!
8696 * match the indent level of that if.
8697 */
8698 if (elselevel <= 0 && whilelevel <= 0)
8699 {
8700 return OK;
8701 }
8702 }
8703 }
8704 return FAIL;
8705}
8706
8707# if defined(FEAT_EVAL) || defined(PROTO)
8708/*
8709 * Get indent level from 'indentexpr'.
8710 */
8711 int
8712get_expr_indent()
8713{
8714 int indent;
8715 pos_T pos;
8716 int save_State;
Bram Moolenaard1f56e62006-02-22 21:25:37 +00008717 int use_sandbox = was_set_insecurely((char_u *)"indentexpr",
8718 OPT_LOCAL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008719
8720 pos = curwin->w_cursor;
8721 set_vim_var_nr(VV_LNUM, curwin->w_cursor.lnum);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00008722 if (use_sandbox)
8723 ++sandbox;
8724 ++textlock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008725 indent = eval_to_number(curbuf->b_p_inde);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00008726 if (use_sandbox)
8727 --sandbox;
8728 --textlock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008729
8730 /* Restore the cursor position so that 'indentexpr' doesn't need to.
8731 * Pretend to be in Insert mode, allow cursor past end of line for "o"
8732 * command. */
8733 save_State = State;
8734 State = INSERT;
8735 curwin->w_cursor = pos;
8736 check_cursor();
8737 State = save_State;
8738
8739 /* If there is an error, just keep the current indent. */
8740 if (indent < 0)
8741 indent = get_indent();
8742
8743 return indent;
8744}
8745# endif
8746
8747#endif /* FEAT_CINDENT */
8748
8749#if defined(FEAT_LISP) || defined(PROTO)
8750
8751static int lisp_match __ARGS((char_u *p));
8752
8753 static int
8754lisp_match(p)
8755 char_u *p;
8756{
8757 char_u buf[LSIZE];
8758 int len;
8759 char_u *word = p_lispwords;
8760
8761 while (*word != NUL)
8762 {
8763 (void)copy_option_part(&word, buf, LSIZE, ",");
8764 len = (int)STRLEN(buf);
8765 if (STRNCMP(buf, p, len) == 0 && p[len] == ' ')
8766 return TRUE;
8767 }
8768 return FALSE;
8769}
8770
8771/*
8772 * When 'p' is present in 'cpoptions, a Vi compatible method is used.
8773 * The incompatible newer method is quite a bit better at indenting
8774 * code in lisp-like languages than the traditional one; it's still
8775 * mostly heuristics however -- Dirk van Deun, dirk@rave.org
8776 *
8777 * TODO:
8778 * Findmatch() should be adapted for lisp, also to make showmatch
8779 * work correctly: now (v5.3) it seems all C/C++ oriented:
8780 * - it does not recognize the #\( and #\) notations as character literals
8781 * - it doesn't know about comments starting with a semicolon
8782 * - it incorrectly interprets '(' as a character literal
8783 * All this messes up get_lisp_indent in some rare cases.
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008784 * Update from Sergey Khorev:
8785 * I tried to fix the first two issues.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008786 */
8787 int
8788get_lisp_indent()
8789{
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008790 pos_T *pos, realpos, paren;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008791 int amount;
8792 char_u *that;
8793 colnr_T col;
8794 colnr_T firsttry;
8795 int parencount, quotecount;
8796 int vi_lisp;
8797
8798 /* Set vi_lisp to use the vi-compatible method */
8799 vi_lisp = (vim_strchr(p_cpo, CPO_LISP) != NULL);
8800
8801 realpos = curwin->w_cursor;
8802 curwin->w_cursor.col = 0;
8803
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008804 if ((pos = findmatch(NULL, '(')) == NULL)
8805 pos = findmatch(NULL, '[');
8806 else
8807 {
8808 paren = *pos;
8809 pos = findmatch(NULL, '[');
8810 if (pos == NULL || ltp(pos, &paren))
8811 pos = &paren;
8812 }
8813 if (pos != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008814 {
8815 /* Extra trick: Take the indent of the first previous non-white
8816 * line that is at the same () level. */
8817 amount = -1;
8818 parencount = 0;
8819
8820 while (--curwin->w_cursor.lnum >= pos->lnum)
8821 {
8822 if (linewhite(curwin->w_cursor.lnum))
8823 continue;
8824 for (that = ml_get_curline(); *that != NUL; ++that)
8825 {
8826 if (*that == ';')
8827 {
8828 while (*(that + 1) != NUL)
8829 ++that;
8830 continue;
8831 }
8832 if (*that == '\\')
8833 {
8834 if (*(that + 1) != NUL)
8835 ++that;
8836 continue;
8837 }
8838 if (*that == '"' && *(that + 1) != NUL)
8839 {
Bram Moolenaar15ff6c12006-09-15 18:18:09 +00008840 while (*++that && *that != '"')
8841 {
8842 /* skipping escaped characters in the string */
8843 if (*that == '\\')
8844 {
8845 if (*++that == NUL)
8846 break;
8847 if (that[1] == NUL)
8848 {
8849 ++that;
8850 break;
8851 }
8852 }
8853 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008854 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008855 if (*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008856 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008857 else if (*that == ')' || *that == ']')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008858 --parencount;
8859 }
8860 if (parencount == 0)
8861 {
8862 amount = get_indent();
8863 break;
8864 }
8865 }
8866
8867 if (amount == -1)
8868 {
8869 curwin->w_cursor.lnum = pos->lnum;
8870 curwin->w_cursor.col = pos->col;
8871 col = pos->col;
8872
8873 that = ml_get_curline();
8874
8875 if (vi_lisp && get_indent() == 0)
8876 amount = 2;
8877 else
8878 {
8879 amount = 0;
8880 while (*that && col)
8881 {
8882 amount += lbr_chartabsize_adv(&that, (colnr_T)amount);
8883 col--;
8884 }
8885
8886 /*
8887 * Some keywords require "body" indenting rules (the
8888 * non-standard-lisp ones are Scheme special forms):
8889 *
8890 * (let ((a 1)) instead (let ((a 1))
8891 * (...)) of (...))
8892 */
8893
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008894 if (!vi_lisp && (*that == '(' || *that == '[')
8895 && lisp_match(that + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008896 amount += 2;
8897 else
8898 {
8899 that++;
8900 amount++;
8901 firsttry = amount;
8902
8903 while (vim_iswhite(*that))
8904 {
8905 amount += lbr_chartabsize(that, (colnr_T)amount);
8906 ++that;
8907 }
8908
8909 if (*that && *that != ';') /* not a comment line */
8910 {
Bram Moolenaare21877a2008-02-13 09:58:14 +00008911 /* test *that != '(' to accommodate first let/do
Bram Moolenaar071d4272004-06-13 20:20:40 +00008912 * argument if it is more than one line */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008913 if (!vi_lisp && *that != '(' && *that != '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008914 firsttry++;
8915
8916 parencount = 0;
8917 quotecount = 0;
8918
8919 if (vi_lisp
8920 || (*that != '"'
8921 && *that != '\''
8922 && *that != '#'
8923 && (*that < '0' || *that > '9')))
8924 {
8925 while (*that
8926 && (!vim_iswhite(*that)
8927 || quotecount
8928 || parencount)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008929 && (!((*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008930 && !quotecount
8931 && !parencount
8932 && vi_lisp)))
8933 {
8934 if (*that == '"')
8935 quotecount = !quotecount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008936 if ((*that == '(' || *that == '[')
8937 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008938 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008939 if ((*that == ')' || *that == ']')
8940 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008941 --parencount;
8942 if (*that == '\\' && *(that+1) != NUL)
8943 amount += lbr_chartabsize_adv(&that,
8944 (colnr_T)amount);
8945 amount += lbr_chartabsize_adv(&that,
8946 (colnr_T)amount);
8947 }
8948 }
8949 while (vim_iswhite(*that))
8950 {
8951 amount += lbr_chartabsize(that, (colnr_T)amount);
8952 that++;
8953 }
8954 if (!*that || *that == ';')
8955 amount = firsttry;
8956 }
8957 }
8958 }
8959 }
8960 }
8961 else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008962 amount = 0; /* no matching '(' or '[' found, use zero indent */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008963
8964 curwin->w_cursor = realpos;
8965
8966 return amount;
8967}
8968#endif /* FEAT_LISP */
8969
8970 void
8971prepare_to_exit()
8972{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00008973#if defined(SIGHUP) && defined(SIG_IGN)
8974 /* Ignore SIGHUP, because a dropped connection causes a read error, which
8975 * makes Vim exit and then handling SIGHUP causes various reentrance
8976 * problems. */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00008977 signal(SIGHUP, SIG_IGN);
8978#endif
8979
Bram Moolenaar071d4272004-06-13 20:20:40 +00008980#ifdef FEAT_GUI
8981 if (gui.in_use)
8982 {
8983 gui.dying = TRUE;
8984 out_trash(); /* trash any pending output */
8985 }
8986 else
8987#endif
8988 {
8989 windgoto((int)Rows - 1, 0);
8990
8991 /*
8992 * Switch terminal mode back now, so messages end up on the "normal"
8993 * screen (if there are two screens).
8994 */
8995 settmode(TMODE_COOK);
8996#ifdef WIN3264
8997 if (can_end_termcap_mode(FALSE) == TRUE)
8998#endif
8999 stoptermcap();
9000 out_flush();
9001 }
9002}
9003
9004/*
9005 * Preserve files and exit.
9006 * When called IObuff must contain a message.
9007 */
9008 void
9009preserve_exit()
9010{
9011 buf_T *buf;
9012
9013 prepare_to_exit();
9014
Bram Moolenaar4770d092006-01-12 23:22:24 +00009015 /* Setting this will prevent free() calls. That avoids calling free()
9016 * recursively when free() was invoked with a bad pointer. */
9017 really_exiting = TRUE;
9018
Bram Moolenaar071d4272004-06-13 20:20:40 +00009019 out_str(IObuff);
9020 screen_start(); /* don't know where cursor is now */
9021 out_flush();
9022
9023 ml_close_notmod(); /* close all not-modified buffers */
9024
9025 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
9026 {
9027 if (buf->b_ml.ml_mfp != NULL && buf->b_ml.ml_mfp->mf_fname != NULL)
9028 {
9029 OUT_STR(_("Vim: preserving files...\n"));
9030 screen_start(); /* don't know where cursor is now */
9031 out_flush();
9032 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
9033 break;
9034 }
9035 }
9036
9037 ml_close_all(FALSE); /* close all memfiles, without deleting */
9038
9039 OUT_STR(_("Vim: Finished.\n"));
9040
9041 getout(1);
9042}
9043
9044/*
9045 * return TRUE if "fname" exists.
9046 */
9047 int
9048vim_fexists(fname)
9049 char_u *fname;
9050{
9051 struct stat st;
9052
9053 if (mch_stat((char *)fname, &st))
9054 return FALSE;
9055 return TRUE;
9056}
9057
9058/*
9059 * Check for CTRL-C pressed, but only once in a while.
9060 * Should be used instead of ui_breakcheck() for functions that check for
9061 * each line in the file. Calling ui_breakcheck() each time takes too much
9062 * time, because it can be a system call.
9063 */
9064
9065#ifndef BREAKCHECK_SKIP
9066# ifdef FEAT_GUI /* assume the GUI only runs on fast computers */
9067# define BREAKCHECK_SKIP 200
9068# else
9069# define BREAKCHECK_SKIP 32
9070# endif
9071#endif
9072
9073static int breakcheck_count = 0;
9074
9075 void
9076line_breakcheck()
9077{
9078 if (++breakcheck_count >= BREAKCHECK_SKIP)
9079 {
9080 breakcheck_count = 0;
9081 ui_breakcheck();
9082 }
9083}
9084
9085/*
9086 * Like line_breakcheck() but check 10 times less often.
9087 */
9088 void
9089fast_breakcheck()
9090{
9091 if (++breakcheck_count >= BREAKCHECK_SKIP * 10)
9092 {
9093 breakcheck_count = 0;
9094 ui_breakcheck();
9095 }
9096}
9097
9098/*
Bram Moolenaard7834d32009-12-02 16:14:36 +00009099 * Invoke expand_wildcards() for one pattern.
9100 * Expand items like "%:h" before the expansion.
9101 * Returns OK or FAIL.
9102 */
9103 int
9104expand_wildcards_eval(pat, num_file, file, flags)
9105 char_u **pat; /* pointer to input pattern */
9106 int *num_file; /* resulting number of files */
9107 char_u ***file; /* array of resulting files */
9108 int flags; /* EW_DIR, etc. */
9109{
9110 int ret = FAIL;
9111 char_u *eval_pat = NULL;
9112 char_u *exp_pat = *pat;
9113 char_u *ignored_msg;
9114 int usedlen;
9115
9116 if (*exp_pat == '%' || *exp_pat == '#' || *exp_pat == '<')
9117 {
9118 ++emsg_off;
9119 eval_pat = eval_vars(exp_pat, exp_pat, &usedlen,
9120 NULL, &ignored_msg, NULL);
9121 --emsg_off;
9122 if (eval_pat != NULL)
9123 exp_pat = concat_str(eval_pat, exp_pat + usedlen);
9124 }
9125
9126 if (exp_pat != NULL)
9127 ret = expand_wildcards(1, &exp_pat, num_file, file, flags);
9128
9129 if (eval_pat != NULL)
9130 {
9131 vim_free(exp_pat);
9132 vim_free(eval_pat);
9133 }
9134
9135 return ret;
9136}
9137
9138/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00009139 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching
9140 * 'wildignore'.
Bram Moolenaar9e193ac2010-07-19 23:11:27 +02009141 * Returns OK or FAIL. When FAIL then "num_file" won't be set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009142 */
9143 int
9144expand_wildcards(num_pat, pat, num_file, file, flags)
9145 int num_pat; /* number of input patterns */
9146 char_u **pat; /* array of input patterns */
9147 int *num_file; /* resulting number of files */
9148 char_u ***file; /* array of resulting files */
9149 int flags; /* EW_DIR, etc. */
9150{
9151 int retval;
9152 int i, j;
9153 char_u *p;
9154 int non_suf_match; /* number without matching suffix */
9155
9156 retval = gen_expand_wildcards(num_pat, pat, num_file, file, flags);
9157
9158 /* When keeping all matches, return here */
Bram Moolenaar9e193ac2010-07-19 23:11:27 +02009159 if ((flags & EW_KEEPALL) || retval == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009160 return retval;
9161
9162#ifdef FEAT_WILDIGN
9163 /*
9164 * Remove names that match 'wildignore'.
9165 */
9166 if (*p_wig)
9167 {
9168 char_u *ffname;
9169
9170 /* check all files in (*file)[] */
9171 for (i = 0; i < *num_file; ++i)
9172 {
9173 ffname = FullName_save((*file)[i], FALSE);
9174 if (ffname == NULL) /* out of memory */
9175 break;
9176# ifdef VMS
9177 vms_remove_version(ffname);
9178# endif
9179 if (match_file_list(p_wig, (*file)[i], ffname))
9180 {
9181 /* remove this matching file from the list */
9182 vim_free((*file)[i]);
9183 for (j = i; j + 1 < *num_file; ++j)
9184 (*file)[j] = (*file)[j + 1];
9185 --*num_file;
9186 --i;
9187 }
9188 vim_free(ffname);
9189 }
9190 }
9191#endif
9192
9193 /*
9194 * Move the names where 'suffixes' match to the end.
9195 */
9196 if (*num_file > 1)
9197 {
9198 non_suf_match = 0;
9199 for (i = 0; i < *num_file; ++i)
9200 {
9201 if (!match_suffix((*file)[i]))
9202 {
9203 /*
9204 * Move the name without matching suffix to the front
9205 * of the list.
9206 */
9207 p = (*file)[i];
9208 for (j = i; j > non_suf_match; --j)
9209 (*file)[j] = (*file)[j - 1];
9210 (*file)[non_suf_match++] = p;
9211 }
9212 }
9213 }
9214
9215 return retval;
9216}
9217
9218/*
9219 * Return TRUE if "fname" matches with an entry in 'suffixes'.
9220 */
9221 int
9222match_suffix(fname)
9223 char_u *fname;
9224{
9225 int fnamelen, setsuflen;
9226 char_u *setsuf;
9227#define MAXSUFLEN 30 /* maximum length of a file suffix */
9228 char_u suf_buf[MAXSUFLEN];
9229
9230 fnamelen = (int)STRLEN(fname);
9231 setsuflen = 0;
9232 for (setsuf = p_su; *setsuf; )
9233 {
9234 setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
Bram Moolenaar055a2ba2009-07-14 19:40:21 +00009235 if (setsuflen == 0)
9236 {
9237 char_u *tail = gettail(fname);
9238
9239 /* empty entry: match name without a '.' */
9240 if (vim_strchr(tail, '.') == NULL)
9241 {
9242 setsuflen = 1;
9243 break;
9244 }
9245 }
9246 else
9247 {
9248 if (fnamelen >= setsuflen
9249 && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
9250 (size_t)setsuflen) == 0)
9251 break;
9252 setsuflen = 0;
9253 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009254 }
9255 return (setsuflen != 0);
9256}
9257
9258#if !defined(NO_EXPANDPATH) || defined(PROTO)
9259
9260# ifdef VIM_BACKTICK
9261static int vim_backtick __ARGS((char_u *p));
9262static int expand_backtick __ARGS((garray_T *gap, char_u *pat, int flags));
9263# endif
9264
9265# if defined(MSDOS) || defined(FEAT_GUI_W16) || defined(WIN3264)
9266/*
9267 * File name expansion code for MS-DOS, Win16 and Win32. It's here because
9268 * it's shared between these systems.
9269 */
9270# if defined(DJGPP) || defined(PROTO)
9271# define _cdecl /* DJGPP doesn't have this */
9272# else
9273# ifdef __BORLANDC__
9274# define _cdecl _RTLENTRYF
9275# endif
9276# endif
9277
9278/*
9279 * comparison function for qsort in dos_expandpath()
9280 */
9281 static int _cdecl
9282pstrcmp(const void *a, const void *b)
9283{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00009284 return (pathcmp(*(char **)a, *(char **)b, -1));
Bram Moolenaar071d4272004-06-13 20:20:40 +00009285}
9286
9287# ifndef WIN3264
9288 static void
9289namelowcpy(
9290 char_u *d,
9291 char_u *s)
9292{
9293# ifdef DJGPP
9294 if (USE_LONG_FNAME) /* don't lower case on Windows 95/NT systems */
9295 while (*s)
9296 *d++ = *s++;
9297 else
9298# endif
9299 while (*s)
9300 *d++ = TOLOWER_LOC(*s++);
9301 *d = NUL;
9302}
9303# endif
9304
9305/*
Bram Moolenaar231334e2005-07-25 20:46:57 +00009306 * Recursively expand one path component into all matching files and/or
9307 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009308 * Return the number of matches found.
9309 * "path" has backslashes before chars that are not to be expanded, starting
9310 * at "path[wildoff]".
Bram Moolenaar231334e2005-07-25 20:46:57 +00009311 * Return the number of matches found.
9312 * NOTE: much of this is identical to unix_expandpath(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00009313 */
9314 static int
9315dos_expandpath(
9316 garray_T *gap,
9317 char_u *path,
9318 int wildoff,
Bram Moolenaar231334e2005-07-25 20:46:57 +00009319 int flags, /* EW_* flags */
Bram Moolenaar25394022007-05-10 19:06:20 +00009320 int didstar) /* expanded "**" once already */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009321{
Bram Moolenaar231334e2005-07-25 20:46:57 +00009322 char_u *buf;
9323 char_u *path_end;
9324 char_u *p, *s, *e;
9325 int start_len = gap->ga_len;
9326 char_u *pat;
9327 regmatch_T regmatch;
9328 int starts_with_dot;
9329 int matches;
9330 int len;
9331 int starstar = FALSE;
9332 static int stardepth = 0; /* depth for "**" expansion */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009333#ifdef WIN3264
9334 WIN32_FIND_DATA fb;
9335 HANDLE hFind = (HANDLE)0;
9336# ifdef FEAT_MBYTE
9337 WIN32_FIND_DATAW wfb;
9338 WCHAR *wn = NULL; /* UCS-2 name, NULL when not used. */
9339# endif
9340#else
9341 struct ffblk fb;
9342#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009343 char_u *matchname;
Bram Moolenaar231334e2005-07-25 20:46:57 +00009344 int ok;
9345
9346 /* Expanding "**" may take a long time, check for CTRL-C. */
9347 if (stardepth > 0)
9348 {
9349 ui_breakcheck();
9350 if (got_int)
9351 return 0;
9352 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009353
9354 /* make room for file name */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009355 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009356 if (buf == NULL)
9357 return 0;
9358
9359 /*
9360 * Find the first part in the path name that contains a wildcard or a ~1.
9361 * Copy it into buf, including the preceding characters.
9362 */
9363 p = buf;
9364 s = buf;
9365 e = NULL;
9366 path_end = path;
9367 while (*path_end != NUL)
9368 {
9369 /* May ignore a wildcard that has a backslash before it; it will
9370 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
9371 if (path_end >= path + wildoff && rem_backslash(path_end))
9372 *p++ = *path_end++;
9373 else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
9374 {
9375 if (e != NULL)
9376 break;
9377 s = p + 1;
9378 }
9379 else if (path_end >= path + wildoff
9380 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
9381 e = p;
9382#ifdef FEAT_MBYTE
9383 if (has_mbyte)
9384 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00009385 len = (*mb_ptr2len)(path_end);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009386 STRNCPY(p, path_end, len);
9387 p += len;
9388 path_end += len;
9389 }
9390 else
9391#endif
9392 *p++ = *path_end++;
9393 }
9394 e = p;
9395 *e = NUL;
9396
9397 /* now we have one wildcard component between s and e */
9398 /* Remove backslashes between "wildoff" and the start of the wildcard
9399 * component. */
9400 for (p = buf + wildoff; p < s; ++p)
9401 if (rem_backslash(p))
9402 {
Bram Moolenaar8c8de832008-06-24 22:58:06 +00009403 STRMOVE(p, p + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009404 --e;
9405 --s;
9406 }
9407
Bram Moolenaar231334e2005-07-25 20:46:57 +00009408 /* Check for "**" between "s" and "e". */
9409 for (p = s; p < e; ++p)
9410 if (p[0] == '*' && p[1] == '*')
9411 starstar = TRUE;
9412
Bram Moolenaar071d4272004-06-13 20:20:40 +00009413 starts_with_dot = (*s == '.');
9414 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
9415 if (pat == NULL)
9416 {
9417 vim_free(buf);
9418 return 0;
9419 }
9420
9421 /* compile the regexp into a program */
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009422 if (flags & (EW_NOERROR | EW_NOTWILD))
Bram Moolenaarb5609832011-07-20 15:04:58 +02009423 ++emsg_silent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009424 regmatch.rm_ic = TRUE; /* Always ignore case */
9425 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009426 if (flags & (EW_NOERROR | EW_NOTWILD))
Bram Moolenaarb5609832011-07-20 15:04:58 +02009427 --emsg_silent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009428 vim_free(pat);
9429
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009430 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009431 {
9432 vim_free(buf);
9433 return 0;
9434 }
9435
9436 /* remember the pattern or file name being looked for */
9437 matchname = vim_strsave(s);
9438
Bram Moolenaar231334e2005-07-25 20:46:57 +00009439 /* If "**" is by itself, this is the first time we encounter it and more
9440 * is following then find matches without any directory. */
9441 if (!didstar && stardepth < 100 && starstar && e - s == 2
9442 && *path_end == '/')
9443 {
9444 STRCPY(s, path_end + 1);
9445 ++stardepth;
9446 (void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
9447 --stardepth;
9448 }
9449
Bram Moolenaar071d4272004-06-13 20:20:40 +00009450 /* Scan all files in the directory with "dir/ *.*" */
9451 STRCPY(s, "*.*");
9452#ifdef WIN3264
9453# ifdef FEAT_MBYTE
9454 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
9455 {
9456 /* The active codepage differs from 'encoding'. Attempt using the
9457 * wide function. If it fails because it is not implemented fall back
9458 * to the non-wide version (for Windows 98) */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009459 wn = enc_to_utf16(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009460 if (wn != NULL)
9461 {
9462 hFind = FindFirstFileW(wn, &wfb);
9463 if (hFind == INVALID_HANDLE_VALUE
9464 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
9465 {
9466 vim_free(wn);
9467 wn = NULL;
9468 }
9469 }
9470 }
9471
9472 if (wn == NULL)
9473# endif
9474 hFind = FindFirstFile(buf, &fb);
9475 ok = (hFind != INVALID_HANDLE_VALUE);
9476#else
9477 /* If we are expanding wildcards we try both files and directories */
9478 ok = (findfirst((char *)buf, &fb,
9479 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
9480#endif
9481
9482 while (ok)
9483 {
9484#ifdef WIN3264
9485# ifdef FEAT_MBYTE
9486 if (wn != NULL)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009487 p = utf16_to_enc(wfb.cFileName, NULL); /* p is allocated here */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009488 else
9489# endif
9490 p = (char_u *)fb.cFileName;
9491#else
9492 p = (char_u *)fb.ff_name;
9493#endif
9494 /* Ignore entries starting with a dot, unless when asked for. Accept
9495 * all entries found with "matchname". */
9496 if ((p[0] != '.' || starts_with_dot)
9497 && (matchname == NULL
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009498 || (regmatch.regprog != NULL
9499 && vim_regexec(&regmatch, p, (colnr_T)0))
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009500 || ((flags & EW_NOTWILD)
9501 && fnamencmp(path + (s - buf), p, e - s) == 0)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009502 {
9503#ifdef WIN3264
9504 STRCPY(s, p);
9505#else
9506 namelowcpy(s, p);
9507#endif
9508 len = (int)STRLEN(buf);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009509
9510 if (starstar && stardepth < 100)
9511 {
9512 /* For "**" in the pattern first go deeper in the tree to
9513 * find matches. */
9514 STRCPY(buf + len, "/**");
9515 STRCPY(buf + len + 3, path_end);
9516 ++stardepth;
9517 (void)dos_expandpath(gap, buf, len + 1, flags, TRUE);
9518 --stardepth;
9519 }
9520
Bram Moolenaar071d4272004-06-13 20:20:40 +00009521 STRCPY(buf + len, path_end);
9522 if (mch_has_exp_wildcard(path_end))
9523 {
9524 /* need to expand another component of the path */
9525 /* remove backslashes for the remaining components only */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009526 (void)dos_expandpath(gap, buf, len + 1, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009527 }
9528 else
9529 {
9530 /* no more wildcards, check if there is a match */
9531 /* remove backslashes for the remaining components only */
9532 if (*path_end != 0)
9533 backslash_halve(buf + len + 1);
9534 if (mch_getperm(buf) >= 0) /* add existing file */
9535 addfile(gap, buf, flags);
9536 }
9537 }
9538
9539#ifdef WIN3264
9540# ifdef FEAT_MBYTE
9541 if (wn != NULL)
9542 {
9543 vim_free(p);
9544 ok = FindNextFileW(hFind, &wfb);
9545 }
9546 else
9547# endif
9548 ok = FindNextFile(hFind, &fb);
9549#else
9550 ok = (findnext(&fb) == 0);
9551#endif
9552
9553 /* If no more matches and no match was used, try expanding the name
9554 * itself. Finds the long name of a short filename. */
9555 if (!ok && matchname != NULL && gap->ga_len == start_len)
9556 {
9557 STRCPY(s, matchname);
9558#ifdef WIN3264
9559 FindClose(hFind);
9560# ifdef FEAT_MBYTE
9561 if (wn != NULL)
9562 {
9563 vim_free(wn);
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009564 wn = enc_to_utf16(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009565 if (wn != NULL)
9566 hFind = FindFirstFileW(wn, &wfb);
9567 }
9568 if (wn == NULL)
9569# endif
9570 hFind = FindFirstFile(buf, &fb);
9571 ok = (hFind != INVALID_HANDLE_VALUE);
9572#else
9573 ok = (findfirst((char *)buf, &fb,
9574 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
9575#endif
9576 vim_free(matchname);
9577 matchname = NULL;
9578 }
9579 }
9580
9581#ifdef WIN3264
9582 FindClose(hFind);
9583# ifdef FEAT_MBYTE
9584 vim_free(wn);
9585# endif
9586#endif
9587 vim_free(buf);
9588 vim_free(regmatch.regprog);
9589 vim_free(matchname);
9590
9591 matches = gap->ga_len - start_len;
9592 if (matches > 0)
9593 qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
9594 sizeof(char_u *), pstrcmp);
9595 return matches;
9596}
9597
9598 int
9599mch_expandpath(
9600 garray_T *gap,
9601 char_u *path,
9602 int flags) /* EW_* flags */
9603{
Bram Moolenaar231334e2005-07-25 20:46:57 +00009604 return dos_expandpath(gap, path, 0, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009605}
9606# endif /* MSDOS || FEAT_GUI_W16 || WIN3264 */
9607
Bram Moolenaar231334e2005-07-25 20:46:57 +00009608#if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
9609 || defined(PROTO)
9610/*
9611 * Unix style wildcard expansion code.
9612 * It's here because it's used both for Unix and Mac.
9613 */
9614static int pstrcmp __ARGS((const void *, const void *));
9615
9616 static int
9617pstrcmp(a, b)
9618 const void *a, *b;
9619{
9620 return (pathcmp(*(char **)a, *(char **)b, -1));
9621}
9622
9623/*
9624 * Recursively expand one path component into all matching files and/or
9625 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
9626 * "path" has backslashes before chars that are not to be expanded, starting
9627 * at "path + wildoff".
9628 * Return the number of matches found.
9629 * NOTE: much of this is identical to dos_expandpath(), keep in sync!
9630 */
9631 int
9632unix_expandpath(gap, path, wildoff, flags, didstar)
9633 garray_T *gap;
9634 char_u *path;
9635 int wildoff;
9636 int flags; /* EW_* flags */
9637 int didstar; /* expanded "**" once already */
9638{
9639 char_u *buf;
9640 char_u *path_end;
9641 char_u *p, *s, *e;
9642 int start_len = gap->ga_len;
9643 char_u *pat;
9644 regmatch_T regmatch;
9645 int starts_with_dot;
9646 int matches;
9647 int len;
9648 int starstar = FALSE;
9649 static int stardepth = 0; /* depth for "**" expansion */
9650
9651 DIR *dirp;
9652 struct dirent *dp;
9653
9654 /* Expanding "**" may take a long time, check for CTRL-C. */
9655 if (stardepth > 0)
9656 {
9657 ui_breakcheck();
9658 if (got_int)
9659 return 0;
9660 }
9661
9662 /* make room for file name */
9663 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
9664 if (buf == NULL)
9665 return 0;
9666
9667 /*
9668 * Find the first part in the path name that contains a wildcard.
Bram Moolenaar2d0b92f2012-04-30 21:09:43 +02009669 * When EW_ICASE is set every letter is considered to be a wildcard.
Bram Moolenaar231334e2005-07-25 20:46:57 +00009670 * Copy it into "buf", including the preceding characters.
9671 */
9672 p = buf;
9673 s = buf;
9674 e = NULL;
9675 path_end = path;
9676 while (*path_end != NUL)
9677 {
9678 /* May ignore a wildcard that has a backslash before it; it will
9679 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
9680 if (path_end >= path + wildoff && rem_backslash(path_end))
9681 *p++ = *path_end++;
9682 else if (*path_end == '/')
9683 {
9684 if (e != NULL)
9685 break;
9686 s = p + 1;
9687 }
9688 else if (path_end >= path + wildoff
Bram Moolenaar2d0b92f2012-04-30 21:09:43 +02009689 && (vim_strchr((char_u *)"*?[{~$", *path_end) != NULL
9690#ifndef CASE_INSENSITIVE_FILENAME
9691 || ((flags & EW_ICASE)
9692 && isalpha(PTR2CHAR(path_end)))
9693#endif
9694 ))
Bram Moolenaar231334e2005-07-25 20:46:57 +00009695 e = p;
9696#ifdef FEAT_MBYTE
9697 if (has_mbyte)
9698 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00009699 len = (*mb_ptr2len)(path_end);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009700 STRNCPY(p, path_end, len);
9701 p += len;
9702 path_end += len;
9703 }
9704 else
9705#endif
9706 *p++ = *path_end++;
9707 }
9708 e = p;
9709 *e = NUL;
9710
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009711 /* Now we have one wildcard component between "s" and "e". */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009712 /* Remove backslashes between "wildoff" and the start of the wildcard
9713 * component. */
9714 for (p = buf + wildoff; p < s; ++p)
9715 if (rem_backslash(p))
9716 {
Bram Moolenaar8c8de832008-06-24 22:58:06 +00009717 STRMOVE(p, p + 1);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009718 --e;
9719 --s;
9720 }
9721
9722 /* Check for "**" between "s" and "e". */
9723 for (p = s; p < e; ++p)
9724 if (p[0] == '*' && p[1] == '*')
9725 starstar = TRUE;
9726
9727 /* convert the file pattern to a regexp pattern */
9728 starts_with_dot = (*s == '.');
9729 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
9730 if (pat == NULL)
9731 {
9732 vim_free(buf);
9733 return 0;
9734 }
9735
9736 /* compile the regexp into a program */
Bram Moolenaarcc016f52005-12-10 20:23:46 +00009737#ifdef CASE_INSENSITIVE_FILENAME
Bram Moolenaar231334e2005-07-25 20:46:57 +00009738 regmatch.rm_ic = TRUE; /* Behave like Terminal.app */
9739#else
Bram Moolenaar94950a92010-12-02 16:01:29 +01009740 if (flags & EW_ICASE)
9741 regmatch.rm_ic = TRUE; /* 'wildignorecase' set */
9742 else
9743 regmatch.rm_ic = FALSE; /* Don't ignore case */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009744#endif
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009745 if (flags & (EW_NOERROR | EW_NOTWILD))
9746 ++emsg_silent;
Bram Moolenaar231334e2005-07-25 20:46:57 +00009747 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009748 if (flags & (EW_NOERROR | EW_NOTWILD))
9749 --emsg_silent;
Bram Moolenaar231334e2005-07-25 20:46:57 +00009750 vim_free(pat);
9751
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009752 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
Bram Moolenaar231334e2005-07-25 20:46:57 +00009753 {
9754 vim_free(buf);
9755 return 0;
9756 }
9757
9758 /* If "**" is by itself, this is the first time we encounter it and more
9759 * is following then find matches without any directory. */
9760 if (!didstar && stardepth < 100 && starstar && e - s == 2
9761 && *path_end == '/')
9762 {
9763 STRCPY(s, path_end + 1);
9764 ++stardepth;
9765 (void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
9766 --stardepth;
9767 }
9768
9769 /* open the directory for scanning */
9770 *s = NUL;
9771 dirp = opendir(*buf == NUL ? "." : (char *)buf);
9772
9773 /* Find all matching entries */
9774 if (dirp != NULL)
9775 {
9776 for (;;)
9777 {
9778 dp = readdir(dirp);
9779 if (dp == NULL)
9780 break;
9781 if ((dp->d_name[0] != '.' || starts_with_dot)
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009782 && ((regmatch.regprog != NULL && vim_regexec(&regmatch,
9783 (char_u *)dp->d_name, (colnr_T)0))
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009784 || ((flags & EW_NOTWILD)
9785 && fnamencmp(path + (s - buf), dp->d_name, e - s) == 0)))
Bram Moolenaar231334e2005-07-25 20:46:57 +00009786 {
9787 STRCPY(s, dp->d_name);
9788 len = STRLEN(buf);
9789
9790 if (starstar && stardepth < 100)
9791 {
9792 /* For "**" in the pattern first go deeper in the tree to
9793 * find matches. */
9794 STRCPY(buf + len, "/**");
9795 STRCPY(buf + len + 3, path_end);
9796 ++stardepth;
9797 (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
9798 --stardepth;
9799 }
9800
9801 STRCPY(buf + len, path_end);
9802 if (mch_has_exp_wildcard(path_end)) /* handle more wildcards */
9803 {
9804 /* need to expand another component of the path */
9805 /* remove backslashes for the remaining components only */
9806 (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
9807 }
9808 else
9809 {
9810 /* no more wildcards, check if there is a match */
9811 /* remove backslashes for the remaining components only */
9812 if (*path_end != NUL)
9813 backslash_halve(buf + len + 1);
9814 if (mch_getperm(buf) >= 0) /* add existing file */
9815 {
Bram Moolenaar95e9b492006-03-15 23:04:43 +00009816#ifdef MACOS_CONVERT
Bram Moolenaar231334e2005-07-25 20:46:57 +00009817 size_t precomp_len = STRLEN(buf)+1;
9818 char_u *precomp_buf =
9819 mac_precompose_path(buf, precomp_len, &precomp_len);
Bram Moolenaar95e9b492006-03-15 23:04:43 +00009820
Bram Moolenaar231334e2005-07-25 20:46:57 +00009821 if (precomp_buf)
9822 {
9823 mch_memmove(buf, precomp_buf, precomp_len);
9824 vim_free(precomp_buf);
9825 }
9826#endif
9827 addfile(gap, buf, flags);
9828 }
9829 }
9830 }
9831 }
9832
9833 closedir(dirp);
9834 }
9835
9836 vim_free(buf);
9837 vim_free(regmatch.regprog);
9838
9839 matches = gap->ga_len - start_len;
9840 if (matches > 0)
9841 qsort(((char_u **)gap->ga_data) + start_len, matches,
9842 sizeof(char_u *), pstrcmp);
9843 return matches;
9844}
9845#endif
9846
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009847#if defined(FEAT_SEARCHPATH)
9848static int find_previous_pathsep __ARGS((char_u *path, char_u **psep));
9849static int is_unique __ARGS((char_u *maybe_unique, garray_T *gap, int i));
Bram Moolenaar162bd912010-07-28 22:29:10 +02009850static void expand_path_option __ARGS((char_u *curdir, garray_T *gap));
9851static char_u *get_path_cutoff __ARGS((char_u *fname, garray_T *gap));
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009852static void uniquefy_paths __ARGS((garray_T *gap, char_u *pattern));
9853static int expand_in_path __ARGS((garray_T *gap, char_u *pattern, int flags));
9854
9855/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009856 * Moves "*psep" back to the previous path separator in "path".
9857 * Returns FAIL is "*psep" ends up at the beginning of "path".
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009858 */
9859 static int
9860find_previous_pathsep(path, psep)
9861 char_u *path;
9862 char_u **psep;
9863{
9864 /* skip the current separator */
9865 if (*psep > path && vim_ispathsep(**psep))
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009866 --*psep;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009867
9868 /* find the previous separator */
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009869 while (*psep > path)
9870 {
9871 if (vim_ispathsep(**psep))
9872 return OK;
9873 mb_ptr_back(path, *psep);
9874 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009875
9876 return FAIL;
9877}
9878
9879/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009880 * Returns TRUE if "maybe_unique" is unique wrt other_paths in "gap".
9881 * "maybe_unique" is the end portion of "((char_u **)gap->ga_data)[i]".
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009882 */
9883 static int
9884is_unique(maybe_unique, gap, i)
9885 char_u *maybe_unique;
9886 garray_T *gap;
9887 int i;
9888{
9889 int j;
9890 int candidate_len;
9891 int other_path_len;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009892 char_u **other_paths = (char_u **)gap->ga_data;
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009893 char_u *rival;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009894
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009895 for (j = 0; j < gap->ga_len; j++)
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009896 {
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009897 if (j == i)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009898 continue; /* don't compare it with itself */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009899
Bram Moolenaar624c7aa2010-07-16 20:38:52 +02009900 candidate_len = (int)STRLEN(maybe_unique);
9901 other_path_len = (int)STRLEN(other_paths[j]);
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009902 if (other_path_len < candidate_len)
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009903 continue; /* it's different when it's shorter */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009904
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009905 rival = other_paths[j] + other_path_len - candidate_len;
Bram Moolenaarda9836c2010-08-16 21:53:27 +02009906 if (fnamecmp(maybe_unique, rival) == 0
9907 && (rival == other_paths[j] || vim_ispathsep(*(rival - 1))))
Bram Moolenaar162bd912010-07-28 22:29:10 +02009908 return FALSE; /* match */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009909 }
9910
Bram Moolenaar162bd912010-07-28 22:29:10 +02009911 return TRUE; /* no match found */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009912}
9913
9914/*
Bram Moolenaar1a509df2010-08-01 17:59:57 +02009915 * Split the 'path' option into an array of strings in garray_T. Relative
Bram Moolenaar162bd912010-07-28 22:29:10 +02009916 * paths are expanded to their equivalent fullpath. This includes the "."
9917 * (relative to current buffer directory) and empty path (relative to current
9918 * directory) notations.
9919 *
9920 * TODO: handle upward search (;) and path limiter (**N) notations by
9921 * expanding each into their equivalent path(s).
9922 */
9923 static void
9924expand_path_option(curdir, gap)
9925 char_u *curdir;
9926 garray_T *gap;
9927{
9928 char_u *path_option = *curbuf->b_p_path == NUL
9929 ? p_path : curbuf->b_p_path;
9930 char_u *buf;
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009931 char_u *p;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009932 int len;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009933
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +02009934 if ((buf = alloc((int)MAXPATHL)) == NULL)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009935 return;
9936
9937 while (*path_option != NUL)
9938 {
9939 copy_option_part(&path_option, buf, MAXPATHL, " ,");
9940
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009941 if (buf[0] == '.' && (buf[1] == NUL || vim_ispathsep(buf[1])))
Bram Moolenaar162bd912010-07-28 22:29:10 +02009942 {
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009943 /* Relative to current buffer:
9944 * "/path/file" + "." -> "/path/"
9945 * "/path/file" + "./subdir" -> "/path/subdir" */
Bram Moolenaar162bd912010-07-28 22:29:10 +02009946 if (curbuf->b_ffname == NULL)
9947 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009948 p = gettail(curbuf->b_ffname);
9949 len = (int)(p - curbuf->b_ffname);
9950 if (len + (int)STRLEN(buf) >= MAXPATHL)
9951 continue;
9952 if (buf[1] == NUL)
9953 buf[len] = NUL;
9954 else
9955 STRMOVE(buf + len, buf + 2);
9956 mch_memmove(buf, curbuf->b_ffname, len);
9957 simplify_filename(buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009958 }
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009959 else if (buf[0] == NUL)
9960 /* relative to current directory */
Bram Moolenaar162bd912010-07-28 22:29:10 +02009961 STRCPY(buf, curdir);
Bram Moolenaar84f888a2010-08-05 21:40:16 +02009962 else if (path_with_url(buf))
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009963 /* URL can't be used here */
Bram Moolenaar84f888a2010-08-05 21:40:16 +02009964 continue;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009965 else if (!mch_isFullName(buf))
9966 {
9967 /* Expand relative path to their full path equivalent */
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009968 len = (int)STRLEN(curdir);
9969 if (len + (int)STRLEN(buf) + 3 > MAXPATHL)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009970 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009971 STRMOVE(buf + len + 1, buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009972 STRCPY(buf, curdir);
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009973 buf[len] = PATHSEP;
Bram Moolenaar57adda12010-08-03 22:11:29 +02009974 simplify_filename(buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009975 }
9976
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009977 if (ga_grow(gap, 1) == FAIL)
9978 break;
9979 p = vim_strsave(buf);
9980 if (p == NULL)
9981 break;
9982 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009983 }
9984
9985 vim_free(buf);
9986}
9987
9988/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009989 * Returns a pointer to the file or directory name in "fname" that matches the
9990 * longest path in "ga"p, or NULL if there is no match. For example:
Bram Moolenaar162bd912010-07-28 22:29:10 +02009991 *
9992 * path: /foo/bar/baz
9993 * fname: /foo/bar/baz/quux.txt
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009994 * returns: ^this
Bram Moolenaar162bd912010-07-28 22:29:10 +02009995 */
9996 static char_u *
9997get_path_cutoff(fname, gap)
9998 char_u *fname;
9999 garray_T *gap;
10000{
10001 int i;
10002 int maxlen = 0;
10003 char_u **path_part = (char_u **)gap->ga_data;
10004 char_u *cutoff = NULL;
10005
10006 for (i = 0; i < gap->ga_len; i++)
10007 {
10008 int j = 0;
10009
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010010 while ((fname[j] == path_part[i][j]
Bram Moolenaar2d7c47d2010-08-10 19:50:26 +020010011# if defined(MSWIN) || defined(MSDOS)
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010012 || (vim_ispathsep(fname[j]) && vim_ispathsep(path_part[i][j]))
10013#endif
10014 ) && fname[j] != NUL && path_part[i][j] != NUL)
Bram Moolenaar162bd912010-07-28 22:29:10 +020010015 j++;
10016 if (j > maxlen)
10017 {
10018 maxlen = j;
10019 cutoff = &fname[j];
10020 }
10021 }
10022
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010023 /* skip to the file or directory name */
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010024 if (cutoff != NULL)
Bram Moolenaar31710262010-08-13 13:36:15 +020010025 while (vim_ispathsep(*cutoff))
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010026 mb_ptr_adv(cutoff);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010027
10028 return cutoff;
10029}
10030
10031/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010032 * Sorts, removes duplicates and modifies all the fullpath names in "gap" so
10033 * that they are unique with respect to each other while conserving the part
10034 * that matches the pattern. Beware, this is at least O(n^2) wrt "gap->ga_len".
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010035 */
10036 static void
10037uniquefy_paths(gap, pattern)
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +020010038 garray_T *gap;
10039 char_u *pattern;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010040{
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +020010041 int i;
10042 int len;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010043 char_u **fnames = (char_u **)gap->ga_data;
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010044 int sort_again = FALSE;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010045 char_u *pat;
10046 char_u *file_pattern;
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010047 char_u *curdir;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010048 regmatch_T regmatch;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010049 garray_T path_ga;
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010050 char_u **in_curdir = NULL;
10051 char_u *short_name;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010052
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +020010053 remove_duplicates(gap);
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010054 ga_init2(&path_ga, (int)sizeof(char_u *), 1);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010055
10056 /*
10057 * We need to prepend a '*' at the beginning of file_pattern so that the
10058 * regex matches anywhere in the path. FIXME: is this valid for all
Bram Moolenaarb31e4382010-07-24 16:01:56 +020010059 * possible patterns?
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010060 */
Bram Moolenaar624c7aa2010-07-16 20:38:52 +020010061 len = (int)STRLEN(pattern);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010062 file_pattern = alloc(len + 2);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010063 if (file_pattern == NULL)
10064 return;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010065 file_pattern[0] = '*';
Bram Moolenaar162bd912010-07-28 22:29:10 +020010066 file_pattern[1] = NUL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010067 STRCAT(file_pattern, pattern);
10068 pat = file_pat_to_reg_pat(file_pattern, NULL, NULL, TRUE);
10069 vim_free(file_pattern);
Bram Moolenaarb31e4382010-07-24 16:01:56 +020010070 if (pat == NULL)
10071 return;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010072
Bram Moolenaarb31e4382010-07-24 16:01:56 +020010073 regmatch.rm_ic = TRUE; /* always ignore case */
10074 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
10075 vim_free(pat);
10076 if (regmatch.regprog == NULL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010077 return;
10078
Bram Moolenaar162bd912010-07-28 22:29:10 +020010079 if ((curdir = alloc((int)(MAXPATHL))) == NULL)
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010080 goto theend;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010081 mch_dirname(curdir, MAXPATHL);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010082 expand_path_option(curdir, &path_ga);
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010083
10084 in_curdir = (char_u **)alloc_clear(gap->ga_len * sizeof(char_u *));
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010085 if (in_curdir == NULL)
10086 goto theend;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010087
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010088 for (i = 0; i < gap->ga_len && !got_int; i++)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010089 {
Bram Moolenaar162bd912010-07-28 22:29:10 +020010090 char_u *path = fnames[i];
10091 int is_in_curdir;
Bram Moolenaar31710262010-08-13 13:36:15 +020010092 char_u *dir_end = gettail_dir(path);
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010093 char_u *pathsep_p;
10094 char_u *path_cutoff;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010095
Bram Moolenaar624c7aa2010-07-16 20:38:52 +020010096 len = (int)STRLEN(path);
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010097 is_in_curdir = fnamencmp(curdir, path, dir_end - path) == 0
Bram Moolenaar162bd912010-07-28 22:29:10 +020010098 && curdir[dir_end - path] == NUL;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010099 if (is_in_curdir)
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010100 in_curdir[i] = vim_strsave(path);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010101
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010102 /* Shorten the filename while maintaining its uniqueness */
10103 path_cutoff = get_path_cutoff(path, &path_ga);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010104
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010105 /* we start at the end of the path */
10106 pathsep_p = path + len - 1;
10107
10108 while (find_previous_pathsep(path, &pathsep_p))
10109 if (vim_regexec(&regmatch, pathsep_p + 1, (colnr_T)0)
10110 && is_unique(pathsep_p + 1, gap, i)
10111 && path_cutoff != NULL && pathsep_p + 1 >= path_cutoff)
10112 {
10113 sort_again = TRUE;
10114 mch_memmove(path, pathsep_p + 1, STRLEN(pathsep_p));
10115 break;
10116 }
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010117
10118 if (mch_isFullName(path))
10119 {
10120 /*
10121 * Last resort: shorten relative to curdir if possible.
10122 * 'possible' means:
10123 * 1. It is under the current directory.
10124 * 2. The result is actually shorter than the original.
10125 *
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010126 * Before curdir After
10127 * /foo/bar/file.txt /foo/bar ./file.txt
10128 * c:\foo\bar\file.txt c:\foo\bar .\file.txt
10129 * /file.txt / /file.txt
10130 * c:\file.txt c:\ .\file.txt
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010131 */
10132 short_name = shorten_fname(path, curdir);
Bram Moolenaar31710262010-08-13 13:36:15 +020010133 if (short_name != NULL && short_name > path + 1
10134#if defined(MSWIN) || defined(MSDOS)
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010135 /* On windows,
Bram Moolenaar31710262010-08-13 13:36:15 +020010136 * shorten_fname("c:\a\a.txt", "c:\a\b")
Bram Moolenaar31710262010-08-13 13:36:15 +020010137 * returns "\a\a.txt", which is not really the short
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010138 * name, hence: */
Bram Moolenaar31710262010-08-13 13:36:15 +020010139 && !vim_ispathsep(*short_name)
10140#endif
10141 )
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010142 {
10143 STRCPY(path, ".");
10144 add_pathsep(path);
Bram Moolenaarcda000e2010-08-14 13:34:39 +020010145 STRMOVE(path + STRLEN(path), short_name);
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010146 }
10147 }
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010148 ui_breakcheck();
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010149 }
10150
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010151 /* Shorten filenames in /in/current/directory/{filename} */
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010152 for (i = 0; i < gap->ga_len && !got_int; i++)
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010153 {
10154 char_u *rel_path;
10155 char_u *path = in_curdir[i];
10156
10157 if (path == NULL)
10158 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010159
10160 /* If the {filename} is not unique, change it to ./{filename}.
10161 * Else reduce it to {filename} */
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010162 short_name = shorten_fname(path, curdir);
10163 if (short_name == NULL)
10164 short_name = path;
10165 if (is_unique(short_name, gap, i))
10166 {
10167 STRCPY(fnames[i], short_name);
10168 continue;
10169 }
10170
10171 rel_path = alloc((int)(STRLEN(short_name) + STRLEN(PATHSEPSTR) + 2));
10172 if (rel_path == NULL)
10173 goto theend;
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010174 STRCPY(rel_path, ".");
10175 add_pathsep(rel_path);
10176 STRCAT(rel_path, short_name);
10177
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010178 vim_free(fnames[i]);
10179 fnames[i] = rel_path;
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010180 sort_again = TRUE;
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010181 ui_breakcheck();
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010182 }
10183
Bram Moolenaar162bd912010-07-28 22:29:10 +020010184theend:
10185 vim_free(curdir);
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010186 if (in_curdir != NULL)
10187 {
10188 for (i = 0; i < gap->ga_len; i++)
10189 vim_free(in_curdir[i]);
10190 vim_free(in_curdir);
10191 }
Bram Moolenaar162bd912010-07-28 22:29:10 +020010192 ga_clear_strings(&path_ga);
Bram Moolenaarb31e4382010-07-24 16:01:56 +020010193 vim_free(regmatch.regprog);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010194
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010195 if (sort_again)
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +020010196 remove_duplicates(gap);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010197}
10198
10199/*
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010200 * Calls globpath() with 'path' values for the given pattern and stores the
10201 * result in "gap".
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010202 * Returns the total number of matches.
10203 */
10204 static int
10205expand_in_path(gap, pattern, flags)
10206 garray_T *gap;
10207 char_u *pattern;
10208 int flags; /* EW_* flags */
10209{
Bram Moolenaar162bd912010-07-28 22:29:10 +020010210 char_u *curdir;
10211 garray_T path_ga;
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010212 char_u *files = NULL;
10213 char_u *s; /* start */
10214 char_u *e; /* end */
10215 char_u *paths = NULL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010216
Bram Moolenaar7f0f6212010-08-03 22:21:00 +020010217 if ((curdir = alloc((unsigned)MAXPATHL)) == NULL)
Bram Moolenaar162bd912010-07-28 22:29:10 +020010218 return 0;
10219 mch_dirname(curdir, MAXPATHL);
10220
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010221 ga_init2(&path_ga, (int)sizeof(char_u *), 1);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010222 expand_path_option(curdir, &path_ga);
10223 vim_free(curdir);
Bram Moolenaar006d2b02010-08-04 12:39:44 +020010224 if (path_ga.ga_len == 0)
10225 return 0;
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010226
10227 paths = ga_concat_strings(&path_ga);
10228 ga_clear_strings(&path_ga);
10229 if (paths == NULL)
Bram Moolenaar7f0f6212010-08-03 22:21:00 +020010230 return 0;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010231
Bram Moolenaar94950a92010-12-02 16:01:29 +010010232 files = globpath(paths, pattern, (flags & EW_ICASE) ? WILD_ICASE : 0);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010233 vim_free(paths);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010234 if (files == NULL)
10235 return 0;
10236
10237 /* Copy each path in files into gap */
10238 s = e = files;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010239 while (*s != NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010240 {
Bram Moolenaar162bd912010-07-28 22:29:10 +020010241 while (*e != '\n' && *e != NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010242 e++;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010243 if (*e == NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010244 {
10245 addfile(gap, s, flags);
10246 break;
10247 }
10248 else
10249 {
10250 /* *e is '\n' */
Bram Moolenaar162bd912010-07-28 22:29:10 +020010251 *e = NUL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010252 addfile(gap, s, flags);
10253 e++;
10254 s = e;
10255 }
10256 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010257 vim_free(files);
10258
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010259 return gap->ga_len;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010260}
10261#endif
10262
Bram Moolenaar1587a1e2010-07-29 20:59:59 +020010263#if defined(FEAT_SEARCHPATH) || defined(FEAT_CMDL_COMPL) || defined(PROTO)
10264/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010265 * Sort "gap" and remove duplicate entries. "gap" is expected to contain a
10266 * list of file names in allocated memory.
Bram Moolenaar1587a1e2010-07-29 20:59:59 +020010267 */
10268 void
10269remove_duplicates(gap)
10270 garray_T *gap;
10271{
10272 int i;
10273 int j;
10274 char_u **fnames = (char_u **)gap->ga_data;
10275
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010276 sort_strings(fnames, gap->ga_len);
Bram Moolenaar1587a1e2010-07-29 20:59:59 +020010277 for (i = gap->ga_len - 1; i > 0; --i)
10278 if (fnamecmp(fnames[i - 1], fnames[i]) == 0)
10279 {
10280 vim_free(fnames[i]);
10281 for (j = i + 1; j < gap->ga_len; ++j)
10282 fnames[j - 1] = fnames[j];
10283 --gap->ga_len;
10284 }
10285}
10286#endif
10287
Bram Moolenaar071d4272004-06-13 20:20:40 +000010288/*
10289 * Generic wildcard expansion code.
10290 *
10291 * Characters in "pat" that should not be expanded must be preceded with a
10292 * backslash. E.g., "/path\ with\ spaces/my\*star*"
10293 *
10294 * Return FAIL when no single file was found. In this case "num_file" is not
10295 * set, and "file" may contain an error message.
10296 * Return OK when some files found. "num_file" is set to the number of
10297 * matches, "file" to the array of matches. Call FreeWild() later.
10298 */
10299 int
10300gen_expand_wildcards(num_pat, pat, num_file, file, flags)
10301 int num_pat; /* number of input patterns */
10302 char_u **pat; /* array of input patterns */
10303 int *num_file; /* resulting number of files */
10304 char_u ***file; /* array of resulting files */
10305 int flags; /* EW_* flags */
10306{
10307 int i;
10308 garray_T ga;
10309 char_u *p;
10310 static int recursive = FALSE;
10311 int add_pat;
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010312#if defined(FEAT_SEARCHPATH)
10313 int did_expand_in_path = FALSE;
10314#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000010315
10316 /*
10317 * expand_env() is called to expand things like "~user". If this fails,
10318 * it calls ExpandOne(), which brings us back here. In this case, always
10319 * call the machine specific expansion function, if possible. Otherwise,
10320 * return FAIL.
10321 */
10322 if (recursive)
10323#ifdef SPECIAL_WILDCHAR
10324 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
10325#else
10326 return FAIL;
10327#endif
10328
10329#ifdef SPECIAL_WILDCHAR
10330 /*
10331 * If there are any special wildcard characters which we cannot handle
10332 * here, call machine specific function for all the expansion. This
10333 * avoids starting the shell for each argument separately.
10334 * For `=expr` do use the internal function.
10335 */
10336 for (i = 0; i < num_pat; i++)
10337 {
10338 if (vim_strpbrk(pat[i], (char_u *)SPECIAL_WILDCHAR) != NULL
10339# ifdef VIM_BACKTICK
10340 && !(vim_backtick(pat[i]) && pat[i][1] == '=')
10341# endif
10342 )
10343 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
10344 }
10345#endif
10346
10347 recursive = TRUE;
10348
10349 /*
10350 * The matching file names are stored in a growarray. Init it empty.
10351 */
10352 ga_init2(&ga, (int)sizeof(char_u *), 30);
10353
10354 for (i = 0; i < num_pat; ++i)
10355 {
10356 add_pat = -1;
10357 p = pat[i];
10358
10359#ifdef VIM_BACKTICK
10360 if (vim_backtick(p))
10361 add_pat = expand_backtick(&ga, p, flags);
10362 else
10363#endif
10364 {
10365 /*
10366 * First expand environment variables, "~/" and "~user/".
10367 */
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010368 if (vim_strchr(p, '$') != NULL || *p == '~')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010369 {
Bram Moolenaar9f0545d2007-09-26 20:36:32 +000010370 p = expand_env_save_opt(p, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010371 if (p == NULL)
10372 p = pat[i];
10373#ifdef UNIX
10374 /*
10375 * On Unix, if expand_env() can't expand an environment
10376 * variable, use the shell to do that. Discard previously
10377 * found file names and start all over again.
10378 */
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010379 else if (vim_strchr(p, '$') != NULL || *p == '~')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010380 {
10381 vim_free(p);
Bram Moolenaar782027e2009-06-24 14:25:49 +000010382 ga_clear_strings(&ga);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010383 i = mch_expand_wildcards(num_pat, pat, num_file, file,
10384 flags);
10385 recursive = FALSE;
10386 return i;
10387 }
10388#endif
10389 }
10390
10391 /*
10392 * If there are wildcards: Expand file names and add each match to
10393 * the list. If there is no match, and EW_NOTFOUND is given, add
10394 * the pattern.
10395 * If there are no wildcards: Add the file name if it exists or
10396 * when EW_NOTFOUND is given.
10397 */
10398 if (mch_has_exp_wildcard(p))
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010399 {
10400#if defined(FEAT_SEARCHPATH)
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010401 if ((flags & EW_PATH)
10402 && !mch_isFullName(p)
10403 && !(p[0] == '.'
10404 && (vim_ispathsep(p[1])
10405 || (p[1] == '.' && vim_ispathsep(p[2]))))
10406 )
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010407 {
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010408 /* :find completion where 'path' is used.
10409 * Recursiveness is OK here. */
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010410 recursive = FALSE;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010411 add_pat = expand_in_path(&ga, p, flags);
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010412 recursive = TRUE;
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010413 did_expand_in_path = TRUE;
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010414 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010415 else
10416#endif
10417 add_pat = mch_expandpath(&ga, p, flags);
10418 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010419 }
10420
10421 if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
10422 {
10423 char_u *t = backslash_halve_save(p);
10424
10425#if defined(MACOS_CLASSIC)
10426 slash_to_colon(t);
10427#endif
10428 /* When EW_NOTFOUND is used, always add files and dirs. Makes
10429 * "vim c:/" work. */
10430 if (flags & EW_NOTFOUND)
10431 addfile(&ga, t, flags | EW_DIR | EW_FILE);
10432 else if (mch_getperm(t) >= 0)
10433 addfile(&ga, t, flags);
10434 vim_free(t);
10435 }
10436
Bram Moolenaarb28ebbc2010-07-14 16:59:57 +020010437#if defined(FEAT_SEARCHPATH)
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010438 if (did_expand_in_path && ga.ga_len > 0 && (flags & EW_PATH))
Bram Moolenaarb28ebbc2010-07-14 16:59:57 +020010439 uniquefy_paths(&ga, p);
10440#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000010441 if (p != pat[i])
10442 vim_free(p);
10443 }
10444
10445 *num_file = ga.ga_len;
10446 *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data : (char_u **)"";
10447
10448 recursive = FALSE;
10449
10450 return (ga.ga_data != NULL) ? OK : FAIL;
10451}
10452
10453# ifdef VIM_BACKTICK
10454
10455/*
10456 * Return TRUE if we can expand this backtick thing here.
10457 */
10458 static int
10459vim_backtick(p)
10460 char_u *p;
10461{
10462 return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
10463}
10464
10465/*
10466 * Expand an item in `backticks` by executing it as a command.
10467 * Currently only works when pat[] starts and ends with a `.
10468 * Returns number of file names found.
10469 */
10470 static int
10471expand_backtick(gap, pat, flags)
10472 garray_T *gap;
10473 char_u *pat;
10474 int flags; /* EW_* flags */
10475{
10476 char_u *p;
10477 char_u *cmd;
10478 char_u *buffer;
10479 int cnt = 0;
10480 int i;
10481
10482 /* Create the command: lop off the backticks. */
10483 cmd = vim_strnsave(pat + 1, (int)STRLEN(pat) - 2);
10484 if (cmd == NULL)
10485 return 0;
10486
10487#ifdef FEAT_EVAL
10488 if (*cmd == '=') /* `={expr}`: Expand expression */
Bram Moolenaar362e1a32006-03-06 23:29:24 +000010489 buffer = eval_to_string(cmd + 1, &p, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010490 else
10491#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010492 buffer = get_cmd_output(cmd, NULL,
10493 (flags & EW_SILENT) ? SHELL_SILENT : 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010494 vim_free(cmd);
10495 if (buffer == NULL)
10496 return 0;
10497
10498 cmd = buffer;
10499 while (*cmd != NUL)
10500 {
10501 cmd = skipwhite(cmd); /* skip over white space */
10502 p = cmd;
10503 while (*p != NUL && *p != '\r' && *p != '\n') /* skip over entry */
10504 ++p;
10505 /* add an entry if it is not empty */
10506 if (p > cmd)
10507 {
10508 i = *p;
10509 *p = NUL;
10510 addfile(gap, cmd, flags);
10511 *p = i;
10512 ++cnt;
10513 }
10514 cmd = p;
10515 while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
10516 ++cmd;
10517 }
10518
10519 vim_free(buffer);
10520 return cnt;
10521}
10522# endif /* VIM_BACKTICK */
10523
10524/*
10525 * Add a file to a file list. Accepted flags:
10526 * EW_DIR add directories
10527 * EW_FILE add files
Bram Moolenaar1f35bf92006-03-07 22:38:47 +000010528 * EW_EXEC add executable files
Bram Moolenaar071d4272004-06-13 20:20:40 +000010529 * EW_NOTFOUND add even when it doesn't exist
10530 * EW_ADDSLASH add slash after directory name
10531 */
10532 void
10533addfile(gap, f, flags)
10534 garray_T *gap;
10535 char_u *f; /* filename */
10536 int flags;
10537{
10538 char_u *p;
10539 int isdir;
10540
10541 /* if the file/dir doesn't exist, may not add it */
10542 if (!(flags & EW_NOTFOUND) && mch_getperm(f) < 0)
10543 return;
10544
10545#ifdef FNAME_ILLEGAL
10546 /* if the file/dir contains illegal characters, don't add it */
10547 if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
10548 return;
10549#endif
10550
10551 isdir = mch_isdir(f);
10552 if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
10553 return;
10554
Bram Moolenaar1f35bf92006-03-07 22:38:47 +000010555 /* If the file isn't executable, may not add it. Do accept directories. */
10556 if (!isdir && (flags & EW_EXEC) && !mch_can_exe(f))
10557 return;
10558
Bram Moolenaar071d4272004-06-13 20:20:40 +000010559 /* Make room for another item in the file list. */
10560 if (ga_grow(gap, 1) == FAIL)
10561 return;
10562
10563 p = alloc((unsigned)(STRLEN(f) + 1 + isdir));
10564 if (p == NULL)
10565 return;
10566
10567 STRCPY(p, f);
10568#ifdef BACKSLASH_IN_FILENAME
10569 slash_adjust(p);
10570#endif
10571 /*
10572 * Append a slash or backslash after directory names if none is present.
10573 */
10574#ifndef DONT_ADD_PATHSEP_TO_DIR
10575 if (isdir && (flags & EW_ADDSLASH))
10576 add_pathsep(p);
10577#endif
10578 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010579}
10580#endif /* !NO_EXPANDPATH */
10581
10582#if defined(VIM_BACKTICK) || defined(FEAT_EVAL) || defined(PROTO)
10583
10584#ifndef SEEK_SET
10585# define SEEK_SET 0
10586#endif
10587#ifndef SEEK_END
10588# define SEEK_END 2
10589#endif
10590
10591/*
10592 * Get the stdout of an external command.
10593 * Returns an allocated string, or NULL for error.
10594 */
10595 char_u *
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010596get_cmd_output(cmd, infile, flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010597 char_u *cmd;
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010598 char_u *infile; /* optional input file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010599 int flags; /* can be SHELL_SILENT */
10600{
10601 char_u *tempname;
10602 char_u *command;
10603 char_u *buffer = NULL;
10604 int len;
10605 int i = 0;
10606 FILE *fd;
10607
10608 if (check_restricted() || check_secure())
10609 return NULL;
10610
10611 /* get a name for the temp file */
10612 if ((tempname = vim_tempname('o')) == NULL)
10613 {
10614 EMSG(_(e_notmp));
10615 return NULL;
10616 }
10617
10618 /* Add the redirection stuff */
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010619 command = make_filter_cmd(cmd, infile, tempname);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010620 if (command == NULL)
10621 goto done;
10622
10623 /*
10624 * Call the shell to execute the command (errors are ignored).
10625 * Don't check timestamps here.
10626 */
10627 ++no_check_timestamps;
10628 call_shell(command, SHELL_DOOUT | SHELL_EXPAND | flags);
10629 --no_check_timestamps;
10630
10631 vim_free(command);
10632
10633 /*
10634 * read the names from the file into memory
10635 */
10636# ifdef VMS
Bram Moolenaar25394022007-05-10 19:06:20 +000010637 /* created temporary file is not always readable as binary */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010638 fd = mch_fopen((char *)tempname, "r");
10639# else
10640 fd = mch_fopen((char *)tempname, READBIN);
10641# endif
10642
10643 if (fd == NULL)
10644 {
10645 EMSG2(_(e_notopen), tempname);
10646 goto done;
10647 }
10648
10649 fseek(fd, 0L, SEEK_END);
10650 len = ftell(fd); /* get size of temp file */
10651 fseek(fd, 0L, SEEK_SET);
10652
10653 buffer = alloc(len + 1);
10654 if (buffer != NULL)
10655 i = (int)fread((char *)buffer, (size_t)1, (size_t)len, fd);
10656 fclose(fd);
10657 mch_remove(tempname);
10658 if (buffer == NULL)
10659 goto done;
10660#ifdef VMS
10661 len = i; /* VMS doesn't give us what we asked for... */
10662#endif
10663 if (i != len)
10664 {
10665 EMSG2(_(e_notread), tempname);
10666 vim_free(buffer);
10667 buffer = NULL;
10668 }
10669 else
Bram Moolenaar162bd912010-07-28 22:29:10 +020010670 buffer[len] = NUL; /* make sure the buffer is terminated */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010671
10672done:
10673 vim_free(tempname);
10674 return buffer;
10675}
10676#endif
10677
10678/*
10679 * Free the list of files returned by expand_wildcards() or other expansion
10680 * functions.
10681 */
10682 void
10683FreeWild(count, files)
10684 int count;
10685 char_u **files;
10686{
Bram Moolenaarfc1421e2006-04-20 22:17:20 +000010687 if (count <= 0 || files == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010688 return;
10689#if defined(__EMX__) && defined(__ALWAYS_HAS_TRAILING_NULL_POINTER) /* XXX */
10690 /*
10691 * Is this still OK for when other functions than expand_wildcards() have
10692 * been used???
10693 */
10694 _fnexplodefree((char **)files);
10695#else
10696 while (count--)
10697 vim_free(files[count]);
10698 vim_free(files);
10699#endif
10700}
10701
10702/*
Bram Moolenaara9dc3752010-07-11 20:46:53 +020010703 * Return TRUE when need to go to Insert mode because of 'insertmode'.
Bram Moolenaar071d4272004-06-13 20:20:40 +000010704 * Don't do this when still processing a command or a mapping.
10705 * Don't do this when inside a ":normal" command.
10706 */
10707 int
10708goto_im()
10709{
10710 return (p_im && stuff_empty() && typebuf_typed());
10711}