blob: 69ede43ff2530abbb69a2a9481d949a96f261918 [file] [log] [blame]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001/* vi:set ts=8 sts=4 sw=4:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * misc1.c: functions that didn't seem to fit elsewhere
12 */
13
14#include "vim.h"
15#include "version.h"
16
Bram Moolenaar071d4272004-06-13 20:20:40 +000017static char_u *vim_version_dir __ARGS((char_u *vimdir));
18static char_u *remove_tail __ARGS((char_u *p, char_u *pend, char_u *name));
Bram Moolenaar071d4272004-06-13 20:20:40 +000019static int copy_indent __ARGS((int size, char_u *src));
20
21/*
22 * Count the size (in window cells) of the indent in the current line.
23 */
24 int
25get_indent()
26{
27 return get_indent_str(ml_get_curline(), (int)curbuf->b_p_ts);
28}
29
30/*
31 * Count the size (in window cells) of the indent in line "lnum".
32 */
33 int
34get_indent_lnum(lnum)
35 linenr_T lnum;
36{
37 return get_indent_str(ml_get(lnum), (int)curbuf->b_p_ts);
38}
39
40#if defined(FEAT_FOLDING) || defined(PROTO)
41/*
42 * Count the size (in window cells) of the indent in line "lnum" of buffer
43 * "buf".
44 */
45 int
46get_indent_buf(buf, lnum)
47 buf_T *buf;
48 linenr_T lnum;
49{
50 return get_indent_str(ml_get_buf(buf, lnum, FALSE), (int)buf->b_p_ts);
51}
52#endif
53
54/*
55 * count the size (in window cells) of the indent in line "ptr", with
56 * 'tabstop' at "ts"
57 */
Bram Moolenaar4399ef42005-02-12 14:29:27 +000058 int
Bram Moolenaar071d4272004-06-13 20:20:40 +000059get_indent_str(ptr, ts)
60 char_u *ptr;
61 int ts;
62{
63 int count = 0;
64
65 for ( ; *ptr; ++ptr)
66 {
67 if (*ptr == TAB) /* count a tab for what it is worth */
68 count += ts - (count % ts);
69 else if (*ptr == ' ')
70 ++count; /* count a space for one */
71 else
72 break;
73 }
Bram Moolenaar4399ef42005-02-12 14:29:27 +000074 return count;
Bram Moolenaar071d4272004-06-13 20:20:40 +000075}
76
77/*
78 * Set the indent of the current line.
79 * Leaves the cursor on the first non-blank in the line.
80 * Caller must take care of undo.
81 * "flags":
82 * SIN_CHANGED: call changed_bytes() if the line was changed.
83 * SIN_INSERT: insert the indent in front of the line.
84 * SIN_UNDO: save line for undo before changing it.
85 * Returns TRUE if the line was changed.
86 */
87 int
88set_indent(size, flags)
Bram Moolenaar5002c292007-07-24 13:26:15 +000089 int size; /* measured in spaces */
Bram Moolenaar071d4272004-06-13 20:20:40 +000090 int flags;
91{
92 char_u *p;
93 char_u *newline;
94 char_u *oldline;
95 char_u *s;
96 int todo;
Bram Moolenaar5002c292007-07-24 13:26:15 +000097 int ind_len; /* measured in characters */
Bram Moolenaar071d4272004-06-13 20:20:40 +000098 int line_len;
99 int doit = FALSE;
Bram Moolenaar5002c292007-07-24 13:26:15 +0000100 int ind_done = 0; /* measured in spaces */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000101 int tab_pad;
Bram Moolenaar5409c052005-03-18 20:27:04 +0000102 int retval = FALSE;
Bram Moolenaar4d64b782007-08-14 20:16:42 +0000103 int orig_char_len = -1; /* number of initial whitespace chars when
Bram Moolenaar5002c292007-07-24 13:26:15 +0000104 'et' and 'pi' are both set */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000105
106 /*
107 * First check if there is anything to do and compute the number of
108 * characters needed for the indent.
109 */
110 todo = size;
111 ind_len = 0;
112 p = oldline = ml_get_curline();
113
114 /* Calculate the buffer size for the new indent, and check to see if it
115 * isn't already set */
116
Bram Moolenaar5002c292007-07-24 13:26:15 +0000117 /* if 'expandtab' isn't set: use TABs; if both 'expandtab' and
118 * 'preserveindent' are set count the number of characters at the
119 * beginning of the line to be copied */
120 if (!curbuf->b_p_et || (!(flags & SIN_INSERT) && curbuf->b_p_pi))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000121 {
122 /* If 'preserveindent' is set then reuse as much as possible of
123 * the existing indent structure for the new indent */
124 if (!(flags & SIN_INSERT) && curbuf->b_p_pi)
125 {
126 ind_done = 0;
127
128 /* count as many characters as we can use */
129 while (todo > 0 && vim_iswhite(*p))
130 {
131 if (*p == TAB)
132 {
133 tab_pad = (int)curbuf->b_p_ts
134 - (ind_done % (int)curbuf->b_p_ts);
135 /* stop if this tab will overshoot the target */
136 if (todo < tab_pad)
137 break;
138 todo -= tab_pad;
139 ++ind_len;
140 ind_done += tab_pad;
141 }
142 else
143 {
144 --todo;
145 ++ind_len;
146 ++ind_done;
147 }
148 ++p;
149 }
150
Bram Moolenaar5002c292007-07-24 13:26:15 +0000151 /* Set initial number of whitespace chars to copy if we are
152 * preserving indent but expandtab is set */
153 if (curbuf->b_p_et)
154 orig_char_len = ind_len;
155
Bram Moolenaar071d4272004-06-13 20:20:40 +0000156 /* Fill to next tabstop with a tab, if possible */
157 tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
Bram Moolenaar4d64b782007-08-14 20:16:42 +0000158 if (todo >= tab_pad && orig_char_len == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000159 {
160 doit = TRUE;
161 todo -= tab_pad;
162 ++ind_len;
163 /* ind_done += tab_pad; */
164 }
165 }
166
167 /* count tabs required for indent */
168 while (todo >= (int)curbuf->b_p_ts)
169 {
170 if (*p != TAB)
171 doit = TRUE;
172 else
173 ++p;
174 todo -= (int)curbuf->b_p_ts;
175 ++ind_len;
176 /* ind_done += (int)curbuf->b_p_ts; */
177 }
178 }
179 /* count spaces required for indent */
180 while (todo > 0)
181 {
182 if (*p != ' ')
183 doit = TRUE;
184 else
185 ++p;
186 --todo;
187 ++ind_len;
188 /* ++ind_done; */
189 }
190
191 /* Return if the indent is OK already. */
192 if (!doit && !vim_iswhite(*p) && !(flags & SIN_INSERT))
193 return FALSE;
194
195 /* Allocate memory for the new line. */
196 if (flags & SIN_INSERT)
197 p = oldline;
198 else
199 p = skipwhite(p);
200 line_len = (int)STRLEN(p) + 1;
Bram Moolenaar5002c292007-07-24 13:26:15 +0000201
202 /* If 'preserveindent' and 'expandtab' are both set keep the original
203 * characters and allocate accordingly. We will fill the rest with spaces
204 * after the if (!curbuf->b_p_et) below. */
Bram Moolenaar4d64b782007-08-14 20:16:42 +0000205 if (orig_char_len != -1)
Bram Moolenaar5002c292007-07-24 13:26:15 +0000206 {
207 newline = alloc(orig_char_len + size - ind_done + line_len);
208 if (newline == NULL)
209 return FALSE;
Bram Moolenaar4d64b782007-08-14 20:16:42 +0000210 todo = size - ind_done;
211 ind_len = orig_char_len + todo; /* Set total length of indent in
212 * characters, which may have been
213 * undercounted until now */
Bram Moolenaar5002c292007-07-24 13:26:15 +0000214 p = oldline;
215 s = newline;
216 while (orig_char_len > 0)
217 {
218 *s++ = *p++;
219 orig_char_len--;
220 }
Bram Moolenaar913626c2008-01-03 11:43:42 +0000221
Bram Moolenaar5002c292007-07-24 13:26:15 +0000222 /* Skip over any additional white space (useful when newindent is less
223 * than old) */
224 while (vim_iswhite(*p))
Bram Moolenaar913626c2008-01-03 11:43:42 +0000225 ++p;
Bram Moolenaarcc00b952007-08-11 12:32:57 +0000226
Bram Moolenaar5002c292007-07-24 13:26:15 +0000227 }
228 else
229 {
230 todo = size;
231 newline = alloc(ind_len + line_len);
232 if (newline == NULL)
233 return FALSE;
234 s = newline;
235 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000236
237 /* Put the characters in the new line. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000238 /* if 'expandtab' isn't set: use TABs */
239 if (!curbuf->b_p_et)
240 {
241 /* If 'preserveindent' is set then reuse as much as possible of
242 * the existing indent structure for the new indent */
243 if (!(flags & SIN_INSERT) && curbuf->b_p_pi)
244 {
245 p = oldline;
246 ind_done = 0;
247
248 while (todo > 0 && vim_iswhite(*p))
249 {
250 if (*p == TAB)
251 {
252 tab_pad = (int)curbuf->b_p_ts
253 - (ind_done % (int)curbuf->b_p_ts);
254 /* stop if this tab will overshoot the target */
255 if (todo < tab_pad)
256 break;
257 todo -= tab_pad;
258 ind_done += tab_pad;
259 }
260 else
261 {
262 --todo;
263 ++ind_done;
264 }
265 *s++ = *p++;
266 }
267
268 /* Fill to next tabstop with a tab, if possible */
269 tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
270 if (todo >= tab_pad)
271 {
272 *s++ = TAB;
273 todo -= tab_pad;
274 }
275
276 p = skipwhite(p);
277 }
278
279 while (todo >= (int)curbuf->b_p_ts)
280 {
281 *s++ = TAB;
282 todo -= (int)curbuf->b_p_ts;
283 }
284 }
285 while (todo > 0)
286 {
287 *s++ = ' ';
288 --todo;
289 }
290 mch_memmove(s, p, (size_t)line_len);
291
292 /* Replace the line (unless undo fails). */
293 if (!(flags & SIN_UNDO) || u_savesub(curwin->w_cursor.lnum) == OK)
294 {
295 ml_replace(curwin->w_cursor.lnum, newline, FALSE);
296 if (flags & SIN_CHANGED)
297 changed_bytes(curwin->w_cursor.lnum, 0);
298 /* Correct saved cursor position if it's after the indent. */
299 if (saved_cursor.lnum == curwin->w_cursor.lnum
300 && saved_cursor.col >= (colnr_T)(p - oldline))
Bram Moolenaara93fa7e2006-04-17 22:14:47 +0000301 saved_cursor.col += ind_len - (colnr_T)(p - oldline);
Bram Moolenaar5409c052005-03-18 20:27:04 +0000302 retval = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000303 }
304 else
305 vim_free(newline);
306
307 curwin->w_cursor.col = ind_len;
Bram Moolenaar5409c052005-03-18 20:27:04 +0000308 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000309}
310
311/*
312 * Copy the indent from ptr to the current line (and fill to size)
313 * Leaves the cursor on the first non-blank in the line.
314 * Returns TRUE if the line was changed.
315 */
316 static int
317copy_indent(size, src)
318 int size;
319 char_u *src;
320{
321 char_u *p = NULL;
322 char_u *line = NULL;
323 char_u *s;
324 int todo;
325 int ind_len;
326 int line_len = 0;
327 int tab_pad;
328 int ind_done;
329 int round;
330
331 /* Round 1: compute the number of characters needed for the indent
332 * Round 2: copy the characters. */
333 for (round = 1; round <= 2; ++round)
334 {
335 todo = size;
336 ind_len = 0;
337 ind_done = 0;
338 s = src;
339
340 /* Count/copy the usable portion of the source line */
341 while (todo > 0 && vim_iswhite(*s))
342 {
343 if (*s == TAB)
344 {
345 tab_pad = (int)curbuf->b_p_ts
346 - (ind_done % (int)curbuf->b_p_ts);
347 /* Stop if this tab will overshoot the target */
348 if (todo < tab_pad)
349 break;
350 todo -= tab_pad;
351 ind_done += tab_pad;
352 }
353 else
354 {
355 --todo;
356 ++ind_done;
357 }
358 ++ind_len;
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000359 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000360 *p++ = *s;
361 ++s;
362 }
363
364 /* Fill to next tabstop with a tab, if possible */
365 tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
Bram Moolenaarc42e7ed2011-09-07 19:58:09 +0200366 if (todo >= tab_pad && !curbuf->b_p_et)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000367 {
368 todo -= tab_pad;
369 ++ind_len;
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000370 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000371 *p++ = TAB;
372 }
373
374 /* Add tabs required for indent */
Bram Moolenaarc42e7ed2011-09-07 19:58:09 +0200375 while (todo >= (int)curbuf->b_p_ts && !curbuf->b_p_et)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000376 {
377 todo -= (int)curbuf->b_p_ts;
378 ++ind_len;
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000379 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000380 *p++ = TAB;
381 }
382
383 /* Count/add spaces required for indent */
384 while (todo > 0)
385 {
386 --todo;
387 ++ind_len;
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000388 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000389 *p++ = ' ';
390 }
391
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000392 if (p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000393 {
394 /* Allocate memory for the result: the copied indent, new indent
395 * and the rest of the line. */
396 line_len = (int)STRLEN(ml_get_curline()) + 1;
397 line = alloc(ind_len + line_len);
398 if (line == NULL)
399 return FALSE;
400 p = line;
401 }
402 }
403
404 /* Append the original line */
405 mch_memmove(p, ml_get_curline(), (size_t)line_len);
406
407 /* Replace the line */
408 ml_replace(curwin->w_cursor.lnum, line, FALSE);
409
410 /* Put the cursor after the indent. */
411 curwin->w_cursor.col = ind_len;
412 return TRUE;
413}
414
415/*
416 * Return the indent of the current line after a number. Return -1 if no
417 * number was found. Used for 'n' in 'formatoptions': numbered list.
Bram Moolenaar86b68352004-12-27 21:59:20 +0000418 * Since a pattern is used it can actually handle more than numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000419 */
420 int
421get_number_indent(lnum)
422 linenr_T lnum;
423{
Bram Moolenaar071d4272004-06-13 20:20:40 +0000424 colnr_T col;
425 pos_T pos;
426
Bram Moolenaar96b7ca52012-06-29 15:04:49 +0200427 regmatch_T regmatch;
428 int lead_len = 0; /* length of comment leader */
429
Bram Moolenaar071d4272004-06-13 20:20:40 +0000430 if (lnum > curbuf->b_ml.ml_line_count)
431 return -1;
Bram Moolenaar86b68352004-12-27 21:59:20 +0000432 pos.lnum = 0;
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200433
434#ifdef FEAT_COMMENTS
Bram Moolenaar96b7ca52012-06-29 15:04:49 +0200435 /* In format_lines() (i.e. not insert mode), fo+=q is needed too... */
436 if ((State & INSERT) || has_format_option(FO_Q_COMS))
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200437 lead_len = get_leader_len(ml_get(lnum), NULL, FALSE, TRUE);
Bram Moolenaar86b68352004-12-27 21:59:20 +0000438#endif
Bram Moolenaar96b7ca52012-06-29 15:04:49 +0200439 regmatch.regprog = vim_regcomp(curbuf->b_p_flp, RE_MAGIC);
440 if (regmatch.regprog != NULL)
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200441 {
Bram Moolenaar96b7ca52012-06-29 15:04:49 +0200442 regmatch.rm_ic = FALSE;
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200443
Bram Moolenaar96b7ca52012-06-29 15:04:49 +0200444 /* vim_regexec() expects a pointer to a line. This lets us
445 * start matching for the flp beyond any comment leader... */
446 if (vim_regexec(&regmatch, ml_get(lnum) + lead_len, (colnr_T)0))
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200447 {
Bram Moolenaar96b7ca52012-06-29 15:04:49 +0200448 pos.lnum = lnum;
449 pos.col = (colnr_T)(*regmatch.endp - ml_get(lnum));
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200450#ifdef FEAT_VIRTUALEDIT
Bram Moolenaar96b7ca52012-06-29 15:04:49 +0200451 pos.coladd = 0;
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200452#endif
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200453 }
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200454 }
Bram Moolenaar96b7ca52012-06-29 15:04:49 +0200455 vim_free(regmatch.regprog);
Bram Moolenaar86b68352004-12-27 21:59:20 +0000456
457 if (pos.lnum == 0 || *ml_get_pos(&pos) == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000458 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000459 getvcol(curwin, &pos, &col, NULL, NULL);
460 return (int)col;
461}
462
463#if defined(FEAT_CINDENT) || defined(FEAT_SMARTINDENT)
464
465static int cin_is_cinword __ARGS((char_u *line));
466
467/*
468 * Return TRUE if the string "line" starts with a word from 'cinwords'.
469 */
470 static int
471cin_is_cinword(line)
472 char_u *line;
473{
474 char_u *cinw;
475 char_u *cinw_buf;
476 int cinw_len;
477 int retval = FALSE;
478 int len;
479
480 cinw_len = (int)STRLEN(curbuf->b_p_cinw) + 1;
481 cinw_buf = alloc((unsigned)cinw_len);
482 if (cinw_buf != NULL)
483 {
484 line = skipwhite(line);
485 for (cinw = curbuf->b_p_cinw; *cinw; )
486 {
487 len = copy_option_part(&cinw, cinw_buf, cinw_len, ",");
488 if (STRNCMP(line, cinw_buf, len) == 0
489 && (!vim_iswordc(line[len]) || !vim_iswordc(line[len - 1])))
490 {
491 retval = TRUE;
492 break;
493 }
494 }
495 vim_free(cinw_buf);
496 }
497 return retval;
498}
499#endif
500
501/*
502 * open_line: Add a new line below or above the current line.
503 *
504 * For VREPLACE mode, we only add a new line when we get to the end of the
505 * file, otherwise we just start replacing the next line.
506 *
507 * Caller must take care of undo. Since VREPLACE may affect any number of
508 * lines however, it may call u_save_cursor() again when starting to change a
509 * new line.
510 * "flags": OPENLINE_DELSPACES delete spaces after cursor
511 * OPENLINE_DO_COM format comments
512 * OPENLINE_KEEPTRAIL keep trailing spaces
513 * OPENLINE_MARKFIX adjust mark positions after the line break
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200514 * OPENLINE_COM_LIST format comments with list or 2nd line indent
515 *
516 * "second_line_indent": indent for after ^^D in Insert mode or if flag
517 * OPENLINE_COM_LIST
Bram Moolenaar071d4272004-06-13 20:20:40 +0000518 *
519 * Return TRUE for success, FALSE for failure
520 */
521 int
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200522open_line(dir, flags, second_line_indent)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000523 int dir; /* FORWARD or BACKWARD */
524 int flags;
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200525 int second_line_indent;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000526{
527 char_u *saved_line; /* copy of the original line */
528 char_u *next_line = NULL; /* copy of the next line */
529 char_u *p_extra = NULL; /* what goes to next line */
530 int less_cols = 0; /* less columns for mark in new line */
531 int less_cols_off = 0; /* columns to skip for mark adjust */
532 pos_T old_cursor; /* old cursor position */
533 int newcol = 0; /* new cursor column */
534 int newindent = 0; /* auto-indent of the new line */
535 int n;
536 int trunc_line = FALSE; /* truncate current line afterwards */
537 int retval = FALSE; /* return value, default is FAIL */
538#ifdef FEAT_COMMENTS
539 int extra_len = 0; /* length of p_extra string */
540 int lead_len; /* length of comment leader */
541 char_u *lead_flags; /* position in 'comments' for comment leader */
542 char_u *leader = NULL; /* copy of comment leader */
543#endif
544 char_u *allocated = NULL; /* allocated memory */
545#if defined(FEAT_SMARTINDENT) || defined(FEAT_VREPLACE) || defined(FEAT_LISP) \
546 || defined(FEAT_CINDENT) || defined(FEAT_COMMENTS)
547 char_u *p;
548#endif
549 int saved_char = NUL; /* init for GCC */
550#if defined(FEAT_SMARTINDENT) || defined(FEAT_COMMENTS)
551 pos_T *pos;
552#endif
553#ifdef FEAT_SMARTINDENT
554 int do_si = (!p_paste && curbuf->b_p_si
555# ifdef FEAT_CINDENT
556 && !curbuf->b_p_cin
557# endif
558 );
559 int no_si = FALSE; /* reset did_si afterwards */
560 int first_char = NUL; /* init for GCC */
561#endif
562#if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
563 int vreplace_mode;
564#endif
565 int did_append; /* appended a new line */
566 int saved_pi = curbuf->b_p_pi; /* copy of preserveindent setting */
567
568 /*
569 * make a copy of the current line so we can mess with it
570 */
571 saved_line = vim_strsave(ml_get_curline());
572 if (saved_line == NULL) /* out of memory! */
573 return FALSE;
574
575#ifdef FEAT_VREPLACE
576 if (State & VREPLACE_FLAG)
577 {
578 /*
579 * With VREPLACE we make a copy of the next line, which we will be
580 * starting to replace. First make the new line empty and let vim play
581 * with the indenting and comment leader to its heart's content. Then
582 * we grab what it ended up putting on the new line, put back the
583 * original line, and call ins_char() to put each new character onto
584 * the line, replacing what was there before and pushing the right
585 * stuff onto the replace stack. -- webb.
586 */
587 if (curwin->w_cursor.lnum < orig_line_count)
588 next_line = vim_strsave(ml_get(curwin->w_cursor.lnum + 1));
589 else
590 next_line = vim_strsave((char_u *)"");
591 if (next_line == NULL) /* out of memory! */
592 goto theend;
593
594 /*
595 * In VREPLACE mode, a NL replaces the rest of the line, and starts
596 * replacing the next line, so push all of the characters left on the
597 * line onto the replace stack. We'll push any other characters that
598 * might be replaced at the start of the next line (due to autoindent
599 * etc) a bit later.
600 */
601 replace_push(NUL); /* Call twice because BS over NL expects it */
602 replace_push(NUL);
603 p = saved_line + curwin->w_cursor.col;
604 while (*p != NUL)
Bram Moolenaar2c994e82008-01-02 16:49:36 +0000605 {
606#ifdef FEAT_MBYTE
607 if (has_mbyte)
608 p += replace_push_mb(p);
609 else
610#endif
611 replace_push(*p++);
612 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000613 saved_line[curwin->w_cursor.col] = NUL;
614 }
615#endif
616
617 if ((State & INSERT)
618#ifdef FEAT_VREPLACE
619 && !(State & VREPLACE_FLAG)
620#endif
621 )
622 {
623 p_extra = saved_line + curwin->w_cursor.col;
624#ifdef FEAT_SMARTINDENT
625 if (do_si) /* need first char after new line break */
626 {
627 p = skipwhite(p_extra);
628 first_char = *p;
629 }
630#endif
631#ifdef FEAT_COMMENTS
632 extra_len = (int)STRLEN(p_extra);
633#endif
634 saved_char = *p_extra;
635 *p_extra = NUL;
636 }
637
638 u_clearline(); /* cannot do "U" command when adding lines */
639#ifdef FEAT_SMARTINDENT
640 did_si = FALSE;
641#endif
642 ai_col = 0;
643
644 /*
645 * If we just did an auto-indent, then we didn't type anything on
646 * the prior line, and it should be truncated. Do this even if 'ai' is not
647 * set because automatically inserting a comment leader also sets did_ai.
648 */
649 if (dir == FORWARD && did_ai)
650 trunc_line = TRUE;
651
652 /*
653 * If 'autoindent' and/or 'smartindent' is set, try to figure out what
654 * indent to use for the new line.
655 */
656 if (curbuf->b_p_ai
657#ifdef FEAT_SMARTINDENT
658 || do_si
659#endif
660 )
661 {
662 /*
663 * count white space on current line
664 */
665 newindent = get_indent_str(saved_line, (int)curbuf->b_p_ts);
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200666 if (newindent == 0 && !(flags & OPENLINE_COM_LIST))
667 newindent = second_line_indent; /* for ^^D command in insert mode */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000668
669#ifdef FEAT_SMARTINDENT
670 /*
671 * Do smart indenting.
672 * In insert/replace mode (only when dir == FORWARD)
673 * we may move some text to the next line. If it starts with '{'
674 * don't add an indent. Fixes inserting a NL before '{' in line
675 * "if (condition) {"
676 */
677 if (!trunc_line && do_si && *saved_line != NUL
678 && (p_extra == NULL || first_char != '{'))
679 {
680 char_u *ptr;
681 char_u last_char;
682
683 old_cursor = curwin->w_cursor;
684 ptr = saved_line;
685# ifdef FEAT_COMMENTS
686 if (flags & OPENLINE_DO_COM)
Bram Moolenaar81340392012-06-06 16:12:59 +0200687 lead_len = get_leader_len(ptr, NULL, FALSE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000688 else
689 lead_len = 0;
690# endif
691 if (dir == FORWARD)
692 {
693 /*
694 * Skip preprocessor directives, unless they are
695 * recognised as comments.
696 */
697 if (
698# ifdef FEAT_COMMENTS
699 lead_len == 0 &&
700# endif
701 ptr[0] == '#')
702 {
703 while (ptr[0] == '#' && curwin->w_cursor.lnum > 1)
704 ptr = ml_get(--curwin->w_cursor.lnum);
705 newindent = get_indent();
706 }
707# ifdef FEAT_COMMENTS
708 if (flags & OPENLINE_DO_COM)
Bram Moolenaar81340392012-06-06 16:12:59 +0200709 lead_len = get_leader_len(ptr, NULL, FALSE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000710 else
711 lead_len = 0;
712 if (lead_len > 0)
713 {
714 /*
715 * This case gets the following right:
716 * \*
717 * * A comment (read '\' as '/').
718 * *\
719 * #define IN_THE_WAY
720 * This should line up here;
721 */
722 p = skipwhite(ptr);
723 if (p[0] == '/' && p[1] == '*')
724 p++;
725 if (p[0] == '*')
726 {
727 for (p++; *p; p++)
728 {
729 if (p[0] == '/' && p[-1] == '*')
730 {
731 /*
732 * End of C comment, indent should line up
733 * with the line containing the start of
734 * the comment
735 */
736 curwin->w_cursor.col = (colnr_T)(p - ptr);
737 if ((pos = findmatch(NULL, NUL)) != NULL)
738 {
739 curwin->w_cursor.lnum = pos->lnum;
740 newindent = get_indent();
741 }
742 }
743 }
744 }
745 }
746 else /* Not a comment line */
747# endif
748 {
749 /* Find last non-blank in line */
750 p = ptr + STRLEN(ptr) - 1;
751 while (p > ptr && vim_iswhite(*p))
752 --p;
753 last_char = *p;
754
755 /*
756 * find the character just before the '{' or ';'
757 */
758 if (last_char == '{' || last_char == ';')
759 {
760 if (p > ptr)
761 --p;
762 while (p > ptr && vim_iswhite(*p))
763 --p;
764 }
765 /*
766 * Try to catch lines that are split over multiple
767 * lines. eg:
768 * if (condition &&
769 * condition) {
770 * Should line up here!
771 * }
772 */
773 if (*p == ')')
774 {
775 curwin->w_cursor.col = (colnr_T)(p - ptr);
776 if ((pos = findmatch(NULL, '(')) != NULL)
777 {
778 curwin->w_cursor.lnum = pos->lnum;
779 newindent = get_indent();
780 ptr = ml_get_curline();
781 }
782 }
783 /*
784 * If last character is '{' do indent, without
785 * checking for "if" and the like.
786 */
787 if (last_char == '{')
788 {
789 did_si = TRUE; /* do indent */
790 no_si = TRUE; /* don't delete it when '{' typed */
791 }
792 /*
793 * Look for "if" and the like, use 'cinwords'.
794 * Don't do this if the previous line ended in ';' or
795 * '}'.
796 */
797 else if (last_char != ';' && last_char != '}'
798 && cin_is_cinword(ptr))
799 did_si = TRUE;
800 }
801 }
802 else /* dir == BACKWARD */
803 {
804 /*
805 * Skip preprocessor directives, unless they are
806 * recognised as comments.
807 */
808 if (
809# ifdef FEAT_COMMENTS
810 lead_len == 0 &&
811# endif
812 ptr[0] == '#')
813 {
814 int was_backslashed = FALSE;
815
816 while ((ptr[0] == '#' || was_backslashed) &&
817 curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
818 {
819 if (*ptr && ptr[STRLEN(ptr) - 1] == '\\')
820 was_backslashed = TRUE;
821 else
822 was_backslashed = FALSE;
823 ptr = ml_get(++curwin->w_cursor.lnum);
824 }
825 if (was_backslashed)
826 newindent = 0; /* Got to end of file */
827 else
828 newindent = get_indent();
829 }
830 p = skipwhite(ptr);
831 if (*p == '}') /* if line starts with '}': do indent */
832 did_si = TRUE;
833 else /* can delete indent when '{' typed */
834 can_si_back = TRUE;
835 }
836 curwin->w_cursor = old_cursor;
837 }
838 if (do_si)
839 can_si = TRUE;
840#endif /* FEAT_SMARTINDENT */
841
842 did_ai = TRUE;
843 }
844
845#ifdef FEAT_COMMENTS
846 /*
847 * Find out if the current line starts with a comment leader.
848 * This may then be inserted in front of the new line.
849 */
850 end_comment_pending = NUL;
851 if (flags & OPENLINE_DO_COM)
Bram Moolenaar81340392012-06-06 16:12:59 +0200852 lead_len = get_leader_len(saved_line, &lead_flags, dir == BACKWARD, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000853 else
854 lead_len = 0;
855 if (lead_len > 0)
856 {
857 char_u *lead_repl = NULL; /* replaces comment leader */
858 int lead_repl_len = 0; /* length of *lead_repl */
859 char_u lead_middle[COM_MAX_LEN]; /* middle-comment string */
860 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
861 char_u *comment_end = NULL; /* where lead_end has been found */
862 int extra_space = FALSE; /* append extra space */
863 int current_flag;
864 int require_blank = FALSE; /* requires blank after middle */
865 char_u *p2;
866
867 /*
868 * If the comment leader has the start, middle or end flag, it may not
869 * be used or may be replaced with the middle leader.
870 */
871 for (p = lead_flags; *p && *p != ':'; ++p)
872 {
873 if (*p == COM_BLANK)
874 {
875 require_blank = TRUE;
876 continue;
877 }
878 if (*p == COM_START || *p == COM_MIDDLE)
879 {
880 current_flag = *p;
881 if (*p == COM_START)
882 {
883 /*
884 * Doing "O" on a start of comment does not insert leader.
885 */
886 if (dir == BACKWARD)
887 {
888 lead_len = 0;
889 break;
890 }
891
892 /* find start of middle part */
893 (void)copy_option_part(&p, lead_middle, COM_MAX_LEN, ",");
894 require_blank = FALSE;
895 }
896
897 /*
898 * Isolate the strings of the middle and end leader.
899 */
900 while (*p && p[-1] != ':') /* find end of middle flags */
901 {
902 if (*p == COM_BLANK)
903 require_blank = TRUE;
904 ++p;
905 }
906 (void)copy_option_part(&p, lead_middle, COM_MAX_LEN, ",");
907
908 while (*p && p[-1] != ':') /* find end of end flags */
909 {
910 /* Check whether we allow automatic ending of comments */
911 if (*p == COM_AUTO_END)
912 end_comment_pending = -1; /* means we want to set it */
913 ++p;
914 }
915 n = copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
916
917 if (end_comment_pending == -1) /* we can set it now */
918 end_comment_pending = lead_end[n - 1];
919
920 /*
921 * If the end of the comment is in the same line, don't use
922 * the comment leader.
923 */
924 if (dir == FORWARD)
925 {
926 for (p = saved_line + lead_len; *p; ++p)
927 if (STRNCMP(p, lead_end, n) == 0)
928 {
929 comment_end = p;
930 lead_len = 0;
931 break;
932 }
933 }
934
935 /*
936 * Doing "o" on a start of comment inserts the middle leader.
937 */
938 if (lead_len > 0)
939 {
940 if (current_flag == COM_START)
941 {
942 lead_repl = lead_middle;
943 lead_repl_len = (int)STRLEN(lead_middle);
944 }
945
946 /*
947 * If we have hit RETURN immediately after the start
948 * comment leader, then put a space after the middle
949 * comment leader on the next line.
950 */
951 if (!vim_iswhite(saved_line[lead_len - 1])
952 && ((p_extra != NULL
953 && (int)curwin->w_cursor.col == lead_len)
954 || (p_extra == NULL
955 && saved_line[lead_len] == NUL)
956 || require_blank))
957 extra_space = TRUE;
958 }
959 break;
960 }
961 if (*p == COM_END)
962 {
963 /*
964 * Doing "o" on the end of a comment does not insert leader.
965 * Remember where the end is, might want to use it to find the
966 * start (for C-comments).
967 */
968 if (dir == FORWARD)
969 {
970 comment_end = skipwhite(saved_line);
971 lead_len = 0;
972 break;
973 }
974
975 /*
976 * Doing "O" on the end of a comment inserts the middle leader.
977 * Find the string for the middle leader, searching backwards.
978 */
979 while (p > curbuf->b_p_com && *p != ',')
980 --p;
981 for (lead_repl = p; lead_repl > curbuf->b_p_com
982 && lead_repl[-1] != ':'; --lead_repl)
983 ;
984 lead_repl_len = (int)(p - lead_repl);
985
986 /* We can probably always add an extra space when doing "O" on
987 * the comment-end */
988 extra_space = TRUE;
989
990 /* Check whether we allow automatic ending of comments */
991 for (p2 = p; *p2 && *p2 != ':'; p2++)
992 {
993 if (*p2 == COM_AUTO_END)
994 end_comment_pending = -1; /* means we want to set it */
995 }
996 if (end_comment_pending == -1)
997 {
998 /* Find last character in end-comment string */
999 while (*p2 && *p2 != ',')
1000 p2++;
1001 end_comment_pending = p2[-1];
1002 }
1003 break;
1004 }
1005 if (*p == COM_FIRST)
1006 {
1007 /*
1008 * Comment leader for first line only: Don't repeat leader
1009 * when using "O", blank out leader when using "o".
1010 */
1011 if (dir == BACKWARD)
1012 lead_len = 0;
1013 else
1014 {
1015 lead_repl = (char_u *)"";
1016 lead_repl_len = 0;
1017 }
1018 break;
1019 }
1020 }
1021 if (lead_len)
1022 {
Bram Moolenaardc7e85e2012-06-20 12:40:08 +02001023 /* allocate buffer (may concatenate p_extra later) */
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +02001024 leader = alloc(lead_len + lead_repl_len + extra_space + extra_len
Bram Moolenaardc7e85e2012-06-20 12:40:08 +02001025 + (second_line_indent > 0 ? second_line_indent : 0) + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001026 allocated = leader; /* remember to free it later */
1027
1028 if (leader == NULL)
1029 lead_len = 0;
1030 else
1031 {
Bram Moolenaarce0842a2005-07-18 21:58:11 +00001032 vim_strncpy(leader, saved_line, lead_len);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001033
1034 /*
1035 * Replace leader with lead_repl, right or left adjusted
1036 */
1037 if (lead_repl != NULL)
1038 {
1039 int c = 0;
1040 int off = 0;
1041
Bram Moolenaard7d5b472009-11-11 16:30:08 +00001042 for (p = lead_flags; *p != NUL && *p != ':'; )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001043 {
1044 if (*p == COM_RIGHT || *p == COM_LEFT)
Bram Moolenaard7d5b472009-11-11 16:30:08 +00001045 c = *p++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001046 else if (VIM_ISDIGIT(*p) || *p == '-')
1047 off = getdigits(&p);
Bram Moolenaard7d5b472009-11-11 16:30:08 +00001048 else
1049 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001050 }
1051 if (c == COM_RIGHT) /* right adjusted leader */
1052 {
1053 /* find last non-white in the leader to line up with */
1054 for (p = leader + lead_len - 1; p > leader
1055 && vim_iswhite(*p); --p)
1056 ;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001057 ++p;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001058
1059#ifdef FEAT_MBYTE
1060 /* Compute the length of the replaced characters in
1061 * screen characters, not bytes. */
1062 {
1063 int repl_size = vim_strnsize(lead_repl,
1064 lead_repl_len);
1065 int old_size = 0;
1066 char_u *endp = p;
1067 int l;
1068
1069 while (old_size < repl_size && p > leader)
1070 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001071 mb_ptr_back(leader, p);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001072 old_size += ptr2cells(p);
1073 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001074 l = lead_repl_len - (int)(endp - p);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001075 if (l != 0)
1076 mch_memmove(endp + l, endp,
1077 (size_t)((leader + lead_len) - endp));
1078 lead_len += l;
1079 }
1080#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001081 if (p < leader + lead_repl_len)
1082 p = leader;
1083 else
1084 p -= lead_repl_len;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001085#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001086 mch_memmove(p, lead_repl, (size_t)lead_repl_len);
1087 if (p + lead_repl_len > leader + lead_len)
1088 p[lead_repl_len] = NUL;
1089
1090 /* blank-out any other chars from the old leader. */
1091 while (--p >= leader)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001092 {
1093#ifdef FEAT_MBYTE
1094 int l = mb_head_off(leader, p);
1095
1096 if (l > 1)
1097 {
1098 p -= l;
1099 if (ptr2cells(p) > 1)
1100 {
1101 p[1] = ' ';
1102 --l;
1103 }
1104 mch_memmove(p + 1, p + l + 1,
1105 (size_t)((leader + lead_len) - (p + l + 1)));
1106 lead_len -= l;
1107 *p = ' ';
1108 }
1109 else
1110#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001111 if (!vim_iswhite(*p))
1112 *p = ' ';
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001113 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001114 }
1115 else /* left adjusted leader */
1116 {
1117 p = skipwhite(leader);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001118#ifdef FEAT_MBYTE
1119 /* Compute the length of the replaced characters in
1120 * screen characters, not bytes. Move the part that is
1121 * not to be overwritten. */
1122 {
1123 int repl_size = vim_strnsize(lead_repl,
1124 lead_repl_len);
1125 int i;
1126 int l;
1127
1128 for (i = 0; p[i] != NUL && i < lead_len; i += l)
1129 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00001130 l = (*mb_ptr2len)(p + i);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001131 if (vim_strnsize(p, i + l) > repl_size)
1132 break;
1133 }
1134 if (i != lead_repl_len)
1135 {
1136 mch_memmove(p + lead_repl_len, p + i,
Bram Moolenaar2d7ff052009-11-17 15:08:26 +00001137 (size_t)(lead_len - i - (p - leader)));
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001138 lead_len += lead_repl_len - i;
1139 }
1140 }
1141#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001142 mch_memmove(p, lead_repl, (size_t)lead_repl_len);
1143
1144 /* Replace any remaining non-white chars in the old
1145 * leader by spaces. Keep Tabs, the indent must
1146 * remain the same. */
1147 for (p += lead_repl_len; p < leader + lead_len; ++p)
1148 if (!vim_iswhite(*p))
1149 {
1150 /* Don't put a space before a TAB. */
1151 if (p + 1 < leader + lead_len && p[1] == TAB)
1152 {
1153 --lead_len;
1154 mch_memmove(p, p + 1,
1155 (leader + lead_len) - p);
1156 }
1157 else
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001158 {
1159#ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00001160 int l = (*mb_ptr2len)(p);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001161
1162 if (l > 1)
1163 {
1164 if (ptr2cells(p) > 1)
1165 {
1166 /* Replace a double-wide char with
1167 * two spaces */
1168 --l;
1169 *p++ = ' ';
1170 }
1171 mch_memmove(p + 1, p + l,
1172 (leader + lead_len) - p);
1173 lead_len -= l - 1;
1174 }
1175#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001176 *p = ' ';
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001177 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001178 }
1179 *p = NUL;
1180 }
1181
1182 /* Recompute the indent, it may have changed. */
1183 if (curbuf->b_p_ai
1184#ifdef FEAT_SMARTINDENT
1185 || do_si
1186#endif
1187 )
1188 newindent = get_indent_str(leader, (int)curbuf->b_p_ts);
1189
1190 /* Add the indent offset */
1191 if (newindent + off < 0)
1192 {
1193 off = -newindent;
1194 newindent = 0;
1195 }
1196 else
1197 newindent += off;
1198
1199 /* Correct trailing spaces for the shift, so that
1200 * alignment remains equal. */
1201 while (off > 0 && lead_len > 0
1202 && leader[lead_len - 1] == ' ')
1203 {
1204 /* Don't do it when there is a tab before the space */
1205 if (vim_strchr(skipwhite(leader), '\t') != NULL)
1206 break;
1207 --lead_len;
1208 --off;
1209 }
1210
1211 /* If the leader ends in white space, don't add an
1212 * extra space */
1213 if (lead_len > 0 && vim_iswhite(leader[lead_len - 1]))
1214 extra_space = FALSE;
1215 leader[lead_len] = NUL;
1216 }
1217
1218 if (extra_space)
1219 {
1220 leader[lead_len++] = ' ';
1221 leader[lead_len] = NUL;
1222 }
1223
1224 newcol = lead_len;
1225
1226 /*
1227 * if a new indent will be set below, remove the indent that
1228 * is in the comment leader
1229 */
1230 if (newindent
1231#ifdef FEAT_SMARTINDENT
1232 || did_si
1233#endif
1234 )
1235 {
1236 while (lead_len && vim_iswhite(*leader))
1237 {
1238 --lead_len;
1239 --newcol;
1240 ++leader;
1241 }
1242 }
1243
1244 }
1245#ifdef FEAT_SMARTINDENT
1246 did_si = can_si = FALSE;
1247#endif
1248 }
1249 else if (comment_end != NULL)
1250 {
1251 /*
1252 * We have finished a comment, so we don't use the leader.
1253 * If this was a C-comment and 'ai' or 'si' is set do a normal
1254 * indent to align with the line containing the start of the
1255 * comment.
1256 */
1257 if (comment_end[0] == '*' && comment_end[1] == '/' &&
1258 (curbuf->b_p_ai
1259#ifdef FEAT_SMARTINDENT
1260 || do_si
1261#endif
1262 ))
1263 {
1264 old_cursor = curwin->w_cursor;
1265 curwin->w_cursor.col = (colnr_T)(comment_end - saved_line);
1266 if ((pos = findmatch(NULL, NUL)) != NULL)
1267 {
1268 curwin->w_cursor.lnum = pos->lnum;
1269 newindent = get_indent();
1270 }
1271 curwin->w_cursor = old_cursor;
1272 }
1273 }
1274 }
1275#endif
1276
1277 /* (State == INSERT || State == REPLACE), only when dir == FORWARD */
1278 if (p_extra != NULL)
1279 {
1280 *p_extra = saved_char; /* restore char that NUL replaced */
1281
1282 /*
1283 * When 'ai' set or "flags" has OPENLINE_DELSPACES, skip to the first
1284 * non-blank.
1285 *
1286 * When in REPLACE mode, put the deleted blanks on the replace stack,
1287 * preceded by a NUL, so they can be put back when a BS is entered.
1288 */
1289 if (REPLACE_NORMAL(State))
1290 replace_push(NUL); /* end of extra blanks */
1291 if (curbuf->b_p_ai || (flags & OPENLINE_DELSPACES))
1292 {
1293 while ((*p_extra == ' ' || *p_extra == '\t')
1294#ifdef FEAT_MBYTE
1295 && (!enc_utf8
1296 || !utf_iscomposing(utf_ptr2char(p_extra + 1)))
1297#endif
1298 )
1299 {
1300 if (REPLACE_NORMAL(State))
1301 replace_push(*p_extra);
1302 ++p_extra;
1303 ++less_cols_off;
1304 }
1305 }
1306 if (*p_extra != NUL)
1307 did_ai = FALSE; /* append some text, don't truncate now */
1308
1309 /* columns for marks adjusted for removed columns */
1310 less_cols = (int)(p_extra - saved_line);
1311 }
1312
1313 if (p_extra == NULL)
1314 p_extra = (char_u *)""; /* append empty line */
1315
1316#ifdef FEAT_COMMENTS
1317 /* concatenate leader and p_extra, if there is a leader */
1318 if (lead_len)
1319 {
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +02001320 if (flags & OPENLINE_COM_LIST && second_line_indent > 0)
1321 {
1322 int i;
Bram Moolenaar36105782012-06-14 20:59:25 +02001323 int padding = second_line_indent
1324 - (newindent + (int)STRLEN(leader));
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +02001325
1326 /* Here whitespace is inserted after the comment char.
1327 * Below, set_indent(newindent, SIN_INSERT) will insert the
1328 * whitespace needed before the comment char. */
1329 for (i = 0; i < padding; i++)
1330 {
1331 STRCAT(leader, " ");
Bram Moolenaar5fb9ec52012-07-25 16:10:03 +02001332 less_cols--;
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +02001333 newcol++;
1334 }
1335 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001336 STRCAT(leader, p_extra);
1337 p_extra = leader;
1338 did_ai = TRUE; /* So truncating blanks works with comments */
1339 less_cols -= lead_len;
1340 }
1341 else
1342 end_comment_pending = NUL; /* turns out there was no leader */
1343#endif
1344
1345 old_cursor = curwin->w_cursor;
1346 if (dir == BACKWARD)
1347 --curwin->w_cursor.lnum;
1348#ifdef FEAT_VREPLACE
1349 if (!(State & VREPLACE_FLAG) || old_cursor.lnum >= orig_line_count)
1350#endif
1351 {
1352 if (ml_append(curwin->w_cursor.lnum, p_extra, (colnr_T)0, FALSE)
1353 == FAIL)
1354 goto theend;
1355 /* Postpone calling changed_lines(), because it would mess up folding
1356 * with markers. */
1357 mark_adjust(curwin->w_cursor.lnum + 1, (linenr_T)MAXLNUM, 1L, 0L);
1358 did_append = TRUE;
1359 }
1360#ifdef FEAT_VREPLACE
1361 else
1362 {
1363 /*
1364 * In VREPLACE mode we are starting to replace the next line.
1365 */
1366 curwin->w_cursor.lnum++;
1367 if (curwin->w_cursor.lnum >= Insstart.lnum + vr_lines_changed)
1368 {
1369 /* In case we NL to a new line, BS to the previous one, and NL
1370 * again, we don't want to save the new line for undo twice.
1371 */
1372 (void)u_save_cursor(); /* errors are ignored! */
1373 vr_lines_changed++;
1374 }
1375 ml_replace(curwin->w_cursor.lnum, p_extra, TRUE);
1376 changed_bytes(curwin->w_cursor.lnum, 0);
1377 curwin->w_cursor.lnum--;
1378 did_append = FALSE;
1379 }
1380#endif
1381
1382 if (newindent
1383#ifdef FEAT_SMARTINDENT
1384 || did_si
1385#endif
1386 )
1387 {
1388 ++curwin->w_cursor.lnum;
1389#ifdef FEAT_SMARTINDENT
1390 if (did_si)
1391 {
1392 if (p_sr)
1393 newindent -= newindent % (int)curbuf->b_p_sw;
1394 newindent += (int)curbuf->b_p_sw;
1395 }
1396#endif
Bram Moolenaar5002c292007-07-24 13:26:15 +00001397 /* Copy the indent */
1398 if (curbuf->b_p_ci)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001399 {
1400 (void)copy_indent(newindent, saved_line);
1401
1402 /*
1403 * Set the 'preserveindent' option so that any further screwing
1404 * with the line doesn't entirely destroy our efforts to preserve
1405 * it. It gets restored at the function end.
1406 */
1407 curbuf->b_p_pi = TRUE;
1408 }
1409 else
1410 (void)set_indent(newindent, SIN_INSERT);
1411 less_cols -= curwin->w_cursor.col;
1412
1413 ai_col = curwin->w_cursor.col;
1414
1415 /*
1416 * In REPLACE mode, for each character in the new indent, there must
1417 * be a NUL on the replace stack, for when it is deleted with BS
1418 */
1419 if (REPLACE_NORMAL(State))
1420 for (n = 0; n < (int)curwin->w_cursor.col; ++n)
1421 replace_push(NUL);
1422 newcol += curwin->w_cursor.col;
1423#ifdef FEAT_SMARTINDENT
1424 if (no_si)
1425 did_si = FALSE;
1426#endif
1427 }
1428
1429#ifdef FEAT_COMMENTS
1430 /*
1431 * In REPLACE mode, for each character in the extra leader, there must be
1432 * a NUL on the replace stack, for when it is deleted with BS.
1433 */
1434 if (REPLACE_NORMAL(State))
1435 while (lead_len-- > 0)
1436 replace_push(NUL);
1437#endif
1438
1439 curwin->w_cursor = old_cursor;
1440
1441 if (dir == FORWARD)
1442 {
1443 if (trunc_line || (State & INSERT))
1444 {
1445 /* truncate current line at cursor */
1446 saved_line[curwin->w_cursor.col] = NUL;
1447 /* Remove trailing white space, unless OPENLINE_KEEPTRAIL used. */
1448 if (trunc_line && !(flags & OPENLINE_KEEPTRAIL))
1449 truncate_spaces(saved_line);
1450 ml_replace(curwin->w_cursor.lnum, saved_line, FALSE);
1451 saved_line = NULL;
1452 if (did_append)
1453 {
1454 changed_lines(curwin->w_cursor.lnum, curwin->w_cursor.col,
1455 curwin->w_cursor.lnum + 1, 1L);
1456 did_append = FALSE;
1457
1458 /* Move marks after the line break to the new line. */
1459 if (flags & OPENLINE_MARKFIX)
1460 mark_col_adjust(curwin->w_cursor.lnum,
1461 curwin->w_cursor.col + less_cols_off,
1462 1L, (long)-less_cols);
1463 }
1464 else
1465 changed_bytes(curwin->w_cursor.lnum, curwin->w_cursor.col);
1466 }
1467
1468 /*
1469 * Put the cursor on the new line. Careful: the scrollup() above may
1470 * have moved w_cursor, we must use old_cursor.
1471 */
1472 curwin->w_cursor.lnum = old_cursor.lnum + 1;
1473 }
1474 if (did_append)
1475 changed_lines(curwin->w_cursor.lnum, 0, curwin->w_cursor.lnum, 1L);
1476
1477 curwin->w_cursor.col = newcol;
1478#ifdef FEAT_VIRTUALEDIT
1479 curwin->w_cursor.coladd = 0;
1480#endif
1481
1482#if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
1483 /*
1484 * In VREPLACE mode, we are handling the replace stack ourselves, so stop
1485 * fixthisline() from doing it (via change_indent()) by telling it we're in
1486 * normal INSERT mode.
1487 */
1488 if (State & VREPLACE_FLAG)
1489 {
1490 vreplace_mode = State; /* So we know to put things right later */
1491 State = INSERT;
1492 }
1493 else
1494 vreplace_mode = 0;
1495#endif
1496#ifdef FEAT_LISP
1497 /*
1498 * May do lisp indenting.
1499 */
1500 if (!p_paste
1501# ifdef FEAT_COMMENTS
1502 && leader == NULL
1503# endif
1504 && curbuf->b_p_lisp
1505 && curbuf->b_p_ai)
1506 {
1507 fixthisline(get_lisp_indent);
1508 p = ml_get_curline();
1509 ai_col = (colnr_T)(skipwhite(p) - p);
1510 }
1511#endif
1512#ifdef FEAT_CINDENT
1513 /*
1514 * May do indenting after opening a new line.
1515 */
1516 if (!p_paste
1517 && (curbuf->b_p_cin
1518# ifdef FEAT_EVAL
1519 || *curbuf->b_p_inde != NUL
1520# endif
1521 )
1522 && in_cinkeys(dir == FORWARD
1523 ? KEY_OPEN_FORW
1524 : KEY_OPEN_BACK, ' ', linewhite(curwin->w_cursor.lnum)))
1525 {
1526 do_c_expr_indent();
1527 p = ml_get_curline();
1528 ai_col = (colnr_T)(skipwhite(p) - p);
1529 }
1530#endif
1531#if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
1532 if (vreplace_mode != 0)
1533 State = vreplace_mode;
1534#endif
1535
1536#ifdef FEAT_VREPLACE
1537 /*
1538 * Finally, VREPLACE gets the stuff on the new line, then puts back the
1539 * original line, and inserts the new stuff char by char, pushing old stuff
1540 * onto the replace stack (via ins_char()).
1541 */
1542 if (State & VREPLACE_FLAG)
1543 {
1544 /* Put new line in p_extra */
1545 p_extra = vim_strsave(ml_get_curline());
1546 if (p_extra == NULL)
1547 goto theend;
1548
1549 /* Put back original line */
1550 ml_replace(curwin->w_cursor.lnum, next_line, FALSE);
1551
1552 /* Insert new stuff into line again */
1553 curwin->w_cursor.col = 0;
1554#ifdef FEAT_VIRTUALEDIT
1555 curwin->w_cursor.coladd = 0;
1556#endif
1557 ins_bytes(p_extra); /* will call changed_bytes() */
1558 vim_free(p_extra);
1559 next_line = NULL;
1560 }
1561#endif
1562
1563 retval = TRUE; /* success! */
1564theend:
1565 curbuf->b_p_pi = saved_pi;
1566 vim_free(saved_line);
1567 vim_free(next_line);
1568 vim_free(allocated);
1569 return retval;
1570}
1571
1572#if defined(FEAT_COMMENTS) || defined(PROTO)
1573/*
1574 * get_leader_len() returns the length of the prefix of the given string
1575 * which introduces a comment. If this string is not a comment then 0 is
1576 * returned.
1577 * When "flags" is not NULL, it is set to point to the flags of the recognized
1578 * comment leader.
1579 * "backward" must be true for the "O" command.
Bram Moolenaar81340392012-06-06 16:12:59 +02001580 * If "include_space" is set, include trailing whitespace while calculating the
1581 * length.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001582 */
1583 int
Bram Moolenaar81340392012-06-06 16:12:59 +02001584get_leader_len(line, flags, backward, include_space)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001585 char_u *line;
1586 char_u **flags;
1587 int backward;
Bram Moolenaar81340392012-06-06 16:12:59 +02001588 int include_space;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001589{
1590 int i, j;
Bram Moolenaar81340392012-06-06 16:12:59 +02001591 int result;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001592 int got_com = FALSE;
1593 int found_one;
1594 char_u part_buf[COM_MAX_LEN]; /* buffer for one option part */
1595 char_u *string; /* pointer to comment string */
1596 char_u *list;
Bram Moolenaara4271d52011-05-10 13:38:27 +02001597 int middle_match_len = 0;
1598 char_u *prev_list;
Bram Moolenaar05da4282011-05-10 14:44:11 +02001599 char_u *saved_flags = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001600
Bram Moolenaar81340392012-06-06 16:12:59 +02001601 result = i = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001602 while (vim_iswhite(line[i])) /* leading white space is ignored */
1603 ++i;
1604
1605 /*
1606 * Repeat to match several nested comment strings.
1607 */
Bram Moolenaara4271d52011-05-10 13:38:27 +02001608 while (line[i] != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001609 {
1610 /*
1611 * scan through the 'comments' option for a match
1612 */
1613 found_one = FALSE;
1614 for (list = curbuf->b_p_com; *list; )
1615 {
Bram Moolenaara4271d52011-05-10 13:38:27 +02001616 /* Get one option part into part_buf[]. Advance "list" to next
1617 * one. Put "string" at start of string. */
1618 if (!got_com && flags != NULL)
1619 *flags = list; /* remember where flags started */
1620 prev_list = list;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001621 (void)copy_option_part(&list, part_buf, COM_MAX_LEN, ",");
1622 string = vim_strchr(part_buf, ':');
1623 if (string == NULL) /* missing ':', ignore this part */
1624 continue;
1625 *string++ = NUL; /* isolate flags from string */
1626
Bram Moolenaara4271d52011-05-10 13:38:27 +02001627 /* If we found a middle match previously, use that match when this
1628 * is not a middle or end. */
1629 if (middle_match_len != 0
1630 && vim_strchr(part_buf, COM_MIDDLE) == NULL
1631 && vim_strchr(part_buf, COM_END) == NULL)
1632 break;
1633
1634 /* When we already found a nested comment, only accept further
1635 * nested comments. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001636 if (got_com && vim_strchr(part_buf, COM_NEST) == NULL)
1637 continue;
1638
Bram Moolenaara4271d52011-05-10 13:38:27 +02001639 /* When 'O' flag present and using "O" command skip this one. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001640 if (backward && vim_strchr(part_buf, COM_NOBACK) != NULL)
1641 continue;
1642
Bram Moolenaara4271d52011-05-10 13:38:27 +02001643 /* Line contents and string must match.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001644 * When string starts with white space, must have some white space
1645 * (but the amount does not need to match, there might be a mix of
Bram Moolenaara4271d52011-05-10 13:38:27 +02001646 * TABs and spaces). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001647 if (vim_iswhite(string[0]))
1648 {
1649 if (i == 0 || !vim_iswhite(line[i - 1]))
Bram Moolenaara4271d52011-05-10 13:38:27 +02001650 continue; /* missing shite space */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001651 while (vim_iswhite(string[0]))
1652 ++string;
1653 }
1654 for (j = 0; string[j] != NUL && string[j] == line[i + j]; ++j)
1655 ;
1656 if (string[j] != NUL)
Bram Moolenaara4271d52011-05-10 13:38:27 +02001657 continue; /* string doesn't match */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001658
Bram Moolenaara4271d52011-05-10 13:38:27 +02001659 /* When 'b' flag used, there must be white space or an
1660 * end-of-line after the string in the line. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001661 if (vim_strchr(part_buf, COM_BLANK) != NULL
1662 && !vim_iswhite(line[i + j]) && line[i + j] != NUL)
1663 continue;
1664
Bram Moolenaara4271d52011-05-10 13:38:27 +02001665 /* We have found a match, stop searching unless this is a middle
1666 * comment. The middle comment can be a substring of the end
1667 * comment in which case it's better to return the length of the
1668 * end comment and its flags. Thus we keep searching with middle
1669 * and end matches and use an end match if it matches better. */
1670 if (vim_strchr(part_buf, COM_MIDDLE) != NULL)
1671 {
1672 if (middle_match_len == 0)
1673 {
1674 middle_match_len = j;
1675 saved_flags = prev_list;
1676 }
1677 continue;
1678 }
1679 if (middle_match_len != 0 && j > middle_match_len)
1680 /* Use this match instead of the middle match, since it's a
1681 * longer thus better match. */
1682 middle_match_len = 0;
1683
1684 if (middle_match_len == 0)
1685 i += j;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001686 found_one = TRUE;
1687 break;
1688 }
1689
Bram Moolenaara4271d52011-05-10 13:38:27 +02001690 if (middle_match_len != 0)
1691 {
1692 /* Use the previously found middle match after failing to find a
1693 * match with an end. */
1694 if (!got_com && flags != NULL)
1695 *flags = saved_flags;
1696 i += middle_match_len;
1697 found_one = TRUE;
1698 }
1699
1700 /* No match found, stop scanning. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001701 if (!found_one)
1702 break;
1703
Bram Moolenaar81340392012-06-06 16:12:59 +02001704 result = i;
1705
Bram Moolenaara4271d52011-05-10 13:38:27 +02001706 /* Include any trailing white space. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001707 while (vim_iswhite(line[i]))
1708 ++i;
1709
Bram Moolenaar81340392012-06-06 16:12:59 +02001710 if (include_space)
1711 result = i;
1712
Bram Moolenaara4271d52011-05-10 13:38:27 +02001713 /* If this comment doesn't nest, stop here. */
1714 got_com = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001715 if (vim_strchr(part_buf, COM_NEST) == NULL)
1716 break;
1717 }
Bram Moolenaar81340392012-06-06 16:12:59 +02001718 return result;
1719}
Bram Moolenaara4271d52011-05-10 13:38:27 +02001720
Bram Moolenaar81340392012-06-06 16:12:59 +02001721/*
1722 * Return the offset at which the last comment in line starts. If there is no
1723 * comment in the whole line, -1 is returned.
1724 *
1725 * When "flags" is not null, it is set to point to the flags describing the
1726 * recognized comment leader.
1727 */
1728 int
1729get_last_leader_offset(line, flags)
1730 char_u *line;
1731 char_u **flags;
1732{
1733 int result = -1;
1734 int i, j;
1735 int lower_check_bound = 0;
1736 char_u *string;
1737 char_u *com_leader;
1738 char_u *com_flags;
1739 char_u *list;
1740 int found_one;
1741 char_u part_buf[COM_MAX_LEN]; /* buffer for one option part */
1742
1743 /*
1744 * Repeat to match several nested comment strings.
1745 */
1746 i = (int)STRLEN(line);
1747 while (--i >= lower_check_bound)
1748 {
1749 /*
1750 * scan through the 'comments' option for a match
1751 */
1752 found_one = FALSE;
1753 for (list = curbuf->b_p_com; *list; )
1754 {
1755 char_u *flags_save = list;
1756
1757 /*
1758 * Get one option part into part_buf[]. Advance list to next one.
1759 * put string at start of string.
1760 */
1761 (void)copy_option_part(&list, part_buf, COM_MAX_LEN, ",");
1762 string = vim_strchr(part_buf, ':');
1763 if (string == NULL) /* If everything is fine, this cannot actually
1764 * happen. */
1765 {
1766 continue;
1767 }
1768 *string++ = NUL; /* Isolate flags from string. */
1769 com_leader = string;
1770
1771 /*
1772 * Line contents and string must match.
1773 * When string starts with white space, must have some white space
1774 * (but the amount does not need to match, there might be a mix of
1775 * TABs and spaces).
1776 */
1777 if (vim_iswhite(string[0]))
1778 {
1779 if (i == 0 || !vim_iswhite(line[i - 1]))
1780 continue;
1781 while (vim_iswhite(string[0]))
1782 ++string;
1783 }
1784 for (j = 0; string[j] != NUL && string[j] == line[i + j]; ++j)
1785 /* do nothing */;
1786 if (string[j] != NUL)
1787 continue;
1788
1789 /*
1790 * When 'b' flag used, there must be white space or an
1791 * end-of-line after the string in the line.
1792 */
1793 if (vim_strchr(part_buf, COM_BLANK) != NULL
1794 && !vim_iswhite(line[i + j]) && line[i + j] != NUL)
1795 {
1796 continue;
1797 }
1798
1799 /*
1800 * We have found a match, stop searching.
1801 */
1802 found_one = TRUE;
1803
1804 if (flags)
1805 *flags = flags_save;
1806 com_flags = flags_save;
1807
1808 break;
1809 }
1810
1811 if (found_one)
1812 {
1813 char_u part_buf2[COM_MAX_LEN]; /* buffer for one option part */
1814 int len1, len2, off;
1815
1816 result = i;
1817 /*
1818 * If this comment nests, continue searching.
1819 */
1820 if (vim_strchr(part_buf, COM_NEST) != NULL)
1821 continue;
1822
1823 lower_check_bound = i;
1824
1825 /* Let's verify whether the comment leader found is a substring
1826 * of other comment leaders. If it is, let's adjust the
1827 * lower_check_bound so that we make sure that we have determined
1828 * the comment leader correctly.
1829 */
1830
1831 while (vim_iswhite(*com_leader))
1832 ++com_leader;
1833 len1 = (int)STRLEN(com_leader);
1834
1835 for (list = curbuf->b_p_com; *list; )
1836 {
1837 char_u *flags_save = list;
1838
1839 (void)copy_option_part(&list, part_buf2, COM_MAX_LEN, ",");
1840 if (flags_save == com_flags)
1841 continue;
1842 string = vim_strchr(part_buf2, ':');
1843 ++string;
1844 while (vim_iswhite(*string))
1845 ++string;
1846 len2 = (int)STRLEN(string);
1847 if (len2 == 0)
1848 continue;
1849
1850 /* Now we have to verify whether string ends with a substring
1851 * beginning the com_leader. */
1852 for (off = (len2 > i ? i : len2); off > 0 && off + len1 > len2;)
1853 {
1854 --off;
1855 if (!STRNCMP(string + off, com_leader, len2 - off))
1856 {
1857 if (i - off < lower_check_bound)
1858 lower_check_bound = i - off;
1859 }
1860 }
1861 }
1862 }
1863 }
1864 return result;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001865}
1866#endif
1867
1868/*
1869 * Return the number of window lines occupied by buffer line "lnum".
1870 */
1871 int
1872plines(lnum)
1873 linenr_T lnum;
1874{
1875 return plines_win(curwin, lnum, TRUE);
1876}
1877
1878 int
1879plines_win(wp, lnum, winheight)
1880 win_T *wp;
1881 linenr_T lnum;
1882 int winheight; /* when TRUE limit to window height */
1883{
1884#if defined(FEAT_DIFF) || defined(PROTO)
1885 /* Check for filler lines above this buffer line. When folded the result
1886 * is one line anyway. */
1887 return plines_win_nofill(wp, lnum, winheight) + diff_check_fill(wp, lnum);
1888}
1889
1890 int
1891plines_nofill(lnum)
1892 linenr_T lnum;
1893{
1894 return plines_win_nofill(curwin, lnum, TRUE);
1895}
1896
1897 int
1898plines_win_nofill(wp, lnum, winheight)
1899 win_T *wp;
1900 linenr_T lnum;
1901 int winheight; /* when TRUE limit to window height */
1902{
1903#endif
1904 int lines;
1905
1906 if (!wp->w_p_wrap)
1907 return 1;
1908
1909#ifdef FEAT_VERTSPLIT
1910 if (wp->w_width == 0)
1911 return 1;
1912#endif
1913
1914#ifdef FEAT_FOLDING
1915 /* A folded lines is handled just like an empty line. */
1916 /* NOTE: Caller must handle lines that are MAYBE folded. */
1917 if (lineFolded(wp, lnum) == TRUE)
1918 return 1;
1919#endif
1920
1921 lines = plines_win_nofold(wp, lnum);
1922 if (winheight > 0 && lines > wp->w_height)
1923 return (int)wp->w_height;
1924 return lines;
1925}
1926
1927/*
1928 * Return number of window lines physical line "lnum" will occupy in window
1929 * "wp". Does not care about folding, 'wrap' or 'diff'.
1930 */
1931 int
1932plines_win_nofold(wp, lnum)
1933 win_T *wp;
1934 linenr_T lnum;
1935{
1936 char_u *s;
1937 long col;
1938 int width;
1939
1940 s = ml_get_buf(wp->w_buffer, lnum, FALSE);
1941 if (*s == NUL) /* empty line */
1942 return 1;
1943 col = win_linetabsize(wp, s, (colnr_T)MAXCOL);
1944
1945 /*
1946 * If list mode is on, then the '$' at the end of the line may take up one
1947 * extra column.
1948 */
1949 if (wp->w_p_list && lcs_eol != NUL)
1950 col += 1;
1951
1952 /*
Bram Moolenaar64486672010-05-16 15:46:46 +02001953 * Add column offset for 'number', 'relativenumber' and 'foldcolumn'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001954 */
1955 width = W_WIDTH(wp) - win_col_off(wp);
1956 if (width <= 0)
1957 return 32000;
1958 if (col <= width)
1959 return 1;
1960 col -= width;
1961 width += win_col_off2(wp);
1962 return (col + (width - 1)) / width + 1;
1963}
1964
1965/*
1966 * Like plines_win(), but only reports the number of physical screen lines
1967 * used from the start of the line to the given column number.
1968 */
1969 int
1970plines_win_col(wp, lnum, column)
1971 win_T *wp;
1972 linenr_T lnum;
1973 long column;
1974{
1975 long col;
1976 char_u *s;
1977 int lines = 0;
1978 int width;
1979
1980#ifdef FEAT_DIFF
1981 /* Check for filler lines above this buffer line. When folded the result
1982 * is one line anyway. */
1983 lines = diff_check_fill(wp, lnum);
1984#endif
1985
1986 if (!wp->w_p_wrap)
1987 return lines + 1;
1988
1989#ifdef FEAT_VERTSPLIT
1990 if (wp->w_width == 0)
1991 return lines + 1;
1992#endif
1993
1994 s = ml_get_buf(wp->w_buffer, lnum, FALSE);
1995
1996 col = 0;
1997 while (*s != NUL && --column >= 0)
1998 {
1999 col += win_lbr_chartabsize(wp, s, (colnr_T)col, NULL);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002000 mb_ptr_adv(s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002001 }
2002
2003 /*
2004 * If *s is a TAB, and the TAB is not displayed as ^I, and we're not in
2005 * INSERT mode, then col must be adjusted so that it represents the last
2006 * screen position of the TAB. This only fixes an error when the TAB wraps
2007 * from one screen line to the next (when 'columns' is not a multiple of
2008 * 'ts') -- webb.
2009 */
2010 if (*s == TAB && (State & NORMAL) && (!wp->w_p_list || lcs_tab1))
2011 col += win_lbr_chartabsize(wp, s, (colnr_T)col, NULL) - 1;
2012
2013 /*
Bram Moolenaar64486672010-05-16 15:46:46 +02002014 * Add column offset for 'number', 'relativenumber', 'foldcolumn', etc.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002015 */
2016 width = W_WIDTH(wp) - win_col_off(wp);
Bram Moolenaar26470632006-10-24 19:12:40 +00002017 if (width <= 0)
2018 return 9999;
2019
2020 lines += 1;
2021 if (col > width)
2022 lines += (col - width) / (width + win_col_off2(wp)) + 1;
2023 return lines;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002024}
2025
2026 int
2027plines_m_win(wp, first, last)
2028 win_T *wp;
2029 linenr_T first, last;
2030{
2031 int count = 0;
2032
2033 while (first <= last)
2034 {
2035#ifdef FEAT_FOLDING
2036 int x;
2037
2038 /* Check if there are any really folded lines, but also included lines
2039 * that are maybe folded. */
2040 x = foldedCount(wp, first, NULL);
2041 if (x > 0)
2042 {
2043 ++count; /* count 1 for "+-- folded" line */
2044 first += x;
2045 }
2046 else
2047#endif
2048 {
2049#ifdef FEAT_DIFF
2050 if (first == wp->w_topline)
2051 count += plines_win_nofill(wp, first, TRUE) + wp->w_topfill;
2052 else
2053#endif
2054 count += plines_win(wp, first, TRUE);
2055 ++first;
2056 }
2057 }
2058 return (count);
2059}
2060
2061#if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) || defined(PROTO)
2062/*
2063 * Insert string "p" at the cursor position. Stops at a NUL byte.
2064 * Handles Replace mode and multi-byte characters.
2065 */
2066 void
2067ins_bytes(p)
2068 char_u *p;
2069{
2070 ins_bytes_len(p, (int)STRLEN(p));
2071}
2072#endif
2073
2074#if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) \
2075 || defined(FEAT_COMMENTS) || defined(FEAT_MBYTE) || defined(PROTO)
2076/*
2077 * Insert string "p" with length "len" at the cursor position.
2078 * Handles Replace mode and multi-byte characters.
2079 */
2080 void
2081ins_bytes_len(p, len)
2082 char_u *p;
2083 int len;
2084{
2085 int i;
2086# ifdef FEAT_MBYTE
2087 int n;
2088
Bram Moolenaar176dd1e2008-06-21 14:30:28 +00002089 if (has_mbyte)
2090 for (i = 0; i < len; i += n)
2091 {
2092 if (enc_utf8)
2093 /* avoid reading past p[len] */
2094 n = utfc_ptr2len_len(p + i, len - i);
2095 else
2096 n = (*mb_ptr2len)(p + i);
2097 ins_char_bytes(p + i, n);
2098 }
2099 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002100# endif
Bram Moolenaar176dd1e2008-06-21 14:30:28 +00002101 for (i = 0; i < len; ++i)
2102 ins_char(p[i]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002103}
2104#endif
2105
2106/*
2107 * Insert or replace a single character at the cursor position.
2108 * When in REPLACE or VREPLACE mode, replace any existing character.
2109 * Caller must have prepared for undo.
2110 * For multi-byte characters we get the whole character, the caller must
2111 * convert bytes to a character.
2112 */
2113 void
2114ins_char(c)
2115 int c;
2116{
2117#if defined(FEAT_MBYTE) || defined(PROTO)
Bram Moolenaar9a920d82012-06-01 15:21:02 +02002118 char_u buf[MB_MAXBYTES + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002119 int n;
2120
2121 n = (*mb_char2bytes)(c, buf);
2122
2123 /* When "c" is 0x100, 0x200, etc. we don't want to insert a NUL byte.
2124 * Happens for CTRL-Vu9900. */
2125 if (buf[0] == 0)
2126 buf[0] = '\n';
2127
2128 ins_char_bytes(buf, n);
2129}
2130
2131 void
2132ins_char_bytes(buf, charlen)
2133 char_u *buf;
2134 int charlen;
2135{
2136 int c = buf[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002137#endif
2138 int newlen; /* nr of bytes inserted */
2139 int oldlen; /* nr of bytes deleted (0 when not replacing) */
2140 char_u *p;
2141 char_u *newp;
2142 char_u *oldp;
2143 int linelen; /* length of old line including NUL */
2144 colnr_T col;
2145 linenr_T lnum = curwin->w_cursor.lnum;
2146 int i;
2147
2148#ifdef FEAT_VIRTUALEDIT
2149 /* Break tabs if needed. */
2150 if (virtual_active() && curwin->w_cursor.coladd > 0)
2151 coladvance_force(getviscol());
2152#endif
2153
2154 col = curwin->w_cursor.col;
2155 oldp = ml_get(lnum);
2156 linelen = (int)STRLEN(oldp) + 1;
2157
2158 /* The lengths default to the values for when not replacing. */
2159 oldlen = 0;
2160#ifdef FEAT_MBYTE
2161 newlen = charlen;
2162#else
2163 newlen = 1;
2164#endif
2165
2166 if (State & REPLACE_FLAG)
2167 {
2168#ifdef FEAT_VREPLACE
2169 if (State & VREPLACE_FLAG)
2170 {
2171 colnr_T new_vcol = 0; /* init for GCC */
2172 colnr_T vcol;
2173 int old_list;
2174#ifndef FEAT_MBYTE
2175 char_u buf[2];
2176#endif
2177
2178 /*
2179 * Disable 'list' temporarily, unless 'cpo' contains the 'L' flag.
2180 * Returns the old value of list, so when finished,
2181 * curwin->w_p_list should be set back to this.
2182 */
2183 old_list = curwin->w_p_list;
2184 if (old_list && vim_strchr(p_cpo, CPO_LISTWM) == NULL)
2185 curwin->w_p_list = FALSE;
2186
2187 /*
2188 * In virtual replace mode each character may replace one or more
2189 * characters (zero if it's a TAB). Count the number of bytes to
2190 * be deleted to make room for the new character, counting screen
2191 * cells. May result in adding spaces to fill a gap.
2192 */
2193 getvcol(curwin, &curwin->w_cursor, NULL, &vcol, NULL);
2194#ifndef FEAT_MBYTE
2195 buf[0] = c;
2196 buf[1] = NUL;
2197#endif
2198 new_vcol = vcol + chartabsize(buf, vcol);
2199 while (oldp[col + oldlen] != NUL && vcol < new_vcol)
2200 {
2201 vcol += chartabsize(oldp + col + oldlen, vcol);
2202 /* Don't need to remove a TAB that takes us to the right
2203 * position. */
2204 if (vcol > new_vcol && oldp[col + oldlen] == TAB)
2205 break;
2206#ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002207 oldlen += (*mb_ptr2len)(oldp + col + oldlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002208#else
2209 ++oldlen;
2210#endif
2211 /* Deleted a bit too much, insert spaces. */
2212 if (vcol > new_vcol)
2213 newlen += vcol - new_vcol;
2214 }
2215 curwin->w_p_list = old_list;
2216 }
2217 else
2218#endif
2219 if (oldp[col] != NUL)
2220 {
2221 /* normal replace */
2222#ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002223 oldlen = (*mb_ptr2len)(oldp + col);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002224#else
2225 oldlen = 1;
2226#endif
2227 }
2228
2229
2230 /* Push the replaced bytes onto the replace stack, so that they can be
2231 * put back when BS is used. The bytes of a multi-byte character are
2232 * done the other way around, so that the first byte is popped off
2233 * first (it tells the byte length of the character). */
2234 replace_push(NUL);
2235 for (i = 0; i < oldlen; ++i)
2236 {
2237#ifdef FEAT_MBYTE
Bram Moolenaar2c994e82008-01-02 16:49:36 +00002238 if (has_mbyte)
2239 i += replace_push_mb(oldp + col + i) - 1;
2240 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002241#endif
Bram Moolenaar2c994e82008-01-02 16:49:36 +00002242 replace_push(oldp[col + i]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002243 }
2244 }
2245
2246 newp = alloc_check((unsigned)(linelen + newlen - oldlen));
2247 if (newp == NULL)
2248 return;
2249
2250 /* Copy bytes before the cursor. */
2251 if (col > 0)
2252 mch_memmove(newp, oldp, (size_t)col);
2253
2254 /* Copy bytes after the changed character(s). */
2255 p = newp + col;
2256 mch_memmove(p + newlen, oldp + col + oldlen,
2257 (size_t)(linelen - col - oldlen));
2258
2259 /* Insert or overwrite the new character. */
2260#ifdef FEAT_MBYTE
2261 mch_memmove(p, buf, charlen);
2262 i = charlen;
2263#else
2264 *p = c;
2265 i = 1;
2266#endif
2267
2268 /* Fill with spaces when necessary. */
2269 while (i < newlen)
2270 p[i++] = ' ';
2271
2272 /* Replace the line in the buffer. */
2273 ml_replace(lnum, newp, FALSE);
2274
2275 /* mark the buffer as changed and prepare for displaying */
2276 changed_bytes(lnum, col);
2277
2278 /*
2279 * If we're in Insert or Replace mode and 'showmatch' is set, then briefly
2280 * show the match for right parens and braces.
2281 */
2282 if (p_sm && (State & INSERT)
2283 && msg_silent == 0
2284#ifdef FEAT_MBYTE
2285 && charlen == 1
2286#endif
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00002287#ifdef FEAT_INS_EXPAND
2288 && !ins_compl_active()
2289#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002290 )
2291 showmatch(c);
2292
2293#ifdef FEAT_RIGHTLEFT
2294 if (!p_ri || (State & REPLACE_FLAG))
2295#endif
2296 {
2297 /* Normal insert: move cursor right */
2298#ifdef FEAT_MBYTE
2299 curwin->w_cursor.col += charlen;
2300#else
2301 ++curwin->w_cursor.col;
2302#endif
2303 }
2304 /*
2305 * TODO: should try to update w_row here, to avoid recomputing it later.
2306 */
2307}
2308
2309/*
2310 * Insert a string at the cursor position.
2311 * Note: Does NOT handle Replace mode.
2312 * Caller must have prepared for undo.
2313 */
2314 void
2315ins_str(s)
2316 char_u *s;
2317{
2318 char_u *oldp, *newp;
2319 int newlen = (int)STRLEN(s);
2320 int oldlen;
2321 colnr_T col;
2322 linenr_T lnum = curwin->w_cursor.lnum;
2323
2324#ifdef FEAT_VIRTUALEDIT
2325 if (virtual_active() && curwin->w_cursor.coladd > 0)
2326 coladvance_force(getviscol());
2327#endif
2328
2329 col = curwin->w_cursor.col;
2330 oldp = ml_get(lnum);
2331 oldlen = (int)STRLEN(oldp);
2332
2333 newp = alloc_check((unsigned)(oldlen + newlen + 1));
2334 if (newp == NULL)
2335 return;
2336 if (col > 0)
2337 mch_memmove(newp, oldp, (size_t)col);
2338 mch_memmove(newp + col, s, (size_t)newlen);
2339 mch_memmove(newp + col + newlen, oldp + col, (size_t)(oldlen - col + 1));
2340 ml_replace(lnum, newp, FALSE);
2341 changed_bytes(lnum, col);
2342 curwin->w_cursor.col += newlen;
2343}
2344
2345/*
2346 * Delete one character under the cursor.
2347 * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
2348 * Caller must have prepared for undo.
2349 *
2350 * return FAIL for failure, OK otherwise
2351 */
2352 int
2353del_char(fixpos)
2354 int fixpos;
2355{
2356#ifdef FEAT_MBYTE
2357 if (has_mbyte)
2358 {
2359 /* Make sure the cursor is at the start of a character. */
2360 mb_adjust_cursor();
2361 if (*ml_get_cursor() == NUL)
2362 return FAIL;
2363 return del_chars(1L, fixpos);
2364 }
2365#endif
Bram Moolenaare3226be2005-12-18 22:10:00 +00002366 return del_bytes(1L, fixpos, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002367}
2368
2369#if defined(FEAT_MBYTE) || defined(PROTO)
2370/*
2371 * Like del_bytes(), but delete characters instead of bytes.
2372 */
2373 int
2374del_chars(count, fixpos)
2375 long count;
2376 int fixpos;
2377{
2378 long bytes = 0;
2379 long i;
2380 char_u *p;
2381 int l;
2382
2383 p = ml_get_cursor();
2384 for (i = 0; i < count && *p != NUL; ++i)
2385 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002386 l = (*mb_ptr2len)(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002387 bytes += l;
2388 p += l;
2389 }
Bram Moolenaare3226be2005-12-18 22:10:00 +00002390 return del_bytes(bytes, fixpos, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002391}
2392#endif
2393
2394/*
2395 * Delete "count" bytes under the cursor.
2396 * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
2397 * Caller must have prepared for undo.
2398 *
2399 * return FAIL for failure, OK otherwise
2400 */
2401 int
Bram Moolenaarca003e12006-03-17 23:19:38 +00002402del_bytes(count, fixpos_arg, use_delcombine)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002403 long count;
Bram Moolenaarca003e12006-03-17 23:19:38 +00002404 int fixpos_arg;
Bram Moolenaar78a15312009-05-15 19:33:18 +00002405 int use_delcombine UNUSED; /* 'delcombine' option applies */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002406{
2407 char_u *oldp, *newp;
2408 colnr_T oldlen;
2409 linenr_T lnum = curwin->w_cursor.lnum;
2410 colnr_T col = curwin->w_cursor.col;
2411 int was_alloced;
2412 long movelen;
Bram Moolenaarca003e12006-03-17 23:19:38 +00002413 int fixpos = fixpos_arg;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002414
2415 oldp = ml_get(lnum);
2416 oldlen = (int)STRLEN(oldp);
2417
2418 /*
2419 * Can't do anything when the cursor is on the NUL after the line.
2420 */
2421 if (col >= oldlen)
2422 return FAIL;
2423
2424#ifdef FEAT_MBYTE
2425 /* If 'delcombine' is set and deleting (less than) one character, only
2426 * delete the last combining character. */
Bram Moolenaare3226be2005-12-18 22:10:00 +00002427 if (p_deco && use_delcombine && enc_utf8
2428 && utfc_ptr2len(oldp + col) >= count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002429 {
Bram Moolenaar362e1a32006-03-06 23:29:24 +00002430 int cc[MAX_MCO];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002431 int n;
2432
Bram Moolenaar362e1a32006-03-06 23:29:24 +00002433 (void)utfc_ptr2char(oldp + col, cc);
2434 if (cc[0] != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002435 {
2436 /* Find the last composing char, there can be several. */
2437 n = col;
2438 do
2439 {
2440 col = n;
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002441 count = utf_ptr2len(oldp + n);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002442 n += count;
2443 } while (UTF_COMPOSINGLIKE(oldp + col, oldp + n));
2444 fixpos = 0;
2445 }
2446 }
2447#endif
2448
2449 /*
2450 * When count is too big, reduce it.
2451 */
2452 movelen = (long)oldlen - (long)col - count + 1; /* includes trailing NUL */
2453 if (movelen <= 1)
2454 {
2455 /*
2456 * If we just took off the last character of a non-blank line, and
Bram Moolenaarca003e12006-03-17 23:19:38 +00002457 * fixpos is TRUE, we don't want to end up positioned at the NUL,
2458 * unless "restart_edit" is set or 'virtualedit' contains "onemore".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002459 */
Bram Moolenaarca003e12006-03-17 23:19:38 +00002460 if (col > 0 && fixpos && restart_edit == 0
2461#ifdef FEAT_VIRTUALEDIT
2462 && (ve_flags & VE_ONEMORE) == 0
2463#endif
2464 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00002465 {
2466 --curwin->w_cursor.col;
2467#ifdef FEAT_VIRTUALEDIT
2468 curwin->w_cursor.coladd = 0;
2469#endif
2470#ifdef FEAT_MBYTE
2471 if (has_mbyte)
2472 curwin->w_cursor.col -=
2473 (*mb_head_off)(oldp, oldp + curwin->w_cursor.col);
2474#endif
2475 }
2476 count = oldlen - col;
2477 movelen = 1;
2478 }
2479
2480 /*
2481 * If the old line has been allocated the deletion can be done in the
2482 * existing line. Otherwise a new line has to be allocated
Bram Moolenaare21877a2008-02-13 09:58:14 +00002483 * Can't do this when using Netbeans, because we would need to invoke
2484 * netbeans_removed(), which deallocates the line. Let ml_replace() take
Bram Moolenaar1a509df2010-08-01 17:59:57 +02002485 * care of notifying Netbeans.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002486 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002487#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02002488 if (netbeans_active())
Bram Moolenaare21877a2008-02-13 09:58:14 +00002489 was_alloced = FALSE;
2490 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002491#endif
Bram Moolenaare21877a2008-02-13 09:58:14 +00002492 was_alloced = ml_line_alloced(); /* check if oldp was allocated */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002493 if (was_alloced)
2494 newp = oldp; /* use same allocated memory */
2495 else
2496 { /* need to allocate a new line */
2497 newp = alloc((unsigned)(oldlen + 1 - count));
2498 if (newp == NULL)
2499 return FAIL;
2500 mch_memmove(newp, oldp, (size_t)col);
2501 }
2502 mch_memmove(newp + col, oldp + col + count, (size_t)movelen);
2503 if (!was_alloced)
2504 ml_replace(lnum, newp, FALSE);
2505
2506 /* mark the buffer as changed and prepare for displaying */
2507 changed_bytes(lnum, curwin->w_cursor.col);
2508
2509 return OK;
2510}
2511
2512/*
2513 * Delete from cursor to end of line.
2514 * Caller must have prepared for undo.
2515 *
2516 * return FAIL for failure, OK otherwise
2517 */
2518 int
2519truncate_line(fixpos)
2520 int fixpos; /* if TRUE fix the cursor position when done */
2521{
2522 char_u *newp;
2523 linenr_T lnum = curwin->w_cursor.lnum;
2524 colnr_T col = curwin->w_cursor.col;
2525
2526 if (col == 0)
2527 newp = vim_strsave((char_u *)"");
2528 else
2529 newp = vim_strnsave(ml_get(lnum), col);
2530
2531 if (newp == NULL)
2532 return FAIL;
2533
2534 ml_replace(lnum, newp, FALSE);
2535
2536 /* mark the buffer as changed and prepare for displaying */
2537 changed_bytes(lnum, curwin->w_cursor.col);
2538
2539 /*
2540 * If "fixpos" is TRUE we don't want to end up positioned at the NUL.
2541 */
2542 if (fixpos && curwin->w_cursor.col > 0)
2543 --curwin->w_cursor.col;
2544
2545 return OK;
2546}
2547
2548/*
2549 * Delete "nlines" lines at the cursor.
2550 * Saves the lines for undo first if "undo" is TRUE.
2551 */
2552 void
2553del_lines(nlines, undo)
2554 long nlines; /* number of lines to delete */
2555 int undo; /* if TRUE, prepare for undo */
2556{
2557 long n;
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002558 linenr_T first = curwin->w_cursor.lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002559
2560 if (nlines <= 0)
2561 return;
2562
2563 /* save the deleted lines for undo */
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002564 if (undo && u_savedel(first, nlines) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002565 return;
2566
2567 for (n = 0; n < nlines; )
2568 {
2569 if (curbuf->b_ml.ml_flags & ML_EMPTY) /* nothing to delete */
2570 break;
2571
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002572 ml_delete(first, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002573 ++n;
2574
2575 /* If we delete the last line in the file, stop */
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002576 if (first > curbuf->b_ml.ml_line_count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002577 break;
2578 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002579
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002580 /* Correct the cursor position before calling deleted_lines_mark(), it may
2581 * trigger a callback to display the cursor. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002582 curwin->w_cursor.col = 0;
2583 check_cursor_lnum();
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002584
2585 /* adjust marks, mark the buffer as changed and prepare for displaying */
2586 deleted_lines_mark(first, n);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002587}
2588
2589 int
2590gchar_pos(pos)
2591 pos_T *pos;
2592{
2593 char_u *ptr = ml_get_pos(pos);
2594
2595#ifdef FEAT_MBYTE
2596 if (has_mbyte)
2597 return (*mb_ptr2char)(ptr);
2598#endif
2599 return (int)*ptr;
2600}
2601
2602 int
2603gchar_cursor()
2604{
2605#ifdef FEAT_MBYTE
2606 if (has_mbyte)
2607 return (*mb_ptr2char)(ml_get_cursor());
2608#endif
2609 return (int)*ml_get_cursor();
2610}
2611
2612/*
2613 * Write a character at the current cursor position.
2614 * It is directly written into the block.
2615 */
2616 void
2617pchar_cursor(c)
2618 int c;
2619{
2620 *(ml_get_buf(curbuf, curwin->w_cursor.lnum, TRUE)
2621 + curwin->w_cursor.col) = c;
2622}
2623
Bram Moolenaar071d4272004-06-13 20:20:40 +00002624/*
2625 * When extra == 0: Return TRUE if the cursor is before or on the first
2626 * non-blank in the line.
2627 * When extra == 1: Return TRUE if the cursor is before the first non-blank in
2628 * the line.
2629 */
2630 int
2631inindent(extra)
2632 int extra;
2633{
2634 char_u *ptr;
2635 colnr_T col;
2636
2637 for (col = 0, ptr = ml_get_curline(); vim_iswhite(*ptr); ++col)
2638 ++ptr;
2639 if (col >= curwin->w_cursor.col + extra)
2640 return TRUE;
2641 else
2642 return FALSE;
2643}
2644
2645/*
2646 * Skip to next part of an option argument: Skip space and comma.
2647 */
2648 char_u *
2649skip_to_option_part(p)
2650 char_u *p;
2651{
2652 if (*p == ',')
2653 ++p;
2654 while (*p == ' ')
2655 ++p;
2656 return p;
2657}
2658
2659/*
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002660 * Call this function when something in the current buffer is changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002661 *
2662 * Most often called through changed_bytes() and changed_lines(), which also
2663 * mark the area of the display to be redrawn.
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002664 *
2665 * Careful: may trigger autocommands that reload the buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002666 */
2667 void
2668changed()
2669{
2670#if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
2671 /* The text of the preediting area is inserted, but this doesn't
2672 * mean a change of the buffer yet. That is delayed until the
2673 * text is committed. (this means preedit becomes empty) */
2674 if (im_is_preediting() && !xim_changed_while_preediting)
2675 return;
2676 xim_changed_while_preediting = FALSE;
2677#endif
2678
2679 if (!curbuf->b_changed)
2680 {
2681 int save_msg_scroll = msg_scroll;
2682
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002683 /* Give a warning about changing a read-only file. This may also
2684 * check-out the file, thus change "curbuf"! */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002685 change_warning(0);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002686
Bram Moolenaar071d4272004-06-13 20:20:40 +00002687 /* Create a swap file if that is wanted.
2688 * Don't do this for "nofile" and "nowrite" buffer types. */
2689 if (curbuf->b_may_swap
2690#ifdef FEAT_QUICKFIX
2691 && !bt_dontwrite(curbuf)
2692#endif
2693 )
2694 {
2695 ml_open_file(curbuf);
2696
2697 /* The ml_open_file() can cause an ATTENTION message.
2698 * Wait two seconds, to make sure the user reads this unexpected
2699 * message. Since we could be anywhere, call wait_return() now,
2700 * and don't let the emsg() set msg_scroll. */
2701 if (need_wait_return && emsg_silent == 0)
2702 {
2703 out_flush();
2704 ui_delay(2000L, TRUE);
2705 wait_return(TRUE);
2706 msg_scroll = save_msg_scroll;
2707 }
2708 }
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02002709 changed_int();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002710 }
2711 ++curbuf->b_changedtick;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002712}
2713
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02002714/*
2715 * Internal part of changed(), no user interaction.
2716 */
2717 void
2718changed_int()
2719{
2720 curbuf->b_changed = TRUE;
2721 ml_setflags(curbuf);
2722#ifdef FEAT_WINDOWS
2723 check_status(curbuf);
2724 redraw_tabline = TRUE;
2725#endif
2726#ifdef FEAT_TITLE
2727 need_maketitle = TRUE; /* set window title later */
2728#endif
2729}
2730
Bram Moolenaardba8a912005-04-24 22:08:39 +00002731static void changedOneline __ARGS((buf_T *buf, linenr_T lnum));
2732static void changed_lines_buf __ARGS((buf_T *buf, linenr_T lnum, linenr_T lnume, long xtra));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002733static void changed_common __ARGS((linenr_T lnum, colnr_T col, linenr_T lnume, long xtra));
2734
2735/*
2736 * Changed bytes within a single line for the current buffer.
2737 * - marks the windows on this buffer to be redisplayed
2738 * - marks the buffer changed by calling changed()
2739 * - invalidates cached values
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002740 * Careful: may trigger autocommands that reload the buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002741 */
2742 void
2743changed_bytes(lnum, col)
2744 linenr_T lnum;
2745 colnr_T col;
2746{
Bram Moolenaardba8a912005-04-24 22:08:39 +00002747 changedOneline(curbuf, lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002748 changed_common(lnum, col, lnum + 1, 0L);
Bram Moolenaardba8a912005-04-24 22:08:39 +00002749
2750#ifdef FEAT_DIFF
2751 /* Diff highlighting in other diff windows may need to be updated too. */
2752 if (curwin->w_p_diff)
2753 {
2754 win_T *wp;
2755 linenr_T wlnum;
2756
2757 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2758 if (wp->w_p_diff && wp != curwin)
2759 {
2760 redraw_win_later(wp, VALID);
2761 wlnum = diff_lnum_win(lnum, wp);
2762 if (wlnum > 0)
2763 changedOneline(wp->w_buffer, wlnum);
2764 }
2765 }
2766#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002767}
2768
2769 static void
Bram Moolenaardba8a912005-04-24 22:08:39 +00002770changedOneline(buf, lnum)
2771 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002772 linenr_T lnum;
2773{
Bram Moolenaardba8a912005-04-24 22:08:39 +00002774 if (buf->b_mod_set)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002775 {
2776 /* find the maximum area that must be redisplayed */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002777 if (lnum < buf->b_mod_top)
2778 buf->b_mod_top = lnum;
2779 else if (lnum >= buf->b_mod_bot)
2780 buf->b_mod_bot = lnum + 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002781 }
2782 else
2783 {
2784 /* set the area that must be redisplayed to one line */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002785 buf->b_mod_set = TRUE;
2786 buf->b_mod_top = lnum;
2787 buf->b_mod_bot = lnum + 1;
2788 buf->b_mod_xlines = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002789 }
2790}
2791
2792/*
2793 * Appended "count" lines below line "lnum" in the current buffer.
2794 * Must be called AFTER the change and after mark_adjust().
2795 * Takes care of marking the buffer to be redrawn and sets the changed flag.
2796 */
2797 void
2798appended_lines(lnum, count)
2799 linenr_T lnum;
2800 long count;
2801{
2802 changed_lines(lnum + 1, 0, lnum + 1, count);
2803}
2804
2805/*
2806 * Like appended_lines(), but adjust marks first.
2807 */
2808 void
2809appended_lines_mark(lnum, count)
2810 linenr_T lnum;
2811 long count;
2812{
2813 mark_adjust(lnum + 1, (linenr_T)MAXLNUM, count, 0L);
2814 changed_lines(lnum + 1, 0, lnum + 1, count);
2815}
2816
2817/*
2818 * Deleted "count" lines at line "lnum" in the current buffer.
2819 * Must be called AFTER the change and after mark_adjust().
2820 * Takes care of marking the buffer to be redrawn and sets the changed flag.
2821 */
2822 void
2823deleted_lines(lnum, count)
2824 linenr_T lnum;
2825 long count;
2826{
2827 changed_lines(lnum, 0, lnum + count, -count);
2828}
2829
2830/*
2831 * Like deleted_lines(), but adjust marks first.
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002832 * Make sure the cursor is on a valid line before calling, a GUI callback may
2833 * be triggered to display the cursor.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002834 */
2835 void
2836deleted_lines_mark(lnum, count)
2837 linenr_T lnum;
2838 long count;
2839{
2840 mark_adjust(lnum, (linenr_T)(lnum + count - 1), (long)MAXLNUM, -count);
2841 changed_lines(lnum, 0, lnum + count, -count);
2842}
2843
2844/*
2845 * Changed lines for the current buffer.
2846 * Must be called AFTER the change and after mark_adjust().
2847 * - mark the buffer changed by calling changed()
2848 * - mark the windows on this buffer to be redisplayed
2849 * - invalidate cached values
2850 * "lnum" is the first line that needs displaying, "lnume" the first line
2851 * below the changed lines (BEFORE the change).
2852 * When only inserting lines, "lnum" and "lnume" are equal.
2853 * Takes care of calling changed() and updating b_mod_*.
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002854 * Careful: may trigger autocommands that reload the buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002855 */
2856 void
2857changed_lines(lnum, col, lnume, xtra)
2858 linenr_T lnum; /* first line with change */
2859 colnr_T col; /* column in first line with change */
2860 linenr_T lnume; /* line below last changed line */
2861 long xtra; /* number of extra lines (negative when deleting) */
2862{
Bram Moolenaardba8a912005-04-24 22:08:39 +00002863 changed_lines_buf(curbuf, lnum, lnume, xtra);
2864
2865#ifdef FEAT_DIFF
2866 if (xtra == 0 && curwin->w_p_diff)
2867 {
2868 /* When the number of lines doesn't change then mark_adjust() isn't
2869 * called and other diff buffers still need to be marked for
2870 * displaying. */
2871 win_T *wp;
2872 linenr_T wlnum;
2873
2874 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2875 if (wp->w_p_diff && wp != curwin)
2876 {
2877 redraw_win_later(wp, VALID);
2878 wlnum = diff_lnum_win(lnum, wp);
2879 if (wlnum > 0)
2880 changed_lines_buf(wp->w_buffer, wlnum,
2881 lnume - lnum + wlnum, 0L);
2882 }
2883 }
2884#endif
2885
2886 changed_common(lnum, col, lnume, xtra);
2887}
2888
2889 static void
2890changed_lines_buf(buf, lnum, lnume, xtra)
2891 buf_T *buf;
2892 linenr_T lnum; /* first line with change */
2893 linenr_T lnume; /* line below last changed line */
2894 long xtra; /* number of extra lines (negative when deleting) */
2895{
2896 if (buf->b_mod_set)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002897 {
2898 /* find the maximum area that must be redisplayed */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002899 if (lnum < buf->b_mod_top)
2900 buf->b_mod_top = lnum;
2901 if (lnum < buf->b_mod_bot)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002902 {
2903 /* adjust old bot position for xtra lines */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002904 buf->b_mod_bot += xtra;
2905 if (buf->b_mod_bot < lnum)
2906 buf->b_mod_bot = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002907 }
Bram Moolenaardba8a912005-04-24 22:08:39 +00002908 if (lnume + xtra > buf->b_mod_bot)
2909 buf->b_mod_bot = lnume + xtra;
2910 buf->b_mod_xlines += xtra;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002911 }
2912 else
2913 {
2914 /* set the area that must be redisplayed */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002915 buf->b_mod_set = TRUE;
2916 buf->b_mod_top = lnum;
2917 buf->b_mod_bot = lnume + xtra;
2918 buf->b_mod_xlines = xtra;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002919 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002920}
2921
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002922/*
2923 * Common code for when a change is was made.
2924 * See changed_lines() for the arguments.
2925 * Careful: may trigger autocommands that reload the buffer.
2926 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002927 static void
2928changed_common(lnum, col, lnume, xtra)
2929 linenr_T lnum;
2930 colnr_T col;
2931 linenr_T lnume;
2932 long xtra;
2933{
2934 win_T *wp;
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00002935#ifdef FEAT_WINDOWS
2936 tabpage_T *tp;
2937#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002938 int i;
2939#ifdef FEAT_JUMPLIST
2940 int cols;
2941 pos_T *p;
2942 int add;
2943#endif
2944
2945 /* mark the buffer as modified */
2946 changed();
2947
2948 /* set the '. mark */
2949 if (!cmdmod.keepjumps)
2950 {
2951 curbuf->b_last_change.lnum = lnum;
2952 curbuf->b_last_change.col = col;
2953
2954#ifdef FEAT_JUMPLIST
2955 /* Create a new entry if a new undo-able change was started or we
2956 * don't have an entry yet. */
2957 if (curbuf->b_new_change || curbuf->b_changelistlen == 0)
2958 {
2959 if (curbuf->b_changelistlen == 0)
2960 add = TRUE;
2961 else
2962 {
2963 /* Don't create a new entry when the line number is the same
2964 * as the last one and the column is not too far away. Avoids
2965 * creating many entries for typing "xxxxx". */
2966 p = &curbuf->b_changelist[curbuf->b_changelistlen - 1];
2967 if (p->lnum != lnum)
2968 add = TRUE;
2969 else
2970 {
2971 cols = comp_textwidth(FALSE);
2972 if (cols == 0)
2973 cols = 79;
2974 add = (p->col + cols < col || col + cols < p->col);
2975 }
2976 }
2977 if (add)
2978 {
2979 /* This is the first of a new sequence of undo-able changes
2980 * and it's at some distance of the last change. Use a new
2981 * position in the changelist. */
2982 curbuf->b_new_change = FALSE;
2983
2984 if (curbuf->b_changelistlen == JUMPLISTSIZE)
2985 {
2986 /* changelist is full: remove oldest entry */
2987 curbuf->b_changelistlen = JUMPLISTSIZE - 1;
2988 mch_memmove(curbuf->b_changelist, curbuf->b_changelist + 1,
2989 sizeof(pos_T) * (JUMPLISTSIZE - 1));
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00002990 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002991 {
2992 /* Correct position in changelist for other windows on
2993 * this buffer. */
2994 if (wp->w_buffer == curbuf && wp->w_changelistidx > 0)
2995 --wp->w_changelistidx;
2996 }
2997 }
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00002998 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002999 {
3000 /* For other windows, if the position in the changelist is
3001 * at the end it stays at the end. */
3002 if (wp->w_buffer == curbuf
3003 && wp->w_changelistidx == curbuf->b_changelistlen)
3004 ++wp->w_changelistidx;
3005 }
3006 ++curbuf->b_changelistlen;
3007 }
3008 }
3009 curbuf->b_changelist[curbuf->b_changelistlen - 1] =
3010 curbuf->b_last_change;
3011 /* The current window is always after the last change, so that "g,"
3012 * takes you back to it. */
3013 curwin->w_changelistidx = curbuf->b_changelistlen;
3014#endif
3015 }
3016
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00003017 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003018 {
3019 if (wp->w_buffer == curbuf)
3020 {
3021 /* Mark this window to be redrawn later. */
3022 if (wp->w_redr_type < VALID)
3023 wp->w_redr_type = VALID;
3024
3025 /* Check if a change in the buffer has invalidated the cached
3026 * values for the cursor. */
3027#ifdef FEAT_FOLDING
3028 /*
3029 * Update the folds for this window. Can't postpone this, because
3030 * a following operator might work on the whole fold: ">>dd".
3031 */
3032 foldUpdate(wp, lnum, lnume + xtra - 1);
3033
3034 /* The change may cause lines above or below the change to become
3035 * included in a fold. Set lnum/lnume to the first/last line that
3036 * might be displayed differently.
3037 * Set w_cline_folded here as an efficient way to update it when
3038 * inserting lines just above a closed fold. */
3039 i = hasFoldingWin(wp, lnum, &lnum, NULL, FALSE, NULL);
3040 if (wp->w_cursor.lnum == lnum)
3041 wp->w_cline_folded = i;
3042 i = hasFoldingWin(wp, lnume, NULL, &lnume, FALSE, NULL);
3043 if (wp->w_cursor.lnum == lnume)
3044 wp->w_cline_folded = i;
3045
3046 /* If the changed line is in a range of previously folded lines,
3047 * compare with the first line in that range. */
3048 if (wp->w_cursor.lnum <= lnum)
3049 {
3050 i = find_wl_entry(wp, lnum);
3051 if (i >= 0 && wp->w_cursor.lnum > wp->w_lines[i].wl_lnum)
3052 changed_line_abv_curs_win(wp);
3053 }
3054#endif
3055
3056 if (wp->w_cursor.lnum > lnum)
3057 changed_line_abv_curs_win(wp);
3058 else if (wp->w_cursor.lnum == lnum && wp->w_cursor.col >= col)
3059 changed_cline_bef_curs_win(wp);
3060 if (wp->w_botline >= lnum)
3061 {
3062 /* Assume that botline doesn't change (inserted lines make
3063 * other lines scroll down below botline). */
3064 approximate_botline_win(wp);
3065 }
3066
3067 /* Check if any w_lines[] entries have become invalid.
3068 * For entries below the change: Correct the lnums for
3069 * inserted/deleted lines. Makes it possible to stop displaying
3070 * after the change. */
3071 for (i = 0; i < wp->w_lines_valid; ++i)
3072 if (wp->w_lines[i].wl_valid)
3073 {
3074 if (wp->w_lines[i].wl_lnum >= lnum)
3075 {
3076 if (wp->w_lines[i].wl_lnum < lnume)
3077 {
3078 /* line included in change */
3079 wp->w_lines[i].wl_valid = FALSE;
3080 }
3081 else if (xtra != 0)
3082 {
3083 /* line below change */
3084 wp->w_lines[i].wl_lnum += xtra;
3085#ifdef FEAT_FOLDING
3086 wp->w_lines[i].wl_lastlnum += xtra;
3087#endif
3088 }
3089 }
3090#ifdef FEAT_FOLDING
3091 else if (wp->w_lines[i].wl_lastlnum >= lnum)
3092 {
3093 /* change somewhere inside this range of folded lines,
3094 * may need to be redrawn */
3095 wp->w_lines[i].wl_valid = FALSE;
3096 }
3097#endif
3098 }
Bram Moolenaar3234cc62009-11-03 17:47:12 +00003099
3100#ifdef FEAT_FOLDING
3101 /* Take care of side effects for setting w_topline when folds have
3102 * changed. Esp. when the buffer was changed in another window. */
3103 if (hasAnyFolding(wp))
3104 set_topline(wp, wp->w_topline);
3105#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003106 }
3107 }
3108
3109 /* Call update_screen() later, which checks out what needs to be redrawn,
3110 * since it notices b_mod_set and then uses b_mod_*. */
3111 if (must_redraw < VALID)
3112 must_redraw = VALID;
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00003113
3114#ifdef FEAT_AUTOCMD
3115 /* when the cursor line is changed always trigger CursorMoved */
Bram Moolenaare163f1c2006-10-17 09:12:21 +00003116 if (lnum <= curwin->w_cursor.lnum
3117 && lnume + (xtra < 0 ? -xtra : xtra) > curwin->w_cursor.lnum)
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00003118 last_cursormoved.lnum = 0;
3119#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003120}
3121
3122/*
3123 * unchanged() is called when the changed flag must be reset for buffer 'buf'
3124 */
3125 void
3126unchanged(buf, ff)
3127 buf_T *buf;
3128 int ff; /* also reset 'fileformat' */
3129{
Bram Moolenaar164c60f2011-01-22 00:11:50 +01003130 if (buf->b_changed || (ff && file_ff_differs(buf, FALSE)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003131 {
3132 buf->b_changed = 0;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003133 ml_setflags(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003134 if (ff)
3135 save_file_ff(buf);
3136#ifdef FEAT_WINDOWS
3137 check_status(buf);
Bram Moolenaar997fb4b2006-02-17 21:53:23 +00003138 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003139#endif
3140#ifdef FEAT_TITLE
3141 need_maketitle = TRUE; /* set window title later */
3142#endif
3143 }
3144 ++buf->b_changedtick;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003145#ifdef FEAT_NETBEANS_INTG
3146 netbeans_unmodified(buf);
3147#endif
3148}
3149
3150#if defined(FEAT_WINDOWS) || defined(PROTO)
3151/*
3152 * check_status: called when the status bars for the buffer 'buf'
3153 * need to be updated
3154 */
3155 void
3156check_status(buf)
3157 buf_T *buf;
3158{
3159 win_T *wp;
3160
3161 for (wp = firstwin; wp != NULL; wp = wp->w_next)
3162 if (wp->w_buffer == buf && wp->w_status_height)
3163 {
3164 wp->w_redr_status = TRUE;
3165 if (must_redraw < VALID)
3166 must_redraw = VALID;
3167 }
3168}
3169#endif
3170
3171/*
3172 * If the file is readonly, give a warning message with the first change.
3173 * Don't do this for autocommands.
3174 * Don't use emsg(), because it flushes the macro buffer.
Bram Moolenaard5cdbeb2005-10-10 20:59:28 +00003175 * If we have undone all changes b_changed will be FALSE, but "b_did_warn"
Bram Moolenaar071d4272004-06-13 20:20:40 +00003176 * will be TRUE.
Bram Moolenaarb0b50882010-07-07 18:26:28 +02003177 * Careful: may trigger autocommands that reload the buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003178 */
3179 void
3180change_warning(col)
3181 int col; /* column for message; non-zero when in insert
3182 mode and 'showmode' is on */
3183{
Bram Moolenaar496c5262009-03-18 14:42:00 +00003184 static char *w_readonly = N_("W10: Warning: Changing a readonly file");
3185
Bram Moolenaar071d4272004-06-13 20:20:40 +00003186 if (curbuf->b_did_warn == FALSE
3187 && curbufIsChanged() == 0
3188#ifdef FEAT_AUTOCMD
3189 && !autocmd_busy
3190#endif
3191 && curbuf->b_p_ro)
3192 {
3193#ifdef FEAT_AUTOCMD
Bram Moolenaar910f66f2006-04-05 20:41:53 +00003194 ++curbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003195 apply_autocmds(EVENT_FILECHANGEDRO, NULL, NULL, FALSE, curbuf);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00003196 --curbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003197 if (!curbuf->b_p_ro)
3198 return;
3199#endif
3200 /*
3201 * Do what msg() does, but with a column offset if the warning should
3202 * be after the mode message.
3203 */
3204 msg_start();
3205 if (msg_row == Rows - 1)
3206 msg_col = col;
Bram Moolenaar2df6dcc2004-07-12 15:53:54 +00003207 msg_source(hl_attr(HLF_W));
Bram Moolenaar496c5262009-03-18 14:42:00 +00003208 MSG_PUTS_ATTR(_(w_readonly), hl_attr(HLF_W) | MSG_HIST);
3209#ifdef FEAT_EVAL
3210 set_vim_var_string(VV_WARNINGMSG, (char_u *)_(w_readonly), -1);
3211#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003212 msg_clr_eos();
3213 (void)msg_end();
3214 if (msg_silent == 0 && !silent_mode)
3215 {
3216 out_flush();
3217 ui_delay(1000L, TRUE); /* give the user time to think about it */
3218 }
3219 curbuf->b_did_warn = TRUE;
3220 redraw_cmdline = FALSE; /* don't redraw and erase the message */
3221 if (msg_row < Rows - 1)
3222 showmode();
3223 }
3224}
3225
3226/*
3227 * Ask for a reply from the user, a 'y' or a 'n'.
3228 * No other characters are accepted, the message is repeated until a valid
3229 * reply is entered or CTRL-C is hit.
3230 * If direct is TRUE, don't use vgetc() but ui_inchar(), don't get characters
3231 * from any buffers but directly from the user.
3232 *
3233 * return the 'y' or 'n'
3234 */
3235 int
3236ask_yesno(str, direct)
3237 char_u *str;
3238 int direct;
3239{
3240 int r = ' ';
3241 int save_State = State;
3242
3243 if (exiting) /* put terminal in raw mode for this question */
3244 settmode(TMODE_RAW);
3245 ++no_wait_return;
3246#ifdef USE_ON_FLY_SCROLL
3247 dont_scroll = TRUE; /* disallow scrolling here */
3248#endif
3249 State = CONFIRM; /* mouse behaves like with :confirm */
3250#ifdef FEAT_MOUSE
3251 setmouse(); /* disables mouse for xterm */
3252#endif
3253 ++no_mapping;
3254 ++allow_keys; /* no mapping here, but recognize keys */
3255
3256 while (r != 'y' && r != 'n')
3257 {
3258 /* same highlighting as for wait_return */
3259 smsg_attr(hl_attr(HLF_R), (char_u *)"%s (y/n)?", str);
3260 if (direct)
3261 r = get_keystroke();
3262 else
Bram Moolenaar913626c2008-01-03 11:43:42 +00003263 r = plain_vgetc();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003264 if (r == Ctrl_C || r == ESC)
3265 r = 'n';
3266 msg_putchar(r); /* show what you typed */
3267 out_flush();
3268 }
3269 --no_wait_return;
3270 State = save_State;
3271#ifdef FEAT_MOUSE
3272 setmouse();
3273#endif
3274 --no_mapping;
3275 --allow_keys;
3276
3277 return r;
3278}
3279
3280/*
3281 * Get a key stroke directly from the user.
3282 * Ignores mouse clicks and scrollbar events, except a click for the left
3283 * button (used at the more prompt).
3284 * Doesn't use vgetc(), because it syncs undo and eats mapped characters.
3285 * Disadvantage: typeahead is ignored.
3286 * Translates the interrupt character for unix to ESC.
3287 */
3288 int
3289get_keystroke()
3290{
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003291 char_u *buf = NULL;
3292 int buflen = 150;
3293 int maxlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003294 int len = 0;
3295 int n;
3296 int save_mapped_ctrl_c = mapped_ctrl_c;
Bram Moolenaar4395a712006-09-05 18:57:57 +00003297 int waited = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003298
3299 mapped_ctrl_c = FALSE; /* mappings are not used here */
3300 for (;;)
3301 {
3302 cursor_on();
3303 out_flush();
3304
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003305 /* Leave some room for check_termcode() to insert a key code into (max
3306 * 5 chars plus NUL). And fix_input_buffer() can triple the number of
3307 * bytes. */
3308 maxlen = (buflen - 6 - len) / 3;
3309 if (buf == NULL)
3310 buf = alloc(buflen);
3311 else if (maxlen < 10)
3312 {
Bram Moolenaardc7e85e2012-06-20 12:40:08 +02003313 /* Need some more space. This might happen when receiving a long
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003314 * escape sequence. */
3315 buflen += 100;
3316 buf = vim_realloc(buf, buflen);
3317 maxlen = (buflen - 6 - len) / 3;
3318 }
3319 if (buf == NULL)
3320 {
3321 do_outofmem_msg((long_u)buflen);
3322 return ESC; /* panic! */
3323 }
3324
Bram Moolenaar071d4272004-06-13 20:20:40 +00003325 /* First time: blocking wait. Second time: wait up to 100ms for a
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003326 * terminal code to complete. */
3327 n = ui_inchar(buf + len, maxlen, len == 0 ? -1L : 100L, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003328 if (n > 0)
3329 {
3330 /* Replace zero and CSI by a special key code. */
3331 n = fix_input_buffer(buf + len, n, FALSE);
3332 len += n;
Bram Moolenaar4395a712006-09-05 18:57:57 +00003333 waited = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003334 }
Bram Moolenaar4395a712006-09-05 18:57:57 +00003335 else if (len > 0)
3336 ++waited; /* keep track of the waiting time */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003337
Bram Moolenaar4395a712006-09-05 18:57:57 +00003338 /* Incomplete termcode and not timed out yet: get more characters */
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003339 if ((n = check_termcode(1, buf, buflen, &len)) < 0
Bram Moolenaar4395a712006-09-05 18:57:57 +00003340 && (!p_ttimeout || waited * 100L < (p_ttm < 0 ? p_tm : p_ttm)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003341 continue;
Bram Moolenaar4395a712006-09-05 18:57:57 +00003342
Bram Moolenaar946ffd42010-12-30 12:30:31 +01003343 if (n == KEYLEN_REMOVED) /* key code removed */
Bram Moolenaar6eb634e2011-03-03 15:04:08 +01003344 {
Bram Moolenaarfd30cd42011-03-22 13:07:26 +01003345 if (must_redraw != 0 && !need_wait_return && (State & CMDLINE) == 0)
Bram Moolenaar6eb634e2011-03-03 15:04:08 +01003346 {
3347 /* Redrawing was postponed, do it now. */
3348 update_screen(0);
3349 setcursor(); /* put cursor back where it belongs */
3350 }
Bram Moolenaar946ffd42010-12-30 12:30:31 +01003351 continue;
Bram Moolenaar6eb634e2011-03-03 15:04:08 +01003352 }
Bram Moolenaar946ffd42010-12-30 12:30:31 +01003353 if (n > 0) /* found a termcode: adjust length */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003354 len = n;
Bram Moolenaar946ffd42010-12-30 12:30:31 +01003355 if (len == 0) /* nothing typed yet */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003356 continue;
3357
3358 /* Handle modifier and/or special key code. */
3359 n = buf[0];
3360 if (n == K_SPECIAL)
3361 {
3362 n = TO_SPECIAL(buf[1], buf[2]);
3363 if (buf[1] == KS_MODIFIER
3364 || n == K_IGNORE
3365#ifdef FEAT_MOUSE
3366 || n == K_LEFTMOUSE_NM
3367 || n == K_LEFTDRAG
3368 || n == K_LEFTRELEASE
3369 || n == K_LEFTRELEASE_NM
3370 || n == K_MIDDLEMOUSE
3371 || n == K_MIDDLEDRAG
3372 || n == K_MIDDLERELEASE
3373 || n == K_RIGHTMOUSE
3374 || n == K_RIGHTDRAG
3375 || n == K_RIGHTRELEASE
3376 || n == K_MOUSEDOWN
3377 || n == K_MOUSEUP
Bram Moolenaar8d9b40e2010-07-25 15:49:07 +02003378 || n == K_MOUSELEFT
3379 || n == K_MOUSERIGHT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003380 || n == K_X1MOUSE
3381 || n == K_X1DRAG
3382 || n == K_X1RELEASE
3383 || n == K_X2MOUSE
3384 || n == K_X2DRAG
3385 || n == K_X2RELEASE
3386# ifdef FEAT_GUI
3387 || n == K_VER_SCROLLBAR
3388 || n == K_HOR_SCROLLBAR
3389# endif
3390#endif
3391 )
3392 {
3393 if (buf[1] == KS_MODIFIER)
3394 mod_mask = buf[2];
3395 len -= 3;
3396 if (len > 0)
3397 mch_memmove(buf, buf + 3, (size_t)len);
3398 continue;
3399 }
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00003400 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003401 }
3402#ifdef FEAT_MBYTE
3403 if (has_mbyte)
3404 {
3405 if (MB_BYTE2LEN(n) > len)
3406 continue; /* more bytes to get */
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003407 buf[len >= buflen ? buflen - 1 : len] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003408 n = (*mb_ptr2char)(buf);
3409 }
3410#endif
3411#ifdef UNIX
3412 if (n == intr_char)
3413 n = ESC;
3414#endif
3415 break;
3416 }
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003417 vim_free(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003418
3419 mapped_ctrl_c = save_mapped_ctrl_c;
3420 return n;
3421}
3422
3423/*
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003424 * Get a number from the user.
3425 * When "mouse_used" is not NULL allow using the mouse.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003426 */
3427 int
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003428get_number(colon, mouse_used)
3429 int colon; /* allow colon to abort */
3430 int *mouse_used;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003431{
3432 int n = 0;
3433 int c;
Bram Moolenaar3991dab2006-03-27 17:01:56 +00003434 int typed = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003435
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003436 if (mouse_used != NULL)
3437 *mouse_used = FALSE;
3438
Bram Moolenaar071d4272004-06-13 20:20:40 +00003439 /* When not printing messages, the user won't know what to type, return a
3440 * zero (as if CR was hit). */
3441 if (msg_silent != 0)
3442 return 0;
3443
3444#ifdef USE_ON_FLY_SCROLL
3445 dont_scroll = TRUE; /* disallow scrolling here */
3446#endif
3447 ++no_mapping;
3448 ++allow_keys; /* no mapping here, but recognize keys */
3449 for (;;)
3450 {
3451 windgoto(msg_row, msg_col);
3452 c = safe_vgetc();
3453 if (VIM_ISDIGIT(c))
3454 {
3455 n = n * 10 + c - '0';
3456 msg_putchar(c);
Bram Moolenaar3991dab2006-03-27 17:01:56 +00003457 ++typed;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003458 }
3459 else if (c == K_DEL || c == K_KDEL || c == K_BS || c == Ctrl_H)
3460 {
Bram Moolenaar3991dab2006-03-27 17:01:56 +00003461 if (typed > 0)
3462 {
3463 MSG_PUTS("\b \b");
3464 --typed;
3465 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003466 n /= 10;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003467 }
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003468#ifdef FEAT_MOUSE
3469 else if (mouse_used != NULL && c == K_LEFTMOUSE)
3470 {
3471 *mouse_used = TRUE;
3472 n = mouse_row + 1;
3473 break;
3474 }
3475#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003476 else if (n == 0 && c == ':' && colon)
3477 {
3478 stuffcharReadbuff(':');
3479 if (!exmode_active)
3480 cmdline_row = msg_row;
3481 skip_redraw = TRUE; /* skip redraw once */
3482 do_redraw = FALSE;
3483 break;
3484 }
3485 else if (c == CAR || c == NL || c == Ctrl_C || c == ESC)
3486 break;
3487 }
3488 --no_mapping;
3489 --allow_keys;
3490 return n;
3491}
3492
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003493/*
3494 * Ask the user to enter a number.
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003495 * When "mouse_used" is not NULL allow using the mouse and in that case return
3496 * the line number.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003497 */
3498 int
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003499prompt_for_number(mouse_used)
3500 int *mouse_used;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003501{
3502 int i;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003503 int save_cmdline_row;
3504 int save_State;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003505
3506 /* When using ":silent" assume that <CR> was entered. */
Bram Moolenaar42eeac32005-06-29 22:40:58 +00003507 if (mouse_used != NULL)
Bram Moolenaard812df62008-11-09 12:46:09 +00003508 MSG_PUTS(_("Type number and <Enter> or click with mouse (empty cancels): "));
Bram Moolenaar42eeac32005-06-29 22:40:58 +00003509 else
Bram Moolenaard812df62008-11-09 12:46:09 +00003510 MSG_PUTS(_("Type number and <Enter> (empty cancels): "));
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003511
Bram Moolenaar203335e2006-09-03 14:35:42 +00003512 /* Set the state such that text can be selected/copied/pasted and we still
3513 * get mouse events. */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003514 save_cmdline_row = cmdline_row;
Bram Moolenaar203335e2006-09-03 14:35:42 +00003515 cmdline_row = 0;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003516 save_State = State;
Bram Moolenaar203335e2006-09-03 14:35:42 +00003517 State = CMDLINE;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003518
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003519 i = get_number(TRUE, mouse_used);
3520 if (KeyTyped)
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003521 {
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003522 /* don't call wait_return() now */
3523 /* msg_putchar('\n'); */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003524 cmdline_row = msg_row - 1;
3525 need_wait_return = FALSE;
3526 msg_didany = FALSE;
Bram Moolenaarb2450162009-07-22 09:04:20 +00003527 msg_didout = FALSE;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003528 }
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003529 else
3530 cmdline_row = save_cmdline_row;
3531 State = save_State;
3532
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003533 return i;
3534}
3535
Bram Moolenaar071d4272004-06-13 20:20:40 +00003536 void
3537msgmore(n)
3538 long n;
3539{
3540 long pn;
3541
3542 if (global_busy /* no messages now, wait until global is finished */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003543 || !messaging()) /* 'lazyredraw' set, don't do messages now */
3544 return;
3545
Bram Moolenaar7df2d662005-01-25 22:18:08 +00003546 /* We don't want to overwrite another important message, but do overwrite
3547 * a previous "more lines" or "fewer lines" message, so that "5dd" and
3548 * then "put" reports the last action. */
3549 if (keep_msg != NULL && !keep_msg_more)
3550 return;
3551
Bram Moolenaar071d4272004-06-13 20:20:40 +00003552 if (n > 0)
3553 pn = n;
3554 else
3555 pn = -n;
3556
3557 if (pn > p_report)
3558 {
3559 if (pn == 1)
3560 {
3561 if (n > 0)
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003562 vim_strncpy(msg_buf, (char_u *)_("1 more line"),
3563 MSG_BUF_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003564 else
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003565 vim_strncpy(msg_buf, (char_u *)_("1 line less"),
3566 MSG_BUF_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003567 }
3568 else
3569 {
3570 if (n > 0)
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003571 vim_snprintf((char *)msg_buf, MSG_BUF_LEN,
3572 _("%ld more lines"), pn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003573 else
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003574 vim_snprintf((char *)msg_buf, MSG_BUF_LEN,
3575 _("%ld fewer lines"), pn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003576 }
3577 if (got_int)
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003578 vim_strcat(msg_buf, (char_u *)_(" (Interrupted)"), MSG_BUF_LEN);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003579 if (msg(msg_buf))
3580 {
Bram Moolenaar238a5642006-02-21 22:12:05 +00003581 set_keep_msg(msg_buf, 0);
Bram Moolenaar7df2d662005-01-25 22:18:08 +00003582 keep_msg_more = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003583 }
3584 }
3585}
3586
3587/*
3588 * flush map and typeahead buffers and give a warning for an error
3589 */
3590 void
3591beep_flush()
3592{
3593 if (emsg_silent == 0)
3594 {
3595 flush_buffers(FALSE);
3596 vim_beep();
3597 }
3598}
3599
3600/*
3601 * give a warning for an error
3602 */
3603 void
3604vim_beep()
3605{
3606 if (emsg_silent == 0)
3607 {
3608 if (p_vb
3609#ifdef FEAT_GUI
3610 /* While the GUI is starting up the termcap is set for the GUI
3611 * but the output still goes to a terminal. */
3612 && !(gui.in_use && gui.starting)
3613#endif
3614 )
3615 {
3616 out_str(T_VB);
3617 }
3618 else
3619 {
3620#ifdef MSDOS
3621 /*
3622 * The number of beeps outputted is reduced to avoid having to wait
3623 * for all the beeps to finish. This is only a problem on systems
3624 * where the beeps don't overlap.
3625 */
3626 if (beep_count == 0 || beep_count == 10)
3627 {
3628 out_char(BELL);
3629 beep_count = 1;
3630 }
3631 else
3632 ++beep_count;
3633#else
3634 out_char(BELL);
3635#endif
3636 }
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003637
3638 /* When 'verbose' is set and we are sourcing a script or executing a
3639 * function give the user a hint where the beep comes from. */
3640 if (vim_strchr(p_debug, 'e') != NULL)
3641 {
3642 msg_source(hl_attr(HLF_W));
3643 msg_attr((char_u *)_("Beep!"), hl_attr(HLF_W));
3644 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003645 }
3646}
3647
3648/*
3649 * To get the "real" home directory:
3650 * - get value of $HOME
3651 * For Unix:
3652 * - go to that directory
3653 * - do mch_dirname() to get the real name of that directory.
3654 * This also works with mounts and links.
3655 * Don't do this for MS-DOS, it will change the "current dir" for a drive.
3656 */
3657static char_u *homedir = NULL;
3658
3659 void
3660init_homedir()
3661{
3662 char_u *var;
3663
Bram Moolenaar05159a02005-02-26 23:04:13 +00003664 /* In case we are called a second time (when 'encoding' changes). */
3665 vim_free(homedir);
3666 homedir = NULL;
3667
Bram Moolenaar071d4272004-06-13 20:20:40 +00003668#ifdef VMS
3669 var = mch_getenv((char_u *)"SYS$LOGIN");
3670#else
3671 var = mch_getenv((char_u *)"HOME");
3672#endif
3673
3674 if (var != NULL && *var == NUL) /* empty is same as not set */
3675 var = NULL;
3676
3677#ifdef WIN3264
3678 /*
3679 * Weird but true: $HOME may contain an indirect reference to another
3680 * variable, esp. "%USERPROFILE%". Happens when $USERPROFILE isn't set
3681 * when $HOME is being set.
3682 */
3683 if (var != NULL && *var == '%')
3684 {
3685 char_u *p;
3686 char_u *exp;
3687
3688 p = vim_strchr(var + 1, '%');
3689 if (p != NULL)
3690 {
Bram Moolenaarce0842a2005-07-18 21:58:11 +00003691 vim_strncpy(NameBuff, var + 1, p - (var + 1));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003692 exp = mch_getenv(NameBuff);
3693 if (exp != NULL && *exp != NUL
3694 && STRLEN(exp) + STRLEN(p) < MAXPATHL)
3695 {
Bram Moolenaar555b2802005-05-19 21:08:39 +00003696 vim_snprintf((char *)NameBuff, MAXPATHL, "%s%s", exp, p + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003697 var = NameBuff;
3698 /* Also set $HOME, it's needed for _viminfo. */
3699 vim_setenv((char_u *)"HOME", NameBuff);
3700 }
3701 }
3702 }
3703
3704 /*
3705 * Typically, $HOME is not defined on Windows, unless the user has
3706 * specifically defined it for Vim's sake. However, on Windows NT
3707 * platforms, $HOMEDRIVE and $HOMEPATH are automatically defined for
3708 * each user. Try constructing $HOME from these.
3709 */
3710 if (var == NULL)
3711 {
3712 char_u *homedrive, *homepath;
3713
3714 homedrive = mch_getenv((char_u *)"HOMEDRIVE");
3715 homepath = mch_getenv((char_u *)"HOMEPATH");
Bram Moolenaar6f977012010-01-06 17:53:38 +01003716 if (homepath == NULL || *homepath == NUL)
3717 homepath = "\\";
3718 if (homedrive != NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00003719 && STRLEN(homedrive) + STRLEN(homepath) < MAXPATHL)
3720 {
3721 sprintf((char *)NameBuff, "%s%s", homedrive, homepath);
3722 if (NameBuff[0] != NUL)
3723 {
3724 var = NameBuff;
3725 /* Also set $HOME, it's needed for _viminfo. */
3726 vim_setenv((char_u *)"HOME", NameBuff);
3727 }
3728 }
3729 }
Bram Moolenaar05159a02005-02-26 23:04:13 +00003730
3731# if defined(FEAT_MBYTE)
3732 if (enc_utf8 && var != NULL)
3733 {
3734 int len;
Bram Moolenaarb453a532011-04-28 17:48:44 +02003735 char_u *pp = NULL;
Bram Moolenaar05159a02005-02-26 23:04:13 +00003736
3737 /* Convert from active codepage to UTF-8. Other conversions are
3738 * not done, because they would fail for non-ASCII characters. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003739 acp_to_enc(var, (int)STRLEN(var), &pp, &len);
Bram Moolenaar05159a02005-02-26 23:04:13 +00003740 if (pp != NULL)
3741 {
3742 homedir = pp;
3743 return;
3744 }
3745 }
3746# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003747#endif
3748
3749#if defined(OS2) || defined(MSDOS) || defined(MSWIN)
3750 /*
3751 * Default home dir is C:/
3752 * Best assumption we can make in such a situation.
3753 */
3754 if (var == NULL)
3755 var = "C:/";
3756#endif
3757 if (var != NULL)
3758 {
3759#ifdef UNIX
3760 /*
3761 * Change to the directory and get the actual path. This resolves
3762 * links. Don't do it when we can't return.
3763 */
3764 if (mch_dirname(NameBuff, MAXPATHL) == OK
3765 && mch_chdir((char *)NameBuff) == 0)
3766 {
3767 if (!mch_chdir((char *)var) && mch_dirname(IObuff, IOSIZE) == OK)
3768 var = IObuff;
3769 if (mch_chdir((char *)NameBuff) != 0)
3770 EMSG(_(e_prev_dir));
3771 }
3772#endif
3773 homedir = vim_strsave(var);
3774 }
3775}
3776
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003777#if defined(EXITFREE) || defined(PROTO)
3778 void
3779free_homedir()
3780{
3781 vim_free(homedir);
3782}
3783#endif
3784
Bram Moolenaar071d4272004-06-13 20:20:40 +00003785/*
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003786 * Call expand_env() and store the result in an allocated string.
3787 * This is not very memory efficient, this expects the result to be freed
3788 * again soon.
3789 */
3790 char_u *
3791expand_env_save(src)
3792 char_u *src;
3793{
3794 return expand_env_save_opt(src, FALSE);
3795}
3796
3797/*
3798 * Idem, but when "one" is TRUE handle the string as one file name, only
3799 * expand "~" at the start.
3800 */
3801 char_u *
3802expand_env_save_opt(src, one)
3803 char_u *src;
3804 int one;
3805{
3806 char_u *p;
3807
3808 p = alloc(MAXPATHL);
3809 if (p != NULL)
3810 expand_env_esc(src, p, MAXPATHL, FALSE, one, NULL);
3811 return p;
3812}
3813
3814/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003815 * Expand environment variable with path name.
3816 * "~/" is also expanded, using $HOME. For Unix "~user/" is expanded.
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003817 * Skips over "\ ", "\~" and "\$" (not for Win32 though).
Bram Moolenaar071d4272004-06-13 20:20:40 +00003818 * If anything fails no expansion is done and dst equals src.
3819 */
3820 void
3821expand_env(src, dst, dstlen)
3822 char_u *src; /* input string e.g. "$HOME/vim.hlp" */
3823 char_u *dst; /* where to put the result */
3824 int dstlen; /* maximum length of the result */
3825{
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003826 expand_env_esc(src, dst, dstlen, FALSE, FALSE, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003827}
3828
3829 void
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003830expand_env_esc(srcp, dst, dstlen, esc, one, startstr)
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003831 char_u *srcp; /* input string e.g. "$HOME/vim.hlp" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003832 char_u *dst; /* where to put the result */
3833 int dstlen; /* maximum length of the result */
3834 int esc; /* escape spaces in expanded variables */
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003835 int one; /* "srcp" is one file name */
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003836 char_u *startstr; /* start again after this (can be NULL) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003837{
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003838 char_u *src;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003839 char_u *tail;
3840 int c;
3841 char_u *var;
3842 int copy_char;
3843 int mustfree; /* var was allocated, need to free it later */
3844 int at_start = TRUE; /* at start of a name */
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003845 int startstr_len = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003846
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003847 if (startstr != NULL)
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003848 startstr_len = (int)STRLEN(startstr);
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003849
3850 src = skipwhite(srcp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003851 --dstlen; /* leave one char space for "\," */
3852 while (*src && dstlen > 0)
3853 {
3854 copy_char = TRUE;
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003855 if ((*src == '$'
3856#ifdef VMS
3857 && at_start
3858#endif
3859 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003860#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3861 || *src == '%'
3862#endif
3863 || (*src == '~' && at_start))
3864 {
3865 mustfree = FALSE;
3866
3867 /*
3868 * The variable name is copied into dst temporarily, because it may
3869 * be a string in read-only memory and a NUL needs to be appended.
3870 */
3871 if (*src != '~') /* environment var */
3872 {
3873 tail = src + 1;
3874 var = dst;
3875 c = dstlen - 1;
3876
3877#ifdef UNIX
3878 /* Unix has ${var-name} type environment vars */
3879 if (*tail == '{' && !vim_isIDc('{'))
3880 {
3881 tail++; /* ignore '{' */
3882 while (c-- > 0 && *tail && *tail != '}')
3883 *var++ = *tail++;
3884 }
3885 else
3886#endif
3887 {
3888 while (c-- > 0 && *tail != NUL && ((vim_isIDc(*tail))
3889#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3890 || (*src == '%' && *tail != '%')
3891#endif
3892 ))
3893 {
3894#ifdef OS2 /* env vars only in uppercase */
3895 *var++ = TOUPPER_LOC(*tail);
3896 tail++; /* toupper() may be a macro! */
3897#else
3898 *var++ = *tail++;
3899#endif
3900 }
3901 }
3902
3903#if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
3904# ifdef UNIX
3905 if (src[1] == '{' && *tail != '}')
3906# else
3907 if (*src == '%' && *tail != '%')
3908# endif
3909 var = NULL;
3910 else
3911 {
3912# ifdef UNIX
3913 if (src[1] == '{')
3914# else
3915 if (*src == '%')
3916#endif
3917 ++tail;
3918#endif
3919 *var = NUL;
3920 var = vim_getenv(dst, &mustfree);
3921#if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
3922 }
3923#endif
3924 }
3925 /* home directory */
3926 else if ( src[1] == NUL
3927 || vim_ispathsep(src[1])
3928 || vim_strchr((char_u *)" ,\t\n", src[1]) != NULL)
3929 {
3930 var = homedir;
3931 tail = src + 1;
3932 }
3933 else /* user directory */
3934 {
3935#if defined(UNIX) || (defined(VMS) && defined(USER_HOME))
3936 /*
3937 * Copy ~user to dst[], so we can put a NUL after it.
3938 */
3939 tail = src;
3940 var = dst;
3941 c = dstlen - 1;
3942 while ( c-- > 0
3943 && *tail
3944 && vim_isfilec(*tail)
3945 && !vim_ispathsep(*tail))
3946 *var++ = *tail++;
3947 *var = NUL;
3948# ifdef UNIX
3949 /*
3950 * If the system supports getpwnam(), use it.
3951 * Otherwise, or if getpwnam() fails, the shell is used to
3952 * expand ~user. This is slower and may fail if the shell
3953 * does not support ~user (old versions of /bin/sh).
3954 */
3955# if defined(HAVE_GETPWNAM) && defined(HAVE_PWD_H)
3956 {
3957 struct passwd *pw;
3958
Bram Moolenaara40ceaf2006-01-13 22:35:40 +00003959 /* Note: memory allocated by getpwnam() is never freed.
3960 * Calling endpwent() apparently doesn't help. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003961 pw = getpwnam((char *)dst + 1);
3962 if (pw != NULL)
3963 var = (char_u *)pw->pw_dir;
3964 else
3965 var = NULL;
3966 }
3967 if (var == NULL)
3968# endif
3969 {
3970 expand_T xpc;
3971
3972 ExpandInit(&xpc);
3973 xpc.xp_context = EXPAND_FILES;
3974 var = ExpandOne(&xpc, dst, NULL,
3975 WILD_ADD_SLASH|WILD_SILENT, WILD_EXPAND_FREE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003976 mustfree = TRUE;
3977 }
3978
3979# else /* !UNIX, thus VMS */
3980 /*
3981 * USER_HOME is a comma-separated list of
3982 * directories to search for the user account in.
3983 */
3984 {
3985 char_u test[MAXPATHL], paths[MAXPATHL];
3986 char_u *path, *next_path, *ptr;
3987 struct stat st;
3988
3989 STRCPY(paths, USER_HOME);
3990 next_path = paths;
3991 while (*next_path)
3992 {
3993 for (path = next_path; *next_path && *next_path != ',';
3994 next_path++);
3995 if (*next_path)
3996 *next_path++ = NUL;
3997 STRCPY(test, path);
3998 STRCAT(test, "/");
3999 STRCAT(test, dst + 1);
4000 if (mch_stat(test, &st) == 0)
4001 {
4002 var = alloc(STRLEN(test) + 1);
4003 STRCPY(var, test);
4004 mustfree = TRUE;
4005 break;
4006 }
4007 }
4008 }
4009# endif /* UNIX */
4010#else
4011 /* cannot expand user's home directory, so don't try */
4012 var = NULL;
4013 tail = (char_u *)""; /* for gcc */
4014#endif /* UNIX || VMS */
4015 }
4016
4017#ifdef BACKSLASH_IN_FILENAME
4018 /* If 'shellslash' is set change backslashes to forward slashes.
4019 * Can't use slash_adjust(), p_ssl may be set temporarily. */
4020 if (p_ssl && var != NULL && vim_strchr(var, '\\') != NULL)
4021 {
4022 char_u *p = vim_strsave(var);
4023
4024 if (p != NULL)
4025 {
4026 if (mustfree)
4027 vim_free(var);
4028 var = p;
4029 mustfree = TRUE;
4030 forward_slash(var);
4031 }
4032 }
4033#endif
4034
4035 /* If "var" contains white space, escape it with a backslash.
4036 * Required for ":e ~/tt" when $HOME includes a space. */
4037 if (esc && var != NULL && vim_strpbrk(var, (char_u *)" \t") != NULL)
4038 {
4039 char_u *p = vim_strsave_escaped(var, (char_u *)" \t");
4040
4041 if (p != NULL)
4042 {
4043 if (mustfree)
4044 vim_free(var);
4045 var = p;
4046 mustfree = TRUE;
4047 }
4048 }
4049
4050 if (var != NULL && *var != NUL
4051 && (STRLEN(var) + STRLEN(tail) + 1 < (unsigned)dstlen))
4052 {
4053 STRCPY(dst, var);
4054 dstlen -= (int)STRLEN(var);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004055 c = (int)STRLEN(var);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004056 /* if var[] ends in a path separator and tail[] starts
4057 * with it, skip a character */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004058 if (*var != NUL && after_pathsep(dst, dst + c)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004059#if defined(BACKSLASH_IN_FILENAME) || defined(AMIGA)
4060 && dst[-1] != ':'
4061#endif
4062 && vim_ispathsep(*tail))
4063 ++tail;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004064 dst += c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004065 src = tail;
4066 copy_char = FALSE;
4067 }
4068 if (mustfree)
4069 vim_free(var);
4070 }
4071
4072 if (copy_char) /* copy at least one char */
4073 {
4074 /*
Bram Moolenaar25394022007-05-10 19:06:20 +00004075 * Recognize the start of a new name, for '~'.
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00004076 * Don't do this when "one" is TRUE, to avoid expanding "~" in
4077 * ":edit foo ~ foo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00004078 */
4079 at_start = FALSE;
4080 if (src[0] == '\\' && src[1] != NUL)
4081 {
4082 *dst++ = *src++;
4083 --dstlen;
4084 }
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00004085 else if ((src[0] == ' ' || src[0] == ',') && !one)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004086 at_start = TRUE;
4087 *dst++ = *src++;
4088 --dstlen;
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00004089
4090 if (startstr != NULL && src - startstr_len >= srcp
4091 && STRNCMP(src - startstr_len, startstr, startstr_len) == 0)
4092 at_start = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004093 }
4094 }
4095 *dst = NUL;
4096}
4097
4098/*
4099 * Vim's version of getenv().
4100 * Special handling of $HOME, $VIM and $VIMRUNTIME.
Bram Moolenaar2f6b0b82005-03-08 22:43:10 +00004101 * Also does ACP to 'enc' conversion for Win32.
Bram Moolenaarb453a532011-04-28 17:48:44 +02004102 * "mustfree" is set to TRUE when returned is allocated, it must be
4103 * initialized to FALSE by the caller.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004104 */
4105 char_u *
4106vim_getenv(name, mustfree)
4107 char_u *name;
Bram Moolenaarb453a532011-04-28 17:48:44 +02004108 int *mustfree;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004109{
4110 char_u *p;
4111 char_u *pend;
4112 int vimruntime;
4113
4114#if defined(OS2) || defined(MSDOS) || defined(MSWIN)
4115 /* use "C:/" when $HOME is not set */
4116 if (STRCMP(name, "HOME") == 0)
4117 return homedir;
4118#endif
4119
4120 p = mch_getenv(name);
4121 if (p != NULL && *p == NUL) /* empty is the same as not set */
4122 p = NULL;
4123
4124 if (p != NULL)
Bram Moolenaar05159a02005-02-26 23:04:13 +00004125 {
4126#if defined(FEAT_MBYTE) && defined(WIN3264)
4127 if (enc_utf8)
4128 {
4129 int len;
Bram Moolenaarb453a532011-04-28 17:48:44 +02004130 char_u *pp = NULL;
Bram Moolenaar05159a02005-02-26 23:04:13 +00004131
4132 /* Convert from active codepage to UTF-8. Other conversions are
4133 * not done, because they would fail for non-ASCII characters. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004134 acp_to_enc(p, (int)STRLEN(p), &pp, &len);
Bram Moolenaar05159a02005-02-26 23:04:13 +00004135 if (pp != NULL)
4136 {
4137 p = pp;
4138 *mustfree = TRUE;
4139 }
4140 }
4141#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004142 return p;
Bram Moolenaar05159a02005-02-26 23:04:13 +00004143 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004144
4145 vimruntime = (STRCMP(name, "VIMRUNTIME") == 0);
4146 if (!vimruntime && STRCMP(name, "VIM") != 0)
4147 return NULL;
4148
4149 /*
4150 * When expanding $VIMRUNTIME fails, try using $VIM/vim<version> or $VIM.
4151 * Don't do this when default_vimruntime_dir is non-empty.
4152 */
4153 if (vimruntime
4154#ifdef HAVE_PATHDEF
4155 && *default_vimruntime_dir == NUL
4156#endif
4157 )
4158 {
4159 p = mch_getenv((char_u *)"VIM");
4160 if (p != NULL && *p == NUL) /* empty is the same as not set */
4161 p = NULL;
4162 if (p != NULL)
4163 {
4164 p = vim_version_dir(p);
4165 if (p != NULL)
4166 *mustfree = TRUE;
4167 else
4168 p = mch_getenv((char_u *)"VIM");
Bram Moolenaar05159a02005-02-26 23:04:13 +00004169
4170#if defined(FEAT_MBYTE) && defined(WIN3264)
4171 if (enc_utf8)
4172 {
4173 int len;
Bram Moolenaarb453a532011-04-28 17:48:44 +02004174 char_u *pp = NULL;
Bram Moolenaar05159a02005-02-26 23:04:13 +00004175
4176 /* Convert from active codepage to UTF-8. Other conversions
4177 * are not done, because they would fail for non-ASCII
4178 * characters. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004179 acp_to_enc(p, (int)STRLEN(p), &pp, &len);
Bram Moolenaar05159a02005-02-26 23:04:13 +00004180 if (pp != NULL)
4181 {
Bram Moolenaarb453a532011-04-28 17:48:44 +02004182 if (*mustfree)
Bram Moolenaar05159a02005-02-26 23:04:13 +00004183 vim_free(p);
4184 p = pp;
4185 *mustfree = TRUE;
4186 }
4187 }
4188#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004189 }
4190 }
4191
4192 /*
4193 * When expanding $VIM or $VIMRUNTIME fails, try using:
4194 * - the directory name from 'helpfile' (unless it contains '$')
4195 * - the executable name from argv[0]
4196 */
4197 if (p == NULL)
4198 {
4199 if (p_hf != NULL && vim_strchr(p_hf, '$') == NULL)
4200 p = p_hf;
4201#ifdef USE_EXE_NAME
4202 /*
4203 * Use the name of the executable, obtained from argv[0].
4204 */
4205 else
4206 p = exe_name;
4207#endif
4208 if (p != NULL)
4209 {
4210 /* remove the file name */
4211 pend = gettail(p);
4212
4213 /* remove "doc/" from 'helpfile', if present */
4214 if (p == p_hf)
4215 pend = remove_tail(p, pend, (char_u *)"doc");
4216
4217#ifdef USE_EXE_NAME
4218# ifdef MACOS_X
Bram Moolenaar95e9b492006-03-15 23:04:43 +00004219 /* remove "MacOS" from exe_name and add "Resources/vim" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004220 if (p == exe_name)
4221 {
4222 char_u *pend1;
Bram Moolenaar95e9b492006-03-15 23:04:43 +00004223 char_u *pnew;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004224
Bram Moolenaar95e9b492006-03-15 23:04:43 +00004225 pend1 = remove_tail(p, pend, (char_u *)"MacOS");
4226 if (pend1 != pend)
4227 {
4228 pnew = alloc((unsigned)(pend1 - p) + 15);
4229 if (pnew != NULL)
4230 {
4231 STRNCPY(pnew, p, (pend1 - p));
4232 STRCPY(pnew + (pend1 - p), "Resources/vim");
4233 p = pnew;
4234 pend = p + STRLEN(p);
4235 }
4236 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004237 }
4238# endif
4239 /* remove "src/" from exe_name, if present */
4240 if (p == exe_name)
4241 pend = remove_tail(p, pend, (char_u *)"src");
4242#endif
4243
4244 /* for $VIM, remove "runtime/" or "vim54/", if present */
4245 if (!vimruntime)
4246 {
4247 pend = remove_tail(p, pend, (char_u *)RUNTIME_DIRNAME);
4248 pend = remove_tail(p, pend, (char_u *)VIM_VERSION_NODOT);
4249 }
4250
4251 /* remove trailing path separator */
4252#ifndef MACOS_CLASSIC
4253 /* With MacOS path (with colons) the final colon is required */
Bram Moolenaare21877a2008-02-13 09:58:14 +00004254 /* to avoid confusion between absolute and relative path */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004255 if (pend > p && after_pathsep(p, pend))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004256 --pend;
4257#endif
4258
Bram Moolenaar95e9b492006-03-15 23:04:43 +00004259#ifdef MACOS_X
4260 if (p == exe_name || p == p_hf)
4261#endif
4262 /* check that the result is a directory name */
4263 p = vim_strnsave(p, (int)(pend - p));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004264
4265 if (p != NULL && !mch_isdir(p))
4266 {
4267 vim_free(p);
4268 p = NULL;
4269 }
4270 else
4271 {
4272#ifdef USE_EXE_NAME
4273 /* may add "/vim54" or "/runtime" if it exists */
4274 if (vimruntime && (pend = vim_version_dir(p)) != NULL)
4275 {
4276 vim_free(p);
4277 p = pend;
4278 }
4279#endif
4280 *mustfree = TRUE;
4281 }
4282 }
4283 }
4284
4285#ifdef HAVE_PATHDEF
4286 /* When there is a pathdef.c file we can use default_vim_dir and
4287 * default_vimruntime_dir */
4288 if (p == NULL)
4289 {
4290 /* Only use default_vimruntime_dir when it is not empty */
4291 if (vimruntime && *default_vimruntime_dir != NUL)
4292 {
4293 p = default_vimruntime_dir;
4294 *mustfree = FALSE;
4295 }
4296 else if (*default_vim_dir != NUL)
4297 {
4298 if (vimruntime && (p = vim_version_dir(default_vim_dir)) != NULL)
4299 *mustfree = TRUE;
4300 else
4301 {
4302 p = default_vim_dir;
4303 *mustfree = FALSE;
4304 }
4305 }
4306 }
4307#endif
4308
4309 /*
4310 * Set the environment variable, so that the new value can be found fast
4311 * next time, and others can also use it (e.g. Perl).
4312 */
4313 if (p != NULL)
4314 {
4315 if (vimruntime)
4316 {
4317 vim_setenv((char_u *)"VIMRUNTIME", p);
4318 didset_vimruntime = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004319 }
4320 else
4321 {
4322 vim_setenv((char_u *)"VIM", p);
4323 didset_vim = TRUE;
4324 }
4325 }
4326 return p;
4327}
4328
4329/*
4330 * Check if the directory "vimdir/<version>" or "vimdir/runtime" exists.
4331 * Return NULL if not, return its name in allocated memory otherwise.
4332 */
4333 static char_u *
4334vim_version_dir(vimdir)
4335 char_u *vimdir;
4336{
4337 char_u *p;
4338
4339 if (vimdir == NULL || *vimdir == NUL)
4340 return NULL;
4341 p = concat_fnames(vimdir, (char_u *)VIM_VERSION_NODOT, TRUE);
4342 if (p != NULL && mch_isdir(p))
4343 return p;
4344 vim_free(p);
4345 p = concat_fnames(vimdir, (char_u *)RUNTIME_DIRNAME, TRUE);
4346 if (p != NULL && mch_isdir(p))
4347 return p;
4348 vim_free(p);
4349 return NULL;
4350}
4351
4352/*
4353 * If the string between "p" and "pend" ends in "name/", return "pend" minus
4354 * the length of "name/". Otherwise return "pend".
4355 */
4356 static char_u *
4357remove_tail(p, pend, name)
4358 char_u *p;
4359 char_u *pend;
4360 char_u *name;
4361{
4362 int len = (int)STRLEN(name) + 1;
4363 char_u *newend = pend - len;
4364
4365 if (newend >= p
4366 && fnamencmp(newend, name, len - 1) == 0
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004367 && (newend == p || after_pathsep(p, newend)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004368 return newend;
4369 return pend;
4370}
4371
Bram Moolenaar071d4272004-06-13 20:20:40 +00004372/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004373 * Our portable version of setenv.
4374 */
4375 void
4376vim_setenv(name, val)
4377 char_u *name;
4378 char_u *val;
4379{
4380#ifdef HAVE_SETENV
4381 mch_setenv((char *)name, (char *)val, 1);
4382#else
4383 char_u *envbuf;
4384
4385 /*
4386 * Putenv does not copy the string, it has to remain
4387 * valid. The allocated memory will never be freed.
4388 */
4389 envbuf = alloc((unsigned)(STRLEN(name) + STRLEN(val) + 2));
4390 if (envbuf != NULL)
4391 {
4392 sprintf((char *)envbuf, "%s=%s", name, val);
4393 putenv((char *)envbuf);
4394 }
4395#endif
Bram Moolenaar011a34d2012-02-29 13:49:09 +01004396#ifdef FEAT_GETTEXT
4397 /*
4398 * When setting $VIMRUNTIME adjust the directory to find message
4399 * translations to $VIMRUNTIME/lang.
4400 */
4401 if (*val != NUL && STRICMP(name, "VIMRUNTIME") == 0)
4402 {
4403 char_u *buf = concat_str(val, (char_u *)"/lang");
4404
4405 if (buf != NULL)
4406 {
4407 bindtextdomain(VIMPACKAGE, (char *)buf);
4408 vim_free(buf);
4409 }
4410 }
4411#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004412}
4413
4414#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
4415/*
4416 * Function given to ExpandGeneric() to obtain an environment variable name.
4417 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004418 char_u *
4419get_env_name(xp, idx)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00004420 expand_T *xp UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004421 int idx;
4422{
4423# if defined(AMIGA) || defined(__MRC__) || defined(__SC__)
4424 /*
4425 * No environ[] on the Amiga and on the Mac (using MPW).
4426 */
4427 return NULL;
4428# else
4429# ifndef __WIN32__
4430 /* Borland C++ 5.2 has this in a header file. */
4431 extern char **environ;
4432# endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00004433# define ENVNAMELEN 100
4434 static char_u name[ENVNAMELEN];
Bram Moolenaar071d4272004-06-13 20:20:40 +00004435 char_u *str;
4436 int n;
4437
4438 str = (char_u *)environ[idx];
4439 if (str == NULL)
4440 return NULL;
4441
Bram Moolenaar21cf8232004-07-16 20:18:37 +00004442 for (n = 0; n < ENVNAMELEN - 1; ++n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004443 {
4444 if (str[n] == '=' || str[n] == NUL)
4445 break;
4446 name[n] = str[n];
4447 }
4448 name[n] = NUL;
4449 return name;
4450# endif
4451}
4452#endif
4453
4454/*
4455 * Replace home directory by "~" in each space or comma separated file name in
4456 * 'src'.
4457 * If anything fails (except when out of space) dst equals src.
4458 */
4459 void
4460home_replace(buf, src, dst, dstlen, one)
4461 buf_T *buf; /* when not NULL, check for help files */
4462 char_u *src; /* input file name */
4463 char_u *dst; /* where to put the result */
4464 int dstlen; /* maximum length of the result */
4465 int one; /* if TRUE, only replace one file name, include
4466 spaces and commas in the file name. */
4467{
4468 size_t dirlen = 0, envlen = 0;
4469 size_t len;
Bram Moolenaar9158f9e2012-06-20 14:02:27 +02004470 char_u *homedir_env, *homedir_env_orig;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004471 char_u *p;
4472
4473 if (src == NULL)
4474 {
4475 *dst = NUL;
4476 return;
4477 }
4478
4479 /*
4480 * If the file is a help file, remove the path completely.
4481 */
4482 if (buf != NULL && buf->b_help)
4483 {
4484 STRCPY(dst, gettail(src));
4485 return;
4486 }
4487
4488 /*
4489 * We check both the value of the $HOME environment variable and the
4490 * "real" home directory.
4491 */
4492 if (homedir != NULL)
4493 dirlen = STRLEN(homedir);
4494
4495#ifdef VMS
Bram Moolenaar9158f9e2012-06-20 14:02:27 +02004496 homedir_env_orig = homedir_env = mch_getenv((char_u *)"SYS$LOGIN");
Bram Moolenaar071d4272004-06-13 20:20:40 +00004497#else
Bram Moolenaar9158f9e2012-06-20 14:02:27 +02004498 homedir_env_orig = homedir_env = mch_getenv((char_u *)"HOME");
4499#endif
Bram Moolenaarbef47902012-07-06 16:49:40 +02004500 /* Empty is the same as not set. */
4501 if (homedir_env != NULL && *homedir_env == NUL)
4502 homedir_env = NULL;
4503
Bram Moolenaar9158f9e2012-06-20 14:02:27 +02004504#if defined(FEAT_MODIFY_FNAME) || defined(WIN3264)
Bram Moolenaarbef47902012-07-06 16:49:40 +02004505 if (homedir_env != NULL && vim_strchr(homedir_env, '~') != NULL)
Bram Moolenaar9158f9e2012-06-20 14:02:27 +02004506 {
4507 int usedlen = 0;
4508 int flen;
4509 char_u *fbuf = NULL;
4510
4511 flen = (int)STRLEN(homedir_env);
Bram Moolenaard12f8112012-06-20 17:56:09 +02004512 (void)modify_fname((char_u *)":p", &usedlen,
4513 &homedir_env, &fbuf, &flen);
Bram Moolenaar9158f9e2012-06-20 14:02:27 +02004514 flen = (int)STRLEN(homedir_env);
4515 if (flen > 0 && vim_ispathsep(homedir_env[flen - 1]))
4516 /* Remove the trailing / that is added to a directory. */
4517 homedir_env[flen - 1] = NUL;
4518 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004519#endif
4520
Bram Moolenaar071d4272004-06-13 20:20:40 +00004521 if (homedir_env != NULL)
4522 envlen = STRLEN(homedir_env);
4523
4524 if (!one)
4525 src = skipwhite(src);
4526 while (*src && dstlen > 0)
4527 {
4528 /*
4529 * Here we are at the beginning of a file name.
4530 * First, check to see if the beginning of the file name matches
4531 * $HOME or the "real" home directory. Check that there is a '/'
4532 * after the match (so that if e.g. the file is "/home/pieter/bla",
4533 * and the home directory is "/home/piet", the file does not end up
4534 * as "~er/bla" (which would seem to indicate the file "bla" in user
4535 * er's home directory)).
4536 */
4537 p = homedir;
4538 len = dirlen;
4539 for (;;)
4540 {
4541 if ( len
4542 && fnamencmp(src, p, len) == 0
4543 && (vim_ispathsep(src[len])
4544 || (!one && (src[len] == ',' || src[len] == ' '))
4545 || src[len] == NUL))
4546 {
4547 src += len;
4548 if (--dstlen > 0)
4549 *dst++ = '~';
4550
4551 /*
4552 * If it's just the home directory, add "/".
4553 */
4554 if (!vim_ispathsep(src[0]) && --dstlen > 0)
4555 *dst++ = '/';
4556 break;
4557 }
4558 if (p == homedir_env)
4559 break;
4560 p = homedir_env;
4561 len = envlen;
4562 }
4563
4564 /* if (!one) skip to separator: space or comma */
4565 while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
4566 *dst++ = *src++;
4567 /* skip separator */
4568 while ((*src == ' ' || *src == ',') && --dstlen > 0)
4569 *dst++ = *src++;
4570 }
4571 /* if (dstlen == 0) out of space, what to do??? */
4572
4573 *dst = NUL;
Bram Moolenaar9158f9e2012-06-20 14:02:27 +02004574
4575 if (homedir_env != homedir_env_orig)
4576 vim_free(homedir_env);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004577}
4578
4579/*
4580 * Like home_replace, store the replaced string in allocated memory.
4581 * When something fails, NULL is returned.
4582 */
4583 char_u *
4584home_replace_save(buf, src)
4585 buf_T *buf; /* when not NULL, check for help files */
4586 char_u *src; /* input file name */
4587{
4588 char_u *dst;
4589 unsigned len;
4590
4591 len = 3; /* space for "~/" and trailing NUL */
4592 if (src != NULL) /* just in case */
4593 len += (unsigned)STRLEN(src);
4594 dst = alloc(len);
4595 if (dst != NULL)
4596 home_replace(buf, src, dst, len, TRUE);
4597 return dst;
4598}
4599
4600/*
4601 * Compare two file names and return:
4602 * FPC_SAME if they both exist and are the same file.
4603 * FPC_SAMEX if they both don't exist and have the same file name.
4604 * FPC_DIFF if they both exist and are different files.
4605 * FPC_NOTX if they both don't exist.
4606 * FPC_DIFFX if one of them doesn't exist.
4607 * For the first name environment variables are expanded
4608 */
4609 int
4610fullpathcmp(s1, s2, checkname)
4611 char_u *s1, *s2;
4612 int checkname; /* when both don't exist, check file names */
4613{
4614#ifdef UNIX
4615 char_u exp1[MAXPATHL];
4616 char_u full1[MAXPATHL];
4617 char_u full2[MAXPATHL];
4618 struct stat st1, st2;
4619 int r1, r2;
4620
4621 expand_env(s1, exp1, MAXPATHL);
4622 r1 = mch_stat((char *)exp1, &st1);
4623 r2 = mch_stat((char *)s2, &st2);
4624 if (r1 != 0 && r2 != 0)
4625 {
4626 /* if mch_stat() doesn't work, may compare the names */
4627 if (checkname)
4628 {
4629 if (fnamecmp(exp1, s2) == 0)
4630 return FPC_SAMEX;
4631 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4632 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4633 if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
4634 return FPC_SAMEX;
4635 }
4636 return FPC_NOTX;
4637 }
4638 if (r1 != 0 || r2 != 0)
4639 return FPC_DIFFX;
4640 if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
4641 return FPC_SAME;
4642 return FPC_DIFF;
4643#else
4644 char_u *exp1; /* expanded s1 */
4645 char_u *full1; /* full path of s1 */
4646 char_u *full2; /* full path of s2 */
4647 int retval = FPC_DIFF;
4648 int r1, r2;
4649
4650 /* allocate one buffer to store three paths (alloc()/free() is slow!) */
4651 if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
4652 {
4653 full1 = exp1 + MAXPATHL;
4654 full2 = full1 + MAXPATHL;
4655
4656 expand_env(s1, exp1, MAXPATHL);
4657 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4658 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4659
4660 /* If vim_FullName() fails, the file probably doesn't exist. */
4661 if (r1 != OK && r2 != OK)
4662 {
4663 if (checkname && fnamecmp(exp1, s2) == 0)
4664 retval = FPC_SAMEX;
4665 else
4666 retval = FPC_NOTX;
4667 }
4668 else if (r1 != OK || r2 != OK)
4669 retval = FPC_DIFFX;
4670 else if (fnamecmp(full1, full2))
4671 retval = FPC_DIFF;
4672 else
4673 retval = FPC_SAME;
4674 vim_free(exp1);
4675 }
4676 return retval;
4677#endif
4678}
4679
4680/*
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004681 * Get the tail of a path: the file name.
Bram Moolenaar31710262010-08-13 13:36:15 +02004682 * When the path ends in a path separator the tail is the NUL after it.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004683 * Fail safe: never returns NULL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004684 */
4685 char_u *
4686gettail(fname)
4687 char_u *fname;
4688{
4689 char_u *p1, *p2;
4690
4691 if (fname == NULL)
4692 return (char_u *)"";
4693 for (p1 = p2 = fname; *p2; ) /* find last part of path */
4694 {
4695 if (vim_ispathsep(*p2))
4696 p1 = p2 + 1;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004697 mb_ptr_adv(p2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004698 }
4699 return p1;
4700}
4701
Bram Moolenaar31710262010-08-13 13:36:15 +02004702#if defined(FEAT_SEARCHPATH)
4703static char_u *gettail_dir __ARGS((char_u *fname));
4704
4705/*
4706 * Return the end of the directory name, on the first path
4707 * separator:
4708 * "/path/file", "/path/dir/", "/path//dir", "/file"
4709 * ^ ^ ^ ^
4710 */
4711 static char_u *
4712gettail_dir(fname)
4713 char_u *fname;
4714{
4715 char_u *dir_end = fname;
4716 char_u *next_dir_end = fname;
4717 int look_for_sep = TRUE;
4718 char_u *p;
4719
4720 for (p = fname; *p != NUL; )
4721 {
4722 if (vim_ispathsep(*p))
4723 {
4724 if (look_for_sep)
4725 {
4726 next_dir_end = p;
4727 look_for_sep = FALSE;
4728 }
4729 }
4730 else
4731 {
4732 if (!look_for_sep)
4733 dir_end = next_dir_end;
4734 look_for_sep = TRUE;
4735 }
4736 mb_ptr_adv(p);
4737 }
4738 return dir_end;
4739}
4740#endif
4741
Bram Moolenaar071d4272004-06-13 20:20:40 +00004742/*
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004743 * Get pointer to tail of "fname", including path separators. Putting a NUL
4744 * here leaves the directory name. Takes care of "c:/" and "//".
4745 * Always returns a valid pointer.
4746 */
4747 char_u *
4748gettail_sep(fname)
4749 char_u *fname;
4750{
4751 char_u *p;
4752 char_u *t;
4753
4754 p = get_past_head(fname); /* don't remove the '/' from "c:/file" */
4755 t = gettail(fname);
4756 while (t > p && after_pathsep(fname, t))
4757 --t;
4758#ifdef VMS
4759 /* path separator is part of the path */
4760 ++t;
4761#endif
4762 return t;
4763}
4764
4765/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004766 * get the next path component (just after the next path separator).
4767 */
4768 char_u *
4769getnextcomp(fname)
4770 char_u *fname;
4771{
4772 while (*fname && !vim_ispathsep(*fname))
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004773 mb_ptr_adv(fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004774 if (*fname)
4775 ++fname;
4776 return fname;
4777}
4778
Bram Moolenaar071d4272004-06-13 20:20:40 +00004779/*
4780 * Get a pointer to one character past the head of a path name.
4781 * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
4782 * If there is no head, path is returned.
4783 */
4784 char_u *
4785get_past_head(path)
4786 char_u *path;
4787{
4788 char_u *retval;
4789
4790#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
4791 /* may skip "c:" */
4792 if (isalpha(path[0]) && path[1] == ':')
4793 retval = path + 2;
4794 else
4795 retval = path;
4796#else
4797# if defined(AMIGA)
4798 /* may skip "label:" */
4799 retval = vim_strchr(path, ':');
4800 if (retval == NULL)
4801 retval = path;
4802# else /* Unix */
4803 retval = path;
4804# endif
4805#endif
4806
4807 while (vim_ispathsep(*retval))
4808 ++retval;
4809
4810 return retval;
4811}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004812
4813/*
4814 * return TRUE if 'c' is a path separator.
4815 */
4816 int
4817vim_ispathsep(c)
4818 int c;
4819{
Bram Moolenaare60acc12011-05-10 16:41:25 +02004820#ifdef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00004821 return (c == '/'); /* UNIX has ':' inside file names */
Bram Moolenaare60acc12011-05-10 16:41:25 +02004822#else
4823# ifdef BACKSLASH_IN_FILENAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00004824 return (c == ':' || c == '/' || c == '\\');
Bram Moolenaare60acc12011-05-10 16:41:25 +02004825# else
4826# ifdef VMS
Bram Moolenaar071d4272004-06-13 20:20:40 +00004827 /* server"user passwd"::device:[full.path.name]fname.extension;version" */
4828 return (c == ':' || c == '[' || c == ']' || c == '/'
4829 || c == '<' || c == '>' || c == '"' );
Bram Moolenaare60acc12011-05-10 16:41:25 +02004830# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004831 return (c == ':' || c == '/');
Bram Moolenaare60acc12011-05-10 16:41:25 +02004832# endif /* VMS */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004833# endif
Bram Moolenaare60acc12011-05-10 16:41:25 +02004834#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004835}
4836
4837#if defined(FEAT_SEARCHPATH) || defined(PROTO)
4838/*
4839 * return TRUE if 'c' is a path list separator.
4840 */
4841 int
4842vim_ispathlistsep(c)
4843 int c;
4844{
4845#ifdef UNIX
4846 return (c == ':');
4847#else
Bram Moolenaar25394022007-05-10 19:06:20 +00004848 return (c == ';'); /* might not be right for every system... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004849#endif
4850}
4851#endif
4852
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004853#if defined(FEAT_GUI_TABLINE) || defined(FEAT_WINDOWS) \
4854 || defined(FEAT_EVAL) || defined(PROTO)
4855/*
4856 * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
4857 * It's done in-place.
4858 */
4859 void
4860shorten_dir(str)
4861 char_u *str;
4862{
4863 char_u *tail, *s, *d;
4864 int skip = FALSE;
4865
4866 tail = gettail(str);
4867 d = str;
4868 for (s = str; ; ++s)
4869 {
4870 if (s >= tail) /* copy the whole tail */
4871 {
4872 *d++ = *s;
4873 if (*s == NUL)
4874 break;
4875 }
4876 else if (vim_ispathsep(*s)) /* copy '/' and next char */
4877 {
4878 *d++ = *s;
4879 skip = FALSE;
4880 }
4881 else if (!skip)
4882 {
4883 *d++ = *s; /* copy next char */
4884 if (*s != '~' && *s != '.') /* and leading "~" and "." */
4885 skip = TRUE;
4886# ifdef FEAT_MBYTE
4887 if (has_mbyte)
4888 {
4889 int l = mb_ptr2len(s);
4890
4891 while (--l > 0)
Bram Moolenaarb6baca52006-08-15 20:24:14 +00004892 *d++ = *++s;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004893 }
4894# endif
4895 }
4896 }
4897}
4898#endif
4899
Bram Moolenaar900b4d72005-12-12 22:05:50 +00004900/*
4901 * Return TRUE if the directory of "fname" exists, FALSE otherwise.
4902 * Also returns TRUE if there is no directory name.
4903 * "fname" must be writable!.
4904 */
4905 int
4906dir_of_file_exists(fname)
4907 char_u *fname;
4908{
4909 char_u *p;
4910 int c;
4911 int retval;
4912
4913 p = gettail_sep(fname);
4914 if (p == fname)
4915 return TRUE;
4916 c = *p;
4917 *p = NUL;
4918 retval = mch_isdir(fname);
4919 *p = c;
4920 return retval;
4921}
4922
Bram Moolenaar071d4272004-06-13 20:20:40 +00004923#if (defined(CASE_INSENSITIVE_FILENAME) && defined(BACKSLASH_IN_FILENAME)) \
4924 || defined(PROTO)
4925/*
4926 * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally.
4927 */
4928 int
4929vim_fnamecmp(x, y)
4930 char_u *x, *y;
4931{
4932 return vim_fnamencmp(x, y, MAXPATHL);
4933}
4934
4935 int
4936vim_fnamencmp(x, y, len)
4937 char_u *x, *y;
4938 size_t len;
4939{
4940 while (len > 0 && *x && *y)
4941 {
4942 if (TOLOWER_LOC(*x) != TOLOWER_LOC(*y)
4943 && !(*x == '/' && *y == '\\')
4944 && !(*x == '\\' && *y == '/'))
4945 break;
4946 ++x;
4947 ++y;
4948 --len;
4949 }
4950 if (len == 0)
4951 return 0;
4952 return (*x - *y);
4953}
4954#endif
4955
4956/*
4957 * Concatenate file names fname1 and fname2 into allocated memory.
Bram Moolenaar25394022007-05-10 19:06:20 +00004958 * Only add a '/' or '\\' when 'sep' is TRUE and it is necessary.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004959 */
4960 char_u *
4961concat_fnames(fname1, fname2, sep)
4962 char_u *fname1;
4963 char_u *fname2;
4964 int sep;
4965{
4966 char_u *dest;
4967
4968 dest = alloc((unsigned)(STRLEN(fname1) + STRLEN(fname2) + 3));
4969 if (dest != NULL)
4970 {
4971 STRCPY(dest, fname1);
4972 if (sep)
4973 add_pathsep(dest);
4974 STRCAT(dest, fname2);
4975 }
4976 return dest;
4977}
4978
Bram Moolenaard6754642005-01-17 22:18:45 +00004979/*
4980 * Concatenate two strings and return the result in allocated memory.
4981 * Returns NULL when out of memory.
4982 */
4983 char_u *
4984concat_str(str1, str2)
4985 char_u *str1;
4986 char_u *str2;
4987{
4988 char_u *dest;
4989 size_t l = STRLEN(str1);
4990
4991 dest = alloc((unsigned)(l + STRLEN(str2) + 1L));
4992 if (dest != NULL)
4993 {
4994 STRCPY(dest, str1);
4995 STRCPY(dest + l, str2);
4996 }
4997 return dest;
4998}
Bram Moolenaard6754642005-01-17 22:18:45 +00004999
Bram Moolenaar071d4272004-06-13 20:20:40 +00005000/*
5001 * Add a path separator to a file name, unless it already ends in a path
5002 * separator.
5003 */
5004 void
5005add_pathsep(p)
5006 char_u *p;
5007{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005008 if (*p != NUL && !after_pathsep(p, p + STRLEN(p)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005009 STRCAT(p, PATHSEPSTR);
5010}
5011
5012/*
5013 * FullName_save - Make an allocated copy of a full file name.
5014 * Returns NULL when out of memory.
5015 */
5016 char_u *
5017FullName_save(fname, force)
5018 char_u *fname;
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +02005019 int force; /* force expansion, even when it already looks
5020 * like a full path name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005021{
5022 char_u *buf;
5023 char_u *new_fname = NULL;
5024
5025 if (fname == NULL)
5026 return NULL;
5027
5028 buf = alloc((unsigned)MAXPATHL);
5029 if (buf != NULL)
5030 {
5031 if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
5032 new_fname = vim_strsave(buf);
5033 else
5034 new_fname = vim_strsave(fname);
5035 vim_free(buf);
5036 }
5037 return new_fname;
5038}
5039
5040#if defined(FEAT_CINDENT) || defined(FEAT_SYN_HL)
5041
5042static char_u *skip_string __ARGS((char_u *p));
5043
5044/*
5045 * Find the start of a comment, not knowing if we are in a comment right now.
5046 * Search starts at w_cursor.lnum and goes backwards.
5047 */
5048 pos_T *
5049find_start_comment(ind_maxcomment) /* XXX */
5050 int ind_maxcomment;
5051{
5052 pos_T *pos;
5053 char_u *line;
5054 char_u *p;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005055 int cur_maxcomment = ind_maxcomment;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005056
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005057 for (;;)
5058 {
5059 pos = findmatchlimit(NULL, '*', FM_BACKWARD, cur_maxcomment);
5060 if (pos == NULL)
5061 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005062
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005063 /*
5064 * Check if the comment start we found is inside a string.
5065 * If it is then restrict the search to below this line and try again.
5066 */
5067 line = ml_get(pos->lnum);
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00005068 for (p = line; *p && (colnr_T)(p - line) < pos->col; ++p)
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005069 p = skip_string(p);
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00005070 if ((colnr_T)(p - line) <= pos->col)
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005071 break;
5072 cur_maxcomment = curwin->w_cursor.lnum - pos->lnum - 1;
5073 if (cur_maxcomment <= 0)
5074 {
5075 pos = NULL;
5076 break;
5077 }
5078 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005079 return pos;
5080}
5081
5082/*
5083 * Skip to the end of a "string" and a 'c' character.
5084 * If there is no string or character, return argument unmodified.
5085 */
5086 static char_u *
5087skip_string(p)
5088 char_u *p;
5089{
5090 int i;
5091
5092 /*
5093 * We loop, because strings may be concatenated: "date""time".
5094 */
5095 for ( ; ; ++p)
5096 {
5097 if (p[0] == '\'') /* 'c' or '\n' or '\000' */
5098 {
5099 if (!p[1]) /* ' at end of line */
5100 break;
5101 i = 2;
5102 if (p[1] == '\\') /* '\n' or '\000' */
5103 {
5104 ++i;
5105 while (vim_isdigit(p[i - 1])) /* '\000' */
5106 ++i;
5107 }
5108 if (p[i] == '\'') /* check for trailing ' */
5109 {
5110 p += i;
5111 continue;
5112 }
5113 }
5114 else if (p[0] == '"') /* start of string */
5115 {
5116 for (++p; p[0]; ++p)
5117 {
5118 if (p[0] == '\\' && p[1] != NUL)
5119 ++p;
5120 else if (p[0] == '"') /* end of string */
5121 break;
5122 }
5123 if (p[0] == '"')
5124 continue;
5125 }
5126 break; /* no string found */
5127 }
5128 if (!*p)
5129 --p; /* backup from NUL */
5130 return p;
5131}
5132#endif /* FEAT_CINDENT || FEAT_SYN_HL */
5133
5134#if defined(FEAT_CINDENT) || defined(PROTO)
5135
5136/*
5137 * Do C or expression indenting on the current line.
5138 */
5139 void
5140do_c_expr_indent()
5141{
5142# ifdef FEAT_EVAL
5143 if (*curbuf->b_p_inde != NUL)
5144 fixthisline(get_expr_indent);
5145 else
5146# endif
5147 fixthisline(get_c_indent);
5148}
5149
5150/*
5151 * Functions for C-indenting.
5152 * Most of this originally comes from Eric Fischer.
5153 */
5154/*
5155 * Below "XXX" means that this function may unlock the current line.
5156 */
5157
5158static char_u *cin_skipcomment __ARGS((char_u *));
5159static int cin_nocode __ARGS((char_u *));
5160static pos_T *find_line_comment __ARGS((void));
5161static int cin_islabel_skip __ARGS((char_u **));
5162static int cin_isdefault __ARGS((char_u *));
5163static char_u *after_label __ARGS((char_u *l));
5164static int get_indent_nolabel __ARGS((linenr_T lnum));
5165static int skip_label __ARGS((linenr_T, char_u **pp, int ind_maxcomment));
5166static int cin_first_id_amount __ARGS((void));
5167static int cin_get_equal_amount __ARGS((linenr_T lnum));
5168static int cin_ispreproc __ARGS((char_u *));
5169static int cin_ispreproc_cont __ARGS((char_u **pp, linenr_T *lnump));
5170static int cin_iscomment __ARGS((char_u *));
5171static int cin_islinecomment __ARGS((char_u *));
5172static int cin_isterminated __ARGS((char_u *, int, int));
5173static int cin_isinit __ARGS((void));
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005174static int cin_isfuncdecl __ARGS((char_u **, linenr_T, linenr_T, int, int));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005175static int cin_isif __ARGS((char_u *));
5176static int cin_iselse __ARGS((char_u *));
5177static int cin_isdo __ARGS((char_u *));
5178static int cin_iswhileofdo __ARGS((char_u *, linenr_T, int));
Bram Moolenaarb345d492012-04-09 20:42:26 +02005179static int cin_is_if_for_while_before_offset __ARGS((char_u *line, int *poffset));
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005180static int cin_iswhileofdo_end __ARGS((int terminated, int ind_maxparen, int ind_maxcomment));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005181static int cin_isbreak __ARGS((char_u *));
Bram Moolenaare7c56862007-08-04 10:14:52 +00005182static int cin_is_cpp_baseclass __ARGS((colnr_T *col));
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005183static int get_baseclass_amount __ARGS((int col, int ind_maxparen, int ind_maxcomment, int ind_cpp_baseclass));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005184static int cin_ends_in __ARGS((char_u *, char_u *, char_u *));
5185static int cin_skip2pos __ARGS((pos_T *trypos));
5186static pos_T *find_start_brace __ARGS((int));
5187static pos_T *find_match_paren __ARGS((int, int));
5188static int corr_ind_maxparen __ARGS((int ind_maxparen, pos_T *startpos));
5189static int find_last_paren __ARGS((char_u *l, int start, int end));
5190static int find_match __ARGS((int lookfor, linenr_T ourscope, int ind_maxparen, int ind_maxcomment));
Bram Moolenaared38b0a2011-05-25 15:16:18 +02005191static int cin_is_cpp_namespace __ARGS((char_u *));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005192
Bram Moolenaar39353fd2007-03-27 09:02:11 +00005193static int ind_hash_comment = 0; /* # starts a comment */
5194
Bram Moolenaar071d4272004-06-13 20:20:40 +00005195/*
5196 * Skip over white space and C comments within the line.
Bram Moolenaar39353fd2007-03-27 09:02:11 +00005197 * Also skip over Perl/shell comments if desired.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005198 */
5199 static char_u *
5200cin_skipcomment(s)
5201 char_u *s;
5202{
5203 while (*s)
5204 {
Bram Moolenaar39353fd2007-03-27 09:02:11 +00005205 char_u *prev_s = s;
5206
Bram Moolenaar071d4272004-06-13 20:20:40 +00005207 s = skipwhite(s);
Bram Moolenaar39353fd2007-03-27 09:02:11 +00005208
5209 /* Perl/shell # comment comment continues until eol. Require a space
5210 * before # to avoid recognizing $#array. */
5211 if (ind_hash_comment != 0 && s != prev_s && *s == '#')
5212 {
5213 s += STRLEN(s);
5214 break;
5215 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005216 if (*s != '/')
5217 break;
5218 ++s;
5219 if (*s == '/') /* slash-slash comment continues till eol */
5220 {
5221 s += STRLEN(s);
5222 break;
5223 }
5224 if (*s != '*')
5225 break;
5226 for (++s; *s; ++s) /* skip slash-star comment */
5227 if (s[0] == '*' && s[1] == '/')
5228 {
5229 s += 2;
5230 break;
5231 }
5232 }
5233 return s;
5234}
5235
5236/*
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005237 * Return TRUE if there is no code at *s. White space and comments are
Bram Moolenaar071d4272004-06-13 20:20:40 +00005238 * not considered code.
5239 */
5240 static int
5241cin_nocode(s)
5242 char_u *s;
5243{
5244 return *cin_skipcomment(s) == NUL;
5245}
5246
5247/*
5248 * Check previous lines for a "//" line comment, skipping over blank lines.
5249 */
5250 static pos_T *
5251find_line_comment() /* XXX */
5252{
5253 static pos_T pos;
5254 char_u *line;
5255 char_u *p;
5256
5257 pos = curwin->w_cursor;
5258 while (--pos.lnum > 0)
5259 {
5260 line = ml_get(pos.lnum);
5261 p = skipwhite(line);
5262 if (cin_islinecomment(p))
5263 {
5264 pos.col = (int)(p - line);
5265 return &pos;
5266 }
5267 if (*p != NUL)
5268 break;
5269 }
5270 return NULL;
5271}
5272
5273/*
5274 * Check if string matches "label:"; move to character after ':' if true.
5275 */
5276 static int
5277cin_islabel_skip(s)
5278 char_u **s;
5279{
5280 if (!vim_isIDc(**s)) /* need at least one ID character */
5281 return FALSE;
5282
5283 while (vim_isIDc(**s))
5284 (*s)++;
5285
5286 *s = cin_skipcomment(*s);
5287
5288 /* "::" is not a label, it's C++ */
5289 return (**s == ':' && *++*s != ':');
5290}
5291
5292/*
5293 * Recognize a label: "label:".
5294 * Note: curwin->w_cursor must be where we are looking for the label.
5295 */
5296 int
5297cin_islabel(ind_maxcomment) /* XXX */
5298 int ind_maxcomment;
5299{
5300 char_u *s;
5301
5302 s = cin_skipcomment(ml_get_curline());
5303
5304 /*
5305 * Exclude "default" from labels, since it should be indented
5306 * like a switch label. Same for C++ scope declarations.
5307 */
5308 if (cin_isdefault(s))
5309 return FALSE;
5310 if (cin_isscopedecl(s))
5311 return FALSE;
5312
5313 if (cin_islabel_skip(&s))
5314 {
5315 /*
5316 * Only accept a label if the previous line is terminated or is a case
5317 * label.
5318 */
5319 pos_T cursor_save;
5320 pos_T *trypos;
5321 char_u *line;
5322
5323 cursor_save = curwin->w_cursor;
5324 while (curwin->w_cursor.lnum > 1)
5325 {
5326 --curwin->w_cursor.lnum;
5327
5328 /*
5329 * If we're in a comment now, skip to the start of the comment.
5330 */
5331 curwin->w_cursor.col = 0;
5332 if ((trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
5333 curwin->w_cursor = *trypos;
5334
5335 line = ml_get_curline();
5336 if (cin_ispreproc(line)) /* ignore #defines, #if, etc. */
5337 continue;
5338 if (*(line = cin_skipcomment(line)) == NUL)
5339 continue;
5340
5341 curwin->w_cursor = cursor_save;
5342 if (cin_isterminated(line, TRUE, FALSE)
5343 || cin_isscopedecl(line)
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005344 || cin_iscase(line, TRUE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005345 || (cin_islabel_skip(&line) && cin_nocode(line)))
5346 return TRUE;
5347 return FALSE;
5348 }
5349 curwin->w_cursor = cursor_save;
5350 return TRUE; /* label at start of file??? */
5351 }
5352 return FALSE;
5353}
5354
5355/*
5356 * Recognize structure initialization and enumerations.
5357 * Q&D-Implementation:
5358 * check for "=" at end or "[typedef] enum" at beginning of line.
5359 */
5360 static int
5361cin_isinit(void)
5362{
5363 char_u *s;
5364
5365 s = cin_skipcomment(ml_get_curline());
5366
5367 if (STRNCMP(s, "typedef", 7) == 0 && !vim_isIDc(s[7]))
5368 s = cin_skipcomment(s + 7);
5369
Bram Moolenaara5285652011-12-14 20:05:21 +01005370 if (STRNCMP(s, "static", 6) == 0 && !vim_isIDc(s[6]))
5371 s = cin_skipcomment(s + 6);
5372
Bram Moolenaar071d4272004-06-13 20:20:40 +00005373 if (STRNCMP(s, "enum", 4) == 0 && !vim_isIDc(s[4]))
5374 return TRUE;
5375
5376 if (cin_ends_in(s, (char_u *)"=", (char_u *)"{"))
5377 return TRUE;
5378
5379 return FALSE;
5380}
5381
5382/*
5383 * Recognize a switch label: "case .*:" or "default:".
5384 */
5385 int
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005386cin_iscase(s, strict)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005387 char_u *s;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005388 int strict; /* Allow relaxed check of case statement for JS */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005389{
5390 s = cin_skipcomment(s);
5391 if (STRNCMP(s, "case", 4) == 0 && !vim_isIDc(s[4]))
5392 {
5393 for (s += 4; *s; ++s)
5394 {
5395 s = cin_skipcomment(s);
5396 if (*s == ':')
5397 {
5398 if (s[1] == ':') /* skip over "::" for C++ */
5399 ++s;
5400 else
5401 return TRUE;
5402 }
5403 if (*s == '\'' && s[1] && s[2] == '\'')
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005404 s += 2; /* skip over ':' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005405 else if (*s == '/' && (s[1] == '*' || s[1] == '/'))
5406 return FALSE; /* stop at comment */
5407 else if (*s == '"')
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005408 {
5409 /* JS etc. */
5410 if (strict)
5411 return FALSE; /* stop at string */
5412 else
5413 return TRUE;
5414 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005415 }
5416 return FALSE;
5417 }
5418
5419 if (cin_isdefault(s))
5420 return TRUE;
5421 return FALSE;
5422}
5423
5424/*
5425 * Recognize a "default" switch label.
5426 */
5427 static int
5428cin_isdefault(s)
5429 char_u *s;
5430{
5431 return (STRNCMP(s, "default", 7) == 0
5432 && *(s = cin_skipcomment(s + 7)) == ':'
5433 && s[1] != ':');
5434}
5435
5436/*
Bram Moolenaar1a509df2010-08-01 17:59:57 +02005437 * Recognize a "public/private/protected" scope declaration label.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005438 */
5439 int
5440cin_isscopedecl(s)
5441 char_u *s;
5442{
5443 int i;
5444
5445 s = cin_skipcomment(s);
5446 if (STRNCMP(s, "public", 6) == 0)
5447 i = 6;
5448 else if (STRNCMP(s, "protected", 9) == 0)
5449 i = 9;
5450 else if (STRNCMP(s, "private", 7) == 0)
5451 i = 7;
5452 else
5453 return FALSE;
5454 return (*(s = cin_skipcomment(s + i)) == ':' && s[1] != ':');
5455}
5456
Bram Moolenaared38b0a2011-05-25 15:16:18 +02005457/* Maximum number of lines to search back for a "namespace" line. */
5458#define FIND_NAMESPACE_LIM 20
5459
5460/*
5461 * Recognize a "namespace" scope declaration.
5462 */
5463 static int
5464cin_is_cpp_namespace(s)
5465 char_u *s;
5466{
5467 char_u *p;
5468 int has_name = FALSE;
5469
5470 s = cin_skipcomment(s);
5471 if (STRNCMP(s, "namespace", 9) == 0 && (s[9] == NUL || !vim_iswordc(s[9])))
5472 {
5473 p = cin_skipcomment(skipwhite(s + 9));
5474 while (*p != NUL)
5475 {
5476 if (vim_iswhite(*p))
5477 {
5478 has_name = TRUE; /* found end of a name */
5479 p = cin_skipcomment(skipwhite(p));
5480 }
5481 else if (*p == '{')
5482 {
5483 break;
5484 }
5485 else if (vim_iswordc(*p))
5486 {
5487 if (has_name)
5488 return FALSE; /* word character after skipping past name */
5489 ++p;
5490 }
5491 else
5492 {
5493 return FALSE;
5494 }
5495 }
5496 return TRUE;
5497 }
5498 return FALSE;
5499}
5500
Bram Moolenaar071d4272004-06-13 20:20:40 +00005501/*
5502 * Return a pointer to the first non-empty non-comment character after a ':'.
5503 * Return NULL if not found.
5504 * case 234: a = b;
5505 * ^
5506 */
5507 static char_u *
5508after_label(l)
5509 char_u *l;
5510{
5511 for ( ; *l; ++l)
5512 {
5513 if (*l == ':')
5514 {
5515 if (l[1] == ':') /* skip over "::" for C++ */
5516 ++l;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005517 else if (!cin_iscase(l + 1, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005518 break;
5519 }
5520 else if (*l == '\'' && l[1] && l[2] == '\'')
5521 l += 2; /* skip over 'x' */
5522 }
5523 if (*l == NUL)
5524 return NULL;
5525 l = cin_skipcomment(l + 1);
5526 if (*l == NUL)
5527 return NULL;
5528 return l;
5529}
5530
5531/*
5532 * Get indent of line "lnum", skipping a label.
5533 * Return 0 if there is nothing after the label.
5534 */
5535 static int
5536get_indent_nolabel(lnum) /* XXX */
5537 linenr_T lnum;
5538{
5539 char_u *l;
5540 pos_T fp;
5541 colnr_T col;
5542 char_u *p;
5543
5544 l = ml_get(lnum);
5545 p = after_label(l);
5546 if (p == NULL)
5547 return 0;
5548
5549 fp.col = (colnr_T)(p - l);
5550 fp.lnum = lnum;
5551 getvcol(curwin, &fp, &col, NULL, NULL);
5552 return (int)col;
5553}
5554
5555/*
5556 * Find indent for line "lnum", ignoring any case or jump label.
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005557 * Also return a pointer to the text (after the label) in "pp".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005558 * label: if (asdf && asdfasdf)
5559 * ^
5560 */
5561 static int
5562skip_label(lnum, pp, ind_maxcomment)
5563 linenr_T lnum;
5564 char_u **pp;
5565 int ind_maxcomment;
5566{
5567 char_u *l;
5568 int amount;
5569 pos_T cursor_save;
5570
5571 cursor_save = curwin->w_cursor;
5572 curwin->w_cursor.lnum = lnum;
5573 l = ml_get_curline();
5574 /* XXX */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005575 if (cin_iscase(l, FALSE) || cin_isscopedecl(l)
5576 || cin_islabel(ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005577 {
5578 amount = get_indent_nolabel(lnum);
5579 l = after_label(ml_get_curline());
5580 if (l == NULL) /* just in case */
5581 l = ml_get_curline();
5582 }
5583 else
5584 {
5585 amount = get_indent();
5586 l = ml_get_curline();
5587 }
5588 *pp = l;
5589
5590 curwin->w_cursor = cursor_save;
5591 return amount;
5592}
5593
5594/*
5595 * Return the indent of the first variable name after a type in a declaration.
5596 * int a, indent of "a"
5597 * static struct foo b, indent of "b"
5598 * enum bla c, indent of "c"
5599 * Returns zero when it doesn't look like a declaration.
5600 */
5601 static int
5602cin_first_id_amount()
5603{
5604 char_u *line, *p, *s;
5605 int len;
5606 pos_T fp;
5607 colnr_T col;
5608
5609 line = ml_get_curline();
5610 p = skipwhite(line);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005611 len = (int)(skiptowhite(p) - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005612 if (len == 6 && STRNCMP(p, "static", 6) == 0)
5613 {
5614 p = skipwhite(p + 6);
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00005615 len = (int)(skiptowhite(p) - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005616 }
5617 if (len == 6 && STRNCMP(p, "struct", 6) == 0)
5618 p = skipwhite(p + 6);
5619 else if (len == 4 && STRNCMP(p, "enum", 4) == 0)
5620 p = skipwhite(p + 4);
5621 else if ((len == 8 && STRNCMP(p, "unsigned", 8) == 0)
5622 || (len == 6 && STRNCMP(p, "signed", 6) == 0))
5623 {
5624 s = skipwhite(p + len);
5625 if ((STRNCMP(s, "int", 3) == 0 && vim_iswhite(s[3]))
5626 || (STRNCMP(s, "long", 4) == 0 && vim_iswhite(s[4]))
5627 || (STRNCMP(s, "short", 5) == 0 && vim_iswhite(s[5]))
5628 || (STRNCMP(s, "char", 4) == 0 && vim_iswhite(s[4])))
5629 p = s;
5630 }
5631 for (len = 0; vim_isIDc(p[len]); ++len)
5632 ;
5633 if (len == 0 || !vim_iswhite(p[len]) || cin_nocode(p))
5634 return 0;
5635
5636 p = skipwhite(p + len);
5637 fp.lnum = curwin->w_cursor.lnum;
5638 fp.col = (colnr_T)(p - line);
5639 getvcol(curwin, &fp, &col, NULL, NULL);
5640 return (int)col;
5641}
5642
5643/*
5644 * Return the indent of the first non-blank after an equal sign.
5645 * char *foo = "here";
5646 * Return zero if no (useful) equal sign found.
5647 * Return -1 if the line above "lnum" ends in a backslash.
5648 * foo = "asdf\
5649 * asdf\
5650 * here";
5651 */
5652 static int
5653cin_get_equal_amount(lnum)
5654 linenr_T lnum;
5655{
5656 char_u *line;
5657 char_u *s;
5658 colnr_T col;
5659 pos_T fp;
5660
5661 if (lnum > 1)
5662 {
5663 line = ml_get(lnum - 1);
5664 if (*line != NUL && line[STRLEN(line) - 1] == '\\')
5665 return -1;
5666 }
5667
5668 line = s = ml_get(lnum);
5669 while (*s != NUL && vim_strchr((char_u *)"=;{}\"'", *s) == NULL)
5670 {
5671 if (cin_iscomment(s)) /* ignore comments */
5672 s = cin_skipcomment(s);
5673 else
5674 ++s;
5675 }
5676 if (*s != '=')
5677 return 0;
5678
5679 s = skipwhite(s + 1);
5680 if (cin_nocode(s))
5681 return 0;
5682
5683 if (*s == '"') /* nice alignment for continued strings */
5684 ++s;
5685
5686 fp.lnum = lnum;
5687 fp.col = (colnr_T)(s - line);
5688 getvcol(curwin, &fp, &col, NULL, NULL);
5689 return (int)col;
5690}
5691
5692/*
5693 * Recognize a preprocessor statement: Any line that starts with '#'.
5694 */
5695 static int
5696cin_ispreproc(s)
5697 char_u *s;
5698{
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005699 if (*skipwhite(s) == '#')
Bram Moolenaar071d4272004-06-13 20:20:40 +00005700 return TRUE;
5701 return FALSE;
5702}
5703
5704/*
5705 * Return TRUE if line "*pp" at "*lnump" is a preprocessor statement or a
5706 * continuation line of a preprocessor statement. Decrease "*lnump" to the
5707 * start and return the line in "*pp".
5708 */
5709 static int
5710cin_ispreproc_cont(pp, lnump)
5711 char_u **pp;
5712 linenr_T *lnump;
5713{
5714 char_u *line = *pp;
5715 linenr_T lnum = *lnump;
5716 int retval = FALSE;
5717
Bram Moolenaard8e9bb22005-07-09 21:14:46 +00005718 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005719 {
5720 if (cin_ispreproc(line))
5721 {
5722 retval = TRUE;
5723 *lnump = lnum;
5724 break;
5725 }
5726 if (lnum == 1)
5727 break;
5728 line = ml_get(--lnum);
5729 if (*line == NUL || line[STRLEN(line) - 1] != '\\')
5730 break;
5731 }
5732
5733 if (lnum != *lnump)
5734 *pp = ml_get(*lnump);
5735 return retval;
5736}
5737
5738/*
5739 * Recognize the start of a C or C++ comment.
5740 */
5741 static int
5742cin_iscomment(p)
5743 char_u *p;
5744{
5745 return (p[0] == '/' && (p[1] == '*' || p[1] == '/'));
5746}
5747
5748/*
5749 * Recognize the start of a "//" comment.
5750 */
5751 static int
5752cin_islinecomment(p)
5753 char_u *p;
5754{
5755 return (p[0] == '/' && p[1] == '/');
5756}
5757
5758/*
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005759 * Recognize a line that starts with '{' or '}', or ends with ';', ',', '{' or
5760 * '}'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005761 * Don't consider "} else" a terminated line.
Bram Moolenaar496f9512011-05-19 16:35:09 +02005762 * If a line begins with an "else", only consider it terminated if no unmatched
5763 * opening braces follow (handle "else { foo();" correctly).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005764 * Return the character terminating the line (ending char's have precedence if
5765 * both apply in order to determine initializations).
5766 */
5767 static int
5768cin_isterminated(s, incl_open, incl_comma)
5769 char_u *s;
5770 int incl_open; /* include '{' at the end as terminator */
5771 int incl_comma; /* recognize a trailing comma */
5772{
Bram Moolenaar496f9512011-05-19 16:35:09 +02005773 char_u found_start = 0;
5774 unsigned n_open = 0;
5775 int is_else = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005776
5777 s = cin_skipcomment(s);
5778
5779 if (*s == '{' || (*s == '}' && !cin_iselse(s)))
5780 found_start = *s;
5781
Bram Moolenaar496f9512011-05-19 16:35:09 +02005782 if (!found_start)
5783 is_else = cin_iselse(s);
5784
Bram Moolenaar071d4272004-06-13 20:20:40 +00005785 while (*s)
5786 {
5787 /* skip over comments, "" strings and 'c'haracters */
5788 s = skip_string(cin_skipcomment(s));
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005789 if (*s == '}' && n_open > 0)
5790 --n_open;
Bram Moolenaar496f9512011-05-19 16:35:09 +02005791 if ((!is_else || n_open == 0)
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005792 && (*s == ';' || *s == '}' || (incl_comma && *s == ','))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005793 && cin_nocode(s + 1))
5794 return *s;
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005795 else if (*s == '{')
5796 {
5797 if (incl_open && cin_nocode(s + 1))
5798 return *s;
5799 else
5800 ++n_open;
5801 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005802
5803 if (*s)
5804 s++;
5805 }
5806 return found_start;
5807}
5808
5809/*
5810 * Recognize the basic picture of a function declaration -- it needs to
5811 * have an open paren somewhere and a close paren at the end of the line and
5812 * no semicolons anywhere.
5813 * When a line ends in a comma we continue looking in the next line.
5814 * "sp" points to a string with the line. When looking at other lines it must
5815 * be restored to the line. When it's NULL fetch lines here.
5816 * "lnum" is where we start looking.
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005817 * "min_lnum" is the line before which we will not be looking.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005818 */
5819 static int
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005820cin_isfuncdecl(sp, first_lnum, min_lnum, ind_maxparen, ind_maxcomment)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005821 char_u **sp;
5822 linenr_T first_lnum;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005823 linenr_T min_lnum;
5824 int ind_maxparen;
5825 int ind_maxcomment;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005826{
5827 char_u *s;
5828 linenr_T lnum = first_lnum;
5829 int retval = FALSE;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005830 pos_T *trypos;
5831 int just_started = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005832
5833 if (sp == NULL)
5834 s = ml_get(lnum);
5835 else
5836 s = *sp;
5837
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005838 if (find_last_paren(s, '(', ')')
5839 && (trypos = find_match_paren(ind_maxparen, ind_maxcomment)) != NULL)
5840 {
5841 lnum = trypos->lnum;
5842 if (lnum < min_lnum)
5843 return FALSE;
5844
5845 s = ml_get(lnum);
5846 }
5847
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005848 /* Ignore line starting with #. */
5849 if (cin_ispreproc(s))
5850 return FALSE;
5851
Bram Moolenaar071d4272004-06-13 20:20:40 +00005852 while (*s && *s != '(' && *s != ';' && *s != '\'' && *s != '"')
5853 {
5854 if (cin_iscomment(s)) /* ignore comments */
5855 s = cin_skipcomment(s);
5856 else
5857 ++s;
5858 }
5859 if (*s != '(')
5860 return FALSE; /* ';', ' or " before any () or no '(' */
5861
5862 while (*s && *s != ';' && *s != '\'' && *s != '"')
5863 {
5864 if (*s == ')' && cin_nocode(s + 1))
5865 {
5866 /* ')' at the end: may have found a match
5867 * Check for he previous line not to end in a backslash:
5868 * #if defined(x) && \
5869 * defined(y)
5870 */
5871 lnum = first_lnum - 1;
5872 s = ml_get(lnum);
5873 if (*s == NUL || s[STRLEN(s) - 1] != '\\')
5874 retval = TRUE;
5875 goto done;
5876 }
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005877 if ((*s == ',' && cin_nocode(s + 1)) || s[1] == NUL || cin_nocode(s))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005878 {
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005879 int comma = (*s == ',');
5880
5881 /* ',' at the end: continue looking in the next line.
5882 * At the end: check for ',' in the next line, for this style:
5883 * func(arg1
5884 * , arg2) */
5885 for (;;)
5886 {
5887 if (lnum >= curbuf->b_ml.ml_line_count)
5888 break;
5889 s = ml_get(++lnum);
5890 if (!cin_ispreproc(s))
5891 break;
5892 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005893 if (lnum >= curbuf->b_ml.ml_line_count)
5894 break;
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005895 /* Require a comma at end of the line or a comma or ')' at the
5896 * start of next line. */
5897 s = skipwhite(s);
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005898 if (!just_started && (!comma && *s != ',' && *s != ')'))
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005899 break;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005900 just_started = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005901 }
5902 else if (cin_iscomment(s)) /* ignore comments */
5903 s = cin_skipcomment(s);
5904 else
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005905 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005906 ++s;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005907 just_started = FALSE;
5908 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005909 }
5910
5911done:
5912 if (lnum != first_lnum && sp != NULL)
5913 *sp = ml_get(first_lnum);
5914
5915 return retval;
5916}
5917
5918 static int
5919cin_isif(p)
5920 char_u *p;
5921{
5922 return (STRNCMP(p, "if", 2) == 0 && !vim_isIDc(p[2]));
5923}
5924
5925 static int
5926cin_iselse(p)
5927 char_u *p;
5928{
5929 if (*p == '}') /* accept "} else" */
5930 p = cin_skipcomment(p + 1);
5931 return (STRNCMP(p, "else", 4) == 0 && !vim_isIDc(p[4]));
5932}
5933
5934 static int
5935cin_isdo(p)
5936 char_u *p;
5937{
5938 return (STRNCMP(p, "do", 2) == 0 && !vim_isIDc(p[2]));
5939}
5940
5941/*
5942 * Check if this is a "while" that should have a matching "do".
5943 * We only accept a "while (condition) ;", with only white space between the
5944 * ')' and ';'. The condition may be spread over several lines.
5945 */
5946 static int
5947cin_iswhileofdo(p, lnum, ind_maxparen) /* XXX */
5948 char_u *p;
5949 linenr_T lnum;
5950 int ind_maxparen;
5951{
5952 pos_T cursor_save;
5953 pos_T *trypos;
5954 int retval = FALSE;
5955
5956 p = cin_skipcomment(p);
5957 if (*p == '}') /* accept "} while (cond);" */
5958 p = cin_skipcomment(p + 1);
5959 if (STRNCMP(p, "while", 5) == 0 && !vim_isIDc(p[5]))
5960 {
5961 cursor_save = curwin->w_cursor;
5962 curwin->w_cursor.lnum = lnum;
5963 curwin->w_cursor.col = 0;
5964 p = ml_get_curline();
5965 while (*p && *p != 'w') /* skip any '}', until the 'w' of the "while" */
5966 {
5967 ++p;
5968 ++curwin->w_cursor.col;
5969 }
5970 if ((trypos = findmatchlimit(NULL, 0, 0, ind_maxparen)) != NULL
5971 && *cin_skipcomment(ml_get_pos(trypos) + 1) == ';')
5972 retval = TRUE;
5973 curwin->w_cursor = cursor_save;
5974 }
5975 return retval;
5976}
5977
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005978/*
Bram Moolenaarb345d492012-04-09 20:42:26 +02005979 * Check whether in "p" there is an "if", "for" or "while" before "*poffset".
Bram Moolenaar3675fa02012-04-05 17:17:42 +02005980 * Return 0 if there is none.
5981 * Otherwise return !0 and update "*poffset" to point to the place where the
5982 * string was found.
5983 */
5984 static int
Bram Moolenaarb345d492012-04-09 20:42:26 +02005985cin_is_if_for_while_before_offset(line, poffset)
Bram Moolenaar3675fa02012-04-05 17:17:42 +02005986 char_u *line;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02005987 int *poffset;
5988{
Bram Moolenaarb345d492012-04-09 20:42:26 +02005989 int offset = *poffset;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02005990
5991 if (offset-- < 2)
5992 return 0;
5993 while (offset > 2 && vim_iswhite(line[offset]))
5994 --offset;
5995
5996 offset -= 1;
5997 if (!STRNCMP(line + offset, "if", 2))
5998 goto probablyFound;
5999
6000 if (offset >= 1)
6001 {
6002 offset -= 1;
6003 if (!STRNCMP(line + offset, "for", 3))
6004 goto probablyFound;
6005
6006 if (offset >= 2)
6007 {
6008 offset -= 2;
6009 if (!STRNCMP(line + offset, "while", 5))
6010 goto probablyFound;
6011 }
6012 }
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006013 return 0;
Bram Moolenaarb345d492012-04-09 20:42:26 +02006014
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006015probablyFound:
6016 if (!offset || !vim_isIDc(line[offset - 1]))
6017 {
6018 *poffset = offset;
6019 return 1;
6020 }
6021 return 0;
6022}
6023
6024/*
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006025 * Return TRUE if we are at the end of a do-while.
6026 * do
6027 * nothing;
6028 * while (foo
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00006029 * && bar); <-- here
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006030 * Adjust the cursor to the line with "while".
6031 */
6032 static int
6033cin_iswhileofdo_end(terminated, ind_maxparen, ind_maxcomment)
6034 int terminated;
6035 int ind_maxparen;
6036 int ind_maxcomment;
6037{
6038 char_u *line;
6039 char_u *p;
6040 char_u *s;
6041 pos_T *trypos;
6042 int i;
6043
6044 if (terminated != ';') /* there must be a ';' at the end */
6045 return FALSE;
6046
6047 p = line = ml_get_curline();
6048 while (*p != NUL)
6049 {
6050 p = cin_skipcomment(p);
6051 if (*p == ')')
6052 {
6053 s = skipwhite(p + 1);
6054 if (*s == ';' && cin_nocode(s + 1))
6055 {
6056 /* Found ");" at end of the line, now check there is "while"
6057 * before the matching '('. XXX */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006058 i = (int)(p - line);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006059 curwin->w_cursor.col = i;
6060 trypos = find_match_paren(ind_maxparen, ind_maxcomment);
6061 if (trypos != NULL)
6062 {
6063 s = cin_skipcomment(ml_get(trypos->lnum));
6064 if (*s == '}') /* accept "} while (cond);" */
6065 s = cin_skipcomment(s + 1);
6066 if (STRNCMP(s, "while", 5) == 0 && !vim_isIDc(s[5]))
6067 {
6068 curwin->w_cursor.lnum = trypos->lnum;
6069 return TRUE;
6070 }
6071 }
6072
6073 /* Searching may have made "line" invalid, get it again. */
6074 line = ml_get_curline();
6075 p = line + i;
6076 }
6077 }
6078 if (*p != NUL)
6079 ++p;
6080 }
6081 return FALSE;
6082}
6083
Bram Moolenaar071d4272004-06-13 20:20:40 +00006084 static int
6085cin_isbreak(p)
6086 char_u *p;
6087{
6088 return (STRNCMP(p, "break", 5) == 0 && !vim_isIDc(p[5]));
6089}
6090
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006091/*
6092 * Find the position of a C++ base-class declaration or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006093 * constructor-initialization. eg:
6094 *
6095 * class MyClass :
6096 * baseClass <-- here
6097 * class MyClass : public baseClass,
6098 * anotherBaseClass <-- here (should probably lineup ??)
6099 * MyClass::MyClass(...) :
6100 * baseClass(...) <-- here (constructor-initialization)
Bram Moolenaar18144c82006-04-12 21:52:12 +00006101 *
6102 * This is a lot of guessing. Watch out for "cond ? func() : foo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00006103 */
6104 static int
Bram Moolenaare7c56862007-08-04 10:14:52 +00006105cin_is_cpp_baseclass(col)
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006106 colnr_T *col; /* return: column to align with */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006107{
6108 char_u *s;
6109 int class_or_struct, lookfor_ctor_init, cpp_base_class;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006110 linenr_T lnum = curwin->w_cursor.lnum;
Bram Moolenaare7c56862007-08-04 10:14:52 +00006111 char_u *line = ml_get_curline();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006112
6113 *col = 0;
6114
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006115 s = skipwhite(line);
6116 if (*s == '#') /* skip #define FOO x ? (x) : x */
6117 return FALSE;
6118 s = cin_skipcomment(s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006119 if (*s == NUL)
6120 return FALSE;
6121
6122 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
6123
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006124 /* Search for a line starting with '#', empty, ending in ';' or containing
6125 * '{' or '}' and start below it. This handles the following situations:
6126 * a = cond ?
6127 * func() :
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00006128 * asdf;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006129 * func::foo()
6130 * : something
6131 * {}
6132 * Foo::Foo (int one, int two)
6133 * : something(4),
6134 * somethingelse(3)
6135 * {}
6136 */
6137 while (lnum > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006138 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00006139 line = ml_get(lnum - 1);
6140 s = skipwhite(line);
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006141 if (*s == '#' || *s == NUL)
6142 break;
6143 while (*s != NUL)
6144 {
6145 s = cin_skipcomment(s);
6146 if (*s == '{' || *s == '}'
6147 || (*s == ';' && cin_nocode(s + 1)))
6148 break;
6149 if (*s != NUL)
6150 ++s;
6151 }
6152 if (*s != NUL)
6153 break;
6154 --lnum;
6155 }
6156
Bram Moolenaare7c56862007-08-04 10:14:52 +00006157 line = ml_get(lnum);
6158 s = cin_skipcomment(line);
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006159 for (;;)
6160 {
6161 if (*s == NUL)
6162 {
6163 if (lnum == curwin->w_cursor.lnum)
6164 break;
6165 /* Continue in the cursor line. */
Bram Moolenaare7c56862007-08-04 10:14:52 +00006166 line = ml_get(++lnum);
6167 s = cin_skipcomment(line);
6168 if (*s == NUL)
6169 continue;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006170 }
6171
Bram Moolenaaraede6ce2011-05-10 11:56:30 +02006172 if (s[0] == '"')
6173 s = skip_string(s) + 1;
6174 else if (s[0] == ':')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006175 {
6176 if (s[1] == ':')
6177 {
6178 /* skip double colon. It can't be a constructor
6179 * initialization any more */
6180 lookfor_ctor_init = FALSE;
6181 s = cin_skipcomment(s + 2);
6182 }
6183 else if (lookfor_ctor_init || class_or_struct)
6184 {
6185 /* we have something found, that looks like the start of
Bram Moolenaare21877a2008-02-13 09:58:14 +00006186 * cpp-base-class-declaration or constructor-initialization */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006187 cpp_base_class = TRUE;
6188 lookfor_ctor_init = class_or_struct = FALSE;
6189 *col = 0;
6190 s = cin_skipcomment(s + 1);
6191 }
6192 else
6193 s = cin_skipcomment(s + 1);
6194 }
6195 else if ((STRNCMP(s, "class", 5) == 0 && !vim_isIDc(s[5]))
6196 || (STRNCMP(s, "struct", 6) == 0 && !vim_isIDc(s[6])))
6197 {
6198 class_or_struct = TRUE;
6199 lookfor_ctor_init = FALSE;
6200
6201 if (*s == 'c')
6202 s = cin_skipcomment(s + 5);
6203 else
6204 s = cin_skipcomment(s + 6);
6205 }
6206 else
6207 {
6208 if (s[0] == '{' || s[0] == '}' || s[0] == ';')
6209 {
6210 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
6211 }
6212 else if (s[0] == ')')
6213 {
6214 /* Constructor-initialization is assumed if we come across
6215 * something like "):" */
6216 class_or_struct = FALSE;
6217 lookfor_ctor_init = TRUE;
6218 }
Bram Moolenaar18144c82006-04-12 21:52:12 +00006219 else if (s[0] == '?')
6220 {
6221 /* Avoid seeing '() :' after '?' as constructor init. */
6222 return FALSE;
6223 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006224 else if (!vim_isIDc(s[0]))
6225 {
6226 /* if it is not an identifier, we are wrong */
6227 class_or_struct = FALSE;
6228 lookfor_ctor_init = FALSE;
6229 }
6230 else if (*col == 0)
6231 {
6232 /* it can't be a constructor-initialization any more */
6233 lookfor_ctor_init = FALSE;
6234
6235 /* the first statement starts here: lineup with this one... */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006236 if (cpp_base_class)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006237 *col = (colnr_T)(s - line);
6238 }
6239
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006240 /* When the line ends in a comma don't align with it. */
6241 if (lnum == curwin->w_cursor.lnum && *s == ',' && cin_nocode(s + 1))
6242 *col = 0;
6243
Bram Moolenaar071d4272004-06-13 20:20:40 +00006244 s = cin_skipcomment(s + 1);
6245 }
6246 }
6247
6248 return cpp_base_class;
6249}
6250
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006251 static int
6252get_baseclass_amount(col, ind_maxparen, ind_maxcomment, ind_cpp_baseclass)
6253 int col;
6254 int ind_maxparen;
6255 int ind_maxcomment;
6256 int ind_cpp_baseclass;
6257{
6258 int amount;
6259 colnr_T vcol;
6260 pos_T *trypos;
6261
6262 if (col == 0)
6263 {
6264 amount = get_indent();
6265 if (find_last_paren(ml_get_curline(), '(', ')')
6266 && (trypos = find_match_paren(ind_maxparen,
6267 ind_maxcomment)) != NULL)
6268 amount = get_indent_lnum(trypos->lnum); /* XXX */
6269 if (!cin_ends_in(ml_get_curline(), (char_u *)",", NULL))
6270 amount += ind_cpp_baseclass;
6271 }
6272 else
6273 {
6274 curwin->w_cursor.col = col;
6275 getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
6276 amount = (int)vcol;
6277 }
6278 if (amount < ind_cpp_baseclass)
6279 amount = ind_cpp_baseclass;
6280 return amount;
6281}
6282
Bram Moolenaar071d4272004-06-13 20:20:40 +00006283/*
6284 * Return TRUE if string "s" ends with the string "find", possibly followed by
6285 * white space and comments. Skip strings and comments.
6286 * Ignore "ignore" after "find" if it's not NULL.
6287 */
6288 static int
6289cin_ends_in(s, find, ignore)
6290 char_u *s;
6291 char_u *find;
6292 char_u *ignore;
6293{
6294 char_u *p = s;
6295 char_u *r;
6296 int len = (int)STRLEN(find);
6297
6298 while (*p != NUL)
6299 {
6300 p = cin_skipcomment(p);
6301 if (STRNCMP(p, find, len) == 0)
6302 {
6303 r = skipwhite(p + len);
6304 if (ignore != NULL && STRNCMP(r, ignore, STRLEN(ignore)) == 0)
6305 r = skipwhite(r + STRLEN(ignore));
6306 if (cin_nocode(r))
6307 return TRUE;
6308 }
6309 if (*p != NUL)
6310 ++p;
6311 }
6312 return FALSE;
6313}
6314
6315/*
6316 * Skip strings, chars and comments until at or past "trypos".
6317 * Return the column found.
6318 */
6319 static int
6320cin_skip2pos(trypos)
6321 pos_T *trypos;
6322{
6323 char_u *line;
6324 char_u *p;
6325
6326 p = line = ml_get(trypos->lnum);
6327 while (*p && (colnr_T)(p - line) < trypos->col)
6328 {
6329 if (cin_iscomment(p))
6330 p = cin_skipcomment(p);
6331 else
6332 {
6333 p = skip_string(p);
6334 ++p;
6335 }
6336 }
6337 return (int)(p - line);
6338}
6339
6340/*
6341 * Find the '{' at the start of the block we are in.
6342 * Return NULL if no match found.
6343 * Ignore a '{' that is in a comment, makes indenting the next three lines
6344 * work. */
6345/* foo() */
6346/* { */
6347/* } */
6348
6349 static pos_T *
6350find_start_brace(ind_maxcomment) /* XXX */
6351 int ind_maxcomment;
6352{
6353 pos_T cursor_save;
6354 pos_T *trypos;
6355 pos_T *pos;
6356 static pos_T pos_copy;
6357
6358 cursor_save = curwin->w_cursor;
6359 while ((trypos = findmatchlimit(NULL, '{', FM_BLOCKSTOP, 0)) != NULL)
6360 {
6361 pos_copy = *trypos; /* copy pos_T, next findmatch will change it */
6362 trypos = &pos_copy;
6363 curwin->w_cursor = *trypos;
6364 pos = NULL;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006365 /* ignore the { if it's in a // or / * * / comment */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006366 if ((colnr_T)cin_skip2pos(trypos) == trypos->col
6367 && (pos = find_start_comment(ind_maxcomment)) == NULL) /* XXX */
6368 break;
6369 if (pos != NULL)
6370 curwin->w_cursor.lnum = pos->lnum;
6371 }
6372 curwin->w_cursor = cursor_save;
6373 return trypos;
6374}
6375
6376/*
6377 * Find the matching '(', failing if it is in a comment.
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006378 * Return NULL if no match found.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006379 */
6380 static pos_T *
6381find_match_paren(ind_maxparen, ind_maxcomment) /* XXX */
6382 int ind_maxparen;
6383 int ind_maxcomment;
6384{
6385 pos_T cursor_save;
6386 pos_T *trypos;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006387 static pos_T pos_copy;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006388
6389 cursor_save = curwin->w_cursor;
6390 if ((trypos = findmatchlimit(NULL, '(', 0, ind_maxparen)) != NULL)
6391 {
6392 /* check if the ( is in a // comment */
6393 if ((colnr_T)cin_skip2pos(trypos) > trypos->col)
6394 trypos = NULL;
6395 else
6396 {
6397 pos_copy = *trypos; /* copy trypos, findmatch will change it */
6398 trypos = &pos_copy;
6399 curwin->w_cursor = *trypos;
6400 if (find_start_comment(ind_maxcomment) != NULL) /* XXX */
6401 trypos = NULL;
6402 }
6403 }
6404 curwin->w_cursor = cursor_save;
6405 return trypos;
6406}
6407
6408/*
6409 * Return ind_maxparen corrected for the difference in line number between the
6410 * cursor position and "startpos". This makes sure that searching for a
6411 * matching paren above the cursor line doesn't find a match because of
6412 * looking a few lines further.
6413 */
6414 static int
6415corr_ind_maxparen(ind_maxparen, startpos)
6416 int ind_maxparen;
6417 pos_T *startpos;
6418{
6419 long n = (long)startpos->lnum - (long)curwin->w_cursor.lnum;
6420
6421 if (n > 0 && n < ind_maxparen / 2)
6422 return ind_maxparen - (int)n;
6423 return ind_maxparen;
6424}
6425
6426/*
6427 * Set w_cursor.col to the column number of the last unmatched ')' or '{' in
Bram Moolenaar6d8f9c62011-11-30 13:03:28 +01006428 * line "l". "l" must point to the start of the line.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006429 */
6430 static int
6431find_last_paren(l, start, end)
6432 char_u *l;
6433 int start, end;
6434{
6435 int i;
6436 int retval = FALSE;
6437 int open_count = 0;
6438
6439 curwin->w_cursor.col = 0; /* default is start of line */
6440
Bram Moolenaar6d8f9c62011-11-30 13:03:28 +01006441 for (i = 0; l[i] != NUL; i++)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006442 {
6443 i = (int)(cin_skipcomment(l + i) - l); /* ignore parens in comments */
6444 i = (int)(skip_string(l + i) - l); /* ignore parens in quotes */
6445 if (l[i] == start)
6446 ++open_count;
6447 else if (l[i] == end)
6448 {
6449 if (open_count > 0)
6450 --open_count;
6451 else
6452 {
6453 curwin->w_cursor.col = i;
6454 retval = TRUE;
6455 }
6456 }
6457 }
6458 return retval;
6459}
6460
6461 int
6462get_c_indent()
6463{
6464 /*
6465 * spaces from a block's opening brace the prevailing indent for that
6466 * block should be
6467 */
6468 int ind_level = curbuf->b_p_sw;
6469
6470 /*
6471 * spaces from the edge of the line an open brace that's at the end of a
6472 * line is imagined to be.
6473 */
6474 int ind_open_imag = 0;
6475
6476 /*
Bram Moolenaar1a509df2010-08-01 17:59:57 +02006477 * spaces from the prevailing indent for a line that is not preceded by
Bram Moolenaar071d4272004-06-13 20:20:40 +00006478 * an opening brace.
6479 */
6480 int ind_no_brace = 0;
6481
6482 /*
6483 * column where the first { of a function should be located }
6484 */
6485 int ind_first_open = 0;
6486
6487 /*
6488 * spaces from the prevailing indent a leftmost open brace should be
6489 * located
6490 */
6491 int ind_open_extra = 0;
6492
6493 /*
6494 * spaces from the matching open brace (real location for one at the left
6495 * edge; imaginary location from one that ends a line) the matching close
6496 * brace should be located
6497 */
6498 int ind_close_extra = 0;
6499
6500 /*
6501 * spaces from the edge of the line an open brace sitting in the leftmost
6502 * column is imagined to be
6503 */
6504 int ind_open_left_imag = 0;
6505
6506 /*
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006507 * Spaces jump labels should be shifted to the left if N is non-negative,
6508 * otherwise the jump label will be put to column 1.
6509 */
6510 int ind_jump_label = -1;
6511
6512 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006513 * spaces from the switch() indent a "case xx" label should be located
6514 */
6515 int ind_case = curbuf->b_p_sw;
6516
6517 /*
6518 * spaces from the "case xx:" code after a switch() should be located
6519 */
6520 int ind_case_code = curbuf->b_p_sw;
6521
6522 /*
6523 * lineup break at end of case in switch() with case label
6524 */
6525 int ind_case_break = 0;
6526
6527 /*
6528 * spaces from the class declaration indent a scope declaration label
6529 * should be located
6530 */
6531 int ind_scopedecl = curbuf->b_p_sw;
6532
6533 /*
6534 * spaces from the scope declaration label code should be located
6535 */
6536 int ind_scopedecl_code = curbuf->b_p_sw;
6537
6538 /*
6539 * amount K&R-style parameters should be indented
6540 */
6541 int ind_param = curbuf->b_p_sw;
6542
6543 /*
6544 * amount a function type spec should be indented
6545 */
6546 int ind_func_type = curbuf->b_p_sw;
6547
6548 /*
6549 * amount a cpp base class declaration or constructor initialization
6550 * should be indented
6551 */
6552 int ind_cpp_baseclass = curbuf->b_p_sw;
6553
6554 /*
6555 * additional spaces beyond the prevailing indent a continuation line
6556 * should be located
6557 */
6558 int ind_continuation = curbuf->b_p_sw;
6559
6560 /*
6561 * spaces from the indent of the line with an unclosed parentheses
6562 */
6563 int ind_unclosed = curbuf->b_p_sw * 2;
6564
6565 /*
6566 * spaces from the indent of the line with an unclosed parentheses, which
6567 * itself is also unclosed
6568 */
6569 int ind_unclosed2 = curbuf->b_p_sw;
6570
6571 /*
6572 * suppress ignoring spaces from the indent of a line starting with an
6573 * unclosed parentheses.
6574 */
6575 int ind_unclosed_noignore = 0;
6576
6577 /*
6578 * If the opening paren is the last nonwhite character on the line, and
6579 * ind_unclosed_wrapped is nonzero, use this indent relative to the outer
6580 * context (for very long lines).
6581 */
6582 int ind_unclosed_wrapped = 0;
6583
6584 /*
6585 * suppress ignoring white space when lining up with the character after
6586 * an unclosed parentheses.
6587 */
6588 int ind_unclosed_whiteok = 0;
6589
6590 /*
6591 * indent a closing parentheses under the line start of the matching
6592 * opening parentheses.
6593 */
6594 int ind_matching_paren = 0;
6595
6596 /*
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006597 * indent a closing parentheses under the previous line.
6598 */
6599 int ind_paren_prev = 0;
6600
6601 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006602 * Extra indent for comments.
6603 */
6604 int ind_comment = 0;
6605
6606 /*
6607 * spaces from the comment opener when there is nothing after it.
6608 */
6609 int ind_in_comment = 3;
6610
6611 /*
6612 * boolean: if non-zero, use ind_in_comment even if there is something
6613 * after the comment opener.
6614 */
6615 int ind_in_comment2 = 0;
6616
6617 /*
6618 * max lines to search for an open paren
6619 */
6620 int ind_maxparen = 20;
6621
6622 /*
6623 * max lines to search for an open comment
6624 */
6625 int ind_maxcomment = 70;
6626
6627 /*
6628 * handle braces for java code
6629 */
6630 int ind_java = 0;
6631
6632 /*
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006633 * not to confuse JS object properties with labels
6634 */
6635 int ind_js = 0;
6636
6637 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006638 * handle blocked cases correctly
6639 */
6640 int ind_keep_case_label = 0;
6641
Bram Moolenaared38b0a2011-05-25 15:16:18 +02006642 /*
6643 * handle C++ namespace
6644 */
6645 int ind_cpp_namespace = 0;
6646
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006647 /*
6648 * handle continuation lines containing conditions of if(), for() and
6649 * while()
6650 */
6651 int ind_if_for_while = 0;
6652
Bram Moolenaar071d4272004-06-13 20:20:40 +00006653 pos_T cur_curpos;
6654 int amount;
6655 int scope_amount;
Bram Moolenaarb21e5842006-04-16 18:30:08 +00006656 int cur_amount = MAXCOL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006657 colnr_T col;
6658 char_u *theline;
6659 char_u *linecopy;
6660 pos_T *trypos;
6661 pos_T *tryposBrace = NULL;
6662 pos_T our_paren_pos;
6663 char_u *start;
6664 int start_brace;
Bram Moolenaare21877a2008-02-13 09:58:14 +00006665#define BRACE_IN_COL0 1 /* '{' is in column 0 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006666#define BRACE_AT_START 2 /* '{' is at start of line */
6667#define BRACE_AT_END 3 /* '{' is at end of line */
6668 linenr_T ourscope;
6669 char_u *l;
6670 char_u *look;
6671 char_u terminated;
6672 int lookfor;
6673#define LOOKFOR_INITIAL 0
6674#define LOOKFOR_IF 1
6675#define LOOKFOR_DO 2
6676#define LOOKFOR_CASE 3
6677#define LOOKFOR_ANY 4
6678#define LOOKFOR_TERM 5
6679#define LOOKFOR_UNTERM 6
6680#define LOOKFOR_SCOPEDECL 7
6681#define LOOKFOR_NOBREAK 8
6682#define LOOKFOR_CPP_BASECLASS 9
6683#define LOOKFOR_ENUM_OR_INIT 10
6684
6685 int whilelevel;
6686 linenr_T lnum;
6687 char_u *options;
Bram Moolenaar48d27922012-06-13 13:40:48 +02006688 char_u *digits;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006689 int fraction = 0; /* init for GCC */
6690 int divider;
6691 int n;
6692 int iscase;
6693 int lookfor_break;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02006694 int lookfor_cpp_namespace = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006695 int cont_amount = 0; /* amount for continuation line */
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006696 int original_line_islabel;
Bram Moolenaare79d1532011-10-04 18:03:47 +02006697 int added_to_amount = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006698
6699 for (options = curbuf->b_p_cino; *options; )
6700 {
6701 l = options++;
6702 if (*options == '-')
6703 ++options;
Bram Moolenaar48d27922012-06-13 13:40:48 +02006704 digits = options; /* remember where the digits start */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006705 n = getdigits(&options);
6706 divider = 0;
6707 if (*options == '.') /* ".5s" means a fraction */
6708 {
6709 fraction = atol((char *)++options);
6710 while (VIM_ISDIGIT(*options))
6711 {
6712 ++options;
6713 if (divider)
6714 divider *= 10;
6715 else
6716 divider = 10;
6717 }
6718 }
6719 if (*options == 's') /* "2s" means two times 'shiftwidth' */
6720 {
Bram Moolenaar48d27922012-06-13 13:40:48 +02006721 if (options == digits)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006722 n = curbuf->b_p_sw; /* just "s" is one 'shiftwidth' */
6723 else
6724 {
6725 n *= curbuf->b_p_sw;
6726 if (divider)
6727 n += (curbuf->b_p_sw * fraction + divider / 2) / divider;
6728 }
6729 ++options;
6730 }
6731 if (l[1] == '-')
6732 n = -n;
6733 /* When adding an entry here, also update the default 'cinoptions' in
Bram Moolenaar39353fd2007-03-27 09:02:11 +00006734 * doc/indent.txt, and add explanation for it! */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006735 switch (*l)
6736 {
6737 case '>': ind_level = n; break;
6738 case 'e': ind_open_imag = n; break;
6739 case 'n': ind_no_brace = n; break;
6740 case 'f': ind_first_open = n; break;
6741 case '{': ind_open_extra = n; break;
6742 case '}': ind_close_extra = n; break;
6743 case '^': ind_open_left_imag = n; break;
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006744 case 'L': ind_jump_label = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006745 case ':': ind_case = n; break;
6746 case '=': ind_case_code = n; break;
6747 case 'b': ind_case_break = n; break;
6748 case 'p': ind_param = n; break;
6749 case 't': ind_func_type = n; break;
6750 case '/': ind_comment = n; break;
6751 case 'c': ind_in_comment = n; break;
6752 case 'C': ind_in_comment2 = n; break;
6753 case 'i': ind_cpp_baseclass = n; break;
6754 case '+': ind_continuation = n; break;
6755 case '(': ind_unclosed = n; break;
6756 case 'u': ind_unclosed2 = n; break;
6757 case 'U': ind_unclosed_noignore = n; break;
6758 case 'W': ind_unclosed_wrapped = n; break;
6759 case 'w': ind_unclosed_whiteok = n; break;
6760 case 'm': ind_matching_paren = n; break;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006761 case 'M': ind_paren_prev = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006762 case ')': ind_maxparen = n; break;
6763 case '*': ind_maxcomment = n; break;
6764 case 'g': ind_scopedecl = n; break;
6765 case 'h': ind_scopedecl_code = n; break;
6766 case 'j': ind_java = n; break;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006767 case 'J': ind_js = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006768 case 'l': ind_keep_case_label = n; break;
Bram Moolenaar39353fd2007-03-27 09:02:11 +00006769 case '#': ind_hash_comment = n; break;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02006770 case 'N': ind_cpp_namespace = n; break;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006771 case 'k': ind_if_for_while = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006772 }
Bram Moolenaardfdf3c42010-03-23 18:22:46 +01006773 if (*options == ',')
6774 ++options;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006775 }
6776
6777 /* remember where the cursor was when we started */
6778 cur_curpos = curwin->w_cursor;
6779
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006780 /* if we are at line 1 0 is fine, right? */
6781 if (cur_curpos.lnum == 1)
6782 return 0;
6783
Bram Moolenaar071d4272004-06-13 20:20:40 +00006784 /* Get a copy of the current contents of the line.
6785 * This is required, because only the most recent line obtained with
6786 * ml_get is valid! */
6787 linecopy = vim_strsave(ml_get(cur_curpos.lnum));
6788 if (linecopy == NULL)
6789 return 0;
6790
6791 /*
6792 * In insert mode and the cursor is on a ')' truncate the line at the
6793 * cursor position. We don't want to line up with the matching '(' when
6794 * inserting new stuff.
6795 * For unknown reasons the cursor might be past the end of the line, thus
6796 * check for that.
6797 */
6798 if ((State & INSERT)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006799 && curwin->w_cursor.col < (colnr_T)STRLEN(linecopy)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006800 && linecopy[curwin->w_cursor.col] == ')')
6801 linecopy[curwin->w_cursor.col] = NUL;
6802
6803 theline = skipwhite(linecopy);
6804
6805 /* move the cursor to the start of the line */
6806
6807 curwin->w_cursor.col = 0;
6808
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006809 original_line_islabel = cin_islabel(ind_maxcomment); /* XXX */
6810
Bram Moolenaar071d4272004-06-13 20:20:40 +00006811 /*
6812 * #defines and so on always go at the left when included in 'cinkeys'.
6813 */
6814 if (*theline == '#' && (*linecopy == '#' || in_cinkeys('#', ' ', TRUE)))
6815 {
6816 amount = 0;
6817 }
6818
6819 /*
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006820 * Is it a non-case label? Then that goes at the left margin too unless:
6821 * - JS flag is set.
6822 * - 'L' item has a positive value.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006823 */
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006824 else if (original_line_islabel && !ind_js && ind_jump_label < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006825 {
6826 amount = 0;
6827 }
6828
6829 /*
6830 * If we're inside a "//" comment and there is a "//" comment in a
6831 * previous line, lineup with that one.
6832 */
6833 else if (cin_islinecomment(theline)
6834 && (trypos = find_line_comment()) != NULL) /* XXX */
6835 {
6836 /* find how indented the line beginning the comment is */
6837 getvcol(curwin, trypos, &col, NULL, NULL);
6838 amount = col;
6839 }
6840
6841 /*
6842 * If we're inside a comment and not looking at the start of the
6843 * comment, try using the 'comments' option.
6844 */
6845 else if (!cin_iscomment(theline)
6846 && (trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
6847 {
6848 int lead_start_len = 2;
6849 int lead_middle_len = 1;
6850 char_u lead_start[COM_MAX_LEN]; /* start-comment string */
6851 char_u lead_middle[COM_MAX_LEN]; /* middle-comment string */
6852 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
6853 char_u *p;
6854 int start_align = 0;
6855 int start_off = 0;
6856 int done = FALSE;
6857
6858 /* find how indented the line beginning the comment is */
6859 getvcol(curwin, trypos, &col, NULL, NULL);
6860 amount = col;
Bram Moolenaar4aa97422011-04-11 14:27:38 +02006861 *lead_start = NUL;
6862 *lead_middle = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006863
6864 p = curbuf->b_p_com;
6865 while (*p != NUL)
6866 {
6867 int align = 0;
6868 int off = 0;
6869 int what = 0;
6870
6871 while (*p != NUL && *p != ':')
6872 {
6873 if (*p == COM_START || *p == COM_END || *p == COM_MIDDLE)
6874 what = *p++;
6875 else if (*p == COM_LEFT || *p == COM_RIGHT)
6876 align = *p++;
6877 else if (VIM_ISDIGIT(*p) || *p == '-')
6878 off = getdigits(&p);
6879 else
6880 ++p;
6881 }
6882
6883 if (*p == ':')
6884 ++p;
6885 (void)copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
6886 if (what == COM_START)
6887 {
6888 STRCPY(lead_start, lead_end);
6889 lead_start_len = (int)STRLEN(lead_start);
6890 start_off = off;
6891 start_align = align;
6892 }
6893 else if (what == COM_MIDDLE)
6894 {
6895 STRCPY(lead_middle, lead_end);
6896 lead_middle_len = (int)STRLEN(lead_middle);
6897 }
6898 else if (what == COM_END)
6899 {
6900 /* If our line starts with the middle comment string, line it
6901 * up with the comment opener per the 'comments' option. */
6902 if (STRNCMP(theline, lead_middle, lead_middle_len) == 0
6903 && STRNCMP(theline, lead_end, STRLEN(lead_end)) != 0)
6904 {
6905 done = TRUE;
6906 if (curwin->w_cursor.lnum > 1)
6907 {
6908 /* If the start comment string matches in the previous
Bram Moolenaare21877a2008-02-13 09:58:14 +00006909 * line, use the indent of that line plus offset. If
Bram Moolenaar071d4272004-06-13 20:20:40 +00006910 * the middle comment string matches in the previous
6911 * line, use the indent of that line. XXX */
6912 look = skipwhite(ml_get(curwin->w_cursor.lnum - 1));
6913 if (STRNCMP(look, lead_start, lead_start_len) == 0)
6914 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6915 else if (STRNCMP(look, lead_middle,
6916 lead_middle_len) == 0)
6917 {
6918 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6919 break;
6920 }
6921 /* If the start comment string doesn't match with the
6922 * start of the comment, skip this entry. XXX */
6923 else if (STRNCMP(ml_get(trypos->lnum) + trypos->col,
6924 lead_start, lead_start_len) != 0)
6925 continue;
6926 }
6927 if (start_off != 0)
6928 amount += start_off;
6929 else if (start_align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006930 amount += vim_strsize(lead_start)
6931 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006932 break;
6933 }
6934
6935 /* If our line starts with the end comment string, line it up
6936 * with the middle comment */
6937 if (STRNCMP(theline, lead_middle, lead_middle_len) != 0
6938 && STRNCMP(theline, lead_end, STRLEN(lead_end)) == 0)
6939 {
6940 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6941 /* XXX */
6942 if (off != 0)
6943 amount += off;
6944 else if (align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006945 amount += vim_strsize(lead_start)
6946 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006947 done = TRUE;
6948 break;
6949 }
6950 }
6951 }
6952
6953 /* If our line starts with an asterisk, line up with the
6954 * asterisk in the comment opener; otherwise, line up
6955 * with the first character of the comment text.
6956 */
6957 if (done)
6958 ;
6959 else if (theline[0] == '*')
6960 amount += 1;
6961 else
6962 {
6963 /*
6964 * If we are more than one line away from the comment opener, take
6965 * the indent of the previous non-empty line. If 'cino' has "CO"
6966 * and we are just below the comment opener and there are any
6967 * white characters after it line up with the text after it;
6968 * otherwise, add the amount specified by "c" in 'cino'
6969 */
6970 amount = -1;
6971 for (lnum = cur_curpos.lnum - 1; lnum > trypos->lnum; --lnum)
6972 {
6973 if (linewhite(lnum)) /* skip blank lines */
6974 continue;
6975 amount = get_indent_lnum(lnum); /* XXX */
6976 break;
6977 }
6978 if (amount == -1) /* use the comment opener */
6979 {
6980 if (!ind_in_comment2)
6981 {
6982 start = ml_get(trypos->lnum);
6983 look = start + trypos->col + 2; /* skip / and * */
6984 if (*look != NUL) /* if something after it */
6985 trypos->col = (colnr_T)(skipwhite(look) - start);
6986 }
6987 getvcol(curwin, trypos, &col, NULL, NULL);
6988 amount = col;
6989 if (ind_in_comment2 || *look == NUL)
6990 amount += ind_in_comment;
6991 }
6992 }
6993 }
6994
6995 /*
6996 * Are we inside parentheses or braces?
6997 */ /* XXX */
6998 else if (((trypos = find_match_paren(ind_maxparen, ind_maxcomment)) != NULL
6999 && ind_java == 0)
7000 || (tryposBrace = find_start_brace(ind_maxcomment)) != NULL
7001 || trypos != NULL)
7002 {
7003 if (trypos != NULL && tryposBrace != NULL)
7004 {
7005 /* Both an unmatched '(' and '{' is found. Use the one which is
7006 * closer to the current cursor position, set the other to NULL. */
7007 if (trypos->lnum != tryposBrace->lnum
7008 ? trypos->lnum < tryposBrace->lnum
7009 : trypos->col < tryposBrace->col)
7010 trypos = NULL;
7011 else
7012 tryposBrace = NULL;
7013 }
7014
7015 if (trypos != NULL)
7016 {
7017 /*
7018 * If the matching paren is more than one line away, use the indent of
7019 * a previous non-empty line that matches the same paren.
7020 */
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007021 if (theline[0] == ')' && ind_paren_prev)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007022 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007023 /* Line up with the start of the matching paren line. */
7024 amount = get_indent_lnum(curwin->w_cursor.lnum - 1); /* XXX */
7025 }
7026 else
7027 {
7028 amount = -1;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007029 our_paren_pos = *trypos;
7030 for (lnum = cur_curpos.lnum - 1; lnum > our_paren_pos.lnum; --lnum)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007031 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007032 l = skipwhite(ml_get(lnum));
7033 if (cin_nocode(l)) /* skip comment lines */
7034 continue;
7035 if (cin_ispreproc_cont(&l, &lnum))
7036 continue; /* ignore #define, #if, etc. */
7037 curwin->w_cursor.lnum = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007038
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007039 /* Skip a comment. XXX */
7040 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
7041 {
7042 lnum = trypos->lnum + 1;
7043 continue;
7044 }
7045
7046 /* XXX */
7047 if ((trypos = find_match_paren(
7048 corr_ind_maxparen(ind_maxparen, &cur_curpos),
Bram Moolenaar071d4272004-06-13 20:20:40 +00007049 ind_maxcomment)) != NULL
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007050 && trypos->lnum == our_paren_pos.lnum
7051 && trypos->col == our_paren_pos.col)
7052 {
7053 amount = get_indent_lnum(lnum); /* XXX */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007054
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007055 if (theline[0] == ')')
7056 {
7057 if (our_paren_pos.lnum != lnum
7058 && cur_amount > amount)
7059 cur_amount = amount;
7060 amount = -1;
7061 }
7062 break;
7063 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007064 }
7065 }
7066
7067 /*
7068 * Line up with line where the matching paren is. XXX
7069 * If the line starts with a '(' or the indent for unclosed
7070 * parentheses is zero, line up with the unclosed parentheses.
7071 */
7072 if (amount == -1)
7073 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007074 int ignore_paren_col = 0;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007075 int is_if_for_while = 0;
7076
7077 if (ind_if_for_while)
7078 {
7079 /* Look for the outermost opening parenthesis on this line
7080 * and check whether it belongs to an "if", "for" or "while". */
7081
7082 pos_T cursor_save = curwin->w_cursor;
7083 pos_T outermost;
7084 char_u *line;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007085
7086 trypos = &our_paren_pos;
7087 do {
7088 outermost = *trypos;
7089 curwin->w_cursor.lnum = outermost.lnum;
7090 curwin->w_cursor.col = outermost.col;
7091
7092 trypos = find_match_paren(ind_maxparen, ind_maxcomment);
7093 } while (trypos && trypos->lnum == outermost.lnum);
7094
7095 curwin->w_cursor = cursor_save;
7096
7097 line = ml_get(outermost.lnum);
7098
7099 is_if_for_while =
Bram Moolenaarb345d492012-04-09 20:42:26 +02007100 cin_is_if_for_while_before_offset(line, &outermost.col);
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007101 }
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007102
Bram Moolenaar071d4272004-06-13 20:20:40 +00007103 amount = skip_label(our_paren_pos.lnum, &look, ind_maxcomment);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007104 look = skipwhite(look);
7105 if (*look == '(')
7106 {
7107 linenr_T save_lnum = curwin->w_cursor.lnum;
7108 char_u *line;
7109 int look_col;
7110
7111 /* Ignore a '(' in front of the line that has a match before
7112 * our matching '('. */
7113 curwin->w_cursor.lnum = our_paren_pos.lnum;
7114 line = ml_get_curline();
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007115 look_col = (int)(look - line);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007116 curwin->w_cursor.col = look_col + 1;
7117 if ((trypos = findmatchlimit(NULL, ')', 0, ind_maxparen))
7118 != NULL
7119 && trypos->lnum == our_paren_pos.lnum
7120 && trypos->col < our_paren_pos.col)
7121 ignore_paren_col = trypos->col + 1;
7122
7123 curwin->w_cursor.lnum = save_lnum;
7124 look = ml_get(our_paren_pos.lnum) + look_col;
7125 }
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007126 if (theline[0] == ')' || (ind_unclosed == 0 && is_if_for_while == 0)
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007127 || (!ind_unclosed_noignore && *look == '('
7128 && ignore_paren_col == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007129 {
7130 /*
7131 * If we're looking at a close paren, line up right there;
7132 * otherwise, line up with the next (non-white) character.
7133 * When ind_unclosed_wrapped is set and the matching paren is
7134 * the last nonwhite character of the line, use either the
7135 * indent of the current line or the indentation of the next
7136 * outer paren and add ind_unclosed_wrapped (for very long
7137 * lines).
7138 */
7139 if (theline[0] != ')')
7140 {
7141 cur_amount = MAXCOL;
7142 l = ml_get(our_paren_pos.lnum);
7143 if (ind_unclosed_wrapped
7144 && cin_ends_in(l, (char_u *)"(", NULL))
7145 {
7146 /* look for opening unmatched paren, indent one level
7147 * for each additional level */
7148 n = 1;
7149 for (col = 0; col < our_paren_pos.col; ++col)
7150 {
7151 switch (l[col])
7152 {
7153 case '(':
7154 case '{': ++n;
7155 break;
7156
7157 case ')':
7158 case '}': if (n > 1)
7159 --n;
7160 break;
7161 }
7162 }
7163
7164 our_paren_pos.col = 0;
7165 amount += n * ind_unclosed_wrapped;
7166 }
7167 else if (ind_unclosed_whiteok)
7168 our_paren_pos.col++;
7169 else
7170 {
7171 col = our_paren_pos.col + 1;
7172 while (vim_iswhite(l[col]))
7173 col++;
7174 if (l[col] != NUL) /* In case of trailing space */
7175 our_paren_pos.col = col;
7176 else
7177 our_paren_pos.col++;
7178 }
7179 }
7180
7181 /*
7182 * Find how indented the paren is, or the character after it
7183 * if we did the above "if".
7184 */
7185 if (our_paren_pos.col > 0)
7186 {
7187 getvcol(curwin, &our_paren_pos, &col, NULL, NULL);
7188 if (cur_amount > (int)col)
7189 cur_amount = col;
7190 }
7191 }
7192
7193 if (theline[0] == ')' && ind_matching_paren)
7194 {
7195 /* Line up with the start of the matching paren line. */
7196 }
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007197 else if ((ind_unclosed == 0 && is_if_for_while == 0)
7198 || (!ind_unclosed_noignore
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007199 && *look == '(' && ignore_paren_col == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007200 {
7201 if (cur_amount != MAXCOL)
7202 amount = cur_amount;
7203 }
7204 else
7205 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007206 /* Add ind_unclosed2 for each '(' before our matching one, but
7207 * ignore (void) before the line (ignore_paren_col). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007208 col = our_paren_pos.col;
Bram Moolenaarb21e5842006-04-16 18:30:08 +00007209 while ((int)our_paren_pos.col > ignore_paren_col)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007210 {
7211 --our_paren_pos.col;
7212 switch (*ml_get_pos(&our_paren_pos))
7213 {
7214 case '(': amount += ind_unclosed2;
7215 col = our_paren_pos.col;
7216 break;
7217 case ')': amount -= ind_unclosed2;
7218 col = MAXCOL;
7219 break;
7220 }
7221 }
7222
7223 /* Use ind_unclosed once, when the first '(' is not inside
7224 * braces */
7225 if (col == MAXCOL)
7226 amount += ind_unclosed;
7227 else
7228 {
7229 curwin->w_cursor.lnum = our_paren_pos.lnum;
7230 curwin->w_cursor.col = col;
Bram Moolenaar367bec82011-04-11 14:26:19 +02007231 if (find_match_paren(ind_maxparen, ind_maxcomment) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007232 amount += ind_unclosed2;
7233 else
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007234 {
7235 if (is_if_for_while)
7236 amount += ind_if_for_while;
7237 else
7238 amount += ind_unclosed;
7239 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007240 }
7241 /*
7242 * For a line starting with ')' use the minimum of the two
7243 * positions, to avoid giving it more indent than the previous
7244 * lines:
7245 * func_long_name( if (x
7246 * arg && yy
7247 * ) ^ not here ) ^ not here
7248 */
7249 if (cur_amount < amount)
7250 amount = cur_amount;
7251 }
7252 }
7253
7254 /* add extra indent for a comment */
7255 if (cin_iscomment(theline))
7256 amount += ind_comment;
7257 }
7258
7259 /*
7260 * Are we at least inside braces, then?
7261 */
7262 else
7263 {
7264 trypos = tryposBrace;
7265
7266 ourscope = trypos->lnum;
7267 start = ml_get(ourscope);
7268
7269 /*
7270 * Now figure out how indented the line is in general.
7271 * If the brace was at the start of the line, we use that;
7272 * otherwise, check out the indentation of the line as
7273 * a whole and then add the "imaginary indent" to that.
7274 */
7275 look = skipwhite(start);
7276 if (*look == '{')
7277 {
7278 getvcol(curwin, trypos, &col, NULL, NULL);
7279 amount = col;
7280 if (*start == '{')
7281 start_brace = BRACE_IN_COL0;
7282 else
7283 start_brace = BRACE_AT_START;
7284 }
7285 else
7286 {
7287 /*
7288 * that opening brace might have been on a continuation
7289 * line. if so, find the start of the line.
7290 */
7291 curwin->w_cursor.lnum = ourscope;
7292
7293 /*
7294 * position the cursor over the rightmost paren, so that
7295 * matching it will take us back to the start of the line.
7296 */
7297 lnum = ourscope;
7298 if (find_last_paren(start, '(', ')')
7299 && (trypos = find_match_paren(ind_maxparen,
7300 ind_maxcomment)) != NULL)
7301 lnum = trypos->lnum;
7302
7303 /*
7304 * It could have been something like
7305 * case 1: if (asdf &&
7306 * ldfd) {
7307 * }
7308 */
Bram Moolenaar6ec154b2011-06-12 21:51:08 +02007309 if (ind_js || (ind_keep_case_label
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007310 && cin_iscase(skipwhite(ml_get_curline()), FALSE)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007311 amount = get_indent();
7312 else
7313 amount = skip_label(lnum, &l, ind_maxcomment);
7314
7315 start_brace = BRACE_AT_END;
7316 }
7317
7318 /*
7319 * if we're looking at a closing brace, that's where
7320 * we want to be. otherwise, add the amount of room
7321 * that an indent is supposed to be.
7322 */
7323 if (theline[0] == '}')
7324 {
7325 /*
7326 * they may want closing braces to line up with something
7327 * other than the open brace. indulge them, if so.
7328 */
7329 amount += ind_close_extra;
7330 }
7331 else
7332 {
7333 /*
7334 * If we're looking at an "else", try to find an "if"
7335 * to match it with.
7336 * If we're looking at a "while", try to find a "do"
7337 * to match it with.
7338 */
7339 lookfor = LOOKFOR_INITIAL;
7340 if (cin_iselse(theline))
7341 lookfor = LOOKFOR_IF;
7342 else if (cin_iswhileofdo(theline, cur_curpos.lnum, ind_maxparen))
7343 /* XXX */
7344 lookfor = LOOKFOR_DO;
7345 if (lookfor != LOOKFOR_INITIAL)
7346 {
7347 curwin->w_cursor.lnum = cur_curpos.lnum;
7348 if (find_match(lookfor, ourscope, ind_maxparen,
7349 ind_maxcomment) == OK)
7350 {
7351 amount = get_indent(); /* XXX */
7352 goto theend;
7353 }
7354 }
7355
7356 /*
7357 * We get here if we are not on an "while-of-do" or "else" (or
7358 * failed to find a matching "if").
7359 * Search backwards for something to line up with.
7360 * First set amount for when we don't find anything.
7361 */
7362
7363 /*
7364 * if the '{' is _really_ at the left margin, use the imaginary
7365 * location of a left-margin brace. Otherwise, correct the
7366 * location for ind_open_extra.
7367 */
7368
7369 if (start_brace == BRACE_IN_COL0) /* '{' is in column 0 */
7370 {
7371 amount = ind_open_left_imag;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007372 lookfor_cpp_namespace = TRUE;
7373 }
7374 else if (start_brace == BRACE_AT_START &&
7375 lookfor_cpp_namespace) /* '{' is at start */
7376 {
7377
7378 lookfor_cpp_namespace = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007379 }
7380 else
7381 {
7382 if (start_brace == BRACE_AT_END) /* '{' is at end of line */
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007383 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007384 amount += ind_open_imag;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007385
7386 l = skipwhite(ml_get_curline());
7387 if (cin_is_cpp_namespace(l))
7388 amount += ind_cpp_namespace;
7389 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007390 else
7391 {
7392 /* Compensate for adding ind_open_extra later. */
7393 amount -= ind_open_extra;
7394 if (amount < 0)
7395 amount = 0;
7396 }
7397 }
7398
7399 lookfor_break = FALSE;
7400
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007401 if (cin_iscase(theline, FALSE)) /* it's a switch() label */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007402 {
7403 lookfor = LOOKFOR_CASE; /* find a previous switch() label */
7404 amount += ind_case;
7405 }
7406 else if (cin_isscopedecl(theline)) /* private:, ... */
7407 {
7408 lookfor = LOOKFOR_SCOPEDECL; /* class decl is this block */
7409 amount += ind_scopedecl;
7410 }
7411 else
7412 {
7413 if (ind_case_break && cin_isbreak(theline)) /* break; ... */
7414 lookfor_break = TRUE;
7415
7416 lookfor = LOOKFOR_INITIAL;
7417 amount += ind_level; /* ind_level from start of block */
7418 }
7419 scope_amount = amount;
7420 whilelevel = 0;
7421
7422 /*
7423 * Search backwards. If we find something we recognize, line up
7424 * with that.
7425 *
7426 * if we're looking at an open brace, indent
7427 * the usual amount relative to the conditional
7428 * that opens the block.
7429 */
7430 curwin->w_cursor = cur_curpos;
7431 for (;;)
7432 {
7433 curwin->w_cursor.lnum--;
7434 curwin->w_cursor.col = 0;
7435
7436 /*
7437 * If we went all the way back to the start of our scope, line
7438 * up with it.
7439 */
7440 if (curwin->w_cursor.lnum <= ourscope)
7441 {
7442 /* we reached end of scope:
7443 * if looking for a enum or structure initialization
7444 * go further back:
7445 * if it is an initializer (enum xxx or xxx =), then
7446 * don't add ind_continuation, otherwise it is a variable
7447 * declaration:
7448 * int x,
7449 * here; <-- add ind_continuation
7450 */
7451 if (lookfor == LOOKFOR_ENUM_OR_INIT)
7452 {
7453 if (curwin->w_cursor.lnum == 0
7454 || curwin->w_cursor.lnum
7455 < ourscope - ind_maxparen)
7456 {
7457 /* nothing found (abuse ind_maxparen as limit)
7458 * assume terminated line (i.e. a variable
7459 * initialization) */
7460 if (cont_amount > 0)
7461 amount = cont_amount;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007462 else if (!ind_js)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007463 amount += ind_continuation;
7464 break;
7465 }
7466
7467 l = ml_get_curline();
7468
7469 /*
7470 * If we're in a comment now, skip to the start of the
7471 * comment.
7472 */
7473 trypos = find_start_comment(ind_maxcomment);
7474 if (trypos != NULL)
7475 {
7476 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007477 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007478 continue;
7479 }
7480
7481 /*
7482 * Skip preprocessor directives and blank lines.
7483 */
7484 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7485 continue;
7486
7487 if (cin_nocode(l))
7488 continue;
7489
7490 terminated = cin_isterminated(l, FALSE, TRUE);
7491
7492 /*
7493 * If we are at top level and the line looks like a
7494 * function declaration, we are done
7495 * (it's a variable declaration).
7496 */
7497 if (start_brace != BRACE_IN_COL0
Bram Moolenaarc367faa2011-12-14 20:21:35 +01007498 || !cin_isfuncdecl(&l, curwin->w_cursor.lnum,
7499 0, ind_maxparen, ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007500 {
7501 /* if the line is terminated with another ','
7502 * it is a continued variable initialization.
7503 * don't add extra indent.
7504 * TODO: does not work, if a function
7505 * declaration is split over multiple lines:
7506 * cin_isfuncdecl returns FALSE then.
7507 */
7508 if (terminated == ',')
7509 break;
7510
7511 /* if it es a enum declaration or an assignment,
7512 * we are done.
7513 */
7514 if (terminated != ';' && cin_isinit())
7515 break;
7516
7517 /* nothing useful found */
7518 if (terminated == 0 || terminated == '{')
7519 continue;
7520 }
7521
7522 if (terminated != ';')
7523 {
7524 /* Skip parens and braces. Position the cursor
7525 * over the rightmost paren, so that matching it
7526 * will take us back to the start of the line.
7527 */ /* XXX */
7528 trypos = NULL;
7529 if (find_last_paren(l, '(', ')'))
7530 trypos = find_match_paren(ind_maxparen,
7531 ind_maxcomment);
7532
7533 if (trypos == NULL && find_last_paren(l, '{', '}'))
7534 trypos = find_start_brace(ind_maxcomment);
7535
7536 if (trypos != NULL)
7537 {
7538 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007539 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007540 continue;
7541 }
7542 }
7543
7544 /* it's a variable declaration, add indentation
7545 * like in
7546 * int a,
7547 * b;
7548 */
7549 if (cont_amount > 0)
7550 amount = cont_amount;
7551 else
7552 amount += ind_continuation;
7553 }
7554 else if (lookfor == LOOKFOR_UNTERM)
7555 {
7556 if (cont_amount > 0)
7557 amount = cont_amount;
7558 else
7559 amount += ind_continuation;
7560 }
Bram Moolenaare79d1532011-10-04 18:03:47 +02007561 else
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007562 {
Bram Moolenaare79d1532011-10-04 18:03:47 +02007563 if (lookfor != LOOKFOR_TERM
Bram Moolenaar071d4272004-06-13 20:20:40 +00007564 && lookfor != LOOKFOR_CPP_BASECLASS)
Bram Moolenaare79d1532011-10-04 18:03:47 +02007565 {
7566 amount = scope_amount;
7567 if (theline[0] == '{')
7568 {
7569 amount += ind_open_extra;
7570 added_to_amount = ind_open_extra;
7571 }
7572 }
7573
7574 if (lookfor_cpp_namespace)
7575 {
7576 /*
7577 * Looking for C++ namespace, need to look further
7578 * back.
7579 */
7580 if (curwin->w_cursor.lnum == ourscope)
7581 continue;
7582
7583 if (curwin->w_cursor.lnum == 0
7584 || curwin->w_cursor.lnum
7585 < ourscope - FIND_NAMESPACE_LIM)
7586 break;
7587
7588 l = ml_get_curline();
7589
7590 /* If we're in a comment now, skip to the start of
7591 * the comment. */
7592 trypos = find_start_comment(ind_maxcomment);
7593 if (trypos != NULL)
7594 {
7595 curwin->w_cursor.lnum = trypos->lnum + 1;
7596 curwin->w_cursor.col = 0;
7597 continue;
7598 }
7599
7600 /* Skip preprocessor directives and blank lines. */
7601 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7602 continue;
7603
7604 /* Finally the actual check for "namespace". */
7605 if (cin_is_cpp_namespace(l))
7606 {
7607 amount += ind_cpp_namespace - added_to_amount;
7608 break;
7609 }
7610
7611 if (cin_nocode(l))
7612 continue;
7613 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007614 }
7615 break;
7616 }
7617
7618 /*
7619 * If we're in a comment now, skip to the start of the comment.
7620 */ /* XXX */
7621 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
7622 {
7623 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007624 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007625 continue;
7626 }
7627
7628 l = ml_get_curline();
7629
7630 /*
7631 * If this is a switch() label, may line up relative to that.
Bram Moolenaar18144c82006-04-12 21:52:12 +00007632 * If this is a C++ scope declaration, do the same.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007633 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007634 iscase = cin_iscase(l, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007635 if (iscase || cin_isscopedecl(l))
7636 {
7637 /* we are only looking for cpp base class
7638 * declaration/initialization any longer */
7639 if (lookfor == LOOKFOR_CPP_BASECLASS)
7640 break;
7641
7642 /* When looking for a "do" we are not interested in
7643 * labels. */
7644 if (whilelevel > 0)
7645 continue;
7646
7647 /*
7648 * case xx:
7649 * c = 99 + <- this indent plus continuation
7650 *-> here;
7651 */
7652 if (lookfor == LOOKFOR_UNTERM
7653 || lookfor == LOOKFOR_ENUM_OR_INIT)
7654 {
7655 if (cont_amount > 0)
7656 amount = cont_amount;
7657 else
7658 amount += ind_continuation;
7659 break;
7660 }
7661
7662 /*
7663 * case xx: <- line up with this case
7664 * x = 333;
7665 * case yy:
7666 */
7667 if ( (iscase && lookfor == LOOKFOR_CASE)
7668 || (iscase && lookfor_break)
7669 || (!iscase && lookfor == LOOKFOR_SCOPEDECL))
7670 {
7671 /*
7672 * Check that this case label is not for another
7673 * switch()
7674 */ /* XXX */
7675 if ((trypos = find_start_brace(ind_maxcomment)) ==
7676 NULL || trypos->lnum == ourscope)
7677 {
7678 amount = get_indent(); /* XXX */
7679 break;
7680 }
7681 continue;
7682 }
7683
7684 n = get_indent_nolabel(curwin->w_cursor.lnum); /* XXX */
7685
7686 /*
7687 * case xx: if (cond) <- line up with this if
7688 * y = y + 1;
7689 * -> s = 99;
7690 *
7691 * case xx:
7692 * if (cond) <- line up with this line
7693 * y = y + 1;
7694 * -> s = 99;
7695 */
7696 if (lookfor == LOOKFOR_TERM)
7697 {
7698 if (n)
7699 amount = n;
7700
7701 if (!lookfor_break)
7702 break;
7703 }
7704
7705 /*
7706 * case xx: x = x + 1; <- line up with this x
7707 * -> y = y + 1;
7708 *
7709 * case xx: if (cond) <- line up with this if
7710 * -> y = y + 1;
7711 */
7712 if (n)
7713 {
7714 amount = n;
7715 l = after_label(ml_get_curline());
7716 if (l != NULL && cin_is_cinword(l))
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007717 {
7718 if (theline[0] == '{')
7719 amount += ind_open_extra;
7720 else
7721 amount += ind_level + ind_no_brace;
7722 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007723 break;
7724 }
7725
7726 /*
7727 * Try to get the indent of a statement before the switch
7728 * label. If nothing is found, line up relative to the
7729 * switch label.
7730 * break; <- may line up with this line
7731 * case xx:
7732 * -> y = 1;
7733 */
7734 scope_amount = get_indent() + (iscase /* XXX */
7735 ? ind_case_code : ind_scopedecl_code);
7736 lookfor = ind_case_break ? LOOKFOR_NOBREAK : LOOKFOR_ANY;
7737 continue;
7738 }
7739
7740 /*
7741 * Looking for a switch() label or C++ scope declaration,
7742 * ignore other lines, skip {}-blocks.
7743 */
7744 if (lookfor == LOOKFOR_CASE || lookfor == LOOKFOR_SCOPEDECL)
7745 {
7746 if (find_last_paren(l, '{', '}') && (trypos =
7747 find_start_brace(ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007748 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007749 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007750 curwin->w_cursor.col = 0;
7751 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007752 continue;
7753 }
7754
7755 /*
7756 * Ignore jump labels with nothing after them.
7757 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007758 if (!ind_js && cin_islabel(ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007759 {
7760 l = after_label(ml_get_curline());
7761 if (l == NULL || cin_nocode(l))
7762 continue;
7763 }
7764
7765 /*
7766 * Ignore #defines, #if, etc.
7767 * Ignore comment and empty lines.
7768 * (need to get the line again, cin_islabel() may have
7769 * unlocked it)
7770 */
7771 l = ml_get_curline();
7772 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum)
7773 || cin_nocode(l))
7774 continue;
7775
7776 /*
7777 * Are we at the start of a cpp base class declaration or
7778 * constructor initialization?
7779 */ /* XXX */
Bram Moolenaar18144c82006-04-12 21:52:12 +00007780 n = FALSE;
7781 if (lookfor != LOOKFOR_TERM && ind_cpp_baseclass > 0)
7782 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00007783 n = cin_is_cpp_baseclass(&col);
Bram Moolenaar18144c82006-04-12 21:52:12 +00007784 l = ml_get_curline();
7785 }
7786 if (n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007787 {
7788 if (lookfor == LOOKFOR_UNTERM)
7789 {
7790 if (cont_amount > 0)
7791 amount = cont_amount;
7792 else
7793 amount += ind_continuation;
7794 }
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007795 else if (theline[0] == '{')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007796 {
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007797 /* Need to find start of the declaration. */
7798 lookfor = LOOKFOR_UNTERM;
7799 ind_continuation = 0;
7800 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007801 }
7802 else
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007803 /* XXX */
7804 amount = get_baseclass_amount(col, ind_maxparen,
7805 ind_maxcomment, ind_cpp_baseclass);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007806 break;
7807 }
7808 else if (lookfor == LOOKFOR_CPP_BASECLASS)
7809 {
7810 /* only look, whether there is a cpp base class
Bram Moolenaar18144c82006-04-12 21:52:12 +00007811 * declaration or initialization before the opening brace.
7812 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007813 if (cin_isterminated(l, TRUE, FALSE))
7814 break;
7815 else
7816 continue;
7817 }
7818
7819 /*
7820 * What happens next depends on the line being terminated.
7821 * If terminated with a ',' only consider it terminating if
Bram Moolenaar25394022007-05-10 19:06:20 +00007822 * there is another unterminated statement behind, eg:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007823 * 123,
7824 * sizeof
7825 * here
7826 * Otherwise check whether it is a enumeration or structure
7827 * initialisation (not indented) or a variable declaration
7828 * (indented).
7829 */
7830 terminated = cin_isterminated(l, FALSE, TRUE);
7831
7832 if (terminated == 0 || (lookfor != LOOKFOR_UNTERM
7833 && terminated == ','))
7834 {
7835 /*
7836 * if we're in the middle of a paren thing,
7837 * go back to the line that starts it so
7838 * we can get the right prevailing indent
7839 * if ( foo &&
7840 * bar )
7841 */
7842 /*
7843 * position the cursor over the rightmost paren, so that
7844 * matching it will take us back to the start of the line.
7845 */
7846 (void)find_last_paren(l, '(', ')');
7847 trypos = find_match_paren(
7848 corr_ind_maxparen(ind_maxparen, &cur_curpos),
7849 ind_maxcomment);
7850
7851 /*
7852 * If we are looking for ',', we also look for matching
7853 * braces.
7854 */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007855 if (trypos == NULL && terminated == ','
7856 && find_last_paren(l, '{', '}'))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007857 trypos = find_start_brace(ind_maxcomment);
7858
7859 if (trypos != NULL)
7860 {
7861 /*
7862 * Check if we are on a case label now. This is
7863 * handled above.
7864 * case xx: if ( asdf &&
7865 * asdf)
7866 */
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007867 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007868 l = ml_get_curline();
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007869 if (cin_iscase(l, FALSE) || cin_isscopedecl(l))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007870 {
7871 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007872 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007873 continue;
7874 }
7875 }
7876
7877 /*
7878 * Skip over continuation lines to find the one to get the
7879 * indent from
7880 * char *usethis = "bla\
7881 * bla",
7882 * here;
7883 */
7884 if (terminated == ',')
7885 {
7886 while (curwin->w_cursor.lnum > 1)
7887 {
7888 l = ml_get(curwin->w_cursor.lnum - 1);
7889 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
7890 break;
7891 --curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007892 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007893 }
7894 }
7895
7896 /*
7897 * Get indent and pointer to text for current line,
7898 * ignoring any jump label. XXX
7899 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007900 if (!ind_js)
7901 cur_amount = skip_label(curwin->w_cursor.lnum,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007902 &l, ind_maxcomment);
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007903 else
7904 cur_amount = get_indent();
Bram Moolenaar071d4272004-06-13 20:20:40 +00007905 /*
7906 * If this is just above the line we are indenting, and it
7907 * starts with a '{', line it up with this line.
7908 * while (not)
7909 * -> {
7910 * }
7911 */
7912 if (terminated != ',' && lookfor != LOOKFOR_TERM
7913 && theline[0] == '{')
7914 {
7915 amount = cur_amount;
7916 /*
7917 * Only add ind_open_extra when the current line
7918 * doesn't start with a '{', which must have a match
7919 * in the same line (scope is the same). Probably:
7920 * { 1, 2 },
7921 * -> { 3, 4 }
7922 */
7923 if (*skipwhite(l) != '{')
7924 amount += ind_open_extra;
7925
7926 if (ind_cpp_baseclass)
7927 {
7928 /* have to look back, whether it is a cpp base
7929 * class declaration or initialization */
7930 lookfor = LOOKFOR_CPP_BASECLASS;
7931 continue;
7932 }
7933 break;
7934 }
7935
7936 /*
7937 * Check if we are after an "if", "while", etc.
7938 * Also allow " } else".
7939 */
7940 if (cin_is_cinword(l) || cin_iselse(skipwhite(l)))
7941 {
7942 /*
7943 * Found an unterminated line after an if (), line up
7944 * with the last one.
7945 * if (cond)
7946 * 100 +
7947 * -> here;
7948 */
7949 if (lookfor == LOOKFOR_UNTERM
7950 || lookfor == LOOKFOR_ENUM_OR_INIT)
7951 {
7952 if (cont_amount > 0)
7953 amount = cont_amount;
7954 else
7955 amount += ind_continuation;
7956 break;
7957 }
7958
7959 /*
7960 * If this is just above the line we are indenting, we
7961 * are finished.
7962 * while (not)
7963 * -> here;
7964 * Otherwise this indent can be used when the line
7965 * before this is terminated.
7966 * yyy;
7967 * if (stat)
7968 * while (not)
7969 * xxx;
7970 * -> here;
7971 */
7972 amount = cur_amount;
7973 if (theline[0] == '{')
7974 amount += ind_open_extra;
7975 if (lookfor != LOOKFOR_TERM)
7976 {
7977 amount += ind_level + ind_no_brace;
7978 break;
7979 }
7980
7981 /*
7982 * Special trick: when expecting the while () after a
7983 * do, line up with the while()
7984 * do
7985 * x = 1;
7986 * -> here
7987 */
7988 l = skipwhite(ml_get_curline());
7989 if (cin_isdo(l))
7990 {
7991 if (whilelevel == 0)
7992 break;
7993 --whilelevel;
7994 }
7995
7996 /*
7997 * When searching for a terminated line, don't use the
Bram Moolenaar334adf02011-05-25 13:34:04 +02007998 * one between the "if" and the matching "else".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007999 * Need to use the scope of this "else". XXX
8000 * If whilelevel != 0 continue looking for a "do {".
8001 */
Bram Moolenaar334adf02011-05-25 13:34:04 +02008002 if (cin_iselse(l) && whilelevel == 0)
8003 {
8004 /* If we're looking at "} else", let's make sure we
8005 * find the opening brace of the enclosing scope,
8006 * not the one from "if () {". */
8007 if (*l == '}')
8008 curwin->w_cursor.col =
Bram Moolenaar9b83c2f2011-05-25 17:29:44 +02008009 (colnr_T)(l - ml_get_curline()) + 1;
Bram Moolenaar334adf02011-05-25 13:34:04 +02008010
8011 if ((trypos = find_start_brace(ind_maxcomment))
8012 == NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00008013 || find_match(LOOKFOR_IF, trypos->lnum,
Bram Moolenaar334adf02011-05-25 13:34:04 +02008014 ind_maxparen, ind_maxcomment) == FAIL)
8015 break;
8016 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008017 }
8018
8019 /*
8020 * If we're below an unterminated line that is not an
8021 * "if" or something, we may line up with this line or
Bram Moolenaar25394022007-05-10 19:06:20 +00008022 * add something for a continuation line, depending on
Bram Moolenaar071d4272004-06-13 20:20:40 +00008023 * the line before this one.
8024 */
8025 else
8026 {
8027 /*
8028 * Found two unterminated lines on a row, line up with
8029 * the last one.
8030 * c = 99 +
8031 * 100 +
8032 * -> here;
8033 */
8034 if (lookfor == LOOKFOR_UNTERM)
8035 {
8036 /* When line ends in a comma add extra indent */
8037 if (terminated == ',')
8038 amount += ind_continuation;
8039 break;
8040 }
8041
8042 if (lookfor == LOOKFOR_ENUM_OR_INIT)
8043 {
8044 /* Found two lines ending in ',', lineup with the
8045 * lowest one, but check for cpp base class
8046 * declaration/initialization, if it is an
8047 * opening brace or we are looking just for
8048 * enumerations/initializations. */
8049 if (terminated == ',')
8050 {
8051 if (ind_cpp_baseclass == 0)
8052 break;
8053
8054 lookfor = LOOKFOR_CPP_BASECLASS;
8055 continue;
8056 }
8057
8058 /* Ignore unterminated lines in between, but
8059 * reduce indent. */
8060 if (amount > cur_amount)
8061 amount = cur_amount;
8062 }
8063 else
8064 {
8065 /*
8066 * Found first unterminated line on a row, may
8067 * line up with this line, remember its indent
8068 * 100 +
8069 * -> here;
8070 */
8071 amount = cur_amount;
8072
8073 /*
8074 * If previous line ends in ',', check whether we
8075 * are in an initialization or enum
8076 * struct xxx =
8077 * {
8078 * sizeof a,
8079 * 124 };
8080 * or a normal possible continuation line.
8081 * but only, of no other statement has been found
8082 * yet.
8083 */
8084 if (lookfor == LOOKFOR_INITIAL && terminated == ',')
8085 {
8086 lookfor = LOOKFOR_ENUM_OR_INIT;
8087 cont_amount = cin_first_id_amount();
8088 }
8089 else
8090 {
8091 if (lookfor == LOOKFOR_INITIAL
8092 && *l != NUL
8093 && l[STRLEN(l) - 1] == '\\')
8094 /* XXX */
8095 cont_amount = cin_get_equal_amount(
8096 curwin->w_cursor.lnum);
8097 if (lookfor != LOOKFOR_TERM)
8098 lookfor = LOOKFOR_UNTERM;
8099 }
8100 }
8101 }
8102 }
8103
8104 /*
8105 * Check if we are after a while (cond);
8106 * If so: Ignore until the matching "do".
8107 */
8108 /* XXX */
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00008109 else if (cin_iswhileofdo_end(terminated, ind_maxparen,
8110 ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008111 {
8112 /*
8113 * Found an unterminated line after a while ();, line up
8114 * with the last one.
8115 * while (cond);
8116 * 100 + <- line up with this one
8117 * -> here;
8118 */
8119 if (lookfor == LOOKFOR_UNTERM
8120 || lookfor == LOOKFOR_ENUM_OR_INIT)
8121 {
8122 if (cont_amount > 0)
8123 amount = cont_amount;
8124 else
8125 amount += ind_continuation;
8126 break;
8127 }
8128
8129 if (whilelevel == 0)
8130 {
8131 lookfor = LOOKFOR_TERM;
8132 amount = get_indent(); /* XXX */
8133 if (theline[0] == '{')
8134 amount += ind_open_extra;
8135 }
8136 ++whilelevel;
8137 }
8138
8139 /*
8140 * We are after a "normal" statement.
8141 * If we had another statement we can stop now and use the
8142 * indent of that other statement.
8143 * Otherwise the indent of the current statement may be used,
8144 * search backwards for the next "normal" statement.
8145 */
8146 else
8147 {
8148 /*
8149 * Skip single break line, if before a switch label. It
8150 * may be lined up with the case label.
8151 */
8152 if (lookfor == LOOKFOR_NOBREAK
8153 && cin_isbreak(skipwhite(ml_get_curline())))
8154 {
8155 lookfor = LOOKFOR_ANY;
8156 continue;
8157 }
8158
8159 /*
8160 * Handle "do {" line.
8161 */
8162 if (whilelevel > 0)
8163 {
8164 l = cin_skipcomment(ml_get_curline());
8165 if (cin_isdo(l))
8166 {
8167 amount = get_indent(); /* XXX */
8168 --whilelevel;
8169 continue;
8170 }
8171 }
8172
8173 /*
8174 * Found a terminated line above an unterminated line. Add
8175 * the amount for a continuation line.
8176 * x = 1;
8177 * y = foo +
8178 * -> here;
8179 * or
8180 * int x = 1;
8181 * int foo,
8182 * -> here;
8183 */
8184 if (lookfor == LOOKFOR_UNTERM
8185 || lookfor == LOOKFOR_ENUM_OR_INIT)
8186 {
8187 if (cont_amount > 0)
8188 amount = cont_amount;
8189 else
8190 amount += ind_continuation;
8191 break;
8192 }
8193
8194 /*
8195 * Found a terminated line above a terminated line or "if"
8196 * etc. line. Use the amount of the line below us.
8197 * x = 1; x = 1;
8198 * if (asdf) y = 2;
8199 * while (asdf) ->here;
8200 * here;
8201 * ->foo;
8202 */
8203 if (lookfor == LOOKFOR_TERM)
8204 {
8205 if (!lookfor_break && whilelevel == 0)
8206 break;
8207 }
8208
8209 /*
8210 * First line above the one we're indenting is terminated.
8211 * To know what needs to be done look further backward for
8212 * a terminated line.
8213 */
8214 else
8215 {
8216 /*
8217 * position the cursor over the rightmost paren, so
8218 * that matching it will take us back to the start of
8219 * the line. Helps for:
8220 * func(asdr,
8221 * asdfasdf);
8222 * here;
8223 */
8224term_again:
8225 l = ml_get_curline();
8226 if (find_last_paren(l, '(', ')')
8227 && (trypos = find_match_paren(ind_maxparen,
8228 ind_maxcomment)) != NULL)
8229 {
8230 /*
8231 * Check if we are on a case label now. This is
8232 * handled above.
8233 * case xx: if ( asdf &&
8234 * asdf)
8235 */
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008236 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008237 l = ml_get_curline();
Bram Moolenaar3acfc302010-07-11 17:23:02 +02008238 if (cin_iscase(l, FALSE) || cin_isscopedecl(l))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008239 {
8240 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008241 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008242 continue;
8243 }
8244 }
8245
8246 /* When aligning with the case statement, don't align
8247 * with a statement after it.
8248 * case 1: { <-- don't use this { position
8249 * stat;
8250 * }
8251 * case 2:
8252 * stat;
8253 * }
8254 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02008255 iscase = (ind_keep_case_label && cin_iscase(l, FALSE));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008256
8257 /*
8258 * Get indent and pointer to text for current line,
8259 * ignoring any jump label.
8260 */
8261 amount = skip_label(curwin->w_cursor.lnum,
8262 &l, ind_maxcomment);
8263
8264 if (theline[0] == '{')
8265 amount += ind_open_extra;
8266 /* See remark above: "Only add ind_open_extra.." */
Bram Moolenaar18144c82006-04-12 21:52:12 +00008267 l = skipwhite(l);
8268 if (*l == '{')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008269 amount -= ind_open_extra;
8270 lookfor = iscase ? LOOKFOR_ANY : LOOKFOR_TERM;
8271
8272 /*
Bram Moolenaar18144c82006-04-12 21:52:12 +00008273 * When a terminated line starts with "else" skip to
8274 * the matching "if":
8275 * else 3;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008276 * indent this;
Bram Moolenaar18144c82006-04-12 21:52:12 +00008277 * Need to use the scope of this "else". XXX
8278 * If whilelevel != 0 continue looking for a "do {".
8279 */
8280 if (lookfor == LOOKFOR_TERM
8281 && *l != '}'
8282 && cin_iselse(l)
8283 && whilelevel == 0)
8284 {
8285 if ((trypos = find_start_brace(ind_maxcomment))
8286 == NULL
8287 || find_match(LOOKFOR_IF, trypos->lnum,
8288 ind_maxparen, ind_maxcomment) == FAIL)
8289 break;
8290 continue;
8291 }
8292
8293 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008294 * If we're at the end of a block, skip to the start of
8295 * that block.
8296 */
Bram Moolenaar6d8f9c62011-11-30 13:03:28 +01008297 l = ml_get_curline();
Bram Moolenaar50f42ca2011-07-15 14:12:30 +02008298 if (find_last_paren(l, '{', '}')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008299 && (trypos = find_start_brace(ind_maxcomment))
8300 != NULL) /* XXX */
8301 {
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008302 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008303 /* if not "else {" check for terminated again */
8304 /* but skip block for "} else {" */
8305 l = cin_skipcomment(ml_get_curline());
8306 if (*l == '}' || !cin_iselse(l))
8307 goto term_again;
8308 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008309 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008310 }
8311 }
8312 }
8313 }
8314 }
8315 }
8316
8317 /* add extra indent for a comment */
8318 if (cin_iscomment(theline))
8319 amount += ind_comment;
Bram Moolenaar02c707a2010-07-17 17:12:06 +02008320
8321 /* subtract extra left-shift for jump labels */
8322 if (ind_jump_label > 0 && original_line_islabel)
8323 amount -= ind_jump_label;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008324 }
8325
8326 /*
8327 * ok -- we're not inside any sort of structure at all!
8328 *
8329 * this means we're at the top level, and everything should
8330 * basically just match where the previous line is, except
8331 * for the lines immediately following a function declaration,
8332 * which are K&R-style parameters and need to be indented.
8333 */
8334 else
8335 {
8336 /*
8337 * if our line starts with an open brace, forget about any
8338 * prevailing indent and make sure it looks like the start
8339 * of a function
8340 */
8341
8342 if (theline[0] == '{')
8343 {
8344 amount = ind_first_open;
8345 }
8346
8347 /*
8348 * If the NEXT line is a function declaration, the current
8349 * line needs to be indented as a function type spec.
Bram Moolenaar1a89bbe2010-03-02 12:38:22 +01008350 * Don't do this if the current line looks like a comment or if the
8351 * current line is terminated, ie. ends in ';', or if the current line
8352 * contains { or }: "void f() {\n if (1)"
Bram Moolenaar071d4272004-06-13 20:20:40 +00008353 */
8354 else if (cur_curpos.lnum < curbuf->b_ml.ml_line_count
8355 && !cin_nocode(theline)
Bram Moolenaar1a89bbe2010-03-02 12:38:22 +01008356 && vim_strchr(theline, '{') == NULL
8357 && vim_strchr(theline, '}') == NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00008358 && !cin_ends_in(theline, (char_u *)":", NULL)
8359 && !cin_ends_in(theline, (char_u *)",", NULL)
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008360 && cin_isfuncdecl(NULL, cur_curpos.lnum + 1,
8361 cur_curpos.lnum + 1,
8362 ind_maxparen, ind_maxcomment)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008363 && !cin_isterminated(theline, FALSE, TRUE))
8364 {
8365 amount = ind_func_type;
8366 }
8367 else
8368 {
8369 amount = 0;
8370 curwin->w_cursor = cur_curpos;
8371
8372 /* search backwards until we find something we recognize */
8373
8374 while (curwin->w_cursor.lnum > 1)
8375 {
8376 curwin->w_cursor.lnum--;
8377 curwin->w_cursor.col = 0;
8378
8379 l = ml_get_curline();
8380
8381 /*
8382 * If we're in a comment now, skip to the start of the comment.
8383 */ /* XXX */
8384 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
8385 {
8386 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008387 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008388 continue;
8389 }
8390
8391 /*
Bram Moolenaar18144c82006-04-12 21:52:12 +00008392 * Are we at the start of a cpp base class declaration or
8393 * constructor initialization?
Bram Moolenaar071d4272004-06-13 20:20:40 +00008394 */ /* XXX */
Bram Moolenaar18144c82006-04-12 21:52:12 +00008395 n = FALSE;
8396 if (ind_cpp_baseclass != 0 && theline[0] != '{')
8397 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00008398 n = cin_is_cpp_baseclass(&col);
Bram Moolenaar18144c82006-04-12 21:52:12 +00008399 l = ml_get_curline();
8400 }
8401 if (n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008402 {
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00008403 /* XXX */
8404 amount = get_baseclass_amount(col, ind_maxparen,
8405 ind_maxcomment, ind_cpp_baseclass);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008406 break;
8407 }
8408
8409 /*
8410 * Skip preprocessor directives and blank lines.
8411 */
8412 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
8413 continue;
8414
8415 if (cin_nocode(l))
8416 continue;
8417
8418 /*
8419 * If the previous line ends in ',', use one level of
8420 * indentation:
8421 * int foo,
8422 * bar;
8423 * do this before checking for '}' in case of eg.
8424 * enum foobar
8425 * {
8426 * ...
8427 * } foo,
8428 * bar;
8429 */
8430 n = 0;
8431 if (cin_ends_in(l, (char_u *)",", NULL)
8432 || (*l != NUL && (n = l[STRLEN(l) - 1]) == '\\'))
8433 {
8434 /* take us back to opening paren */
8435 if (find_last_paren(l, '(', ')')
8436 && (trypos = find_match_paren(ind_maxparen,
8437 ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008438 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008439
8440 /* For a line ending in ',' that is a continuation line go
8441 * back to the first line with a backslash:
8442 * char *foo = "bla\
8443 * bla",
8444 * here;
8445 */
8446 while (n == 0 && curwin->w_cursor.lnum > 1)
8447 {
8448 l = ml_get(curwin->w_cursor.lnum - 1);
8449 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
8450 break;
8451 --curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008452 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008453 }
8454
8455 amount = get_indent(); /* XXX */
8456
8457 if (amount == 0)
8458 amount = cin_first_id_amount();
8459 if (amount == 0)
8460 amount = ind_continuation;
8461 break;
8462 }
8463
8464 /*
8465 * If the line looks like a function declaration, and we're
8466 * not in a comment, put it the left margin.
8467 */
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008468 if (cin_isfuncdecl(NULL, cur_curpos.lnum, 0,
8469 ind_maxparen, ind_maxcomment)) /* XXX */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008470 break;
8471 l = ml_get_curline();
8472
8473 /*
8474 * Finding the closing '}' of a previous function. Put
8475 * current line at the left margin. For when 'cino' has "fs".
8476 */
8477 if (*skipwhite(l) == '}')
8478 break;
8479
8480 /* (matching {)
8481 * If the previous line ends on '};' (maybe followed by
8482 * comments) align at column 0. For example:
8483 * char *string_array[] = { "foo",
8484 * / * x * / "b};ar" }; / * foobar * /
8485 */
8486 if (cin_ends_in(l, (char_u *)"};", NULL))
8487 break;
8488
8489 /*
Bram Moolenaar3388bb42011-11-30 17:20:23 +01008490 * Find a line only has a semicolon that belongs to a previous
8491 * line ending in '}', e.g. before an #endif. Don't increase
8492 * indent then.
8493 */
8494 if (*(look = skipwhite(l)) == ';' && cin_nocode(look + 1))
8495 {
8496 pos_T curpos_save = curwin->w_cursor;
8497
8498 while (curwin->w_cursor.lnum > 1)
8499 {
8500 look = ml_get(--curwin->w_cursor.lnum);
8501 if (!(cin_nocode(look) || cin_ispreproc_cont(
8502 &look, &curwin->w_cursor.lnum)))
8503 break;
8504 }
8505 if (curwin->w_cursor.lnum > 0
8506 && cin_ends_in(look, (char_u *)"}", NULL))
8507 break;
8508
8509 curwin->w_cursor = curpos_save;
8510 }
8511
8512 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008513 * If the PREVIOUS line is a function declaration, the current
8514 * line (and the ones that follow) needs to be indented as
8515 * parameters.
8516 */
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008517 if (cin_isfuncdecl(&l, curwin->w_cursor.lnum, 0,
8518 ind_maxparen, ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008519 {
8520 amount = ind_param;
8521 break;
8522 }
8523
8524 /*
8525 * If the previous line ends in ';' and the line before the
8526 * previous line ends in ',' or '\', ident to column zero:
8527 * int foo,
8528 * bar;
8529 * indent_to_0 here;
8530 */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00008531 if (cin_ends_in(l, (char_u *)";", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008532 {
8533 l = ml_get(curwin->w_cursor.lnum - 1);
8534 if (cin_ends_in(l, (char_u *)",", NULL)
8535 || (*l != NUL && l[STRLEN(l) - 1] == '\\'))
8536 break;
8537 l = ml_get_curline();
8538 }
8539
8540 /*
8541 * Doesn't look like anything interesting -- so just
8542 * use the indent of this line.
8543 *
8544 * Position the cursor over the rightmost paren, so that
8545 * matching it will take us back to the start of the line.
8546 */
8547 find_last_paren(l, '(', ')');
8548
8549 if ((trypos = find_match_paren(ind_maxparen,
8550 ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008551 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008552 amount = get_indent(); /* XXX */
8553 break;
8554 }
8555
8556 /* add extra indent for a comment */
8557 if (cin_iscomment(theline))
8558 amount += ind_comment;
8559
8560 /* add extra indent if the previous line ended in a backslash:
8561 * "asdfasdf\
8562 * here";
8563 * char *foo = "asdf\
8564 * here";
8565 */
8566 if (cur_curpos.lnum > 1)
8567 {
8568 l = ml_get(cur_curpos.lnum - 1);
8569 if (*l != NUL && l[STRLEN(l) - 1] == '\\')
8570 {
8571 cur_amount = cin_get_equal_amount(cur_curpos.lnum - 1);
8572 if (cur_amount > 0)
8573 amount = cur_amount;
8574 else if (cur_amount == 0)
8575 amount += ind_continuation;
8576 }
8577 }
8578 }
8579 }
8580
8581theend:
8582 /* put the cursor back where it belongs */
8583 curwin->w_cursor = cur_curpos;
8584
8585 vim_free(linecopy);
8586
8587 if (amount < 0)
8588 return 0;
8589 return amount;
8590}
8591
8592 static int
8593find_match(lookfor, ourscope, ind_maxparen, ind_maxcomment)
8594 int lookfor;
8595 linenr_T ourscope;
8596 int ind_maxparen;
8597 int ind_maxcomment;
8598{
8599 char_u *look;
8600 pos_T *theirscope;
8601 char_u *mightbeif;
8602 int elselevel;
8603 int whilelevel;
8604
8605 if (lookfor == LOOKFOR_IF)
8606 {
8607 elselevel = 1;
8608 whilelevel = 0;
8609 }
8610 else
8611 {
8612 elselevel = 0;
8613 whilelevel = 1;
8614 }
8615
8616 curwin->w_cursor.col = 0;
8617
8618 while (curwin->w_cursor.lnum > ourscope + 1)
8619 {
8620 curwin->w_cursor.lnum--;
8621 curwin->w_cursor.col = 0;
8622
8623 look = cin_skipcomment(ml_get_curline());
8624 if (cin_iselse(look)
8625 || cin_isif(look)
8626 || cin_isdo(look) /* XXX */
8627 || cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
8628 {
8629 /*
8630 * if we've gone outside the braces entirely,
8631 * we must be out of scope...
8632 */
8633 theirscope = find_start_brace(ind_maxcomment); /* XXX */
8634 if (theirscope == NULL)
8635 break;
8636
8637 /*
8638 * and if the brace enclosing this is further
8639 * back than the one enclosing the else, we're
8640 * out of luck too.
8641 */
8642 if (theirscope->lnum < ourscope)
8643 break;
8644
8645 /*
8646 * and if they're enclosed in a *deeper* brace,
8647 * then we can ignore it because it's in a
8648 * different scope...
8649 */
8650 if (theirscope->lnum > ourscope)
8651 continue;
8652
8653 /*
8654 * if it was an "else" (that's not an "else if")
8655 * then we need to go back to another if, so
8656 * increment elselevel
8657 */
8658 look = cin_skipcomment(ml_get_curline());
8659 if (cin_iselse(look))
8660 {
8661 mightbeif = cin_skipcomment(look + 4);
8662 if (!cin_isif(mightbeif))
8663 ++elselevel;
8664 continue;
8665 }
8666
8667 /*
8668 * if it was a "while" then we need to go back to
8669 * another "do", so increment whilelevel. XXX
8670 */
8671 if (cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
8672 {
8673 ++whilelevel;
8674 continue;
8675 }
8676
8677 /* If it's an "if" decrement elselevel */
8678 look = cin_skipcomment(ml_get_curline());
8679 if (cin_isif(look))
8680 {
8681 elselevel--;
8682 /*
8683 * When looking for an "if" ignore "while"s that
8684 * get in the way.
8685 */
8686 if (elselevel == 0 && lookfor == LOOKFOR_IF)
8687 whilelevel = 0;
8688 }
8689
8690 /* If it's a "do" decrement whilelevel */
8691 if (cin_isdo(look))
8692 whilelevel--;
8693
8694 /*
8695 * if we've used up all the elses, then
8696 * this must be the if that we want!
8697 * match the indent level of that if.
8698 */
8699 if (elselevel <= 0 && whilelevel <= 0)
8700 {
8701 return OK;
8702 }
8703 }
8704 }
8705 return FAIL;
8706}
8707
8708# if defined(FEAT_EVAL) || defined(PROTO)
8709/*
8710 * Get indent level from 'indentexpr'.
8711 */
8712 int
8713get_expr_indent()
8714{
8715 int indent;
8716 pos_T pos;
8717 int save_State;
Bram Moolenaard1f56e62006-02-22 21:25:37 +00008718 int use_sandbox = was_set_insecurely((char_u *)"indentexpr",
8719 OPT_LOCAL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008720
8721 pos = curwin->w_cursor;
8722 set_vim_var_nr(VV_LNUM, curwin->w_cursor.lnum);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00008723 if (use_sandbox)
8724 ++sandbox;
8725 ++textlock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008726 indent = eval_to_number(curbuf->b_p_inde);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00008727 if (use_sandbox)
8728 --sandbox;
8729 --textlock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008730
8731 /* Restore the cursor position so that 'indentexpr' doesn't need to.
8732 * Pretend to be in Insert mode, allow cursor past end of line for "o"
8733 * command. */
8734 save_State = State;
8735 State = INSERT;
8736 curwin->w_cursor = pos;
8737 check_cursor();
8738 State = save_State;
8739
8740 /* If there is an error, just keep the current indent. */
8741 if (indent < 0)
8742 indent = get_indent();
8743
8744 return indent;
8745}
8746# endif
8747
8748#endif /* FEAT_CINDENT */
8749
8750#if defined(FEAT_LISP) || defined(PROTO)
8751
8752static int lisp_match __ARGS((char_u *p));
8753
8754 static int
8755lisp_match(p)
8756 char_u *p;
8757{
8758 char_u buf[LSIZE];
8759 int len;
8760 char_u *word = p_lispwords;
8761
8762 while (*word != NUL)
8763 {
8764 (void)copy_option_part(&word, buf, LSIZE, ",");
8765 len = (int)STRLEN(buf);
8766 if (STRNCMP(buf, p, len) == 0 && p[len] == ' ')
8767 return TRUE;
8768 }
8769 return FALSE;
8770}
8771
8772/*
8773 * When 'p' is present in 'cpoptions, a Vi compatible method is used.
8774 * The incompatible newer method is quite a bit better at indenting
8775 * code in lisp-like languages than the traditional one; it's still
8776 * mostly heuristics however -- Dirk van Deun, dirk@rave.org
8777 *
8778 * TODO:
8779 * Findmatch() should be adapted for lisp, also to make showmatch
8780 * work correctly: now (v5.3) it seems all C/C++ oriented:
8781 * - it does not recognize the #\( and #\) notations as character literals
8782 * - it doesn't know about comments starting with a semicolon
8783 * - it incorrectly interprets '(' as a character literal
8784 * All this messes up get_lisp_indent in some rare cases.
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008785 * Update from Sergey Khorev:
8786 * I tried to fix the first two issues.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008787 */
8788 int
8789get_lisp_indent()
8790{
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008791 pos_T *pos, realpos, paren;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008792 int amount;
8793 char_u *that;
8794 colnr_T col;
8795 colnr_T firsttry;
8796 int parencount, quotecount;
8797 int vi_lisp;
8798
8799 /* Set vi_lisp to use the vi-compatible method */
8800 vi_lisp = (vim_strchr(p_cpo, CPO_LISP) != NULL);
8801
8802 realpos = curwin->w_cursor;
8803 curwin->w_cursor.col = 0;
8804
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008805 if ((pos = findmatch(NULL, '(')) == NULL)
8806 pos = findmatch(NULL, '[');
8807 else
8808 {
8809 paren = *pos;
8810 pos = findmatch(NULL, '[');
8811 if (pos == NULL || ltp(pos, &paren))
8812 pos = &paren;
8813 }
8814 if (pos != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008815 {
8816 /* Extra trick: Take the indent of the first previous non-white
8817 * line that is at the same () level. */
8818 amount = -1;
8819 parencount = 0;
8820
8821 while (--curwin->w_cursor.lnum >= pos->lnum)
8822 {
8823 if (linewhite(curwin->w_cursor.lnum))
8824 continue;
8825 for (that = ml_get_curline(); *that != NUL; ++that)
8826 {
8827 if (*that == ';')
8828 {
8829 while (*(that + 1) != NUL)
8830 ++that;
8831 continue;
8832 }
8833 if (*that == '\\')
8834 {
8835 if (*(that + 1) != NUL)
8836 ++that;
8837 continue;
8838 }
8839 if (*that == '"' && *(that + 1) != NUL)
8840 {
Bram Moolenaar15ff6c12006-09-15 18:18:09 +00008841 while (*++that && *that != '"')
8842 {
8843 /* skipping escaped characters in the string */
8844 if (*that == '\\')
8845 {
8846 if (*++that == NUL)
8847 break;
8848 if (that[1] == NUL)
8849 {
8850 ++that;
8851 break;
8852 }
8853 }
8854 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008855 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008856 if (*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008857 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008858 else if (*that == ')' || *that == ']')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008859 --parencount;
8860 }
8861 if (parencount == 0)
8862 {
8863 amount = get_indent();
8864 break;
8865 }
8866 }
8867
8868 if (amount == -1)
8869 {
8870 curwin->w_cursor.lnum = pos->lnum;
8871 curwin->w_cursor.col = pos->col;
8872 col = pos->col;
8873
8874 that = ml_get_curline();
8875
8876 if (vi_lisp && get_indent() == 0)
8877 amount = 2;
8878 else
8879 {
8880 amount = 0;
8881 while (*that && col)
8882 {
8883 amount += lbr_chartabsize_adv(&that, (colnr_T)amount);
8884 col--;
8885 }
8886
8887 /*
8888 * Some keywords require "body" indenting rules (the
8889 * non-standard-lisp ones are Scheme special forms):
8890 *
8891 * (let ((a 1)) instead (let ((a 1))
8892 * (...)) of (...))
8893 */
8894
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008895 if (!vi_lisp && (*that == '(' || *that == '[')
8896 && lisp_match(that + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008897 amount += 2;
8898 else
8899 {
8900 that++;
8901 amount++;
8902 firsttry = amount;
8903
8904 while (vim_iswhite(*that))
8905 {
8906 amount += lbr_chartabsize(that, (colnr_T)amount);
8907 ++that;
8908 }
8909
8910 if (*that && *that != ';') /* not a comment line */
8911 {
Bram Moolenaare21877a2008-02-13 09:58:14 +00008912 /* test *that != '(' to accommodate first let/do
Bram Moolenaar071d4272004-06-13 20:20:40 +00008913 * argument if it is more than one line */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008914 if (!vi_lisp && *that != '(' && *that != '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008915 firsttry++;
8916
8917 parencount = 0;
8918 quotecount = 0;
8919
8920 if (vi_lisp
8921 || (*that != '"'
8922 && *that != '\''
8923 && *that != '#'
8924 && (*that < '0' || *that > '9')))
8925 {
8926 while (*that
8927 && (!vim_iswhite(*that)
8928 || quotecount
8929 || parencount)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008930 && (!((*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008931 && !quotecount
8932 && !parencount
8933 && vi_lisp)))
8934 {
8935 if (*that == '"')
8936 quotecount = !quotecount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008937 if ((*that == '(' || *that == '[')
8938 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008939 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008940 if ((*that == ')' || *that == ']')
8941 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008942 --parencount;
8943 if (*that == '\\' && *(that+1) != NUL)
8944 amount += lbr_chartabsize_adv(&that,
8945 (colnr_T)amount);
8946 amount += lbr_chartabsize_adv(&that,
8947 (colnr_T)amount);
8948 }
8949 }
8950 while (vim_iswhite(*that))
8951 {
8952 amount += lbr_chartabsize(that, (colnr_T)amount);
8953 that++;
8954 }
8955 if (!*that || *that == ';')
8956 amount = firsttry;
8957 }
8958 }
8959 }
8960 }
8961 }
8962 else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008963 amount = 0; /* no matching '(' or '[' found, use zero indent */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008964
8965 curwin->w_cursor = realpos;
8966
8967 return amount;
8968}
8969#endif /* FEAT_LISP */
8970
8971 void
8972prepare_to_exit()
8973{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00008974#if defined(SIGHUP) && defined(SIG_IGN)
8975 /* Ignore SIGHUP, because a dropped connection causes a read error, which
8976 * makes Vim exit and then handling SIGHUP causes various reentrance
8977 * problems. */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00008978 signal(SIGHUP, SIG_IGN);
8979#endif
8980
Bram Moolenaar071d4272004-06-13 20:20:40 +00008981#ifdef FEAT_GUI
8982 if (gui.in_use)
8983 {
8984 gui.dying = TRUE;
8985 out_trash(); /* trash any pending output */
8986 }
8987 else
8988#endif
8989 {
8990 windgoto((int)Rows - 1, 0);
8991
8992 /*
8993 * Switch terminal mode back now, so messages end up on the "normal"
8994 * screen (if there are two screens).
8995 */
8996 settmode(TMODE_COOK);
8997#ifdef WIN3264
8998 if (can_end_termcap_mode(FALSE) == TRUE)
8999#endif
9000 stoptermcap();
9001 out_flush();
9002 }
9003}
9004
9005/*
9006 * Preserve files and exit.
9007 * When called IObuff must contain a message.
9008 */
9009 void
9010preserve_exit()
9011{
9012 buf_T *buf;
9013
9014 prepare_to_exit();
9015
Bram Moolenaar4770d092006-01-12 23:22:24 +00009016 /* Setting this will prevent free() calls. That avoids calling free()
9017 * recursively when free() was invoked with a bad pointer. */
9018 really_exiting = TRUE;
9019
Bram Moolenaar071d4272004-06-13 20:20:40 +00009020 out_str(IObuff);
9021 screen_start(); /* don't know where cursor is now */
9022 out_flush();
9023
9024 ml_close_notmod(); /* close all not-modified buffers */
9025
9026 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
9027 {
9028 if (buf->b_ml.ml_mfp != NULL && buf->b_ml.ml_mfp->mf_fname != NULL)
9029 {
9030 OUT_STR(_("Vim: preserving files...\n"));
9031 screen_start(); /* don't know where cursor is now */
9032 out_flush();
9033 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
9034 break;
9035 }
9036 }
9037
9038 ml_close_all(FALSE); /* close all memfiles, without deleting */
9039
9040 OUT_STR(_("Vim: Finished.\n"));
9041
9042 getout(1);
9043}
9044
9045/*
9046 * return TRUE if "fname" exists.
9047 */
9048 int
9049vim_fexists(fname)
9050 char_u *fname;
9051{
9052 struct stat st;
9053
9054 if (mch_stat((char *)fname, &st))
9055 return FALSE;
9056 return TRUE;
9057}
9058
9059/*
9060 * Check for CTRL-C pressed, but only once in a while.
9061 * Should be used instead of ui_breakcheck() for functions that check for
9062 * each line in the file. Calling ui_breakcheck() each time takes too much
9063 * time, because it can be a system call.
9064 */
9065
9066#ifndef BREAKCHECK_SKIP
9067# ifdef FEAT_GUI /* assume the GUI only runs on fast computers */
9068# define BREAKCHECK_SKIP 200
9069# else
9070# define BREAKCHECK_SKIP 32
9071# endif
9072#endif
9073
9074static int breakcheck_count = 0;
9075
9076 void
9077line_breakcheck()
9078{
9079 if (++breakcheck_count >= BREAKCHECK_SKIP)
9080 {
9081 breakcheck_count = 0;
9082 ui_breakcheck();
9083 }
9084}
9085
9086/*
9087 * Like line_breakcheck() but check 10 times less often.
9088 */
9089 void
9090fast_breakcheck()
9091{
9092 if (++breakcheck_count >= BREAKCHECK_SKIP * 10)
9093 {
9094 breakcheck_count = 0;
9095 ui_breakcheck();
9096 }
9097}
9098
9099/*
Bram Moolenaard7834d32009-12-02 16:14:36 +00009100 * Invoke expand_wildcards() for one pattern.
9101 * Expand items like "%:h" before the expansion.
9102 * Returns OK or FAIL.
9103 */
9104 int
9105expand_wildcards_eval(pat, num_file, file, flags)
9106 char_u **pat; /* pointer to input pattern */
9107 int *num_file; /* resulting number of files */
9108 char_u ***file; /* array of resulting files */
9109 int flags; /* EW_DIR, etc. */
9110{
9111 int ret = FAIL;
9112 char_u *eval_pat = NULL;
9113 char_u *exp_pat = *pat;
9114 char_u *ignored_msg;
9115 int usedlen;
9116
9117 if (*exp_pat == '%' || *exp_pat == '#' || *exp_pat == '<')
9118 {
9119 ++emsg_off;
9120 eval_pat = eval_vars(exp_pat, exp_pat, &usedlen,
9121 NULL, &ignored_msg, NULL);
9122 --emsg_off;
9123 if (eval_pat != NULL)
9124 exp_pat = concat_str(eval_pat, exp_pat + usedlen);
9125 }
9126
9127 if (exp_pat != NULL)
9128 ret = expand_wildcards(1, &exp_pat, num_file, file, flags);
9129
9130 if (eval_pat != NULL)
9131 {
9132 vim_free(exp_pat);
9133 vim_free(eval_pat);
9134 }
9135
9136 return ret;
9137}
9138
9139/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00009140 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching
9141 * 'wildignore'.
Bram Moolenaar9e193ac2010-07-19 23:11:27 +02009142 * Returns OK or FAIL. When FAIL then "num_file" won't be set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009143 */
9144 int
9145expand_wildcards(num_pat, pat, num_file, file, flags)
9146 int num_pat; /* number of input patterns */
9147 char_u **pat; /* array of input patterns */
9148 int *num_file; /* resulting number of files */
9149 char_u ***file; /* array of resulting files */
9150 int flags; /* EW_DIR, etc. */
9151{
9152 int retval;
9153 int i, j;
9154 char_u *p;
9155 int non_suf_match; /* number without matching suffix */
9156
9157 retval = gen_expand_wildcards(num_pat, pat, num_file, file, flags);
9158
9159 /* When keeping all matches, return here */
Bram Moolenaar9e193ac2010-07-19 23:11:27 +02009160 if ((flags & EW_KEEPALL) || retval == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009161 return retval;
9162
9163#ifdef FEAT_WILDIGN
9164 /*
9165 * Remove names that match 'wildignore'.
9166 */
9167 if (*p_wig)
9168 {
9169 char_u *ffname;
9170
9171 /* check all files in (*file)[] */
9172 for (i = 0; i < *num_file; ++i)
9173 {
9174 ffname = FullName_save((*file)[i], FALSE);
9175 if (ffname == NULL) /* out of memory */
9176 break;
9177# ifdef VMS
9178 vms_remove_version(ffname);
9179# endif
9180 if (match_file_list(p_wig, (*file)[i], ffname))
9181 {
9182 /* remove this matching file from the list */
9183 vim_free((*file)[i]);
9184 for (j = i; j + 1 < *num_file; ++j)
9185 (*file)[j] = (*file)[j + 1];
9186 --*num_file;
9187 --i;
9188 }
9189 vim_free(ffname);
9190 }
9191 }
9192#endif
9193
9194 /*
9195 * Move the names where 'suffixes' match to the end.
9196 */
9197 if (*num_file > 1)
9198 {
9199 non_suf_match = 0;
9200 for (i = 0; i < *num_file; ++i)
9201 {
9202 if (!match_suffix((*file)[i]))
9203 {
9204 /*
9205 * Move the name without matching suffix to the front
9206 * of the list.
9207 */
9208 p = (*file)[i];
9209 for (j = i; j > non_suf_match; --j)
9210 (*file)[j] = (*file)[j - 1];
9211 (*file)[non_suf_match++] = p;
9212 }
9213 }
9214 }
9215
9216 return retval;
9217}
9218
9219/*
9220 * Return TRUE if "fname" matches with an entry in 'suffixes'.
9221 */
9222 int
9223match_suffix(fname)
9224 char_u *fname;
9225{
9226 int fnamelen, setsuflen;
9227 char_u *setsuf;
9228#define MAXSUFLEN 30 /* maximum length of a file suffix */
9229 char_u suf_buf[MAXSUFLEN];
9230
9231 fnamelen = (int)STRLEN(fname);
9232 setsuflen = 0;
9233 for (setsuf = p_su; *setsuf; )
9234 {
9235 setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
Bram Moolenaar055a2ba2009-07-14 19:40:21 +00009236 if (setsuflen == 0)
9237 {
9238 char_u *tail = gettail(fname);
9239
9240 /* empty entry: match name without a '.' */
9241 if (vim_strchr(tail, '.') == NULL)
9242 {
9243 setsuflen = 1;
9244 break;
9245 }
9246 }
9247 else
9248 {
9249 if (fnamelen >= setsuflen
9250 && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
9251 (size_t)setsuflen) == 0)
9252 break;
9253 setsuflen = 0;
9254 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009255 }
9256 return (setsuflen != 0);
9257}
9258
9259#if !defined(NO_EXPANDPATH) || defined(PROTO)
9260
9261# ifdef VIM_BACKTICK
9262static int vim_backtick __ARGS((char_u *p));
9263static int expand_backtick __ARGS((garray_T *gap, char_u *pat, int flags));
9264# endif
9265
9266# if defined(MSDOS) || defined(FEAT_GUI_W16) || defined(WIN3264)
9267/*
9268 * File name expansion code for MS-DOS, Win16 and Win32. It's here because
9269 * it's shared between these systems.
9270 */
9271# if defined(DJGPP) || defined(PROTO)
9272# define _cdecl /* DJGPP doesn't have this */
9273# else
9274# ifdef __BORLANDC__
9275# define _cdecl _RTLENTRYF
9276# endif
9277# endif
9278
9279/*
9280 * comparison function for qsort in dos_expandpath()
9281 */
9282 static int _cdecl
9283pstrcmp(const void *a, const void *b)
9284{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00009285 return (pathcmp(*(char **)a, *(char **)b, -1));
Bram Moolenaar071d4272004-06-13 20:20:40 +00009286}
9287
9288# ifndef WIN3264
9289 static void
9290namelowcpy(
9291 char_u *d,
9292 char_u *s)
9293{
9294# ifdef DJGPP
9295 if (USE_LONG_FNAME) /* don't lower case on Windows 95/NT systems */
9296 while (*s)
9297 *d++ = *s++;
9298 else
9299# endif
9300 while (*s)
9301 *d++ = TOLOWER_LOC(*s++);
9302 *d = NUL;
9303}
9304# endif
9305
9306/*
Bram Moolenaar231334e2005-07-25 20:46:57 +00009307 * Recursively expand one path component into all matching files and/or
9308 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009309 * Return the number of matches found.
9310 * "path" has backslashes before chars that are not to be expanded, starting
9311 * at "path[wildoff]".
Bram Moolenaar231334e2005-07-25 20:46:57 +00009312 * Return the number of matches found.
9313 * NOTE: much of this is identical to unix_expandpath(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00009314 */
9315 static int
9316dos_expandpath(
9317 garray_T *gap,
9318 char_u *path,
9319 int wildoff,
Bram Moolenaar231334e2005-07-25 20:46:57 +00009320 int flags, /* EW_* flags */
Bram Moolenaar25394022007-05-10 19:06:20 +00009321 int didstar) /* expanded "**" once already */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009322{
Bram Moolenaar231334e2005-07-25 20:46:57 +00009323 char_u *buf;
9324 char_u *path_end;
9325 char_u *p, *s, *e;
9326 int start_len = gap->ga_len;
9327 char_u *pat;
9328 regmatch_T regmatch;
9329 int starts_with_dot;
9330 int matches;
9331 int len;
9332 int starstar = FALSE;
9333 static int stardepth = 0; /* depth for "**" expansion */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009334#ifdef WIN3264
9335 WIN32_FIND_DATA fb;
9336 HANDLE hFind = (HANDLE)0;
9337# ifdef FEAT_MBYTE
9338 WIN32_FIND_DATAW wfb;
9339 WCHAR *wn = NULL; /* UCS-2 name, NULL when not used. */
9340# endif
9341#else
9342 struct ffblk fb;
9343#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009344 char_u *matchname;
Bram Moolenaar231334e2005-07-25 20:46:57 +00009345 int ok;
9346
9347 /* Expanding "**" may take a long time, check for CTRL-C. */
9348 if (stardepth > 0)
9349 {
9350 ui_breakcheck();
9351 if (got_int)
9352 return 0;
9353 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009354
9355 /* make room for file name */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009356 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009357 if (buf == NULL)
9358 return 0;
9359
9360 /*
9361 * Find the first part in the path name that contains a wildcard or a ~1.
9362 * Copy it into buf, including the preceding characters.
9363 */
9364 p = buf;
9365 s = buf;
9366 e = NULL;
9367 path_end = path;
9368 while (*path_end != NUL)
9369 {
9370 /* May ignore a wildcard that has a backslash before it; it will
9371 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
9372 if (path_end >= path + wildoff && rem_backslash(path_end))
9373 *p++ = *path_end++;
9374 else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
9375 {
9376 if (e != NULL)
9377 break;
9378 s = p + 1;
9379 }
9380 else if (path_end >= path + wildoff
9381 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
9382 e = p;
9383#ifdef FEAT_MBYTE
9384 if (has_mbyte)
9385 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00009386 len = (*mb_ptr2len)(path_end);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009387 STRNCPY(p, path_end, len);
9388 p += len;
9389 path_end += len;
9390 }
9391 else
9392#endif
9393 *p++ = *path_end++;
9394 }
9395 e = p;
9396 *e = NUL;
9397
9398 /* now we have one wildcard component between s and e */
9399 /* Remove backslashes between "wildoff" and the start of the wildcard
9400 * component. */
9401 for (p = buf + wildoff; p < s; ++p)
9402 if (rem_backslash(p))
9403 {
Bram Moolenaar8c8de832008-06-24 22:58:06 +00009404 STRMOVE(p, p + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009405 --e;
9406 --s;
9407 }
9408
Bram Moolenaar231334e2005-07-25 20:46:57 +00009409 /* Check for "**" between "s" and "e". */
9410 for (p = s; p < e; ++p)
9411 if (p[0] == '*' && p[1] == '*')
9412 starstar = TRUE;
9413
Bram Moolenaar071d4272004-06-13 20:20:40 +00009414 starts_with_dot = (*s == '.');
9415 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
9416 if (pat == NULL)
9417 {
9418 vim_free(buf);
9419 return 0;
9420 }
9421
9422 /* compile the regexp into a program */
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009423 if (flags & (EW_NOERROR | EW_NOTWILD))
Bram Moolenaarb5609832011-07-20 15:04:58 +02009424 ++emsg_silent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009425 regmatch.rm_ic = TRUE; /* Always ignore case */
9426 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009427 if (flags & (EW_NOERROR | EW_NOTWILD))
Bram Moolenaarb5609832011-07-20 15:04:58 +02009428 --emsg_silent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009429 vim_free(pat);
9430
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009431 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009432 {
9433 vim_free(buf);
9434 return 0;
9435 }
9436
9437 /* remember the pattern or file name being looked for */
9438 matchname = vim_strsave(s);
9439
Bram Moolenaar231334e2005-07-25 20:46:57 +00009440 /* If "**" is by itself, this is the first time we encounter it and more
9441 * is following then find matches without any directory. */
9442 if (!didstar && stardepth < 100 && starstar && e - s == 2
9443 && *path_end == '/')
9444 {
9445 STRCPY(s, path_end + 1);
9446 ++stardepth;
9447 (void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
9448 --stardepth;
9449 }
9450
Bram Moolenaar071d4272004-06-13 20:20:40 +00009451 /* Scan all files in the directory with "dir/ *.*" */
9452 STRCPY(s, "*.*");
9453#ifdef WIN3264
9454# ifdef FEAT_MBYTE
9455 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
9456 {
9457 /* The active codepage differs from 'encoding'. Attempt using the
9458 * wide function. If it fails because it is not implemented fall back
9459 * to the non-wide version (for Windows 98) */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009460 wn = enc_to_utf16(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009461 if (wn != NULL)
9462 {
9463 hFind = FindFirstFileW(wn, &wfb);
9464 if (hFind == INVALID_HANDLE_VALUE
9465 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
9466 {
9467 vim_free(wn);
9468 wn = NULL;
9469 }
9470 }
9471 }
9472
9473 if (wn == NULL)
9474# endif
9475 hFind = FindFirstFile(buf, &fb);
9476 ok = (hFind != INVALID_HANDLE_VALUE);
9477#else
9478 /* If we are expanding wildcards we try both files and directories */
9479 ok = (findfirst((char *)buf, &fb,
9480 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
9481#endif
9482
9483 while (ok)
9484 {
9485#ifdef WIN3264
9486# ifdef FEAT_MBYTE
9487 if (wn != NULL)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009488 p = utf16_to_enc(wfb.cFileName, NULL); /* p is allocated here */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009489 else
9490# endif
9491 p = (char_u *)fb.cFileName;
9492#else
9493 p = (char_u *)fb.ff_name;
9494#endif
9495 /* Ignore entries starting with a dot, unless when asked for. Accept
9496 * all entries found with "matchname". */
9497 if ((p[0] != '.' || starts_with_dot)
9498 && (matchname == NULL
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009499 || (regmatch.regprog != NULL
9500 && vim_regexec(&regmatch, p, (colnr_T)0))
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009501 || ((flags & EW_NOTWILD)
9502 && fnamencmp(path + (s - buf), p, e - s) == 0)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009503 {
9504#ifdef WIN3264
9505 STRCPY(s, p);
9506#else
9507 namelowcpy(s, p);
9508#endif
9509 len = (int)STRLEN(buf);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009510
9511 if (starstar && stardepth < 100)
9512 {
9513 /* For "**" in the pattern first go deeper in the tree to
9514 * find matches. */
9515 STRCPY(buf + len, "/**");
9516 STRCPY(buf + len + 3, path_end);
9517 ++stardepth;
9518 (void)dos_expandpath(gap, buf, len + 1, flags, TRUE);
9519 --stardepth;
9520 }
9521
Bram Moolenaar071d4272004-06-13 20:20:40 +00009522 STRCPY(buf + len, path_end);
9523 if (mch_has_exp_wildcard(path_end))
9524 {
9525 /* need to expand another component of the path */
9526 /* remove backslashes for the remaining components only */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009527 (void)dos_expandpath(gap, buf, len + 1, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009528 }
9529 else
9530 {
9531 /* no more wildcards, check if there is a match */
9532 /* remove backslashes for the remaining components only */
9533 if (*path_end != 0)
9534 backslash_halve(buf + len + 1);
9535 if (mch_getperm(buf) >= 0) /* add existing file */
9536 addfile(gap, buf, flags);
9537 }
9538 }
9539
9540#ifdef WIN3264
9541# ifdef FEAT_MBYTE
9542 if (wn != NULL)
9543 {
9544 vim_free(p);
9545 ok = FindNextFileW(hFind, &wfb);
9546 }
9547 else
9548# endif
9549 ok = FindNextFile(hFind, &fb);
9550#else
9551 ok = (findnext(&fb) == 0);
9552#endif
9553
9554 /* If no more matches and no match was used, try expanding the name
9555 * itself. Finds the long name of a short filename. */
9556 if (!ok && matchname != NULL && gap->ga_len == start_len)
9557 {
9558 STRCPY(s, matchname);
9559#ifdef WIN3264
9560 FindClose(hFind);
9561# ifdef FEAT_MBYTE
9562 if (wn != NULL)
9563 {
9564 vim_free(wn);
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009565 wn = enc_to_utf16(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009566 if (wn != NULL)
9567 hFind = FindFirstFileW(wn, &wfb);
9568 }
9569 if (wn == NULL)
9570# endif
9571 hFind = FindFirstFile(buf, &fb);
9572 ok = (hFind != INVALID_HANDLE_VALUE);
9573#else
9574 ok = (findfirst((char *)buf, &fb,
9575 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
9576#endif
9577 vim_free(matchname);
9578 matchname = NULL;
9579 }
9580 }
9581
9582#ifdef WIN3264
9583 FindClose(hFind);
9584# ifdef FEAT_MBYTE
9585 vim_free(wn);
9586# endif
9587#endif
9588 vim_free(buf);
9589 vim_free(regmatch.regprog);
9590 vim_free(matchname);
9591
9592 matches = gap->ga_len - start_len;
9593 if (matches > 0)
9594 qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
9595 sizeof(char_u *), pstrcmp);
9596 return matches;
9597}
9598
9599 int
9600mch_expandpath(
9601 garray_T *gap,
9602 char_u *path,
9603 int flags) /* EW_* flags */
9604{
Bram Moolenaar231334e2005-07-25 20:46:57 +00009605 return dos_expandpath(gap, path, 0, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009606}
9607# endif /* MSDOS || FEAT_GUI_W16 || WIN3264 */
9608
Bram Moolenaar231334e2005-07-25 20:46:57 +00009609#if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
9610 || defined(PROTO)
9611/*
9612 * Unix style wildcard expansion code.
9613 * It's here because it's used both for Unix and Mac.
9614 */
9615static int pstrcmp __ARGS((const void *, const void *));
9616
9617 static int
9618pstrcmp(a, b)
9619 const void *a, *b;
9620{
9621 return (pathcmp(*(char **)a, *(char **)b, -1));
9622}
9623
9624/*
9625 * Recursively expand one path component into all matching files and/or
9626 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
9627 * "path" has backslashes before chars that are not to be expanded, starting
9628 * at "path + wildoff".
9629 * Return the number of matches found.
9630 * NOTE: much of this is identical to dos_expandpath(), keep in sync!
9631 */
9632 int
9633unix_expandpath(gap, path, wildoff, flags, didstar)
9634 garray_T *gap;
9635 char_u *path;
9636 int wildoff;
9637 int flags; /* EW_* flags */
9638 int didstar; /* expanded "**" once already */
9639{
9640 char_u *buf;
9641 char_u *path_end;
9642 char_u *p, *s, *e;
9643 int start_len = gap->ga_len;
9644 char_u *pat;
9645 regmatch_T regmatch;
9646 int starts_with_dot;
9647 int matches;
9648 int len;
9649 int starstar = FALSE;
9650 static int stardepth = 0; /* depth for "**" expansion */
9651
9652 DIR *dirp;
9653 struct dirent *dp;
9654
9655 /* Expanding "**" may take a long time, check for CTRL-C. */
9656 if (stardepth > 0)
9657 {
9658 ui_breakcheck();
9659 if (got_int)
9660 return 0;
9661 }
9662
9663 /* make room for file name */
9664 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
9665 if (buf == NULL)
9666 return 0;
9667
9668 /*
9669 * Find the first part in the path name that contains a wildcard.
Bram Moolenaar2d0b92f2012-04-30 21:09:43 +02009670 * When EW_ICASE is set every letter is considered to be a wildcard.
Bram Moolenaar231334e2005-07-25 20:46:57 +00009671 * Copy it into "buf", including the preceding characters.
9672 */
9673 p = buf;
9674 s = buf;
9675 e = NULL;
9676 path_end = path;
9677 while (*path_end != NUL)
9678 {
9679 /* May ignore a wildcard that has a backslash before it; it will
9680 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
9681 if (path_end >= path + wildoff && rem_backslash(path_end))
9682 *p++ = *path_end++;
9683 else if (*path_end == '/')
9684 {
9685 if (e != NULL)
9686 break;
9687 s = p + 1;
9688 }
9689 else if (path_end >= path + wildoff
Bram Moolenaar2d0b92f2012-04-30 21:09:43 +02009690 && (vim_strchr((char_u *)"*?[{~$", *path_end) != NULL
9691#ifndef CASE_INSENSITIVE_FILENAME
9692 || ((flags & EW_ICASE)
9693 && isalpha(PTR2CHAR(path_end)))
9694#endif
9695 ))
Bram Moolenaar231334e2005-07-25 20:46:57 +00009696 e = p;
9697#ifdef FEAT_MBYTE
9698 if (has_mbyte)
9699 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00009700 len = (*mb_ptr2len)(path_end);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009701 STRNCPY(p, path_end, len);
9702 p += len;
9703 path_end += len;
9704 }
9705 else
9706#endif
9707 *p++ = *path_end++;
9708 }
9709 e = p;
9710 *e = NUL;
9711
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009712 /* Now we have one wildcard component between "s" and "e". */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009713 /* Remove backslashes between "wildoff" and the start of the wildcard
9714 * component. */
9715 for (p = buf + wildoff; p < s; ++p)
9716 if (rem_backslash(p))
9717 {
Bram Moolenaar8c8de832008-06-24 22:58:06 +00009718 STRMOVE(p, p + 1);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009719 --e;
9720 --s;
9721 }
9722
9723 /* Check for "**" between "s" and "e". */
9724 for (p = s; p < e; ++p)
9725 if (p[0] == '*' && p[1] == '*')
9726 starstar = TRUE;
9727
9728 /* convert the file pattern to a regexp pattern */
9729 starts_with_dot = (*s == '.');
9730 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
9731 if (pat == NULL)
9732 {
9733 vim_free(buf);
9734 return 0;
9735 }
9736
9737 /* compile the regexp into a program */
Bram Moolenaarcc016f52005-12-10 20:23:46 +00009738#ifdef CASE_INSENSITIVE_FILENAME
Bram Moolenaar231334e2005-07-25 20:46:57 +00009739 regmatch.rm_ic = TRUE; /* Behave like Terminal.app */
9740#else
Bram Moolenaar94950a92010-12-02 16:01:29 +01009741 if (flags & EW_ICASE)
9742 regmatch.rm_ic = TRUE; /* 'wildignorecase' set */
9743 else
9744 regmatch.rm_ic = FALSE; /* Don't ignore case */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009745#endif
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009746 if (flags & (EW_NOERROR | EW_NOTWILD))
9747 ++emsg_silent;
Bram Moolenaar231334e2005-07-25 20:46:57 +00009748 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009749 if (flags & (EW_NOERROR | EW_NOTWILD))
9750 --emsg_silent;
Bram Moolenaar231334e2005-07-25 20:46:57 +00009751 vim_free(pat);
9752
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009753 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
Bram Moolenaar231334e2005-07-25 20:46:57 +00009754 {
9755 vim_free(buf);
9756 return 0;
9757 }
9758
9759 /* If "**" is by itself, this is the first time we encounter it and more
9760 * is following then find matches without any directory. */
9761 if (!didstar && stardepth < 100 && starstar && e - s == 2
9762 && *path_end == '/')
9763 {
9764 STRCPY(s, path_end + 1);
9765 ++stardepth;
9766 (void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
9767 --stardepth;
9768 }
9769
9770 /* open the directory for scanning */
9771 *s = NUL;
9772 dirp = opendir(*buf == NUL ? "." : (char *)buf);
9773
9774 /* Find all matching entries */
9775 if (dirp != NULL)
9776 {
9777 for (;;)
9778 {
9779 dp = readdir(dirp);
9780 if (dp == NULL)
9781 break;
9782 if ((dp->d_name[0] != '.' || starts_with_dot)
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009783 && ((regmatch.regprog != NULL && vim_regexec(&regmatch,
9784 (char_u *)dp->d_name, (colnr_T)0))
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009785 || ((flags & EW_NOTWILD)
9786 && fnamencmp(path + (s - buf), dp->d_name, e - s) == 0)))
Bram Moolenaar231334e2005-07-25 20:46:57 +00009787 {
9788 STRCPY(s, dp->d_name);
9789 len = STRLEN(buf);
9790
9791 if (starstar && stardepth < 100)
9792 {
9793 /* For "**" in the pattern first go deeper in the tree to
9794 * find matches. */
9795 STRCPY(buf + len, "/**");
9796 STRCPY(buf + len + 3, path_end);
9797 ++stardepth;
9798 (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
9799 --stardepth;
9800 }
9801
9802 STRCPY(buf + len, path_end);
9803 if (mch_has_exp_wildcard(path_end)) /* handle more wildcards */
9804 {
9805 /* need to expand another component of the path */
9806 /* remove backslashes for the remaining components only */
9807 (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
9808 }
9809 else
9810 {
9811 /* no more wildcards, check if there is a match */
9812 /* remove backslashes for the remaining components only */
9813 if (*path_end != NUL)
9814 backslash_halve(buf + len + 1);
9815 if (mch_getperm(buf) >= 0) /* add existing file */
9816 {
Bram Moolenaar95e9b492006-03-15 23:04:43 +00009817#ifdef MACOS_CONVERT
Bram Moolenaar231334e2005-07-25 20:46:57 +00009818 size_t precomp_len = STRLEN(buf)+1;
9819 char_u *precomp_buf =
9820 mac_precompose_path(buf, precomp_len, &precomp_len);
Bram Moolenaar95e9b492006-03-15 23:04:43 +00009821
Bram Moolenaar231334e2005-07-25 20:46:57 +00009822 if (precomp_buf)
9823 {
9824 mch_memmove(buf, precomp_buf, precomp_len);
9825 vim_free(precomp_buf);
9826 }
9827#endif
9828 addfile(gap, buf, flags);
9829 }
9830 }
9831 }
9832 }
9833
9834 closedir(dirp);
9835 }
9836
9837 vim_free(buf);
9838 vim_free(regmatch.regprog);
9839
9840 matches = gap->ga_len - start_len;
9841 if (matches > 0)
9842 qsort(((char_u **)gap->ga_data) + start_len, matches,
9843 sizeof(char_u *), pstrcmp);
9844 return matches;
9845}
9846#endif
9847
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009848#if defined(FEAT_SEARCHPATH)
9849static int find_previous_pathsep __ARGS((char_u *path, char_u **psep));
9850static int is_unique __ARGS((char_u *maybe_unique, garray_T *gap, int i));
Bram Moolenaar162bd912010-07-28 22:29:10 +02009851static void expand_path_option __ARGS((char_u *curdir, garray_T *gap));
9852static char_u *get_path_cutoff __ARGS((char_u *fname, garray_T *gap));
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009853static void uniquefy_paths __ARGS((garray_T *gap, char_u *pattern));
9854static int expand_in_path __ARGS((garray_T *gap, char_u *pattern, int flags));
9855
9856/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009857 * Moves "*psep" back to the previous path separator in "path".
9858 * Returns FAIL is "*psep" ends up at the beginning of "path".
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009859 */
9860 static int
9861find_previous_pathsep(path, psep)
9862 char_u *path;
9863 char_u **psep;
9864{
9865 /* skip the current separator */
9866 if (*psep > path && vim_ispathsep(**psep))
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009867 --*psep;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009868
9869 /* find the previous separator */
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009870 while (*psep > path)
9871 {
9872 if (vim_ispathsep(**psep))
9873 return OK;
9874 mb_ptr_back(path, *psep);
9875 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009876
9877 return FAIL;
9878}
9879
9880/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009881 * Returns TRUE if "maybe_unique" is unique wrt other_paths in "gap".
9882 * "maybe_unique" is the end portion of "((char_u **)gap->ga_data)[i]".
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009883 */
9884 static int
9885is_unique(maybe_unique, gap, i)
9886 char_u *maybe_unique;
9887 garray_T *gap;
9888 int i;
9889{
9890 int j;
9891 int candidate_len;
9892 int other_path_len;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009893 char_u **other_paths = (char_u **)gap->ga_data;
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009894 char_u *rival;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009895
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009896 for (j = 0; j < gap->ga_len; j++)
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009897 {
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009898 if (j == i)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009899 continue; /* don't compare it with itself */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009900
Bram Moolenaar624c7aa2010-07-16 20:38:52 +02009901 candidate_len = (int)STRLEN(maybe_unique);
9902 other_path_len = (int)STRLEN(other_paths[j]);
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009903 if (other_path_len < candidate_len)
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009904 continue; /* it's different when it's shorter */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009905
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009906 rival = other_paths[j] + other_path_len - candidate_len;
Bram Moolenaarda9836c2010-08-16 21:53:27 +02009907 if (fnamecmp(maybe_unique, rival) == 0
9908 && (rival == other_paths[j] || vim_ispathsep(*(rival - 1))))
Bram Moolenaar162bd912010-07-28 22:29:10 +02009909 return FALSE; /* match */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009910 }
9911
Bram Moolenaar162bd912010-07-28 22:29:10 +02009912 return TRUE; /* no match found */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009913}
9914
9915/*
Bram Moolenaar1a509df2010-08-01 17:59:57 +02009916 * Split the 'path' option into an array of strings in garray_T. Relative
Bram Moolenaar162bd912010-07-28 22:29:10 +02009917 * paths are expanded to their equivalent fullpath. This includes the "."
9918 * (relative to current buffer directory) and empty path (relative to current
9919 * directory) notations.
9920 *
9921 * TODO: handle upward search (;) and path limiter (**N) notations by
9922 * expanding each into their equivalent path(s).
9923 */
9924 static void
9925expand_path_option(curdir, gap)
9926 char_u *curdir;
9927 garray_T *gap;
9928{
9929 char_u *path_option = *curbuf->b_p_path == NUL
9930 ? p_path : curbuf->b_p_path;
9931 char_u *buf;
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009932 char_u *p;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009933 int len;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009934
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +02009935 if ((buf = alloc((int)MAXPATHL)) == NULL)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009936 return;
9937
9938 while (*path_option != NUL)
9939 {
9940 copy_option_part(&path_option, buf, MAXPATHL, " ,");
9941
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009942 if (buf[0] == '.' && (buf[1] == NUL || vim_ispathsep(buf[1])))
Bram Moolenaar162bd912010-07-28 22:29:10 +02009943 {
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009944 /* Relative to current buffer:
9945 * "/path/file" + "." -> "/path/"
9946 * "/path/file" + "./subdir" -> "/path/subdir" */
Bram Moolenaar162bd912010-07-28 22:29:10 +02009947 if (curbuf->b_ffname == NULL)
9948 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009949 p = gettail(curbuf->b_ffname);
9950 len = (int)(p - curbuf->b_ffname);
9951 if (len + (int)STRLEN(buf) >= MAXPATHL)
9952 continue;
9953 if (buf[1] == NUL)
9954 buf[len] = NUL;
9955 else
9956 STRMOVE(buf + len, buf + 2);
9957 mch_memmove(buf, curbuf->b_ffname, len);
9958 simplify_filename(buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009959 }
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009960 else if (buf[0] == NUL)
9961 /* relative to current directory */
Bram Moolenaar162bd912010-07-28 22:29:10 +02009962 STRCPY(buf, curdir);
Bram Moolenaar84f888a2010-08-05 21:40:16 +02009963 else if (path_with_url(buf))
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009964 /* URL can't be used here */
Bram Moolenaar84f888a2010-08-05 21:40:16 +02009965 continue;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009966 else if (!mch_isFullName(buf))
9967 {
9968 /* Expand relative path to their full path equivalent */
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009969 len = (int)STRLEN(curdir);
9970 if (len + (int)STRLEN(buf) + 3 > MAXPATHL)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009971 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009972 STRMOVE(buf + len + 1, buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009973 STRCPY(buf, curdir);
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009974 buf[len] = PATHSEP;
Bram Moolenaar57adda12010-08-03 22:11:29 +02009975 simplify_filename(buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +02009976 }
9977
Bram Moolenaarbdc975c2010-08-02 21:33:37 +02009978 if (ga_grow(gap, 1) == FAIL)
9979 break;
9980 p = vim_strsave(buf);
9981 if (p == NULL)
9982 break;
9983 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009984 }
9985
9986 vim_free(buf);
9987}
9988
9989/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009990 * Returns a pointer to the file or directory name in "fname" that matches the
9991 * longest path in "ga"p, or NULL if there is no match. For example:
Bram Moolenaar162bd912010-07-28 22:29:10 +02009992 *
9993 * path: /foo/bar/baz
9994 * fname: /foo/bar/baz/quux.txt
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009995 * returns: ^this
Bram Moolenaar162bd912010-07-28 22:29:10 +02009996 */
9997 static char_u *
9998get_path_cutoff(fname, gap)
9999 char_u *fname;
10000 garray_T *gap;
10001{
10002 int i;
10003 int maxlen = 0;
10004 char_u **path_part = (char_u **)gap->ga_data;
10005 char_u *cutoff = NULL;
10006
10007 for (i = 0; i < gap->ga_len; i++)
10008 {
10009 int j = 0;
10010
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010011 while ((fname[j] == path_part[i][j]
Bram Moolenaar2d7c47d2010-08-10 19:50:26 +020010012# if defined(MSWIN) || defined(MSDOS)
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010013 || (vim_ispathsep(fname[j]) && vim_ispathsep(path_part[i][j]))
10014#endif
10015 ) && fname[j] != NUL && path_part[i][j] != NUL)
Bram Moolenaar162bd912010-07-28 22:29:10 +020010016 j++;
10017 if (j > maxlen)
10018 {
10019 maxlen = j;
10020 cutoff = &fname[j];
10021 }
10022 }
10023
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010024 /* skip to the file or directory name */
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010025 if (cutoff != NULL)
Bram Moolenaar31710262010-08-13 13:36:15 +020010026 while (vim_ispathsep(*cutoff))
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010027 mb_ptr_adv(cutoff);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010028
10029 return cutoff;
10030}
10031
10032/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010033 * Sorts, removes duplicates and modifies all the fullpath names in "gap" so
10034 * that they are unique with respect to each other while conserving the part
10035 * that matches the pattern. Beware, this is at least O(n^2) wrt "gap->ga_len".
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010036 */
10037 static void
10038uniquefy_paths(gap, pattern)
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +020010039 garray_T *gap;
10040 char_u *pattern;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010041{
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +020010042 int i;
10043 int len;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010044 char_u **fnames = (char_u **)gap->ga_data;
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010045 int sort_again = FALSE;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010046 char_u *pat;
10047 char_u *file_pattern;
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010048 char_u *curdir;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010049 regmatch_T regmatch;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010050 garray_T path_ga;
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010051 char_u **in_curdir = NULL;
10052 char_u *short_name;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010053
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +020010054 remove_duplicates(gap);
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010055 ga_init2(&path_ga, (int)sizeof(char_u *), 1);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010056
10057 /*
10058 * We need to prepend a '*' at the beginning of file_pattern so that the
10059 * regex matches anywhere in the path. FIXME: is this valid for all
Bram Moolenaarb31e4382010-07-24 16:01:56 +020010060 * possible patterns?
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010061 */
Bram Moolenaar624c7aa2010-07-16 20:38:52 +020010062 len = (int)STRLEN(pattern);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010063 file_pattern = alloc(len + 2);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010064 if (file_pattern == NULL)
10065 return;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010066 file_pattern[0] = '*';
Bram Moolenaar162bd912010-07-28 22:29:10 +020010067 file_pattern[1] = NUL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010068 STRCAT(file_pattern, pattern);
10069 pat = file_pat_to_reg_pat(file_pattern, NULL, NULL, TRUE);
10070 vim_free(file_pattern);
Bram Moolenaarb31e4382010-07-24 16:01:56 +020010071 if (pat == NULL)
10072 return;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010073
Bram Moolenaarb31e4382010-07-24 16:01:56 +020010074 regmatch.rm_ic = TRUE; /* always ignore case */
10075 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
10076 vim_free(pat);
10077 if (regmatch.regprog == NULL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010078 return;
10079
Bram Moolenaar162bd912010-07-28 22:29:10 +020010080 if ((curdir = alloc((int)(MAXPATHL))) == NULL)
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010081 goto theend;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010082 mch_dirname(curdir, MAXPATHL);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010083 expand_path_option(curdir, &path_ga);
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010084
10085 in_curdir = (char_u **)alloc_clear(gap->ga_len * sizeof(char_u *));
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010086 if (in_curdir == NULL)
10087 goto theend;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010088
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010089 for (i = 0; i < gap->ga_len && !got_int; i++)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010090 {
Bram Moolenaar162bd912010-07-28 22:29:10 +020010091 char_u *path = fnames[i];
10092 int is_in_curdir;
Bram Moolenaar31710262010-08-13 13:36:15 +020010093 char_u *dir_end = gettail_dir(path);
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010094 char_u *pathsep_p;
10095 char_u *path_cutoff;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010096
Bram Moolenaar624c7aa2010-07-16 20:38:52 +020010097 len = (int)STRLEN(path);
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010098 is_in_curdir = fnamencmp(curdir, path, dir_end - path) == 0
Bram Moolenaar162bd912010-07-28 22:29:10 +020010099 && curdir[dir_end - path] == NUL;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010100 if (is_in_curdir)
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010101 in_curdir[i] = vim_strsave(path);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010102
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010103 /* Shorten the filename while maintaining its uniqueness */
10104 path_cutoff = get_path_cutoff(path, &path_ga);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010105
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010106 /* we start at the end of the path */
10107 pathsep_p = path + len - 1;
10108
10109 while (find_previous_pathsep(path, &pathsep_p))
10110 if (vim_regexec(&regmatch, pathsep_p + 1, (colnr_T)0)
10111 && is_unique(pathsep_p + 1, gap, i)
10112 && path_cutoff != NULL && pathsep_p + 1 >= path_cutoff)
10113 {
10114 sort_again = TRUE;
10115 mch_memmove(path, pathsep_p + 1, STRLEN(pathsep_p));
10116 break;
10117 }
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010118
10119 if (mch_isFullName(path))
10120 {
10121 /*
10122 * Last resort: shorten relative to curdir if possible.
10123 * 'possible' means:
10124 * 1. It is under the current directory.
10125 * 2. The result is actually shorter than the original.
10126 *
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010127 * Before curdir After
10128 * /foo/bar/file.txt /foo/bar ./file.txt
10129 * c:\foo\bar\file.txt c:\foo\bar .\file.txt
10130 * /file.txt / /file.txt
10131 * c:\file.txt c:\ .\file.txt
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010132 */
10133 short_name = shorten_fname(path, curdir);
Bram Moolenaar31710262010-08-13 13:36:15 +020010134 if (short_name != NULL && short_name > path + 1
10135#if defined(MSWIN) || defined(MSDOS)
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010136 /* On windows,
Bram Moolenaar31710262010-08-13 13:36:15 +020010137 * shorten_fname("c:\a\a.txt", "c:\a\b")
Bram Moolenaar31710262010-08-13 13:36:15 +020010138 * returns "\a\a.txt", which is not really the short
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010139 * name, hence: */
Bram Moolenaar31710262010-08-13 13:36:15 +020010140 && !vim_ispathsep(*short_name)
10141#endif
10142 )
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010143 {
10144 STRCPY(path, ".");
10145 add_pathsep(path);
Bram Moolenaarcda000e2010-08-14 13:34:39 +020010146 STRMOVE(path + STRLEN(path), short_name);
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010147 }
10148 }
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010149 ui_breakcheck();
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010150 }
10151
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010152 /* Shorten filenames in /in/current/directory/{filename} */
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010153 for (i = 0; i < gap->ga_len && !got_int; i++)
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010154 {
10155 char_u *rel_path;
10156 char_u *path = in_curdir[i];
10157
10158 if (path == NULL)
10159 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010160
10161 /* If the {filename} is not unique, change it to ./{filename}.
10162 * Else reduce it to {filename} */
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010163 short_name = shorten_fname(path, curdir);
10164 if (short_name == NULL)
10165 short_name = path;
10166 if (is_unique(short_name, gap, i))
10167 {
10168 STRCPY(fnames[i], short_name);
10169 continue;
10170 }
10171
10172 rel_path = alloc((int)(STRLEN(short_name) + STRLEN(PATHSEPSTR) + 2));
10173 if (rel_path == NULL)
10174 goto theend;
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010175 STRCPY(rel_path, ".");
10176 add_pathsep(rel_path);
10177 STRCAT(rel_path, short_name);
10178
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010179 vim_free(fnames[i]);
10180 fnames[i] = rel_path;
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010181 sort_again = TRUE;
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010182 ui_breakcheck();
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010183 }
10184
Bram Moolenaar162bd912010-07-28 22:29:10 +020010185theend:
10186 vim_free(curdir);
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010187 if (in_curdir != NULL)
10188 {
10189 for (i = 0; i < gap->ga_len; i++)
10190 vim_free(in_curdir[i]);
10191 vim_free(in_curdir);
10192 }
Bram Moolenaar162bd912010-07-28 22:29:10 +020010193 ga_clear_strings(&path_ga);
Bram Moolenaarb31e4382010-07-24 16:01:56 +020010194 vim_free(regmatch.regprog);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010195
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010196 if (sort_again)
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +020010197 remove_duplicates(gap);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010198}
10199
10200/*
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010201 * Calls globpath() with 'path' values for the given pattern and stores the
10202 * result in "gap".
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010203 * Returns the total number of matches.
10204 */
10205 static int
10206expand_in_path(gap, pattern, flags)
10207 garray_T *gap;
10208 char_u *pattern;
10209 int flags; /* EW_* flags */
10210{
Bram Moolenaar162bd912010-07-28 22:29:10 +020010211 char_u *curdir;
10212 garray_T path_ga;
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010213 char_u *files = NULL;
10214 char_u *s; /* start */
10215 char_u *e; /* end */
10216 char_u *paths = NULL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010217
Bram Moolenaar7f0f6212010-08-03 22:21:00 +020010218 if ((curdir = alloc((unsigned)MAXPATHL)) == NULL)
Bram Moolenaar162bd912010-07-28 22:29:10 +020010219 return 0;
10220 mch_dirname(curdir, MAXPATHL);
10221
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010222 ga_init2(&path_ga, (int)sizeof(char_u *), 1);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010223 expand_path_option(curdir, &path_ga);
10224 vim_free(curdir);
Bram Moolenaar006d2b02010-08-04 12:39:44 +020010225 if (path_ga.ga_len == 0)
10226 return 0;
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010227
10228 paths = ga_concat_strings(&path_ga);
10229 ga_clear_strings(&path_ga);
10230 if (paths == NULL)
Bram Moolenaar7f0f6212010-08-03 22:21:00 +020010231 return 0;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010232
Bram Moolenaar94950a92010-12-02 16:01:29 +010010233 files = globpath(paths, pattern, (flags & EW_ICASE) ? WILD_ICASE : 0);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010234 vim_free(paths);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010235 if (files == NULL)
10236 return 0;
10237
10238 /* Copy each path in files into gap */
10239 s = e = files;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010240 while (*s != NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010241 {
Bram Moolenaar162bd912010-07-28 22:29:10 +020010242 while (*e != '\n' && *e != NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010243 e++;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010244 if (*e == NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010245 {
10246 addfile(gap, s, flags);
10247 break;
10248 }
10249 else
10250 {
10251 /* *e is '\n' */
Bram Moolenaar162bd912010-07-28 22:29:10 +020010252 *e = NUL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010253 addfile(gap, s, flags);
10254 e++;
10255 s = e;
10256 }
10257 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010258 vim_free(files);
10259
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010260 return gap->ga_len;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010261}
10262#endif
10263
Bram Moolenaar1587a1e2010-07-29 20:59:59 +020010264#if defined(FEAT_SEARCHPATH) || defined(FEAT_CMDL_COMPL) || defined(PROTO)
10265/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010266 * Sort "gap" and remove duplicate entries. "gap" is expected to contain a
10267 * list of file names in allocated memory.
Bram Moolenaar1587a1e2010-07-29 20:59:59 +020010268 */
10269 void
10270remove_duplicates(gap)
10271 garray_T *gap;
10272{
10273 int i;
10274 int j;
10275 char_u **fnames = (char_u **)gap->ga_data;
10276
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010277 sort_strings(fnames, gap->ga_len);
Bram Moolenaar1587a1e2010-07-29 20:59:59 +020010278 for (i = gap->ga_len - 1; i > 0; --i)
10279 if (fnamecmp(fnames[i - 1], fnames[i]) == 0)
10280 {
10281 vim_free(fnames[i]);
10282 for (j = i + 1; j < gap->ga_len; ++j)
10283 fnames[j - 1] = fnames[j];
10284 --gap->ga_len;
10285 }
10286}
10287#endif
10288
Bram Moolenaar071d4272004-06-13 20:20:40 +000010289/*
10290 * Generic wildcard expansion code.
10291 *
10292 * Characters in "pat" that should not be expanded must be preceded with a
10293 * backslash. E.g., "/path\ with\ spaces/my\*star*"
10294 *
10295 * Return FAIL when no single file was found. In this case "num_file" is not
10296 * set, and "file" may contain an error message.
10297 * Return OK when some files found. "num_file" is set to the number of
10298 * matches, "file" to the array of matches. Call FreeWild() later.
10299 */
10300 int
10301gen_expand_wildcards(num_pat, pat, num_file, file, flags)
10302 int num_pat; /* number of input patterns */
10303 char_u **pat; /* array of input patterns */
10304 int *num_file; /* resulting number of files */
10305 char_u ***file; /* array of resulting files */
10306 int flags; /* EW_* flags */
10307{
10308 int i;
10309 garray_T ga;
10310 char_u *p;
10311 static int recursive = FALSE;
10312 int add_pat;
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010313#if defined(FEAT_SEARCHPATH)
10314 int did_expand_in_path = FALSE;
10315#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000010316
10317 /*
10318 * expand_env() is called to expand things like "~user". If this fails,
10319 * it calls ExpandOne(), which brings us back here. In this case, always
10320 * call the machine specific expansion function, if possible. Otherwise,
10321 * return FAIL.
10322 */
10323 if (recursive)
10324#ifdef SPECIAL_WILDCHAR
10325 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
10326#else
10327 return FAIL;
10328#endif
10329
10330#ifdef SPECIAL_WILDCHAR
10331 /*
10332 * If there are any special wildcard characters which we cannot handle
10333 * here, call machine specific function for all the expansion. This
10334 * avoids starting the shell for each argument separately.
10335 * For `=expr` do use the internal function.
10336 */
10337 for (i = 0; i < num_pat; i++)
10338 {
10339 if (vim_strpbrk(pat[i], (char_u *)SPECIAL_WILDCHAR) != NULL
10340# ifdef VIM_BACKTICK
10341 && !(vim_backtick(pat[i]) && pat[i][1] == '=')
10342# endif
10343 )
10344 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
10345 }
10346#endif
10347
10348 recursive = TRUE;
10349
10350 /*
10351 * The matching file names are stored in a growarray. Init it empty.
10352 */
10353 ga_init2(&ga, (int)sizeof(char_u *), 30);
10354
10355 for (i = 0; i < num_pat; ++i)
10356 {
10357 add_pat = -1;
10358 p = pat[i];
10359
10360#ifdef VIM_BACKTICK
10361 if (vim_backtick(p))
10362 add_pat = expand_backtick(&ga, p, flags);
10363 else
10364#endif
10365 {
10366 /*
10367 * First expand environment variables, "~/" and "~user/".
10368 */
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010369 if (vim_strchr(p, '$') != NULL || *p == '~')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010370 {
Bram Moolenaar9f0545d2007-09-26 20:36:32 +000010371 p = expand_env_save_opt(p, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010372 if (p == NULL)
10373 p = pat[i];
10374#ifdef UNIX
10375 /*
10376 * On Unix, if expand_env() can't expand an environment
10377 * variable, use the shell to do that. Discard previously
10378 * found file names and start all over again.
10379 */
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010380 else if (vim_strchr(p, '$') != NULL || *p == '~')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010381 {
10382 vim_free(p);
Bram Moolenaar782027e2009-06-24 14:25:49 +000010383 ga_clear_strings(&ga);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010384 i = mch_expand_wildcards(num_pat, pat, num_file, file,
10385 flags);
10386 recursive = FALSE;
10387 return i;
10388 }
10389#endif
10390 }
10391
10392 /*
10393 * If there are wildcards: Expand file names and add each match to
10394 * the list. If there is no match, and EW_NOTFOUND is given, add
10395 * the pattern.
10396 * If there are no wildcards: Add the file name if it exists or
10397 * when EW_NOTFOUND is given.
10398 */
10399 if (mch_has_exp_wildcard(p))
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010400 {
10401#if defined(FEAT_SEARCHPATH)
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010402 if ((flags & EW_PATH)
10403 && !mch_isFullName(p)
10404 && !(p[0] == '.'
10405 && (vim_ispathsep(p[1])
10406 || (p[1] == '.' && vim_ispathsep(p[2]))))
10407 )
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010408 {
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010409 /* :find completion where 'path' is used.
10410 * Recursiveness is OK here. */
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010411 recursive = FALSE;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010412 add_pat = expand_in_path(&ga, p, flags);
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010413 recursive = TRUE;
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010414 did_expand_in_path = TRUE;
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010415 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010416 else
10417#endif
10418 add_pat = mch_expandpath(&ga, p, flags);
10419 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010420 }
10421
10422 if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
10423 {
10424 char_u *t = backslash_halve_save(p);
10425
10426#if defined(MACOS_CLASSIC)
10427 slash_to_colon(t);
10428#endif
10429 /* When EW_NOTFOUND is used, always add files and dirs. Makes
10430 * "vim c:/" work. */
10431 if (flags & EW_NOTFOUND)
10432 addfile(&ga, t, flags | EW_DIR | EW_FILE);
10433 else if (mch_getperm(t) >= 0)
10434 addfile(&ga, t, flags);
10435 vim_free(t);
10436 }
10437
Bram Moolenaarb28ebbc2010-07-14 16:59:57 +020010438#if defined(FEAT_SEARCHPATH)
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010439 if (did_expand_in_path && ga.ga_len > 0 && (flags & EW_PATH))
Bram Moolenaarb28ebbc2010-07-14 16:59:57 +020010440 uniquefy_paths(&ga, p);
10441#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000010442 if (p != pat[i])
10443 vim_free(p);
10444 }
10445
10446 *num_file = ga.ga_len;
10447 *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data : (char_u **)"";
10448
10449 recursive = FALSE;
10450
10451 return (ga.ga_data != NULL) ? OK : FAIL;
10452}
10453
10454# ifdef VIM_BACKTICK
10455
10456/*
10457 * Return TRUE if we can expand this backtick thing here.
10458 */
10459 static int
10460vim_backtick(p)
10461 char_u *p;
10462{
10463 return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
10464}
10465
10466/*
10467 * Expand an item in `backticks` by executing it as a command.
10468 * Currently only works when pat[] starts and ends with a `.
10469 * Returns number of file names found.
10470 */
10471 static int
10472expand_backtick(gap, pat, flags)
10473 garray_T *gap;
10474 char_u *pat;
10475 int flags; /* EW_* flags */
10476{
10477 char_u *p;
10478 char_u *cmd;
10479 char_u *buffer;
10480 int cnt = 0;
10481 int i;
10482
10483 /* Create the command: lop off the backticks. */
10484 cmd = vim_strnsave(pat + 1, (int)STRLEN(pat) - 2);
10485 if (cmd == NULL)
10486 return 0;
10487
10488#ifdef FEAT_EVAL
10489 if (*cmd == '=') /* `={expr}`: Expand expression */
Bram Moolenaar362e1a32006-03-06 23:29:24 +000010490 buffer = eval_to_string(cmd + 1, &p, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010491 else
10492#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010493 buffer = get_cmd_output(cmd, NULL,
10494 (flags & EW_SILENT) ? SHELL_SILENT : 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010495 vim_free(cmd);
10496 if (buffer == NULL)
10497 return 0;
10498
10499 cmd = buffer;
10500 while (*cmd != NUL)
10501 {
10502 cmd = skipwhite(cmd); /* skip over white space */
10503 p = cmd;
10504 while (*p != NUL && *p != '\r' && *p != '\n') /* skip over entry */
10505 ++p;
10506 /* add an entry if it is not empty */
10507 if (p > cmd)
10508 {
10509 i = *p;
10510 *p = NUL;
10511 addfile(gap, cmd, flags);
10512 *p = i;
10513 ++cnt;
10514 }
10515 cmd = p;
10516 while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
10517 ++cmd;
10518 }
10519
10520 vim_free(buffer);
10521 return cnt;
10522}
10523# endif /* VIM_BACKTICK */
10524
10525/*
10526 * Add a file to a file list. Accepted flags:
10527 * EW_DIR add directories
10528 * EW_FILE add files
Bram Moolenaar1f35bf92006-03-07 22:38:47 +000010529 * EW_EXEC add executable files
Bram Moolenaar071d4272004-06-13 20:20:40 +000010530 * EW_NOTFOUND add even when it doesn't exist
10531 * EW_ADDSLASH add slash after directory name
10532 */
10533 void
10534addfile(gap, f, flags)
10535 garray_T *gap;
10536 char_u *f; /* filename */
10537 int flags;
10538{
10539 char_u *p;
10540 int isdir;
10541
10542 /* if the file/dir doesn't exist, may not add it */
10543 if (!(flags & EW_NOTFOUND) && mch_getperm(f) < 0)
10544 return;
10545
10546#ifdef FNAME_ILLEGAL
10547 /* if the file/dir contains illegal characters, don't add it */
10548 if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
10549 return;
10550#endif
10551
10552 isdir = mch_isdir(f);
10553 if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
10554 return;
10555
Bram Moolenaar1f35bf92006-03-07 22:38:47 +000010556 /* If the file isn't executable, may not add it. Do accept directories. */
10557 if (!isdir && (flags & EW_EXEC) && !mch_can_exe(f))
10558 return;
10559
Bram Moolenaar071d4272004-06-13 20:20:40 +000010560 /* Make room for another item in the file list. */
10561 if (ga_grow(gap, 1) == FAIL)
10562 return;
10563
10564 p = alloc((unsigned)(STRLEN(f) + 1 + isdir));
10565 if (p == NULL)
10566 return;
10567
10568 STRCPY(p, f);
10569#ifdef BACKSLASH_IN_FILENAME
10570 slash_adjust(p);
10571#endif
10572 /*
10573 * Append a slash or backslash after directory names if none is present.
10574 */
10575#ifndef DONT_ADD_PATHSEP_TO_DIR
10576 if (isdir && (flags & EW_ADDSLASH))
10577 add_pathsep(p);
10578#endif
10579 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010580}
10581#endif /* !NO_EXPANDPATH */
10582
10583#if defined(VIM_BACKTICK) || defined(FEAT_EVAL) || defined(PROTO)
10584
10585#ifndef SEEK_SET
10586# define SEEK_SET 0
10587#endif
10588#ifndef SEEK_END
10589# define SEEK_END 2
10590#endif
10591
10592/*
10593 * Get the stdout of an external command.
10594 * Returns an allocated string, or NULL for error.
10595 */
10596 char_u *
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010597get_cmd_output(cmd, infile, flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010598 char_u *cmd;
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010599 char_u *infile; /* optional input file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010600 int flags; /* can be SHELL_SILENT */
10601{
10602 char_u *tempname;
10603 char_u *command;
10604 char_u *buffer = NULL;
10605 int len;
10606 int i = 0;
10607 FILE *fd;
10608
10609 if (check_restricted() || check_secure())
10610 return NULL;
10611
10612 /* get a name for the temp file */
10613 if ((tempname = vim_tempname('o')) == NULL)
10614 {
10615 EMSG(_(e_notmp));
10616 return NULL;
10617 }
10618
10619 /* Add the redirection stuff */
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010620 command = make_filter_cmd(cmd, infile, tempname);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010621 if (command == NULL)
10622 goto done;
10623
10624 /*
10625 * Call the shell to execute the command (errors are ignored).
10626 * Don't check timestamps here.
10627 */
10628 ++no_check_timestamps;
10629 call_shell(command, SHELL_DOOUT | SHELL_EXPAND | flags);
10630 --no_check_timestamps;
10631
10632 vim_free(command);
10633
10634 /*
10635 * read the names from the file into memory
10636 */
10637# ifdef VMS
Bram Moolenaar25394022007-05-10 19:06:20 +000010638 /* created temporary file is not always readable as binary */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010639 fd = mch_fopen((char *)tempname, "r");
10640# else
10641 fd = mch_fopen((char *)tempname, READBIN);
10642# endif
10643
10644 if (fd == NULL)
10645 {
10646 EMSG2(_(e_notopen), tempname);
10647 goto done;
10648 }
10649
10650 fseek(fd, 0L, SEEK_END);
10651 len = ftell(fd); /* get size of temp file */
10652 fseek(fd, 0L, SEEK_SET);
10653
10654 buffer = alloc(len + 1);
10655 if (buffer != NULL)
10656 i = (int)fread((char *)buffer, (size_t)1, (size_t)len, fd);
10657 fclose(fd);
10658 mch_remove(tempname);
10659 if (buffer == NULL)
10660 goto done;
10661#ifdef VMS
10662 len = i; /* VMS doesn't give us what we asked for... */
10663#endif
10664 if (i != len)
10665 {
10666 EMSG2(_(e_notread), tempname);
10667 vim_free(buffer);
10668 buffer = NULL;
10669 }
10670 else
Bram Moolenaar162bd912010-07-28 22:29:10 +020010671 buffer[len] = NUL; /* make sure the buffer is terminated */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010672
10673done:
10674 vim_free(tempname);
10675 return buffer;
10676}
10677#endif
10678
10679/*
10680 * Free the list of files returned by expand_wildcards() or other expansion
10681 * functions.
10682 */
10683 void
10684FreeWild(count, files)
10685 int count;
10686 char_u **files;
10687{
Bram Moolenaarfc1421e2006-04-20 22:17:20 +000010688 if (count <= 0 || files == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010689 return;
10690#if defined(__EMX__) && defined(__ALWAYS_HAS_TRAILING_NULL_POINTER) /* XXX */
10691 /*
10692 * Is this still OK for when other functions than expand_wildcards() have
10693 * been used???
10694 */
10695 _fnexplodefree((char **)files);
10696#else
10697 while (count--)
10698 vim_free(files[count]);
10699 vim_free(files);
10700#endif
10701}
10702
10703/*
Bram Moolenaara9dc3752010-07-11 20:46:53 +020010704 * Return TRUE when need to go to Insert mode because of 'insertmode'.
Bram Moolenaar071d4272004-06-13 20:20:40 +000010705 * Don't do this when still processing a command or a mapping.
10706 * Don't do this when inside a ":normal" command.
10707 */
10708 int
10709goto_im()
10710{
10711 return (p_im && stuff_empty() && typebuf_typed());
10712}