blob: 2063d427e321fa5999aae1d5bdc178cd9b193b49 [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 Moolenaar06ae70d2013-06-17 19:26:36 +020019#if defined(FEAT_CMDL_COMPL)
Bram Moolenaar01b626c2013-06-16 22:49:14 +020020static void init_users __ARGS((void));
Bram Moolenaar06ae70d2013-06-17 19:26:36 +020021#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000022static int copy_indent __ARGS((int size, char_u *src));
23
Bram Moolenaar24305862012-08-15 14:05:05 +020024/* All user names (for ~user completion as done by shell). */
25#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
26static garray_T ga_users;
27#endif
28
Bram Moolenaar071d4272004-06-13 20:20:40 +000029/*
30 * Count the size (in window cells) of the indent in the current line.
31 */
32 int
33get_indent()
34{
35 return get_indent_str(ml_get_curline(), (int)curbuf->b_p_ts);
36}
37
38/*
39 * Count the size (in window cells) of the indent in line "lnum".
40 */
41 int
42get_indent_lnum(lnum)
43 linenr_T lnum;
44{
45 return get_indent_str(ml_get(lnum), (int)curbuf->b_p_ts);
46}
47
48#if defined(FEAT_FOLDING) || defined(PROTO)
49/*
50 * Count the size (in window cells) of the indent in line "lnum" of buffer
51 * "buf".
52 */
53 int
54get_indent_buf(buf, lnum)
55 buf_T *buf;
56 linenr_T lnum;
57{
58 return get_indent_str(ml_get_buf(buf, lnum, FALSE), (int)buf->b_p_ts);
59}
60#endif
61
62/*
63 * count the size (in window cells) of the indent in line "ptr", with
64 * 'tabstop' at "ts"
65 */
Bram Moolenaar4399ef42005-02-12 14:29:27 +000066 int
Bram Moolenaar071d4272004-06-13 20:20:40 +000067get_indent_str(ptr, ts)
68 char_u *ptr;
69 int ts;
70{
71 int count = 0;
72
73 for ( ; *ptr; ++ptr)
74 {
75 if (*ptr == TAB) /* count a tab for what it is worth */
76 count += ts - (count % ts);
77 else if (*ptr == ' ')
78 ++count; /* count a space for one */
79 else
80 break;
81 }
Bram Moolenaar4399ef42005-02-12 14:29:27 +000082 return count;
Bram Moolenaar071d4272004-06-13 20:20:40 +000083}
84
85/*
86 * Set the indent of the current line.
87 * Leaves the cursor on the first non-blank in the line.
88 * Caller must take care of undo.
89 * "flags":
90 * SIN_CHANGED: call changed_bytes() if the line was changed.
91 * SIN_INSERT: insert the indent in front of the line.
92 * SIN_UNDO: save line for undo before changing it.
93 * Returns TRUE if the line was changed.
94 */
95 int
96set_indent(size, flags)
Bram Moolenaar5002c292007-07-24 13:26:15 +000097 int size; /* measured in spaces */
Bram Moolenaar071d4272004-06-13 20:20:40 +000098 int flags;
99{
100 char_u *p;
101 char_u *newline;
102 char_u *oldline;
103 char_u *s;
104 int todo;
Bram Moolenaar5002c292007-07-24 13:26:15 +0000105 int ind_len; /* measured in characters */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000106 int line_len;
107 int doit = FALSE;
Bram Moolenaar5002c292007-07-24 13:26:15 +0000108 int ind_done = 0; /* measured in spaces */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000109 int tab_pad;
Bram Moolenaar5409c052005-03-18 20:27:04 +0000110 int retval = FALSE;
Bram Moolenaar4d64b782007-08-14 20:16:42 +0000111 int orig_char_len = -1; /* number of initial whitespace chars when
Bram Moolenaar5002c292007-07-24 13:26:15 +0000112 'et' and 'pi' are both set */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000113
114 /*
115 * First check if there is anything to do and compute the number of
116 * characters needed for the indent.
117 */
118 todo = size;
119 ind_len = 0;
120 p = oldline = ml_get_curline();
121
122 /* Calculate the buffer size for the new indent, and check to see if it
123 * isn't already set */
124
Bram Moolenaar5002c292007-07-24 13:26:15 +0000125 /* if 'expandtab' isn't set: use TABs; if both 'expandtab' and
126 * 'preserveindent' are set count the number of characters at the
127 * beginning of the line to be copied */
128 if (!curbuf->b_p_et || (!(flags & SIN_INSERT) && curbuf->b_p_pi))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000129 {
130 /* If 'preserveindent' is set then reuse as much as possible of
131 * the existing indent structure for the new indent */
132 if (!(flags & SIN_INSERT) && curbuf->b_p_pi)
133 {
134 ind_done = 0;
135
136 /* count as many characters as we can use */
137 while (todo > 0 && vim_iswhite(*p))
138 {
139 if (*p == TAB)
140 {
141 tab_pad = (int)curbuf->b_p_ts
142 - (ind_done % (int)curbuf->b_p_ts);
143 /* stop if this tab will overshoot the target */
144 if (todo < tab_pad)
145 break;
146 todo -= tab_pad;
147 ++ind_len;
148 ind_done += tab_pad;
149 }
150 else
151 {
152 --todo;
153 ++ind_len;
154 ++ind_done;
155 }
156 ++p;
157 }
158
Bram Moolenaar5002c292007-07-24 13:26:15 +0000159 /* Set initial number of whitespace chars to copy if we are
160 * preserving indent but expandtab is set */
161 if (curbuf->b_p_et)
162 orig_char_len = ind_len;
163
Bram Moolenaar071d4272004-06-13 20:20:40 +0000164 /* Fill to next tabstop with a tab, if possible */
165 tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
Bram Moolenaar4d64b782007-08-14 20:16:42 +0000166 if (todo >= tab_pad && orig_char_len == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000167 {
168 doit = TRUE;
169 todo -= tab_pad;
170 ++ind_len;
171 /* ind_done += tab_pad; */
172 }
173 }
174
175 /* count tabs required for indent */
176 while (todo >= (int)curbuf->b_p_ts)
177 {
178 if (*p != TAB)
179 doit = TRUE;
180 else
181 ++p;
182 todo -= (int)curbuf->b_p_ts;
183 ++ind_len;
184 /* ind_done += (int)curbuf->b_p_ts; */
185 }
186 }
187 /* count spaces required for indent */
188 while (todo > 0)
189 {
190 if (*p != ' ')
191 doit = TRUE;
192 else
193 ++p;
194 --todo;
195 ++ind_len;
196 /* ++ind_done; */
197 }
198
199 /* Return if the indent is OK already. */
200 if (!doit && !vim_iswhite(*p) && !(flags & SIN_INSERT))
201 return FALSE;
202
203 /* Allocate memory for the new line. */
204 if (flags & SIN_INSERT)
205 p = oldline;
206 else
207 p = skipwhite(p);
208 line_len = (int)STRLEN(p) + 1;
Bram Moolenaar5002c292007-07-24 13:26:15 +0000209
210 /* If 'preserveindent' and 'expandtab' are both set keep the original
211 * characters and allocate accordingly. We will fill the rest with spaces
212 * after the if (!curbuf->b_p_et) below. */
Bram Moolenaar4d64b782007-08-14 20:16:42 +0000213 if (orig_char_len != -1)
Bram Moolenaar5002c292007-07-24 13:26:15 +0000214 {
215 newline = alloc(orig_char_len + size - ind_done + line_len);
216 if (newline == NULL)
217 return FALSE;
Bram Moolenaar4d64b782007-08-14 20:16:42 +0000218 todo = size - ind_done;
219 ind_len = orig_char_len + todo; /* Set total length of indent in
220 * characters, which may have been
221 * undercounted until now */
Bram Moolenaar5002c292007-07-24 13:26:15 +0000222 p = oldline;
223 s = newline;
224 while (orig_char_len > 0)
225 {
226 *s++ = *p++;
227 orig_char_len--;
228 }
Bram Moolenaar913626c2008-01-03 11:43:42 +0000229
Bram Moolenaar5002c292007-07-24 13:26:15 +0000230 /* Skip over any additional white space (useful when newindent is less
231 * than old) */
232 while (vim_iswhite(*p))
Bram Moolenaar913626c2008-01-03 11:43:42 +0000233 ++p;
Bram Moolenaarcc00b952007-08-11 12:32:57 +0000234
Bram Moolenaar5002c292007-07-24 13:26:15 +0000235 }
236 else
237 {
238 todo = size;
239 newline = alloc(ind_len + line_len);
240 if (newline == NULL)
241 return FALSE;
242 s = newline;
243 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000244
245 /* Put the characters in the new line. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000246 /* if 'expandtab' isn't set: use TABs */
247 if (!curbuf->b_p_et)
248 {
249 /* If 'preserveindent' is set then reuse as much as possible of
250 * the existing indent structure for the new indent */
251 if (!(flags & SIN_INSERT) && curbuf->b_p_pi)
252 {
253 p = oldline;
254 ind_done = 0;
255
256 while (todo > 0 && vim_iswhite(*p))
257 {
258 if (*p == TAB)
259 {
260 tab_pad = (int)curbuf->b_p_ts
261 - (ind_done % (int)curbuf->b_p_ts);
262 /* stop if this tab will overshoot the target */
263 if (todo < tab_pad)
264 break;
265 todo -= tab_pad;
266 ind_done += tab_pad;
267 }
268 else
269 {
270 --todo;
271 ++ind_done;
272 }
273 *s++ = *p++;
274 }
275
276 /* Fill to next tabstop with a tab, if possible */
277 tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
278 if (todo >= tab_pad)
279 {
280 *s++ = TAB;
281 todo -= tab_pad;
282 }
283
284 p = skipwhite(p);
285 }
286
287 while (todo >= (int)curbuf->b_p_ts)
288 {
289 *s++ = TAB;
290 todo -= (int)curbuf->b_p_ts;
291 }
292 }
293 while (todo > 0)
294 {
295 *s++ = ' ';
296 --todo;
297 }
298 mch_memmove(s, p, (size_t)line_len);
299
300 /* Replace the line (unless undo fails). */
301 if (!(flags & SIN_UNDO) || u_savesub(curwin->w_cursor.lnum) == OK)
302 {
303 ml_replace(curwin->w_cursor.lnum, newline, FALSE);
304 if (flags & SIN_CHANGED)
305 changed_bytes(curwin->w_cursor.lnum, 0);
Bram Moolenaar2c019c82013-10-06 17:46:56 +0200306 /* Correct saved cursor position if it is in this line. */
307 if (saved_cursor.lnum == curwin->w_cursor.lnum)
308 {
309 if (saved_cursor.col >= (colnr_T)(p - oldline))
310 /* cursor was after the indent, adjust for the number of
311 * bytes added/removed */
312 saved_cursor.col += ind_len - (colnr_T)(p - oldline);
313 else if (saved_cursor.col >= (colnr_T)(s - newline))
314 /* cursor was in the indent, and is now after it, put it back
315 * at the start of the indent (replacing spaces with TAB) */
316 saved_cursor.col = (colnr_T)(s - newline);
317 }
Bram Moolenaar5409c052005-03-18 20:27:04 +0000318 retval = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000319 }
320 else
321 vim_free(newline);
322
323 curwin->w_cursor.col = ind_len;
Bram Moolenaar5409c052005-03-18 20:27:04 +0000324 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000325}
326
327/*
328 * Copy the indent from ptr to the current line (and fill to size)
329 * Leaves the cursor on the first non-blank in the line.
330 * Returns TRUE if the line was changed.
331 */
332 static int
333copy_indent(size, src)
334 int size;
335 char_u *src;
336{
337 char_u *p = NULL;
338 char_u *line = NULL;
339 char_u *s;
340 int todo;
341 int ind_len;
342 int line_len = 0;
343 int tab_pad;
344 int ind_done;
345 int round;
346
347 /* Round 1: compute the number of characters needed for the indent
348 * Round 2: copy the characters. */
349 for (round = 1; round <= 2; ++round)
350 {
351 todo = size;
352 ind_len = 0;
353 ind_done = 0;
354 s = src;
355
356 /* Count/copy the usable portion of the source line */
357 while (todo > 0 && vim_iswhite(*s))
358 {
359 if (*s == TAB)
360 {
361 tab_pad = (int)curbuf->b_p_ts
362 - (ind_done % (int)curbuf->b_p_ts);
363 /* Stop if this tab will overshoot the target */
364 if (todo < tab_pad)
365 break;
366 todo -= tab_pad;
367 ind_done += tab_pad;
368 }
369 else
370 {
371 --todo;
372 ++ind_done;
373 }
374 ++ind_len;
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000375 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000376 *p++ = *s;
377 ++s;
378 }
379
380 /* Fill to next tabstop with a tab, if possible */
381 tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
Bram Moolenaarc42e7ed2011-09-07 19:58:09 +0200382 if (todo >= tab_pad && !curbuf->b_p_et)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000383 {
384 todo -= tab_pad;
385 ++ind_len;
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000386 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000387 *p++ = TAB;
388 }
389
390 /* Add tabs required for indent */
Bram Moolenaarc42e7ed2011-09-07 19:58:09 +0200391 while (todo >= (int)curbuf->b_p_ts && !curbuf->b_p_et)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000392 {
393 todo -= (int)curbuf->b_p_ts;
394 ++ind_len;
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000395 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000396 *p++ = TAB;
397 }
398
399 /* Count/add spaces required for indent */
400 while (todo > 0)
401 {
402 --todo;
403 ++ind_len;
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000404 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000405 *p++ = ' ';
406 }
407
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000408 if (p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000409 {
410 /* Allocate memory for the result: the copied indent, new indent
411 * and the rest of the line. */
412 line_len = (int)STRLEN(ml_get_curline()) + 1;
413 line = alloc(ind_len + line_len);
414 if (line == NULL)
415 return FALSE;
416 p = line;
417 }
418 }
419
420 /* Append the original line */
421 mch_memmove(p, ml_get_curline(), (size_t)line_len);
422
423 /* Replace the line */
424 ml_replace(curwin->w_cursor.lnum, line, FALSE);
425
426 /* Put the cursor after the indent. */
427 curwin->w_cursor.col = ind_len;
428 return TRUE;
429}
430
431/*
432 * Return the indent of the current line after a number. Return -1 if no
433 * number was found. Used for 'n' in 'formatoptions': numbered list.
Bram Moolenaar86b68352004-12-27 21:59:20 +0000434 * Since a pattern is used it can actually handle more than numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000435 */
436 int
437get_number_indent(lnum)
438 linenr_T lnum;
439{
Bram Moolenaar071d4272004-06-13 20:20:40 +0000440 colnr_T col;
441 pos_T pos;
442
Bram Moolenaar96b7ca52012-06-29 15:04:49 +0200443 regmatch_T regmatch;
444 int lead_len = 0; /* length of comment leader */
445
Bram Moolenaar071d4272004-06-13 20:20:40 +0000446 if (lnum > curbuf->b_ml.ml_line_count)
447 return -1;
Bram Moolenaar86b68352004-12-27 21:59:20 +0000448 pos.lnum = 0;
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200449
450#ifdef FEAT_COMMENTS
Bram Moolenaar96b7ca52012-06-29 15:04:49 +0200451 /* In format_lines() (i.e. not insert mode), fo+=q is needed too... */
452 if ((State & INSERT) || has_format_option(FO_Q_COMS))
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200453 lead_len = get_leader_len(ml_get(lnum), NULL, FALSE, TRUE);
Bram Moolenaar86b68352004-12-27 21:59:20 +0000454#endif
Bram Moolenaar96b7ca52012-06-29 15:04:49 +0200455 regmatch.regprog = vim_regcomp(curbuf->b_p_flp, RE_MAGIC);
456 if (regmatch.regprog != NULL)
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200457 {
Bram Moolenaar96b7ca52012-06-29 15:04:49 +0200458 regmatch.rm_ic = FALSE;
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200459
Bram Moolenaar96b7ca52012-06-29 15:04:49 +0200460 /* vim_regexec() expects a pointer to a line. This lets us
461 * start matching for the flp beyond any comment leader... */
462 if (vim_regexec(&regmatch, ml_get(lnum) + lead_len, (colnr_T)0))
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200463 {
Bram Moolenaar96b7ca52012-06-29 15:04:49 +0200464 pos.lnum = lnum;
465 pos.col = (colnr_T)(*regmatch.endp - ml_get(lnum));
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200466#ifdef FEAT_VIRTUALEDIT
Bram Moolenaar96b7ca52012-06-29 15:04:49 +0200467 pos.coladd = 0;
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200468#endif
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200469 }
Bram Moolenaar473de612013-06-08 18:19:48 +0200470 vim_regfree(regmatch.regprog);
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200471 }
Bram Moolenaar86b68352004-12-27 21:59:20 +0000472
473 if (pos.lnum == 0 || *ml_get_pos(&pos) == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000474 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000475 getvcol(curwin, &pos, &col, NULL, NULL);
476 return (int)col;
477}
478
479#if defined(FEAT_CINDENT) || defined(FEAT_SMARTINDENT)
480
481static int cin_is_cinword __ARGS((char_u *line));
482
483/*
484 * Return TRUE if the string "line" starts with a word from 'cinwords'.
485 */
486 static int
487cin_is_cinword(line)
488 char_u *line;
489{
490 char_u *cinw;
491 char_u *cinw_buf;
492 int cinw_len;
493 int retval = FALSE;
494 int len;
495
496 cinw_len = (int)STRLEN(curbuf->b_p_cinw) + 1;
497 cinw_buf = alloc((unsigned)cinw_len);
498 if (cinw_buf != NULL)
499 {
500 line = skipwhite(line);
501 for (cinw = curbuf->b_p_cinw; *cinw; )
502 {
503 len = copy_option_part(&cinw, cinw_buf, cinw_len, ",");
504 if (STRNCMP(line, cinw_buf, len) == 0
505 && (!vim_iswordc(line[len]) || !vim_iswordc(line[len - 1])))
506 {
507 retval = TRUE;
508 break;
509 }
510 }
511 vim_free(cinw_buf);
512 }
513 return retval;
514}
515#endif
516
517/*
518 * open_line: Add a new line below or above the current line.
519 *
520 * For VREPLACE mode, we only add a new line when we get to the end of the
521 * file, otherwise we just start replacing the next line.
522 *
523 * Caller must take care of undo. Since VREPLACE may affect any number of
524 * lines however, it may call u_save_cursor() again when starting to change a
525 * new line.
526 * "flags": OPENLINE_DELSPACES delete spaces after cursor
527 * OPENLINE_DO_COM format comments
528 * OPENLINE_KEEPTRAIL keep trailing spaces
529 * OPENLINE_MARKFIX adjust mark positions after the line break
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200530 * OPENLINE_COM_LIST format comments with list or 2nd line indent
531 *
532 * "second_line_indent": indent for after ^^D in Insert mode or if flag
533 * OPENLINE_COM_LIST
Bram Moolenaar071d4272004-06-13 20:20:40 +0000534 *
535 * Return TRUE for success, FALSE for failure
536 */
537 int
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200538open_line(dir, flags, second_line_indent)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000539 int dir; /* FORWARD or BACKWARD */
540 int flags;
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200541 int second_line_indent;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000542{
543 char_u *saved_line; /* copy of the original line */
544 char_u *next_line = NULL; /* copy of the next line */
545 char_u *p_extra = NULL; /* what goes to next line */
546 int less_cols = 0; /* less columns for mark in new line */
547 int less_cols_off = 0; /* columns to skip for mark adjust */
548 pos_T old_cursor; /* old cursor position */
549 int newcol = 0; /* new cursor column */
550 int newindent = 0; /* auto-indent of the new line */
551 int n;
552 int trunc_line = FALSE; /* truncate current line afterwards */
553 int retval = FALSE; /* return value, default is FAIL */
554#ifdef FEAT_COMMENTS
555 int extra_len = 0; /* length of p_extra string */
556 int lead_len; /* length of comment leader */
557 char_u *lead_flags; /* position in 'comments' for comment leader */
558 char_u *leader = NULL; /* copy of comment leader */
559#endif
560 char_u *allocated = NULL; /* allocated memory */
561#if defined(FEAT_SMARTINDENT) || defined(FEAT_VREPLACE) || defined(FEAT_LISP) \
562 || defined(FEAT_CINDENT) || defined(FEAT_COMMENTS)
563 char_u *p;
564#endif
565 int saved_char = NUL; /* init for GCC */
566#if defined(FEAT_SMARTINDENT) || defined(FEAT_COMMENTS)
567 pos_T *pos;
568#endif
569#ifdef FEAT_SMARTINDENT
570 int do_si = (!p_paste && curbuf->b_p_si
571# ifdef FEAT_CINDENT
572 && !curbuf->b_p_cin
573# endif
574 );
575 int no_si = FALSE; /* reset did_si afterwards */
576 int first_char = NUL; /* init for GCC */
577#endif
578#if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
579 int vreplace_mode;
580#endif
581 int did_append; /* appended a new line */
582 int saved_pi = curbuf->b_p_pi; /* copy of preserveindent setting */
583
584 /*
585 * make a copy of the current line so we can mess with it
586 */
587 saved_line = vim_strsave(ml_get_curline());
588 if (saved_line == NULL) /* out of memory! */
589 return FALSE;
590
591#ifdef FEAT_VREPLACE
592 if (State & VREPLACE_FLAG)
593 {
594 /*
595 * With VREPLACE we make a copy of the next line, which we will be
596 * starting to replace. First make the new line empty and let vim play
597 * with the indenting and comment leader to its heart's content. Then
598 * we grab what it ended up putting on the new line, put back the
599 * original line, and call ins_char() to put each new character onto
600 * the line, replacing what was there before and pushing the right
601 * stuff onto the replace stack. -- webb.
602 */
603 if (curwin->w_cursor.lnum < orig_line_count)
604 next_line = vim_strsave(ml_get(curwin->w_cursor.lnum + 1));
605 else
606 next_line = vim_strsave((char_u *)"");
607 if (next_line == NULL) /* out of memory! */
608 goto theend;
609
610 /*
611 * In VREPLACE mode, a NL replaces the rest of the line, and starts
612 * replacing the next line, so push all of the characters left on the
613 * line onto the replace stack. We'll push any other characters that
614 * might be replaced at the start of the next line (due to autoindent
615 * etc) a bit later.
616 */
617 replace_push(NUL); /* Call twice because BS over NL expects it */
618 replace_push(NUL);
619 p = saved_line + curwin->w_cursor.col;
620 while (*p != NUL)
Bram Moolenaar2c994e82008-01-02 16:49:36 +0000621 {
622#ifdef FEAT_MBYTE
623 if (has_mbyte)
624 p += replace_push_mb(p);
625 else
626#endif
627 replace_push(*p++);
628 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000629 saved_line[curwin->w_cursor.col] = NUL;
630 }
631#endif
632
633 if ((State & INSERT)
634#ifdef FEAT_VREPLACE
635 && !(State & VREPLACE_FLAG)
636#endif
637 )
638 {
639 p_extra = saved_line + curwin->w_cursor.col;
640#ifdef FEAT_SMARTINDENT
641 if (do_si) /* need first char after new line break */
642 {
643 p = skipwhite(p_extra);
644 first_char = *p;
645 }
646#endif
647#ifdef FEAT_COMMENTS
648 extra_len = (int)STRLEN(p_extra);
649#endif
650 saved_char = *p_extra;
651 *p_extra = NUL;
652 }
653
654 u_clearline(); /* cannot do "U" command when adding lines */
655#ifdef FEAT_SMARTINDENT
656 did_si = FALSE;
657#endif
658 ai_col = 0;
659
660 /*
661 * If we just did an auto-indent, then we didn't type anything on
662 * the prior line, and it should be truncated. Do this even if 'ai' is not
663 * set because automatically inserting a comment leader also sets did_ai.
664 */
665 if (dir == FORWARD && did_ai)
666 trunc_line = TRUE;
667
668 /*
669 * If 'autoindent' and/or 'smartindent' is set, try to figure out what
670 * indent to use for the new line.
671 */
672 if (curbuf->b_p_ai
673#ifdef FEAT_SMARTINDENT
674 || do_si
675#endif
676 )
677 {
678 /*
679 * count white space on current line
680 */
681 newindent = get_indent_str(saved_line, (int)curbuf->b_p_ts);
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200682 if (newindent == 0 && !(flags & OPENLINE_COM_LIST))
683 newindent = second_line_indent; /* for ^^D command in insert mode */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000684
685#ifdef FEAT_SMARTINDENT
686 /*
687 * Do smart indenting.
688 * In insert/replace mode (only when dir == FORWARD)
689 * we may move some text to the next line. If it starts with '{'
690 * don't add an indent. Fixes inserting a NL before '{' in line
691 * "if (condition) {"
692 */
693 if (!trunc_line && do_si && *saved_line != NUL
694 && (p_extra == NULL || first_char != '{'))
695 {
696 char_u *ptr;
697 char_u last_char;
698
699 old_cursor = curwin->w_cursor;
700 ptr = saved_line;
701# ifdef FEAT_COMMENTS
702 if (flags & OPENLINE_DO_COM)
Bram Moolenaar81340392012-06-06 16:12:59 +0200703 lead_len = get_leader_len(ptr, NULL, FALSE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000704 else
705 lead_len = 0;
706# endif
707 if (dir == FORWARD)
708 {
709 /*
710 * Skip preprocessor directives, unless they are
711 * recognised as comments.
712 */
713 if (
714# ifdef FEAT_COMMENTS
715 lead_len == 0 &&
716# endif
717 ptr[0] == '#')
718 {
719 while (ptr[0] == '#' && curwin->w_cursor.lnum > 1)
720 ptr = ml_get(--curwin->w_cursor.lnum);
721 newindent = get_indent();
722 }
723# ifdef FEAT_COMMENTS
724 if (flags & OPENLINE_DO_COM)
Bram Moolenaar81340392012-06-06 16:12:59 +0200725 lead_len = get_leader_len(ptr, NULL, FALSE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000726 else
727 lead_len = 0;
728 if (lead_len > 0)
729 {
730 /*
731 * This case gets the following right:
732 * \*
733 * * A comment (read '\' as '/').
734 * *\
735 * #define IN_THE_WAY
736 * This should line up here;
737 */
738 p = skipwhite(ptr);
739 if (p[0] == '/' && p[1] == '*')
740 p++;
741 if (p[0] == '*')
742 {
743 for (p++; *p; p++)
744 {
745 if (p[0] == '/' && p[-1] == '*')
746 {
747 /*
748 * End of C comment, indent should line up
749 * with the line containing the start of
750 * the comment
751 */
752 curwin->w_cursor.col = (colnr_T)(p - ptr);
753 if ((pos = findmatch(NULL, NUL)) != NULL)
754 {
755 curwin->w_cursor.lnum = pos->lnum;
756 newindent = get_indent();
757 }
758 }
759 }
760 }
761 }
762 else /* Not a comment line */
763# endif
764 {
765 /* Find last non-blank in line */
766 p = ptr + STRLEN(ptr) - 1;
767 while (p > ptr && vim_iswhite(*p))
768 --p;
769 last_char = *p;
770
771 /*
772 * find the character just before the '{' or ';'
773 */
774 if (last_char == '{' || last_char == ';')
775 {
776 if (p > ptr)
777 --p;
778 while (p > ptr && vim_iswhite(*p))
779 --p;
780 }
781 /*
782 * Try to catch lines that are split over multiple
783 * lines. eg:
784 * if (condition &&
785 * condition) {
786 * Should line up here!
787 * }
788 */
789 if (*p == ')')
790 {
791 curwin->w_cursor.col = (colnr_T)(p - ptr);
792 if ((pos = findmatch(NULL, '(')) != NULL)
793 {
794 curwin->w_cursor.lnum = pos->lnum;
795 newindent = get_indent();
796 ptr = ml_get_curline();
797 }
798 }
799 /*
800 * If last character is '{' do indent, without
801 * checking for "if" and the like.
802 */
803 if (last_char == '{')
804 {
805 did_si = TRUE; /* do indent */
806 no_si = TRUE; /* don't delete it when '{' typed */
807 }
808 /*
809 * Look for "if" and the like, use 'cinwords'.
810 * Don't do this if the previous line ended in ';' or
811 * '}'.
812 */
813 else if (last_char != ';' && last_char != '}'
814 && cin_is_cinword(ptr))
815 did_si = TRUE;
816 }
817 }
818 else /* dir == BACKWARD */
819 {
820 /*
821 * Skip preprocessor directives, unless they are
822 * recognised as comments.
823 */
824 if (
825# ifdef FEAT_COMMENTS
826 lead_len == 0 &&
827# endif
828 ptr[0] == '#')
829 {
830 int was_backslashed = FALSE;
831
832 while ((ptr[0] == '#' || was_backslashed) &&
833 curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
834 {
835 if (*ptr && ptr[STRLEN(ptr) - 1] == '\\')
836 was_backslashed = TRUE;
837 else
838 was_backslashed = FALSE;
839 ptr = ml_get(++curwin->w_cursor.lnum);
840 }
841 if (was_backslashed)
842 newindent = 0; /* Got to end of file */
843 else
844 newindent = get_indent();
845 }
846 p = skipwhite(ptr);
847 if (*p == '}') /* if line starts with '}': do indent */
848 did_si = TRUE;
849 else /* can delete indent when '{' typed */
850 can_si_back = TRUE;
851 }
852 curwin->w_cursor = old_cursor;
853 }
854 if (do_si)
855 can_si = TRUE;
856#endif /* FEAT_SMARTINDENT */
857
858 did_ai = TRUE;
859 }
860
861#ifdef FEAT_COMMENTS
862 /*
863 * Find out if the current line starts with a comment leader.
864 * This may then be inserted in front of the new line.
865 */
866 end_comment_pending = NUL;
867 if (flags & OPENLINE_DO_COM)
Bram Moolenaar81340392012-06-06 16:12:59 +0200868 lead_len = get_leader_len(saved_line, &lead_flags, dir == BACKWARD, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000869 else
870 lead_len = 0;
871 if (lead_len > 0)
872 {
873 char_u *lead_repl = NULL; /* replaces comment leader */
874 int lead_repl_len = 0; /* length of *lead_repl */
875 char_u lead_middle[COM_MAX_LEN]; /* middle-comment string */
876 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
877 char_u *comment_end = NULL; /* where lead_end has been found */
878 int extra_space = FALSE; /* append extra space */
879 int current_flag;
880 int require_blank = FALSE; /* requires blank after middle */
881 char_u *p2;
882
883 /*
884 * If the comment leader has the start, middle or end flag, it may not
885 * be used or may be replaced with the middle leader.
886 */
887 for (p = lead_flags; *p && *p != ':'; ++p)
888 {
889 if (*p == COM_BLANK)
890 {
891 require_blank = TRUE;
892 continue;
893 }
894 if (*p == COM_START || *p == COM_MIDDLE)
895 {
896 current_flag = *p;
897 if (*p == COM_START)
898 {
899 /*
900 * Doing "O" on a start of comment does not insert leader.
901 */
902 if (dir == BACKWARD)
903 {
904 lead_len = 0;
905 break;
906 }
907
908 /* find start of middle part */
909 (void)copy_option_part(&p, lead_middle, COM_MAX_LEN, ",");
910 require_blank = FALSE;
911 }
912
913 /*
914 * Isolate the strings of the middle and end leader.
915 */
916 while (*p && p[-1] != ':') /* find end of middle flags */
917 {
918 if (*p == COM_BLANK)
919 require_blank = TRUE;
920 ++p;
921 }
922 (void)copy_option_part(&p, lead_middle, COM_MAX_LEN, ",");
923
924 while (*p && p[-1] != ':') /* find end of end flags */
925 {
926 /* Check whether we allow automatic ending of comments */
927 if (*p == COM_AUTO_END)
928 end_comment_pending = -1; /* means we want to set it */
929 ++p;
930 }
931 n = copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
932
933 if (end_comment_pending == -1) /* we can set it now */
934 end_comment_pending = lead_end[n - 1];
935
936 /*
937 * If the end of the comment is in the same line, don't use
938 * the comment leader.
939 */
940 if (dir == FORWARD)
941 {
942 for (p = saved_line + lead_len; *p; ++p)
943 if (STRNCMP(p, lead_end, n) == 0)
944 {
945 comment_end = p;
946 lead_len = 0;
947 break;
948 }
949 }
950
951 /*
952 * Doing "o" on a start of comment inserts the middle leader.
953 */
954 if (lead_len > 0)
955 {
956 if (current_flag == COM_START)
957 {
958 lead_repl = lead_middle;
959 lead_repl_len = (int)STRLEN(lead_middle);
960 }
961
962 /*
963 * If we have hit RETURN immediately after the start
964 * comment leader, then put a space after the middle
965 * comment leader on the next line.
966 */
967 if (!vim_iswhite(saved_line[lead_len - 1])
968 && ((p_extra != NULL
969 && (int)curwin->w_cursor.col == lead_len)
970 || (p_extra == NULL
971 && saved_line[lead_len] == NUL)
972 || require_blank))
973 extra_space = TRUE;
974 }
975 break;
976 }
977 if (*p == COM_END)
978 {
979 /*
980 * Doing "o" on the end of a comment does not insert leader.
981 * Remember where the end is, might want to use it to find the
982 * start (for C-comments).
983 */
984 if (dir == FORWARD)
985 {
986 comment_end = skipwhite(saved_line);
987 lead_len = 0;
988 break;
989 }
990
991 /*
992 * Doing "O" on the end of a comment inserts the middle leader.
993 * Find the string for the middle leader, searching backwards.
994 */
995 while (p > curbuf->b_p_com && *p != ',')
996 --p;
997 for (lead_repl = p; lead_repl > curbuf->b_p_com
998 && lead_repl[-1] != ':'; --lead_repl)
999 ;
1000 lead_repl_len = (int)(p - lead_repl);
1001
1002 /* We can probably always add an extra space when doing "O" on
1003 * the comment-end */
1004 extra_space = TRUE;
1005
1006 /* Check whether we allow automatic ending of comments */
1007 for (p2 = p; *p2 && *p2 != ':'; p2++)
1008 {
1009 if (*p2 == COM_AUTO_END)
1010 end_comment_pending = -1; /* means we want to set it */
1011 }
1012 if (end_comment_pending == -1)
1013 {
1014 /* Find last character in end-comment string */
1015 while (*p2 && *p2 != ',')
1016 p2++;
1017 end_comment_pending = p2[-1];
1018 }
1019 break;
1020 }
1021 if (*p == COM_FIRST)
1022 {
1023 /*
1024 * Comment leader for first line only: Don't repeat leader
1025 * when using "O", blank out leader when using "o".
1026 */
1027 if (dir == BACKWARD)
1028 lead_len = 0;
1029 else
1030 {
1031 lead_repl = (char_u *)"";
1032 lead_repl_len = 0;
1033 }
1034 break;
1035 }
1036 }
1037 if (lead_len)
1038 {
Bram Moolenaardc7e85e2012-06-20 12:40:08 +02001039 /* allocate buffer (may concatenate p_extra later) */
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +02001040 leader = alloc(lead_len + lead_repl_len + extra_space + extra_len
Bram Moolenaardc7e85e2012-06-20 12:40:08 +02001041 + (second_line_indent > 0 ? second_line_indent : 0) + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001042 allocated = leader; /* remember to free it later */
1043
1044 if (leader == NULL)
1045 lead_len = 0;
1046 else
1047 {
Bram Moolenaarce0842a2005-07-18 21:58:11 +00001048 vim_strncpy(leader, saved_line, lead_len);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001049
1050 /*
1051 * Replace leader with lead_repl, right or left adjusted
1052 */
1053 if (lead_repl != NULL)
1054 {
1055 int c = 0;
1056 int off = 0;
1057
Bram Moolenaard7d5b472009-11-11 16:30:08 +00001058 for (p = lead_flags; *p != NUL && *p != ':'; )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001059 {
1060 if (*p == COM_RIGHT || *p == COM_LEFT)
Bram Moolenaard7d5b472009-11-11 16:30:08 +00001061 c = *p++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001062 else if (VIM_ISDIGIT(*p) || *p == '-')
1063 off = getdigits(&p);
Bram Moolenaard7d5b472009-11-11 16:30:08 +00001064 else
1065 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001066 }
1067 if (c == COM_RIGHT) /* right adjusted leader */
1068 {
1069 /* find last non-white in the leader to line up with */
1070 for (p = leader + lead_len - 1; p > leader
1071 && vim_iswhite(*p); --p)
1072 ;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001073 ++p;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001074
1075#ifdef FEAT_MBYTE
1076 /* Compute the length of the replaced characters in
1077 * screen characters, not bytes. */
1078 {
1079 int repl_size = vim_strnsize(lead_repl,
1080 lead_repl_len);
1081 int old_size = 0;
1082 char_u *endp = p;
1083 int l;
1084
1085 while (old_size < repl_size && p > leader)
1086 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001087 mb_ptr_back(leader, p);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001088 old_size += ptr2cells(p);
1089 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001090 l = lead_repl_len - (int)(endp - p);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001091 if (l != 0)
1092 mch_memmove(endp + l, endp,
1093 (size_t)((leader + lead_len) - endp));
1094 lead_len += l;
1095 }
1096#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001097 if (p < leader + lead_repl_len)
1098 p = leader;
1099 else
1100 p -= lead_repl_len;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001101#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001102 mch_memmove(p, lead_repl, (size_t)lead_repl_len);
1103 if (p + lead_repl_len > leader + lead_len)
1104 p[lead_repl_len] = NUL;
1105
1106 /* blank-out any other chars from the old leader. */
1107 while (--p >= leader)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001108 {
1109#ifdef FEAT_MBYTE
1110 int l = mb_head_off(leader, p);
1111
1112 if (l > 1)
1113 {
1114 p -= l;
1115 if (ptr2cells(p) > 1)
1116 {
1117 p[1] = ' ';
1118 --l;
1119 }
1120 mch_memmove(p + 1, p + l + 1,
1121 (size_t)((leader + lead_len) - (p + l + 1)));
1122 lead_len -= l;
1123 *p = ' ';
1124 }
1125 else
1126#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001127 if (!vim_iswhite(*p))
1128 *p = ' ';
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001129 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001130 }
1131 else /* left adjusted leader */
1132 {
1133 p = skipwhite(leader);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001134#ifdef FEAT_MBYTE
1135 /* Compute the length of the replaced characters in
1136 * screen characters, not bytes. Move the part that is
1137 * not to be overwritten. */
1138 {
1139 int repl_size = vim_strnsize(lead_repl,
1140 lead_repl_len);
1141 int i;
1142 int l;
1143
1144 for (i = 0; p[i] != NUL && i < lead_len; i += l)
1145 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00001146 l = (*mb_ptr2len)(p + i);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001147 if (vim_strnsize(p, i + l) > repl_size)
1148 break;
1149 }
1150 if (i != lead_repl_len)
1151 {
1152 mch_memmove(p + lead_repl_len, p + i,
Bram Moolenaar2d7ff052009-11-17 15:08:26 +00001153 (size_t)(lead_len - i - (p - leader)));
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001154 lead_len += lead_repl_len - i;
1155 }
1156 }
1157#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001158 mch_memmove(p, lead_repl, (size_t)lead_repl_len);
1159
1160 /* Replace any remaining non-white chars in the old
1161 * leader by spaces. Keep Tabs, the indent must
1162 * remain the same. */
1163 for (p += lead_repl_len; p < leader + lead_len; ++p)
1164 if (!vim_iswhite(*p))
1165 {
1166 /* Don't put a space before a TAB. */
1167 if (p + 1 < leader + lead_len && p[1] == TAB)
1168 {
1169 --lead_len;
1170 mch_memmove(p, p + 1,
1171 (leader + lead_len) - p);
1172 }
1173 else
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001174 {
1175#ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00001176 int l = (*mb_ptr2len)(p);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001177
1178 if (l > 1)
1179 {
1180 if (ptr2cells(p) > 1)
1181 {
1182 /* Replace a double-wide char with
1183 * two spaces */
1184 --l;
1185 *p++ = ' ';
1186 }
1187 mch_memmove(p + 1, p + l,
1188 (leader + lead_len) - p);
1189 lead_len -= l - 1;
1190 }
1191#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001192 *p = ' ';
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001193 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001194 }
1195 *p = NUL;
1196 }
1197
1198 /* Recompute the indent, it may have changed. */
1199 if (curbuf->b_p_ai
1200#ifdef FEAT_SMARTINDENT
1201 || do_si
1202#endif
1203 )
1204 newindent = get_indent_str(leader, (int)curbuf->b_p_ts);
1205
1206 /* Add the indent offset */
1207 if (newindent + off < 0)
1208 {
1209 off = -newindent;
1210 newindent = 0;
1211 }
1212 else
1213 newindent += off;
1214
1215 /* Correct trailing spaces for the shift, so that
1216 * alignment remains equal. */
1217 while (off > 0 && lead_len > 0
1218 && leader[lead_len - 1] == ' ')
1219 {
1220 /* Don't do it when there is a tab before the space */
1221 if (vim_strchr(skipwhite(leader), '\t') != NULL)
1222 break;
1223 --lead_len;
1224 --off;
1225 }
1226
1227 /* If the leader ends in white space, don't add an
1228 * extra space */
1229 if (lead_len > 0 && vim_iswhite(leader[lead_len - 1]))
1230 extra_space = FALSE;
1231 leader[lead_len] = NUL;
1232 }
1233
1234 if (extra_space)
1235 {
1236 leader[lead_len++] = ' ';
1237 leader[lead_len] = NUL;
1238 }
1239
1240 newcol = lead_len;
1241
1242 /*
1243 * if a new indent will be set below, remove the indent that
1244 * is in the comment leader
1245 */
1246 if (newindent
1247#ifdef FEAT_SMARTINDENT
1248 || did_si
1249#endif
1250 )
1251 {
1252 while (lead_len && vim_iswhite(*leader))
1253 {
1254 --lead_len;
1255 --newcol;
1256 ++leader;
1257 }
1258 }
1259
1260 }
1261#ifdef FEAT_SMARTINDENT
1262 did_si = can_si = FALSE;
1263#endif
1264 }
1265 else if (comment_end != NULL)
1266 {
1267 /*
1268 * We have finished a comment, so we don't use the leader.
1269 * If this was a C-comment and 'ai' or 'si' is set do a normal
1270 * indent to align with the line containing the start of the
1271 * comment.
1272 */
1273 if (comment_end[0] == '*' && comment_end[1] == '/' &&
1274 (curbuf->b_p_ai
1275#ifdef FEAT_SMARTINDENT
1276 || do_si
1277#endif
1278 ))
1279 {
1280 old_cursor = curwin->w_cursor;
1281 curwin->w_cursor.col = (colnr_T)(comment_end - saved_line);
1282 if ((pos = findmatch(NULL, NUL)) != NULL)
1283 {
1284 curwin->w_cursor.lnum = pos->lnum;
1285 newindent = get_indent();
1286 }
1287 curwin->w_cursor = old_cursor;
1288 }
1289 }
1290 }
1291#endif
1292
1293 /* (State == INSERT || State == REPLACE), only when dir == FORWARD */
1294 if (p_extra != NULL)
1295 {
1296 *p_extra = saved_char; /* restore char that NUL replaced */
1297
1298 /*
1299 * When 'ai' set or "flags" has OPENLINE_DELSPACES, skip to the first
1300 * non-blank.
1301 *
1302 * When in REPLACE mode, put the deleted blanks on the replace stack,
1303 * preceded by a NUL, so they can be put back when a BS is entered.
1304 */
1305 if (REPLACE_NORMAL(State))
1306 replace_push(NUL); /* end of extra blanks */
1307 if (curbuf->b_p_ai || (flags & OPENLINE_DELSPACES))
1308 {
1309 while ((*p_extra == ' ' || *p_extra == '\t')
1310#ifdef FEAT_MBYTE
1311 && (!enc_utf8
1312 || !utf_iscomposing(utf_ptr2char(p_extra + 1)))
1313#endif
1314 )
1315 {
1316 if (REPLACE_NORMAL(State))
1317 replace_push(*p_extra);
1318 ++p_extra;
1319 ++less_cols_off;
1320 }
1321 }
1322 if (*p_extra != NUL)
1323 did_ai = FALSE; /* append some text, don't truncate now */
1324
1325 /* columns for marks adjusted for removed columns */
1326 less_cols = (int)(p_extra - saved_line);
1327 }
1328
1329 if (p_extra == NULL)
1330 p_extra = (char_u *)""; /* append empty line */
1331
1332#ifdef FEAT_COMMENTS
1333 /* concatenate leader and p_extra, if there is a leader */
1334 if (lead_len)
1335 {
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +02001336 if (flags & OPENLINE_COM_LIST && second_line_indent > 0)
1337 {
1338 int i;
Bram Moolenaar36105782012-06-14 20:59:25 +02001339 int padding = second_line_indent
1340 - (newindent + (int)STRLEN(leader));
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +02001341
1342 /* Here whitespace is inserted after the comment char.
1343 * Below, set_indent(newindent, SIN_INSERT) will insert the
1344 * whitespace needed before the comment char. */
1345 for (i = 0; i < padding; i++)
1346 {
1347 STRCAT(leader, " ");
Bram Moolenaar5fb9ec52012-07-25 16:10:03 +02001348 less_cols--;
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +02001349 newcol++;
1350 }
1351 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001352 STRCAT(leader, p_extra);
1353 p_extra = leader;
1354 did_ai = TRUE; /* So truncating blanks works with comments */
1355 less_cols -= lead_len;
1356 }
1357 else
1358 end_comment_pending = NUL; /* turns out there was no leader */
1359#endif
1360
1361 old_cursor = curwin->w_cursor;
1362 if (dir == BACKWARD)
1363 --curwin->w_cursor.lnum;
1364#ifdef FEAT_VREPLACE
1365 if (!(State & VREPLACE_FLAG) || old_cursor.lnum >= orig_line_count)
1366#endif
1367 {
1368 if (ml_append(curwin->w_cursor.lnum, p_extra, (colnr_T)0, FALSE)
1369 == FAIL)
1370 goto theend;
1371 /* Postpone calling changed_lines(), because it would mess up folding
1372 * with markers. */
1373 mark_adjust(curwin->w_cursor.lnum + 1, (linenr_T)MAXLNUM, 1L, 0L);
1374 did_append = TRUE;
1375 }
1376#ifdef FEAT_VREPLACE
1377 else
1378 {
1379 /*
1380 * In VREPLACE mode we are starting to replace the next line.
1381 */
1382 curwin->w_cursor.lnum++;
1383 if (curwin->w_cursor.lnum >= Insstart.lnum + vr_lines_changed)
1384 {
1385 /* In case we NL to a new line, BS to the previous one, and NL
1386 * again, we don't want to save the new line for undo twice.
1387 */
1388 (void)u_save_cursor(); /* errors are ignored! */
1389 vr_lines_changed++;
1390 }
1391 ml_replace(curwin->w_cursor.lnum, p_extra, TRUE);
1392 changed_bytes(curwin->w_cursor.lnum, 0);
1393 curwin->w_cursor.lnum--;
1394 did_append = FALSE;
1395 }
1396#endif
1397
1398 if (newindent
1399#ifdef FEAT_SMARTINDENT
1400 || did_si
1401#endif
1402 )
1403 {
1404 ++curwin->w_cursor.lnum;
1405#ifdef FEAT_SMARTINDENT
1406 if (did_si)
1407 {
Bram Moolenaar14f24742012-08-08 18:01:05 +02001408 int sw = (int)get_sw_value();
1409
Bram Moolenaar071d4272004-06-13 20:20:40 +00001410 if (p_sr)
Bram Moolenaar14f24742012-08-08 18:01:05 +02001411 newindent -= newindent % sw;
1412 newindent += sw;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001413 }
1414#endif
Bram Moolenaar5002c292007-07-24 13:26:15 +00001415 /* Copy the indent */
1416 if (curbuf->b_p_ci)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001417 {
1418 (void)copy_indent(newindent, saved_line);
1419
1420 /*
1421 * Set the 'preserveindent' option so that any further screwing
1422 * with the line doesn't entirely destroy our efforts to preserve
1423 * it. It gets restored at the function end.
1424 */
1425 curbuf->b_p_pi = TRUE;
1426 }
1427 else
1428 (void)set_indent(newindent, SIN_INSERT);
1429 less_cols -= curwin->w_cursor.col;
1430
1431 ai_col = curwin->w_cursor.col;
1432
1433 /*
1434 * In REPLACE mode, for each character in the new indent, there must
1435 * be a NUL on the replace stack, for when it is deleted with BS
1436 */
1437 if (REPLACE_NORMAL(State))
1438 for (n = 0; n < (int)curwin->w_cursor.col; ++n)
1439 replace_push(NUL);
1440 newcol += curwin->w_cursor.col;
1441#ifdef FEAT_SMARTINDENT
1442 if (no_si)
1443 did_si = FALSE;
1444#endif
1445 }
1446
1447#ifdef FEAT_COMMENTS
1448 /*
1449 * In REPLACE mode, for each character in the extra leader, there must be
1450 * a NUL on the replace stack, for when it is deleted with BS.
1451 */
1452 if (REPLACE_NORMAL(State))
1453 while (lead_len-- > 0)
1454 replace_push(NUL);
1455#endif
1456
1457 curwin->w_cursor = old_cursor;
1458
1459 if (dir == FORWARD)
1460 {
1461 if (trunc_line || (State & INSERT))
1462 {
1463 /* truncate current line at cursor */
1464 saved_line[curwin->w_cursor.col] = NUL;
1465 /* Remove trailing white space, unless OPENLINE_KEEPTRAIL used. */
1466 if (trunc_line && !(flags & OPENLINE_KEEPTRAIL))
1467 truncate_spaces(saved_line);
1468 ml_replace(curwin->w_cursor.lnum, saved_line, FALSE);
1469 saved_line = NULL;
1470 if (did_append)
1471 {
1472 changed_lines(curwin->w_cursor.lnum, curwin->w_cursor.col,
1473 curwin->w_cursor.lnum + 1, 1L);
1474 did_append = FALSE;
1475
1476 /* Move marks after the line break to the new line. */
1477 if (flags & OPENLINE_MARKFIX)
1478 mark_col_adjust(curwin->w_cursor.lnum,
1479 curwin->w_cursor.col + less_cols_off,
1480 1L, (long)-less_cols);
1481 }
1482 else
1483 changed_bytes(curwin->w_cursor.lnum, curwin->w_cursor.col);
1484 }
1485
1486 /*
1487 * Put the cursor on the new line. Careful: the scrollup() above may
1488 * have moved w_cursor, we must use old_cursor.
1489 */
1490 curwin->w_cursor.lnum = old_cursor.lnum + 1;
1491 }
1492 if (did_append)
1493 changed_lines(curwin->w_cursor.lnum, 0, curwin->w_cursor.lnum, 1L);
1494
1495 curwin->w_cursor.col = newcol;
1496#ifdef FEAT_VIRTUALEDIT
1497 curwin->w_cursor.coladd = 0;
1498#endif
1499
1500#if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
1501 /*
1502 * In VREPLACE mode, we are handling the replace stack ourselves, so stop
1503 * fixthisline() from doing it (via change_indent()) by telling it we're in
1504 * normal INSERT mode.
1505 */
1506 if (State & VREPLACE_FLAG)
1507 {
1508 vreplace_mode = State; /* So we know to put things right later */
1509 State = INSERT;
1510 }
1511 else
1512 vreplace_mode = 0;
1513#endif
1514#ifdef FEAT_LISP
1515 /*
1516 * May do lisp indenting.
1517 */
1518 if (!p_paste
1519# ifdef FEAT_COMMENTS
1520 && leader == NULL
1521# endif
1522 && curbuf->b_p_lisp
1523 && curbuf->b_p_ai)
1524 {
1525 fixthisline(get_lisp_indent);
1526 p = ml_get_curline();
1527 ai_col = (colnr_T)(skipwhite(p) - p);
1528 }
1529#endif
1530#ifdef FEAT_CINDENT
1531 /*
1532 * May do indenting after opening a new line.
1533 */
1534 if (!p_paste
1535 && (curbuf->b_p_cin
1536# ifdef FEAT_EVAL
1537 || *curbuf->b_p_inde != NUL
1538# endif
1539 )
1540 && in_cinkeys(dir == FORWARD
1541 ? KEY_OPEN_FORW
1542 : KEY_OPEN_BACK, ' ', linewhite(curwin->w_cursor.lnum)))
1543 {
1544 do_c_expr_indent();
1545 p = ml_get_curline();
1546 ai_col = (colnr_T)(skipwhite(p) - p);
1547 }
1548#endif
1549#if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
1550 if (vreplace_mode != 0)
1551 State = vreplace_mode;
1552#endif
1553
1554#ifdef FEAT_VREPLACE
1555 /*
1556 * Finally, VREPLACE gets the stuff on the new line, then puts back the
1557 * original line, and inserts the new stuff char by char, pushing old stuff
1558 * onto the replace stack (via ins_char()).
1559 */
1560 if (State & VREPLACE_FLAG)
1561 {
1562 /* Put new line in p_extra */
1563 p_extra = vim_strsave(ml_get_curline());
1564 if (p_extra == NULL)
1565 goto theend;
1566
1567 /* Put back original line */
1568 ml_replace(curwin->w_cursor.lnum, next_line, FALSE);
1569
1570 /* Insert new stuff into line again */
1571 curwin->w_cursor.col = 0;
1572#ifdef FEAT_VIRTUALEDIT
1573 curwin->w_cursor.coladd = 0;
1574#endif
1575 ins_bytes(p_extra); /* will call changed_bytes() */
1576 vim_free(p_extra);
1577 next_line = NULL;
1578 }
1579#endif
1580
1581 retval = TRUE; /* success! */
1582theend:
1583 curbuf->b_p_pi = saved_pi;
1584 vim_free(saved_line);
1585 vim_free(next_line);
1586 vim_free(allocated);
1587 return retval;
1588}
1589
1590#if defined(FEAT_COMMENTS) || defined(PROTO)
1591/*
Bram Moolenaar2c019c82013-10-06 17:46:56 +02001592 * get_leader_len() returns the length in bytes of the prefix of the given
1593 * string which introduces a comment. If this string is not a comment then
1594 * 0 is returned.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001595 * When "flags" is not NULL, it is set to point to the flags of the recognized
1596 * comment leader.
1597 * "backward" must be true for the "O" command.
Bram Moolenaar81340392012-06-06 16:12:59 +02001598 * If "include_space" is set, include trailing whitespace while calculating the
1599 * length.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001600 */
1601 int
Bram Moolenaar81340392012-06-06 16:12:59 +02001602get_leader_len(line, flags, backward, include_space)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001603 char_u *line;
1604 char_u **flags;
1605 int backward;
Bram Moolenaar81340392012-06-06 16:12:59 +02001606 int include_space;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001607{
1608 int i, j;
Bram Moolenaar81340392012-06-06 16:12:59 +02001609 int result;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001610 int got_com = FALSE;
1611 int found_one;
1612 char_u part_buf[COM_MAX_LEN]; /* buffer for one option part */
1613 char_u *string; /* pointer to comment string */
1614 char_u *list;
Bram Moolenaara4271d52011-05-10 13:38:27 +02001615 int middle_match_len = 0;
1616 char_u *prev_list;
Bram Moolenaar05da4282011-05-10 14:44:11 +02001617 char_u *saved_flags = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001618
Bram Moolenaar81340392012-06-06 16:12:59 +02001619 result = i = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001620 while (vim_iswhite(line[i])) /* leading white space is ignored */
1621 ++i;
1622
1623 /*
1624 * Repeat to match several nested comment strings.
1625 */
Bram Moolenaara4271d52011-05-10 13:38:27 +02001626 while (line[i] != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001627 {
1628 /*
1629 * scan through the 'comments' option for a match
1630 */
1631 found_one = FALSE;
1632 for (list = curbuf->b_p_com; *list; )
1633 {
Bram Moolenaara4271d52011-05-10 13:38:27 +02001634 /* Get one option part into part_buf[]. Advance "list" to next
1635 * one. Put "string" at start of string. */
1636 if (!got_com && flags != NULL)
1637 *flags = list; /* remember where flags started */
1638 prev_list = list;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001639 (void)copy_option_part(&list, part_buf, COM_MAX_LEN, ",");
1640 string = vim_strchr(part_buf, ':');
1641 if (string == NULL) /* missing ':', ignore this part */
1642 continue;
1643 *string++ = NUL; /* isolate flags from string */
1644
Bram Moolenaara4271d52011-05-10 13:38:27 +02001645 /* If we found a middle match previously, use that match when this
1646 * is not a middle or end. */
1647 if (middle_match_len != 0
1648 && vim_strchr(part_buf, COM_MIDDLE) == NULL
1649 && vim_strchr(part_buf, COM_END) == NULL)
1650 break;
1651
1652 /* When we already found a nested comment, only accept further
1653 * nested comments. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001654 if (got_com && vim_strchr(part_buf, COM_NEST) == NULL)
1655 continue;
1656
Bram Moolenaara4271d52011-05-10 13:38:27 +02001657 /* When 'O' flag present and using "O" command skip this one. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001658 if (backward && vim_strchr(part_buf, COM_NOBACK) != NULL)
1659 continue;
1660
Bram Moolenaara4271d52011-05-10 13:38:27 +02001661 /* Line contents and string must match.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001662 * When string starts with white space, must have some white space
1663 * (but the amount does not need to match, there might be a mix of
Bram Moolenaara4271d52011-05-10 13:38:27 +02001664 * TABs and spaces). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001665 if (vim_iswhite(string[0]))
1666 {
1667 if (i == 0 || !vim_iswhite(line[i - 1]))
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001668 continue; /* missing white space */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001669 while (vim_iswhite(string[0]))
1670 ++string;
1671 }
1672 for (j = 0; string[j] != NUL && string[j] == line[i + j]; ++j)
1673 ;
1674 if (string[j] != NUL)
Bram Moolenaara4271d52011-05-10 13:38:27 +02001675 continue; /* string doesn't match */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001676
Bram Moolenaara4271d52011-05-10 13:38:27 +02001677 /* When 'b' flag used, there must be white space or an
1678 * end-of-line after the string in the line. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001679 if (vim_strchr(part_buf, COM_BLANK) != NULL
1680 && !vim_iswhite(line[i + j]) && line[i + j] != NUL)
1681 continue;
1682
Bram Moolenaara4271d52011-05-10 13:38:27 +02001683 /* We have found a match, stop searching unless this is a middle
1684 * comment. The middle comment can be a substring of the end
1685 * comment in which case it's better to return the length of the
1686 * end comment and its flags. Thus we keep searching with middle
1687 * and end matches and use an end match if it matches better. */
1688 if (vim_strchr(part_buf, COM_MIDDLE) != NULL)
1689 {
1690 if (middle_match_len == 0)
1691 {
1692 middle_match_len = j;
1693 saved_flags = prev_list;
1694 }
1695 continue;
1696 }
1697 if (middle_match_len != 0 && j > middle_match_len)
1698 /* Use this match instead of the middle match, since it's a
1699 * longer thus better match. */
1700 middle_match_len = 0;
1701
1702 if (middle_match_len == 0)
1703 i += j;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001704 found_one = TRUE;
1705 break;
1706 }
1707
Bram Moolenaara4271d52011-05-10 13:38:27 +02001708 if (middle_match_len != 0)
1709 {
1710 /* Use the previously found middle match after failing to find a
1711 * match with an end. */
1712 if (!got_com && flags != NULL)
1713 *flags = saved_flags;
1714 i += middle_match_len;
1715 found_one = TRUE;
1716 }
1717
1718 /* No match found, stop scanning. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001719 if (!found_one)
1720 break;
1721
Bram Moolenaar81340392012-06-06 16:12:59 +02001722 result = i;
1723
Bram Moolenaara4271d52011-05-10 13:38:27 +02001724 /* Include any trailing white space. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001725 while (vim_iswhite(line[i]))
1726 ++i;
1727
Bram Moolenaar81340392012-06-06 16:12:59 +02001728 if (include_space)
1729 result = i;
1730
Bram Moolenaara4271d52011-05-10 13:38:27 +02001731 /* If this comment doesn't nest, stop here. */
1732 got_com = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001733 if (vim_strchr(part_buf, COM_NEST) == NULL)
1734 break;
1735 }
Bram Moolenaar81340392012-06-06 16:12:59 +02001736 return result;
1737}
Bram Moolenaara4271d52011-05-10 13:38:27 +02001738
Bram Moolenaar81340392012-06-06 16:12:59 +02001739/*
1740 * Return the offset at which the last comment in line starts. If there is no
1741 * comment in the whole line, -1 is returned.
1742 *
1743 * When "flags" is not null, it is set to point to the flags describing the
1744 * recognized comment leader.
1745 */
1746 int
1747get_last_leader_offset(line, flags)
1748 char_u *line;
1749 char_u **flags;
1750{
1751 int result = -1;
1752 int i, j;
1753 int lower_check_bound = 0;
1754 char_u *string;
1755 char_u *com_leader;
1756 char_u *com_flags;
1757 char_u *list;
1758 int found_one;
1759 char_u part_buf[COM_MAX_LEN]; /* buffer for one option part */
1760
1761 /*
1762 * Repeat to match several nested comment strings.
1763 */
1764 i = (int)STRLEN(line);
1765 while (--i >= lower_check_bound)
1766 {
1767 /*
1768 * scan through the 'comments' option for a match
1769 */
1770 found_one = FALSE;
1771 for (list = curbuf->b_p_com; *list; )
1772 {
1773 char_u *flags_save = list;
1774
1775 /*
1776 * Get one option part into part_buf[]. Advance list to next one.
1777 * put string at start of string.
1778 */
1779 (void)copy_option_part(&list, part_buf, COM_MAX_LEN, ",");
1780 string = vim_strchr(part_buf, ':');
1781 if (string == NULL) /* If everything is fine, this cannot actually
1782 * happen. */
1783 {
1784 continue;
1785 }
1786 *string++ = NUL; /* Isolate flags from string. */
1787 com_leader = string;
1788
1789 /*
1790 * Line contents and string must match.
1791 * When string starts with white space, must have some white space
1792 * (but the amount does not need to match, there might be a mix of
1793 * TABs and spaces).
1794 */
1795 if (vim_iswhite(string[0]))
1796 {
1797 if (i == 0 || !vim_iswhite(line[i - 1]))
1798 continue;
1799 while (vim_iswhite(string[0]))
1800 ++string;
1801 }
1802 for (j = 0; string[j] != NUL && string[j] == line[i + j]; ++j)
1803 /* do nothing */;
1804 if (string[j] != NUL)
1805 continue;
1806
1807 /*
1808 * When 'b' flag used, there must be white space or an
1809 * end-of-line after the string in the line.
1810 */
1811 if (vim_strchr(part_buf, COM_BLANK) != NULL
1812 && !vim_iswhite(line[i + j]) && line[i + j] != NUL)
1813 {
1814 continue;
1815 }
1816
1817 /*
1818 * We have found a match, stop searching.
1819 */
1820 found_one = TRUE;
1821
1822 if (flags)
1823 *flags = flags_save;
1824 com_flags = flags_save;
1825
1826 break;
1827 }
1828
1829 if (found_one)
1830 {
1831 char_u part_buf2[COM_MAX_LEN]; /* buffer for one option part */
1832 int len1, len2, off;
1833
1834 result = i;
1835 /*
1836 * If this comment nests, continue searching.
1837 */
1838 if (vim_strchr(part_buf, COM_NEST) != NULL)
1839 continue;
1840
1841 lower_check_bound = i;
1842
1843 /* Let's verify whether the comment leader found is a substring
1844 * of other comment leaders. If it is, let's adjust the
1845 * lower_check_bound so that we make sure that we have determined
1846 * the comment leader correctly.
1847 */
1848
1849 while (vim_iswhite(*com_leader))
1850 ++com_leader;
1851 len1 = (int)STRLEN(com_leader);
1852
1853 for (list = curbuf->b_p_com; *list; )
1854 {
1855 char_u *flags_save = list;
1856
1857 (void)copy_option_part(&list, part_buf2, COM_MAX_LEN, ",");
1858 if (flags_save == com_flags)
1859 continue;
1860 string = vim_strchr(part_buf2, ':');
1861 ++string;
1862 while (vim_iswhite(*string))
1863 ++string;
1864 len2 = (int)STRLEN(string);
1865 if (len2 == 0)
1866 continue;
1867
1868 /* Now we have to verify whether string ends with a substring
1869 * beginning the com_leader. */
1870 for (off = (len2 > i ? i : len2); off > 0 && off + len1 > len2;)
1871 {
1872 --off;
1873 if (!STRNCMP(string + off, com_leader, len2 - off))
1874 {
1875 if (i - off < lower_check_bound)
1876 lower_check_bound = i - off;
1877 }
1878 }
1879 }
1880 }
1881 }
1882 return result;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001883}
1884#endif
1885
1886/*
1887 * Return the number of window lines occupied by buffer line "lnum".
1888 */
1889 int
1890plines(lnum)
1891 linenr_T lnum;
1892{
1893 return plines_win(curwin, lnum, TRUE);
1894}
1895
1896 int
1897plines_win(wp, lnum, winheight)
1898 win_T *wp;
1899 linenr_T lnum;
1900 int winheight; /* when TRUE limit to window height */
1901{
1902#if defined(FEAT_DIFF) || defined(PROTO)
1903 /* Check for filler lines above this buffer line. When folded the result
1904 * is one line anyway. */
1905 return plines_win_nofill(wp, lnum, winheight) + diff_check_fill(wp, lnum);
1906}
1907
1908 int
1909plines_nofill(lnum)
1910 linenr_T lnum;
1911{
1912 return plines_win_nofill(curwin, lnum, TRUE);
1913}
1914
1915 int
1916plines_win_nofill(wp, lnum, winheight)
1917 win_T *wp;
1918 linenr_T lnum;
1919 int winheight; /* when TRUE limit to window height */
1920{
1921#endif
1922 int lines;
1923
1924 if (!wp->w_p_wrap)
1925 return 1;
1926
1927#ifdef FEAT_VERTSPLIT
1928 if (wp->w_width == 0)
1929 return 1;
1930#endif
1931
1932#ifdef FEAT_FOLDING
1933 /* A folded lines is handled just like an empty line. */
1934 /* NOTE: Caller must handle lines that are MAYBE folded. */
1935 if (lineFolded(wp, lnum) == TRUE)
1936 return 1;
1937#endif
1938
1939 lines = plines_win_nofold(wp, lnum);
1940 if (winheight > 0 && lines > wp->w_height)
1941 return (int)wp->w_height;
1942 return lines;
1943}
1944
1945/*
1946 * Return number of window lines physical line "lnum" will occupy in window
1947 * "wp". Does not care about folding, 'wrap' or 'diff'.
1948 */
1949 int
1950plines_win_nofold(wp, lnum)
1951 win_T *wp;
1952 linenr_T lnum;
1953{
1954 char_u *s;
1955 long col;
1956 int width;
1957
1958 s = ml_get_buf(wp->w_buffer, lnum, FALSE);
1959 if (*s == NUL) /* empty line */
1960 return 1;
1961 col = win_linetabsize(wp, s, (colnr_T)MAXCOL);
1962
1963 /*
1964 * If list mode is on, then the '$' at the end of the line may take up one
1965 * extra column.
1966 */
1967 if (wp->w_p_list && lcs_eol != NUL)
1968 col += 1;
1969
1970 /*
Bram Moolenaar64486672010-05-16 15:46:46 +02001971 * Add column offset for 'number', 'relativenumber' and 'foldcolumn'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001972 */
1973 width = W_WIDTH(wp) - win_col_off(wp);
1974 if (width <= 0)
1975 return 32000;
1976 if (col <= width)
1977 return 1;
1978 col -= width;
1979 width += win_col_off2(wp);
1980 return (col + (width - 1)) / width + 1;
1981}
1982
1983/*
1984 * Like plines_win(), but only reports the number of physical screen lines
1985 * used from the start of the line to the given column number.
1986 */
1987 int
1988plines_win_col(wp, lnum, column)
1989 win_T *wp;
1990 linenr_T lnum;
1991 long column;
1992{
1993 long col;
1994 char_u *s;
1995 int lines = 0;
1996 int width;
1997
1998#ifdef FEAT_DIFF
1999 /* Check for filler lines above this buffer line. When folded the result
2000 * is one line anyway. */
2001 lines = diff_check_fill(wp, lnum);
2002#endif
2003
2004 if (!wp->w_p_wrap)
2005 return lines + 1;
2006
2007#ifdef FEAT_VERTSPLIT
2008 if (wp->w_width == 0)
2009 return lines + 1;
2010#endif
2011
2012 s = ml_get_buf(wp->w_buffer, lnum, FALSE);
2013
2014 col = 0;
2015 while (*s != NUL && --column >= 0)
2016 {
2017 col += win_lbr_chartabsize(wp, s, (colnr_T)col, NULL);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002018 mb_ptr_adv(s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002019 }
2020
2021 /*
2022 * If *s is a TAB, and the TAB is not displayed as ^I, and we're not in
2023 * INSERT mode, then col must be adjusted so that it represents the last
2024 * screen position of the TAB. This only fixes an error when the TAB wraps
2025 * from one screen line to the next (when 'columns' is not a multiple of
2026 * 'ts') -- webb.
2027 */
2028 if (*s == TAB && (State & NORMAL) && (!wp->w_p_list || lcs_tab1))
2029 col += win_lbr_chartabsize(wp, s, (colnr_T)col, NULL) - 1;
2030
2031 /*
Bram Moolenaar64486672010-05-16 15:46:46 +02002032 * Add column offset for 'number', 'relativenumber', 'foldcolumn', etc.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002033 */
2034 width = W_WIDTH(wp) - win_col_off(wp);
Bram Moolenaar26470632006-10-24 19:12:40 +00002035 if (width <= 0)
2036 return 9999;
2037
2038 lines += 1;
2039 if (col > width)
2040 lines += (col - width) / (width + win_col_off2(wp)) + 1;
2041 return lines;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002042}
2043
2044 int
2045plines_m_win(wp, first, last)
2046 win_T *wp;
2047 linenr_T first, last;
2048{
2049 int count = 0;
2050
2051 while (first <= last)
2052 {
2053#ifdef FEAT_FOLDING
2054 int x;
2055
2056 /* Check if there are any really folded lines, but also included lines
2057 * that are maybe folded. */
2058 x = foldedCount(wp, first, NULL);
2059 if (x > 0)
2060 {
2061 ++count; /* count 1 for "+-- folded" line */
2062 first += x;
2063 }
2064 else
2065#endif
2066 {
2067#ifdef FEAT_DIFF
2068 if (first == wp->w_topline)
2069 count += plines_win_nofill(wp, first, TRUE) + wp->w_topfill;
2070 else
2071#endif
2072 count += plines_win(wp, first, TRUE);
2073 ++first;
2074 }
2075 }
2076 return (count);
2077}
2078
2079#if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) || defined(PROTO)
2080/*
2081 * Insert string "p" at the cursor position. Stops at a NUL byte.
2082 * Handles Replace mode and multi-byte characters.
2083 */
2084 void
2085ins_bytes(p)
2086 char_u *p;
2087{
2088 ins_bytes_len(p, (int)STRLEN(p));
2089}
2090#endif
2091
2092#if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) \
2093 || defined(FEAT_COMMENTS) || defined(FEAT_MBYTE) || defined(PROTO)
2094/*
2095 * Insert string "p" with length "len" at the cursor position.
2096 * Handles Replace mode and multi-byte characters.
2097 */
2098 void
2099ins_bytes_len(p, len)
2100 char_u *p;
2101 int len;
2102{
2103 int i;
2104# ifdef FEAT_MBYTE
2105 int n;
2106
Bram Moolenaar176dd1e2008-06-21 14:30:28 +00002107 if (has_mbyte)
2108 for (i = 0; i < len; i += n)
2109 {
2110 if (enc_utf8)
2111 /* avoid reading past p[len] */
2112 n = utfc_ptr2len_len(p + i, len - i);
2113 else
2114 n = (*mb_ptr2len)(p + i);
2115 ins_char_bytes(p + i, n);
2116 }
2117 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002118# endif
Bram Moolenaar176dd1e2008-06-21 14:30:28 +00002119 for (i = 0; i < len; ++i)
2120 ins_char(p[i]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002121}
2122#endif
2123
2124/*
2125 * Insert or replace a single character at the cursor position.
2126 * When in REPLACE or VREPLACE mode, replace any existing character.
2127 * Caller must have prepared for undo.
2128 * For multi-byte characters we get the whole character, the caller must
2129 * convert bytes to a character.
2130 */
2131 void
2132ins_char(c)
2133 int c;
2134{
2135#if defined(FEAT_MBYTE) || defined(PROTO)
Bram Moolenaar9a920d82012-06-01 15:21:02 +02002136 char_u buf[MB_MAXBYTES + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002137 int n;
2138
2139 n = (*mb_char2bytes)(c, buf);
2140
2141 /* When "c" is 0x100, 0x200, etc. we don't want to insert a NUL byte.
2142 * Happens for CTRL-Vu9900. */
2143 if (buf[0] == 0)
2144 buf[0] = '\n';
2145
2146 ins_char_bytes(buf, n);
2147}
2148
2149 void
2150ins_char_bytes(buf, charlen)
2151 char_u *buf;
2152 int charlen;
2153{
2154 int c = buf[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002155#endif
2156 int newlen; /* nr of bytes inserted */
2157 int oldlen; /* nr of bytes deleted (0 when not replacing) */
2158 char_u *p;
2159 char_u *newp;
2160 char_u *oldp;
2161 int linelen; /* length of old line including NUL */
2162 colnr_T col;
2163 linenr_T lnum = curwin->w_cursor.lnum;
2164 int i;
2165
2166#ifdef FEAT_VIRTUALEDIT
2167 /* Break tabs if needed. */
2168 if (virtual_active() && curwin->w_cursor.coladd > 0)
2169 coladvance_force(getviscol());
2170#endif
2171
2172 col = curwin->w_cursor.col;
2173 oldp = ml_get(lnum);
2174 linelen = (int)STRLEN(oldp) + 1;
2175
2176 /* The lengths default to the values for when not replacing. */
2177 oldlen = 0;
2178#ifdef FEAT_MBYTE
2179 newlen = charlen;
2180#else
2181 newlen = 1;
2182#endif
2183
2184 if (State & REPLACE_FLAG)
2185 {
2186#ifdef FEAT_VREPLACE
2187 if (State & VREPLACE_FLAG)
2188 {
2189 colnr_T new_vcol = 0; /* init for GCC */
2190 colnr_T vcol;
2191 int old_list;
2192#ifndef FEAT_MBYTE
2193 char_u buf[2];
2194#endif
2195
2196 /*
2197 * Disable 'list' temporarily, unless 'cpo' contains the 'L' flag.
2198 * Returns the old value of list, so when finished,
2199 * curwin->w_p_list should be set back to this.
2200 */
2201 old_list = curwin->w_p_list;
2202 if (old_list && vim_strchr(p_cpo, CPO_LISTWM) == NULL)
2203 curwin->w_p_list = FALSE;
2204
2205 /*
2206 * In virtual replace mode each character may replace one or more
2207 * characters (zero if it's a TAB). Count the number of bytes to
2208 * be deleted to make room for the new character, counting screen
2209 * cells. May result in adding spaces to fill a gap.
2210 */
2211 getvcol(curwin, &curwin->w_cursor, NULL, &vcol, NULL);
2212#ifndef FEAT_MBYTE
2213 buf[0] = c;
2214 buf[1] = NUL;
2215#endif
2216 new_vcol = vcol + chartabsize(buf, vcol);
2217 while (oldp[col + oldlen] != NUL && vcol < new_vcol)
2218 {
2219 vcol += chartabsize(oldp + col + oldlen, vcol);
2220 /* Don't need to remove a TAB that takes us to the right
2221 * position. */
2222 if (vcol > new_vcol && oldp[col + oldlen] == TAB)
2223 break;
2224#ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002225 oldlen += (*mb_ptr2len)(oldp + col + oldlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002226#else
2227 ++oldlen;
2228#endif
2229 /* Deleted a bit too much, insert spaces. */
2230 if (vcol > new_vcol)
2231 newlen += vcol - new_vcol;
2232 }
2233 curwin->w_p_list = old_list;
2234 }
2235 else
2236#endif
2237 if (oldp[col] != NUL)
2238 {
2239 /* normal replace */
2240#ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002241 oldlen = (*mb_ptr2len)(oldp + col);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002242#else
2243 oldlen = 1;
2244#endif
2245 }
2246
2247
2248 /* Push the replaced bytes onto the replace stack, so that they can be
2249 * put back when BS is used. The bytes of a multi-byte character are
2250 * done the other way around, so that the first byte is popped off
2251 * first (it tells the byte length of the character). */
2252 replace_push(NUL);
2253 for (i = 0; i < oldlen; ++i)
2254 {
2255#ifdef FEAT_MBYTE
Bram Moolenaar2c994e82008-01-02 16:49:36 +00002256 if (has_mbyte)
2257 i += replace_push_mb(oldp + col + i) - 1;
2258 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002259#endif
Bram Moolenaar2c994e82008-01-02 16:49:36 +00002260 replace_push(oldp[col + i]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002261 }
2262 }
2263
2264 newp = alloc_check((unsigned)(linelen + newlen - oldlen));
2265 if (newp == NULL)
2266 return;
2267
2268 /* Copy bytes before the cursor. */
2269 if (col > 0)
2270 mch_memmove(newp, oldp, (size_t)col);
2271
2272 /* Copy bytes after the changed character(s). */
2273 p = newp + col;
2274 mch_memmove(p + newlen, oldp + col + oldlen,
2275 (size_t)(linelen - col - oldlen));
2276
2277 /* Insert or overwrite the new character. */
2278#ifdef FEAT_MBYTE
2279 mch_memmove(p, buf, charlen);
2280 i = charlen;
2281#else
2282 *p = c;
2283 i = 1;
2284#endif
2285
2286 /* Fill with spaces when necessary. */
2287 while (i < newlen)
2288 p[i++] = ' ';
2289
2290 /* Replace the line in the buffer. */
2291 ml_replace(lnum, newp, FALSE);
2292
2293 /* mark the buffer as changed and prepare for displaying */
2294 changed_bytes(lnum, col);
2295
2296 /*
2297 * If we're in Insert or Replace mode and 'showmatch' is set, then briefly
2298 * show the match for right parens and braces.
2299 */
2300 if (p_sm && (State & INSERT)
2301 && msg_silent == 0
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00002302#ifdef FEAT_INS_EXPAND
2303 && !ins_compl_active()
2304#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002305 )
Bram Moolenaar8c7694a2013-01-17 17:02:05 +01002306 {
2307#ifdef FEAT_MBYTE
2308 if (has_mbyte)
2309 showmatch(mb_ptr2char(buf));
2310 else
2311#endif
2312 showmatch(c);
2313 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002314
2315#ifdef FEAT_RIGHTLEFT
2316 if (!p_ri || (State & REPLACE_FLAG))
2317#endif
2318 {
2319 /* Normal insert: move cursor right */
2320#ifdef FEAT_MBYTE
2321 curwin->w_cursor.col += charlen;
2322#else
2323 ++curwin->w_cursor.col;
2324#endif
2325 }
2326 /*
2327 * TODO: should try to update w_row here, to avoid recomputing it later.
2328 */
2329}
2330
2331/*
2332 * Insert a string at the cursor position.
2333 * Note: Does NOT handle Replace mode.
2334 * Caller must have prepared for undo.
2335 */
2336 void
2337ins_str(s)
2338 char_u *s;
2339{
2340 char_u *oldp, *newp;
2341 int newlen = (int)STRLEN(s);
2342 int oldlen;
2343 colnr_T col;
2344 linenr_T lnum = curwin->w_cursor.lnum;
2345
2346#ifdef FEAT_VIRTUALEDIT
2347 if (virtual_active() && curwin->w_cursor.coladd > 0)
2348 coladvance_force(getviscol());
2349#endif
2350
2351 col = curwin->w_cursor.col;
2352 oldp = ml_get(lnum);
2353 oldlen = (int)STRLEN(oldp);
2354
2355 newp = alloc_check((unsigned)(oldlen + newlen + 1));
2356 if (newp == NULL)
2357 return;
2358 if (col > 0)
2359 mch_memmove(newp, oldp, (size_t)col);
2360 mch_memmove(newp + col, s, (size_t)newlen);
2361 mch_memmove(newp + col + newlen, oldp + col, (size_t)(oldlen - col + 1));
2362 ml_replace(lnum, newp, FALSE);
2363 changed_bytes(lnum, col);
2364 curwin->w_cursor.col += newlen;
2365}
2366
2367/*
2368 * Delete one character under the cursor.
2369 * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
2370 * Caller must have prepared for undo.
2371 *
2372 * return FAIL for failure, OK otherwise
2373 */
2374 int
2375del_char(fixpos)
2376 int fixpos;
2377{
2378#ifdef FEAT_MBYTE
2379 if (has_mbyte)
2380 {
2381 /* Make sure the cursor is at the start of a character. */
2382 mb_adjust_cursor();
2383 if (*ml_get_cursor() == NUL)
2384 return FAIL;
2385 return del_chars(1L, fixpos);
2386 }
2387#endif
Bram Moolenaare3226be2005-12-18 22:10:00 +00002388 return del_bytes(1L, fixpos, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002389}
2390
2391#if defined(FEAT_MBYTE) || defined(PROTO)
2392/*
2393 * Like del_bytes(), but delete characters instead of bytes.
2394 */
2395 int
2396del_chars(count, fixpos)
2397 long count;
2398 int fixpos;
2399{
2400 long bytes = 0;
2401 long i;
2402 char_u *p;
2403 int l;
2404
2405 p = ml_get_cursor();
2406 for (i = 0; i < count && *p != NUL; ++i)
2407 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002408 l = (*mb_ptr2len)(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002409 bytes += l;
2410 p += l;
2411 }
Bram Moolenaare3226be2005-12-18 22:10:00 +00002412 return del_bytes(bytes, fixpos, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002413}
2414#endif
2415
2416/*
2417 * Delete "count" bytes under the cursor.
2418 * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
2419 * Caller must have prepared for undo.
2420 *
2421 * return FAIL for failure, OK otherwise
2422 */
2423 int
Bram Moolenaarca003e12006-03-17 23:19:38 +00002424del_bytes(count, fixpos_arg, use_delcombine)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002425 long count;
Bram Moolenaarca003e12006-03-17 23:19:38 +00002426 int fixpos_arg;
Bram Moolenaar78a15312009-05-15 19:33:18 +00002427 int use_delcombine UNUSED; /* 'delcombine' option applies */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002428{
2429 char_u *oldp, *newp;
2430 colnr_T oldlen;
2431 linenr_T lnum = curwin->w_cursor.lnum;
2432 colnr_T col = curwin->w_cursor.col;
2433 int was_alloced;
2434 long movelen;
Bram Moolenaarca003e12006-03-17 23:19:38 +00002435 int fixpos = fixpos_arg;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002436
2437 oldp = ml_get(lnum);
2438 oldlen = (int)STRLEN(oldp);
2439
2440 /*
2441 * Can't do anything when the cursor is on the NUL after the line.
2442 */
2443 if (col >= oldlen)
2444 return FAIL;
2445
2446#ifdef FEAT_MBYTE
2447 /* If 'delcombine' is set and deleting (less than) one character, only
2448 * delete the last combining character. */
Bram Moolenaare3226be2005-12-18 22:10:00 +00002449 if (p_deco && use_delcombine && enc_utf8
2450 && utfc_ptr2len(oldp + col) >= count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002451 {
Bram Moolenaar362e1a32006-03-06 23:29:24 +00002452 int cc[MAX_MCO];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002453 int n;
2454
Bram Moolenaar362e1a32006-03-06 23:29:24 +00002455 (void)utfc_ptr2char(oldp + col, cc);
2456 if (cc[0] != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002457 {
2458 /* Find the last composing char, there can be several. */
2459 n = col;
2460 do
2461 {
2462 col = n;
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002463 count = utf_ptr2len(oldp + n);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002464 n += count;
2465 } while (UTF_COMPOSINGLIKE(oldp + col, oldp + n));
2466 fixpos = 0;
2467 }
2468 }
2469#endif
2470
2471 /*
2472 * When count is too big, reduce it.
2473 */
2474 movelen = (long)oldlen - (long)col - count + 1; /* includes trailing NUL */
2475 if (movelen <= 1)
2476 {
2477 /*
2478 * If we just took off the last character of a non-blank line, and
Bram Moolenaarca003e12006-03-17 23:19:38 +00002479 * fixpos is TRUE, we don't want to end up positioned at the NUL,
2480 * unless "restart_edit" is set or 'virtualedit' contains "onemore".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002481 */
Bram Moolenaarca003e12006-03-17 23:19:38 +00002482 if (col > 0 && fixpos && restart_edit == 0
2483#ifdef FEAT_VIRTUALEDIT
2484 && (ve_flags & VE_ONEMORE) == 0
2485#endif
2486 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00002487 {
2488 --curwin->w_cursor.col;
2489#ifdef FEAT_VIRTUALEDIT
2490 curwin->w_cursor.coladd = 0;
2491#endif
2492#ifdef FEAT_MBYTE
2493 if (has_mbyte)
2494 curwin->w_cursor.col -=
2495 (*mb_head_off)(oldp, oldp + curwin->w_cursor.col);
2496#endif
2497 }
2498 count = oldlen - col;
2499 movelen = 1;
2500 }
2501
2502 /*
2503 * If the old line has been allocated the deletion can be done in the
2504 * existing line. Otherwise a new line has to be allocated
Bram Moolenaare21877a2008-02-13 09:58:14 +00002505 * Can't do this when using Netbeans, because we would need to invoke
2506 * netbeans_removed(), which deallocates the line. Let ml_replace() take
Bram Moolenaar1a509df2010-08-01 17:59:57 +02002507 * care of notifying Netbeans.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002508 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002509#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02002510 if (netbeans_active())
Bram Moolenaare21877a2008-02-13 09:58:14 +00002511 was_alloced = FALSE;
2512 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002513#endif
Bram Moolenaare21877a2008-02-13 09:58:14 +00002514 was_alloced = ml_line_alloced(); /* check if oldp was allocated */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002515 if (was_alloced)
2516 newp = oldp; /* use same allocated memory */
2517 else
2518 { /* need to allocate a new line */
2519 newp = alloc((unsigned)(oldlen + 1 - count));
2520 if (newp == NULL)
2521 return FAIL;
2522 mch_memmove(newp, oldp, (size_t)col);
2523 }
2524 mch_memmove(newp + col, oldp + col + count, (size_t)movelen);
2525 if (!was_alloced)
2526 ml_replace(lnum, newp, FALSE);
2527
2528 /* mark the buffer as changed and prepare for displaying */
2529 changed_bytes(lnum, curwin->w_cursor.col);
2530
2531 return OK;
2532}
2533
2534/*
2535 * Delete from cursor to end of line.
2536 * Caller must have prepared for undo.
2537 *
2538 * return FAIL for failure, OK otherwise
2539 */
2540 int
2541truncate_line(fixpos)
2542 int fixpos; /* if TRUE fix the cursor position when done */
2543{
2544 char_u *newp;
2545 linenr_T lnum = curwin->w_cursor.lnum;
2546 colnr_T col = curwin->w_cursor.col;
2547
2548 if (col == 0)
2549 newp = vim_strsave((char_u *)"");
2550 else
2551 newp = vim_strnsave(ml_get(lnum), col);
2552
2553 if (newp == NULL)
2554 return FAIL;
2555
2556 ml_replace(lnum, newp, FALSE);
2557
2558 /* mark the buffer as changed and prepare for displaying */
2559 changed_bytes(lnum, curwin->w_cursor.col);
2560
2561 /*
2562 * If "fixpos" is TRUE we don't want to end up positioned at the NUL.
2563 */
2564 if (fixpos && curwin->w_cursor.col > 0)
2565 --curwin->w_cursor.col;
2566
2567 return OK;
2568}
2569
2570/*
2571 * Delete "nlines" lines at the cursor.
2572 * Saves the lines for undo first if "undo" is TRUE.
2573 */
2574 void
2575del_lines(nlines, undo)
2576 long nlines; /* number of lines to delete */
2577 int undo; /* if TRUE, prepare for undo */
2578{
2579 long n;
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002580 linenr_T first = curwin->w_cursor.lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002581
2582 if (nlines <= 0)
2583 return;
2584
2585 /* save the deleted lines for undo */
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002586 if (undo && u_savedel(first, nlines) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002587 return;
2588
2589 for (n = 0; n < nlines; )
2590 {
2591 if (curbuf->b_ml.ml_flags & ML_EMPTY) /* nothing to delete */
2592 break;
2593
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002594 ml_delete(first, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002595 ++n;
2596
2597 /* If we delete the last line in the file, stop */
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002598 if (first > curbuf->b_ml.ml_line_count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002599 break;
2600 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002601
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002602 /* Correct the cursor position before calling deleted_lines_mark(), it may
2603 * trigger a callback to display the cursor. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002604 curwin->w_cursor.col = 0;
2605 check_cursor_lnum();
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002606
2607 /* adjust marks, mark the buffer as changed and prepare for displaying */
2608 deleted_lines_mark(first, n);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002609}
2610
2611 int
2612gchar_pos(pos)
2613 pos_T *pos;
2614{
2615 char_u *ptr = ml_get_pos(pos);
2616
2617#ifdef FEAT_MBYTE
2618 if (has_mbyte)
2619 return (*mb_ptr2char)(ptr);
2620#endif
2621 return (int)*ptr;
2622}
2623
2624 int
2625gchar_cursor()
2626{
2627#ifdef FEAT_MBYTE
2628 if (has_mbyte)
2629 return (*mb_ptr2char)(ml_get_cursor());
2630#endif
2631 return (int)*ml_get_cursor();
2632}
2633
2634/*
2635 * Write a character at the current cursor position.
2636 * It is directly written into the block.
2637 */
2638 void
2639pchar_cursor(c)
2640 int c;
2641{
2642 *(ml_get_buf(curbuf, curwin->w_cursor.lnum, TRUE)
2643 + curwin->w_cursor.col) = c;
2644}
2645
Bram Moolenaar071d4272004-06-13 20:20:40 +00002646/*
2647 * When extra == 0: Return TRUE if the cursor is before or on the first
2648 * non-blank in the line.
2649 * When extra == 1: Return TRUE if the cursor is before the first non-blank in
2650 * the line.
2651 */
2652 int
2653inindent(extra)
2654 int extra;
2655{
2656 char_u *ptr;
2657 colnr_T col;
2658
2659 for (col = 0, ptr = ml_get_curline(); vim_iswhite(*ptr); ++col)
2660 ++ptr;
2661 if (col >= curwin->w_cursor.col + extra)
2662 return TRUE;
2663 else
2664 return FALSE;
2665}
2666
2667/*
2668 * Skip to next part of an option argument: Skip space and comma.
2669 */
2670 char_u *
2671skip_to_option_part(p)
2672 char_u *p;
2673{
2674 if (*p == ',')
2675 ++p;
2676 while (*p == ' ')
2677 ++p;
2678 return p;
2679}
2680
2681/*
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002682 * Call this function when something in the current buffer is changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002683 *
2684 * Most often called through changed_bytes() and changed_lines(), which also
2685 * mark the area of the display to be redrawn.
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002686 *
2687 * Careful: may trigger autocommands that reload the buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002688 */
2689 void
2690changed()
2691{
2692#if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
2693 /* The text of the preediting area is inserted, but this doesn't
2694 * mean a change of the buffer yet. That is delayed until the
2695 * text is committed. (this means preedit becomes empty) */
2696 if (im_is_preediting() && !xim_changed_while_preediting)
2697 return;
2698 xim_changed_while_preediting = FALSE;
2699#endif
2700
2701 if (!curbuf->b_changed)
2702 {
2703 int save_msg_scroll = msg_scroll;
2704
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002705 /* Give a warning about changing a read-only file. This may also
2706 * check-out the file, thus change "curbuf"! */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002707 change_warning(0);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002708
Bram Moolenaar071d4272004-06-13 20:20:40 +00002709 /* Create a swap file if that is wanted.
2710 * Don't do this for "nofile" and "nowrite" buffer types. */
2711 if (curbuf->b_may_swap
2712#ifdef FEAT_QUICKFIX
2713 && !bt_dontwrite(curbuf)
2714#endif
2715 )
2716 {
2717 ml_open_file(curbuf);
2718
2719 /* The ml_open_file() can cause an ATTENTION message.
2720 * Wait two seconds, to make sure the user reads this unexpected
2721 * message. Since we could be anywhere, call wait_return() now,
2722 * and don't let the emsg() set msg_scroll. */
2723 if (need_wait_return && emsg_silent == 0)
2724 {
2725 out_flush();
2726 ui_delay(2000L, TRUE);
2727 wait_return(TRUE);
2728 msg_scroll = save_msg_scroll;
2729 }
2730 }
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02002731 changed_int();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002732 }
2733 ++curbuf->b_changedtick;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002734}
2735
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02002736/*
2737 * Internal part of changed(), no user interaction.
2738 */
2739 void
2740changed_int()
2741{
2742 curbuf->b_changed = TRUE;
2743 ml_setflags(curbuf);
2744#ifdef FEAT_WINDOWS
2745 check_status(curbuf);
2746 redraw_tabline = TRUE;
2747#endif
2748#ifdef FEAT_TITLE
2749 need_maketitle = TRUE; /* set window title later */
2750#endif
2751}
2752
Bram Moolenaardba8a912005-04-24 22:08:39 +00002753static void changedOneline __ARGS((buf_T *buf, linenr_T lnum));
2754static void changed_lines_buf __ARGS((buf_T *buf, linenr_T lnum, linenr_T lnume, long xtra));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002755static void changed_common __ARGS((linenr_T lnum, colnr_T col, linenr_T lnume, long xtra));
2756
2757/*
2758 * Changed bytes within a single line for the current buffer.
2759 * - marks the windows on this buffer to be redisplayed
2760 * - marks the buffer changed by calling changed()
2761 * - invalidates cached values
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002762 * Careful: may trigger autocommands that reload the buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002763 */
2764 void
2765changed_bytes(lnum, col)
2766 linenr_T lnum;
2767 colnr_T col;
2768{
Bram Moolenaardba8a912005-04-24 22:08:39 +00002769 changedOneline(curbuf, lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002770 changed_common(lnum, col, lnum + 1, 0L);
Bram Moolenaardba8a912005-04-24 22:08:39 +00002771
2772#ifdef FEAT_DIFF
2773 /* Diff highlighting in other diff windows may need to be updated too. */
2774 if (curwin->w_p_diff)
2775 {
2776 win_T *wp;
2777 linenr_T wlnum;
2778
2779 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2780 if (wp->w_p_diff && wp != curwin)
2781 {
2782 redraw_win_later(wp, VALID);
2783 wlnum = diff_lnum_win(lnum, wp);
2784 if (wlnum > 0)
2785 changedOneline(wp->w_buffer, wlnum);
2786 }
2787 }
2788#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002789}
2790
2791 static void
Bram Moolenaardba8a912005-04-24 22:08:39 +00002792changedOneline(buf, lnum)
2793 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002794 linenr_T lnum;
2795{
Bram Moolenaardba8a912005-04-24 22:08:39 +00002796 if (buf->b_mod_set)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002797 {
2798 /* find the maximum area that must be redisplayed */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002799 if (lnum < buf->b_mod_top)
2800 buf->b_mod_top = lnum;
2801 else if (lnum >= buf->b_mod_bot)
2802 buf->b_mod_bot = lnum + 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002803 }
2804 else
2805 {
2806 /* set the area that must be redisplayed to one line */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002807 buf->b_mod_set = TRUE;
2808 buf->b_mod_top = lnum;
2809 buf->b_mod_bot = lnum + 1;
2810 buf->b_mod_xlines = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002811 }
2812}
2813
2814/*
2815 * Appended "count" lines below line "lnum" in the current buffer.
2816 * Must be called AFTER the change and after mark_adjust().
2817 * Takes care of marking the buffer to be redrawn and sets the changed flag.
2818 */
2819 void
2820appended_lines(lnum, count)
2821 linenr_T lnum;
2822 long count;
2823{
2824 changed_lines(lnum + 1, 0, lnum + 1, count);
2825}
2826
2827/*
2828 * Like appended_lines(), but adjust marks first.
2829 */
2830 void
2831appended_lines_mark(lnum, count)
2832 linenr_T lnum;
2833 long count;
2834{
2835 mark_adjust(lnum + 1, (linenr_T)MAXLNUM, count, 0L);
2836 changed_lines(lnum + 1, 0, lnum + 1, count);
2837}
2838
2839/*
2840 * Deleted "count" lines at line "lnum" in the current buffer.
2841 * Must be called AFTER the change and after mark_adjust().
2842 * Takes care of marking the buffer to be redrawn and sets the changed flag.
2843 */
2844 void
2845deleted_lines(lnum, count)
2846 linenr_T lnum;
2847 long count;
2848{
2849 changed_lines(lnum, 0, lnum + count, -count);
2850}
2851
2852/*
2853 * Like deleted_lines(), but adjust marks first.
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002854 * Make sure the cursor is on a valid line before calling, a GUI callback may
2855 * be triggered to display the cursor.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002856 */
2857 void
2858deleted_lines_mark(lnum, count)
2859 linenr_T lnum;
2860 long count;
2861{
2862 mark_adjust(lnum, (linenr_T)(lnum + count - 1), (long)MAXLNUM, -count);
2863 changed_lines(lnum, 0, lnum + count, -count);
2864}
2865
2866/*
2867 * Changed lines for the current buffer.
2868 * Must be called AFTER the change and after mark_adjust().
2869 * - mark the buffer changed by calling changed()
2870 * - mark the windows on this buffer to be redisplayed
2871 * - invalidate cached values
2872 * "lnum" is the first line that needs displaying, "lnume" the first line
2873 * below the changed lines (BEFORE the change).
2874 * When only inserting lines, "lnum" and "lnume" are equal.
2875 * Takes care of calling changed() and updating b_mod_*.
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002876 * Careful: may trigger autocommands that reload the buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002877 */
2878 void
2879changed_lines(lnum, col, lnume, xtra)
2880 linenr_T lnum; /* first line with change */
2881 colnr_T col; /* column in first line with change */
2882 linenr_T lnume; /* line below last changed line */
2883 long xtra; /* number of extra lines (negative when deleting) */
2884{
Bram Moolenaardba8a912005-04-24 22:08:39 +00002885 changed_lines_buf(curbuf, lnum, lnume, xtra);
2886
2887#ifdef FEAT_DIFF
2888 if (xtra == 0 && curwin->w_p_diff)
2889 {
2890 /* When the number of lines doesn't change then mark_adjust() isn't
2891 * called and other diff buffers still need to be marked for
2892 * displaying. */
2893 win_T *wp;
2894 linenr_T wlnum;
2895
2896 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2897 if (wp->w_p_diff && wp != curwin)
2898 {
2899 redraw_win_later(wp, VALID);
2900 wlnum = diff_lnum_win(lnum, wp);
2901 if (wlnum > 0)
2902 changed_lines_buf(wp->w_buffer, wlnum,
2903 lnume - lnum + wlnum, 0L);
2904 }
2905 }
2906#endif
2907
2908 changed_common(lnum, col, lnume, xtra);
2909}
2910
2911 static void
2912changed_lines_buf(buf, lnum, lnume, xtra)
2913 buf_T *buf;
2914 linenr_T lnum; /* first line with change */
2915 linenr_T lnume; /* line below last changed line */
2916 long xtra; /* number of extra lines (negative when deleting) */
2917{
2918 if (buf->b_mod_set)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002919 {
2920 /* find the maximum area that must be redisplayed */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002921 if (lnum < buf->b_mod_top)
2922 buf->b_mod_top = lnum;
2923 if (lnum < buf->b_mod_bot)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002924 {
2925 /* adjust old bot position for xtra lines */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002926 buf->b_mod_bot += xtra;
2927 if (buf->b_mod_bot < lnum)
2928 buf->b_mod_bot = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002929 }
Bram Moolenaardba8a912005-04-24 22:08:39 +00002930 if (lnume + xtra > buf->b_mod_bot)
2931 buf->b_mod_bot = lnume + xtra;
2932 buf->b_mod_xlines += xtra;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002933 }
2934 else
2935 {
2936 /* set the area that must be redisplayed */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002937 buf->b_mod_set = TRUE;
2938 buf->b_mod_top = lnum;
2939 buf->b_mod_bot = lnume + xtra;
2940 buf->b_mod_xlines = xtra;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002941 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002942}
2943
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002944/*
2945 * Common code for when a change is was made.
2946 * See changed_lines() for the arguments.
2947 * Careful: may trigger autocommands that reload the buffer.
2948 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002949 static void
2950changed_common(lnum, col, lnume, xtra)
2951 linenr_T lnum;
2952 colnr_T col;
2953 linenr_T lnume;
2954 long xtra;
2955{
2956 win_T *wp;
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00002957#ifdef FEAT_WINDOWS
2958 tabpage_T *tp;
2959#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002960 int i;
2961#ifdef FEAT_JUMPLIST
2962 int cols;
2963 pos_T *p;
2964 int add;
2965#endif
2966
2967 /* mark the buffer as modified */
2968 changed();
2969
2970 /* set the '. mark */
2971 if (!cmdmod.keepjumps)
2972 {
2973 curbuf->b_last_change.lnum = lnum;
2974 curbuf->b_last_change.col = col;
2975
2976#ifdef FEAT_JUMPLIST
2977 /* Create a new entry if a new undo-able change was started or we
2978 * don't have an entry yet. */
2979 if (curbuf->b_new_change || curbuf->b_changelistlen == 0)
2980 {
2981 if (curbuf->b_changelistlen == 0)
2982 add = TRUE;
2983 else
2984 {
2985 /* Don't create a new entry when the line number is the same
2986 * as the last one and the column is not too far away. Avoids
2987 * creating many entries for typing "xxxxx". */
2988 p = &curbuf->b_changelist[curbuf->b_changelistlen - 1];
2989 if (p->lnum != lnum)
2990 add = TRUE;
2991 else
2992 {
2993 cols = comp_textwidth(FALSE);
2994 if (cols == 0)
2995 cols = 79;
2996 add = (p->col + cols < col || col + cols < p->col);
2997 }
2998 }
2999 if (add)
3000 {
3001 /* This is the first of a new sequence of undo-able changes
3002 * and it's at some distance of the last change. Use a new
3003 * position in the changelist. */
3004 curbuf->b_new_change = FALSE;
3005
3006 if (curbuf->b_changelistlen == JUMPLISTSIZE)
3007 {
3008 /* changelist is full: remove oldest entry */
3009 curbuf->b_changelistlen = JUMPLISTSIZE - 1;
3010 mch_memmove(curbuf->b_changelist, curbuf->b_changelist + 1,
3011 sizeof(pos_T) * (JUMPLISTSIZE - 1));
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00003012 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003013 {
3014 /* Correct position in changelist for other windows on
3015 * this buffer. */
3016 if (wp->w_buffer == curbuf && wp->w_changelistidx > 0)
3017 --wp->w_changelistidx;
3018 }
3019 }
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00003020 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003021 {
3022 /* For other windows, if the position in the changelist is
3023 * at the end it stays at the end. */
3024 if (wp->w_buffer == curbuf
3025 && wp->w_changelistidx == curbuf->b_changelistlen)
3026 ++wp->w_changelistidx;
3027 }
3028 ++curbuf->b_changelistlen;
3029 }
3030 }
3031 curbuf->b_changelist[curbuf->b_changelistlen - 1] =
3032 curbuf->b_last_change;
3033 /* The current window is always after the last change, so that "g,"
3034 * takes you back to it. */
3035 curwin->w_changelistidx = curbuf->b_changelistlen;
3036#endif
3037 }
3038
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00003039 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003040 {
3041 if (wp->w_buffer == curbuf)
3042 {
3043 /* Mark this window to be redrawn later. */
3044 if (wp->w_redr_type < VALID)
3045 wp->w_redr_type = VALID;
3046
3047 /* Check if a change in the buffer has invalidated the cached
3048 * values for the cursor. */
3049#ifdef FEAT_FOLDING
3050 /*
3051 * Update the folds for this window. Can't postpone this, because
3052 * a following operator might work on the whole fold: ">>dd".
3053 */
3054 foldUpdate(wp, lnum, lnume + xtra - 1);
3055
3056 /* The change may cause lines above or below the change to become
3057 * included in a fold. Set lnum/lnume to the first/last line that
3058 * might be displayed differently.
3059 * Set w_cline_folded here as an efficient way to update it when
3060 * inserting lines just above a closed fold. */
3061 i = hasFoldingWin(wp, lnum, &lnum, NULL, FALSE, NULL);
3062 if (wp->w_cursor.lnum == lnum)
3063 wp->w_cline_folded = i;
3064 i = hasFoldingWin(wp, lnume, NULL, &lnume, FALSE, NULL);
3065 if (wp->w_cursor.lnum == lnume)
3066 wp->w_cline_folded = i;
3067
3068 /* If the changed line is in a range of previously folded lines,
3069 * compare with the first line in that range. */
3070 if (wp->w_cursor.lnum <= lnum)
3071 {
3072 i = find_wl_entry(wp, lnum);
3073 if (i >= 0 && wp->w_cursor.lnum > wp->w_lines[i].wl_lnum)
3074 changed_line_abv_curs_win(wp);
3075 }
3076#endif
3077
3078 if (wp->w_cursor.lnum > lnum)
3079 changed_line_abv_curs_win(wp);
3080 else if (wp->w_cursor.lnum == lnum && wp->w_cursor.col >= col)
3081 changed_cline_bef_curs_win(wp);
3082 if (wp->w_botline >= lnum)
3083 {
3084 /* Assume that botline doesn't change (inserted lines make
3085 * other lines scroll down below botline). */
3086 approximate_botline_win(wp);
3087 }
3088
3089 /* Check if any w_lines[] entries have become invalid.
3090 * For entries below the change: Correct the lnums for
3091 * inserted/deleted lines. Makes it possible to stop displaying
3092 * after the change. */
3093 for (i = 0; i < wp->w_lines_valid; ++i)
3094 if (wp->w_lines[i].wl_valid)
3095 {
3096 if (wp->w_lines[i].wl_lnum >= lnum)
3097 {
3098 if (wp->w_lines[i].wl_lnum < lnume)
3099 {
3100 /* line included in change */
3101 wp->w_lines[i].wl_valid = FALSE;
3102 }
3103 else if (xtra != 0)
3104 {
3105 /* line below change */
3106 wp->w_lines[i].wl_lnum += xtra;
3107#ifdef FEAT_FOLDING
3108 wp->w_lines[i].wl_lastlnum += xtra;
3109#endif
3110 }
3111 }
3112#ifdef FEAT_FOLDING
3113 else if (wp->w_lines[i].wl_lastlnum >= lnum)
3114 {
3115 /* change somewhere inside this range of folded lines,
3116 * may need to be redrawn */
3117 wp->w_lines[i].wl_valid = FALSE;
3118 }
3119#endif
3120 }
Bram Moolenaar3234cc62009-11-03 17:47:12 +00003121
3122#ifdef FEAT_FOLDING
3123 /* Take care of side effects for setting w_topline when folds have
3124 * changed. Esp. when the buffer was changed in another window. */
3125 if (hasAnyFolding(wp))
3126 set_topline(wp, wp->w_topline);
3127#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003128 }
3129 }
3130
3131 /* Call update_screen() later, which checks out what needs to be redrawn,
3132 * since it notices b_mod_set and then uses b_mod_*. */
3133 if (must_redraw < VALID)
3134 must_redraw = VALID;
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00003135
3136#ifdef FEAT_AUTOCMD
3137 /* when the cursor line is changed always trigger CursorMoved */
Bram Moolenaare163f1c2006-10-17 09:12:21 +00003138 if (lnum <= curwin->w_cursor.lnum
3139 && lnume + (xtra < 0 ? -xtra : xtra) > curwin->w_cursor.lnum)
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00003140 last_cursormoved.lnum = 0;
3141#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003142}
3143
3144/*
3145 * unchanged() is called when the changed flag must be reset for buffer 'buf'
3146 */
3147 void
3148unchanged(buf, ff)
3149 buf_T *buf;
3150 int ff; /* also reset 'fileformat' */
3151{
Bram Moolenaar164c60f2011-01-22 00:11:50 +01003152 if (buf->b_changed || (ff && file_ff_differs(buf, FALSE)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003153 {
3154 buf->b_changed = 0;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003155 ml_setflags(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003156 if (ff)
3157 save_file_ff(buf);
3158#ifdef FEAT_WINDOWS
3159 check_status(buf);
Bram Moolenaar997fb4b2006-02-17 21:53:23 +00003160 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003161#endif
3162#ifdef FEAT_TITLE
3163 need_maketitle = TRUE; /* set window title later */
3164#endif
3165 }
3166 ++buf->b_changedtick;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003167#ifdef FEAT_NETBEANS_INTG
3168 netbeans_unmodified(buf);
3169#endif
3170}
3171
3172#if defined(FEAT_WINDOWS) || defined(PROTO)
3173/*
3174 * check_status: called when the status bars for the buffer 'buf'
3175 * need to be updated
3176 */
3177 void
3178check_status(buf)
3179 buf_T *buf;
3180{
3181 win_T *wp;
3182
3183 for (wp = firstwin; wp != NULL; wp = wp->w_next)
3184 if (wp->w_buffer == buf && wp->w_status_height)
3185 {
3186 wp->w_redr_status = TRUE;
3187 if (must_redraw < VALID)
3188 must_redraw = VALID;
3189 }
3190}
3191#endif
3192
3193/*
3194 * If the file is readonly, give a warning message with the first change.
3195 * Don't do this for autocommands.
3196 * Don't use emsg(), because it flushes the macro buffer.
Bram Moolenaard5cdbeb2005-10-10 20:59:28 +00003197 * If we have undone all changes b_changed will be FALSE, but "b_did_warn"
Bram Moolenaar071d4272004-06-13 20:20:40 +00003198 * will be TRUE.
Bram Moolenaarb0b50882010-07-07 18:26:28 +02003199 * Careful: may trigger autocommands that reload the buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003200 */
3201 void
3202change_warning(col)
3203 int col; /* column for message; non-zero when in insert
3204 mode and 'showmode' is on */
3205{
Bram Moolenaar496c5262009-03-18 14:42:00 +00003206 static char *w_readonly = N_("W10: Warning: Changing a readonly file");
3207
Bram Moolenaar071d4272004-06-13 20:20:40 +00003208 if (curbuf->b_did_warn == FALSE
3209 && curbufIsChanged() == 0
3210#ifdef FEAT_AUTOCMD
3211 && !autocmd_busy
3212#endif
3213 && curbuf->b_p_ro)
3214 {
3215#ifdef FEAT_AUTOCMD
Bram Moolenaar910f66f2006-04-05 20:41:53 +00003216 ++curbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003217 apply_autocmds(EVENT_FILECHANGEDRO, NULL, NULL, FALSE, curbuf);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00003218 --curbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003219 if (!curbuf->b_p_ro)
3220 return;
3221#endif
3222 /*
3223 * Do what msg() does, but with a column offset if the warning should
3224 * be after the mode message.
3225 */
3226 msg_start();
3227 if (msg_row == Rows - 1)
3228 msg_col = col;
Bram Moolenaar2df6dcc2004-07-12 15:53:54 +00003229 msg_source(hl_attr(HLF_W));
Bram Moolenaar496c5262009-03-18 14:42:00 +00003230 MSG_PUTS_ATTR(_(w_readonly), hl_attr(HLF_W) | MSG_HIST);
3231#ifdef FEAT_EVAL
3232 set_vim_var_string(VV_WARNINGMSG, (char_u *)_(w_readonly), -1);
3233#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003234 msg_clr_eos();
3235 (void)msg_end();
3236 if (msg_silent == 0 && !silent_mode)
3237 {
3238 out_flush();
3239 ui_delay(1000L, TRUE); /* give the user time to think about it */
3240 }
3241 curbuf->b_did_warn = TRUE;
3242 redraw_cmdline = FALSE; /* don't redraw and erase the message */
3243 if (msg_row < Rows - 1)
3244 showmode();
3245 }
3246}
3247
3248/*
3249 * Ask for a reply from the user, a 'y' or a 'n'.
3250 * No other characters are accepted, the message is repeated until a valid
3251 * reply is entered or CTRL-C is hit.
3252 * If direct is TRUE, don't use vgetc() but ui_inchar(), don't get characters
3253 * from any buffers but directly from the user.
3254 *
3255 * return the 'y' or 'n'
3256 */
3257 int
3258ask_yesno(str, direct)
3259 char_u *str;
3260 int direct;
3261{
3262 int r = ' ';
3263 int save_State = State;
3264
3265 if (exiting) /* put terminal in raw mode for this question */
3266 settmode(TMODE_RAW);
3267 ++no_wait_return;
3268#ifdef USE_ON_FLY_SCROLL
3269 dont_scroll = TRUE; /* disallow scrolling here */
3270#endif
3271 State = CONFIRM; /* mouse behaves like with :confirm */
3272#ifdef FEAT_MOUSE
3273 setmouse(); /* disables mouse for xterm */
3274#endif
3275 ++no_mapping;
3276 ++allow_keys; /* no mapping here, but recognize keys */
3277
3278 while (r != 'y' && r != 'n')
3279 {
3280 /* same highlighting as for wait_return */
3281 smsg_attr(hl_attr(HLF_R), (char_u *)"%s (y/n)?", str);
3282 if (direct)
3283 r = get_keystroke();
3284 else
Bram Moolenaar913626c2008-01-03 11:43:42 +00003285 r = plain_vgetc();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003286 if (r == Ctrl_C || r == ESC)
3287 r = 'n';
3288 msg_putchar(r); /* show what you typed */
3289 out_flush();
3290 }
3291 --no_wait_return;
3292 State = save_State;
3293#ifdef FEAT_MOUSE
3294 setmouse();
3295#endif
3296 --no_mapping;
3297 --allow_keys;
3298
3299 return r;
3300}
3301
Bram Moolenaar2526ef22013-03-16 14:20:51 +01003302#if defined(FEAT_MOUSE) || defined(PROTO)
3303/*
3304 * Return TRUE if "c" is a mouse key.
3305 */
3306 int
3307is_mouse_key(c)
3308 int c;
3309{
3310 return c == K_LEFTMOUSE
3311 || c == K_LEFTMOUSE_NM
3312 || c == K_LEFTDRAG
3313 || c == K_LEFTRELEASE
3314 || c == K_LEFTRELEASE_NM
3315 || c == K_MIDDLEMOUSE
3316 || c == K_MIDDLEDRAG
3317 || c == K_MIDDLERELEASE
3318 || c == K_RIGHTMOUSE
3319 || c == K_RIGHTDRAG
3320 || c == K_RIGHTRELEASE
3321 || c == K_MOUSEDOWN
3322 || c == K_MOUSEUP
3323 || c == K_MOUSELEFT
3324 || c == K_MOUSERIGHT
3325 || c == K_X1MOUSE
3326 || c == K_X1DRAG
3327 || c == K_X1RELEASE
3328 || c == K_X2MOUSE
3329 || c == K_X2DRAG
3330 || c == K_X2RELEASE;
3331}
3332#endif
3333
Bram Moolenaar071d4272004-06-13 20:20:40 +00003334/*
3335 * Get a key stroke directly from the user.
3336 * Ignores mouse clicks and scrollbar events, except a click for the left
3337 * button (used at the more prompt).
3338 * Doesn't use vgetc(), because it syncs undo and eats mapped characters.
3339 * Disadvantage: typeahead is ignored.
3340 * Translates the interrupt character for unix to ESC.
3341 */
3342 int
3343get_keystroke()
3344{
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003345 char_u *buf = NULL;
3346 int buflen = 150;
3347 int maxlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003348 int len = 0;
3349 int n;
3350 int save_mapped_ctrl_c = mapped_ctrl_c;
Bram Moolenaar4395a712006-09-05 18:57:57 +00003351 int waited = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003352
3353 mapped_ctrl_c = FALSE; /* mappings are not used here */
3354 for (;;)
3355 {
3356 cursor_on();
3357 out_flush();
3358
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003359 /* Leave some room for check_termcode() to insert a key code into (max
3360 * 5 chars plus NUL). And fix_input_buffer() can triple the number of
3361 * bytes. */
3362 maxlen = (buflen - 6 - len) / 3;
3363 if (buf == NULL)
3364 buf = alloc(buflen);
3365 else if (maxlen < 10)
3366 {
Bram Moolenaardc7e85e2012-06-20 12:40:08 +02003367 /* Need some more space. This might happen when receiving a long
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003368 * escape sequence. */
3369 buflen += 100;
3370 buf = vim_realloc(buf, buflen);
3371 maxlen = (buflen - 6 - len) / 3;
3372 }
3373 if (buf == NULL)
3374 {
3375 do_outofmem_msg((long_u)buflen);
3376 return ESC; /* panic! */
3377 }
3378
Bram Moolenaar071d4272004-06-13 20:20:40 +00003379 /* First time: blocking wait. Second time: wait up to 100ms for a
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003380 * terminal code to complete. */
3381 n = ui_inchar(buf + len, maxlen, len == 0 ? -1L : 100L, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003382 if (n > 0)
3383 {
3384 /* Replace zero and CSI by a special key code. */
3385 n = fix_input_buffer(buf + len, n, FALSE);
3386 len += n;
Bram Moolenaar4395a712006-09-05 18:57:57 +00003387 waited = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003388 }
Bram Moolenaar4395a712006-09-05 18:57:57 +00003389 else if (len > 0)
3390 ++waited; /* keep track of the waiting time */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003391
Bram Moolenaar4395a712006-09-05 18:57:57 +00003392 /* Incomplete termcode and not timed out yet: get more characters */
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003393 if ((n = check_termcode(1, buf, buflen, &len)) < 0
Bram Moolenaar4395a712006-09-05 18:57:57 +00003394 && (!p_ttimeout || waited * 100L < (p_ttm < 0 ? p_tm : p_ttm)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003395 continue;
Bram Moolenaar4395a712006-09-05 18:57:57 +00003396
Bram Moolenaar946ffd42010-12-30 12:30:31 +01003397 if (n == KEYLEN_REMOVED) /* key code removed */
Bram Moolenaar6eb634e2011-03-03 15:04:08 +01003398 {
Bram Moolenaarfd30cd42011-03-22 13:07:26 +01003399 if (must_redraw != 0 && !need_wait_return && (State & CMDLINE) == 0)
Bram Moolenaar6eb634e2011-03-03 15:04:08 +01003400 {
3401 /* Redrawing was postponed, do it now. */
3402 update_screen(0);
3403 setcursor(); /* put cursor back where it belongs */
3404 }
Bram Moolenaar946ffd42010-12-30 12:30:31 +01003405 continue;
Bram Moolenaar6eb634e2011-03-03 15:04:08 +01003406 }
Bram Moolenaar946ffd42010-12-30 12:30:31 +01003407 if (n > 0) /* found a termcode: adjust length */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003408 len = n;
Bram Moolenaar946ffd42010-12-30 12:30:31 +01003409 if (len == 0) /* nothing typed yet */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003410 continue;
3411
3412 /* Handle modifier and/or special key code. */
3413 n = buf[0];
3414 if (n == K_SPECIAL)
3415 {
3416 n = TO_SPECIAL(buf[1], buf[2]);
3417 if (buf[1] == KS_MODIFIER
3418 || n == K_IGNORE
Bram Moolenaara5be25e2013-03-16 21:35:33 +01003419#ifdef FEAT_MOUSE
Bram Moolenaar2526ef22013-03-16 14:20:51 +01003420 || (is_mouse_key(n) && n != K_LEFTMOUSE)
Bram Moolenaara5be25e2013-03-16 21:35:33 +01003421#endif
Bram Moolenaar2526ef22013-03-16 14:20:51 +01003422#ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00003423 || n == K_VER_SCROLLBAR
3424 || n == K_HOR_SCROLLBAR
Bram Moolenaar071d4272004-06-13 20:20:40 +00003425#endif
3426 )
3427 {
3428 if (buf[1] == KS_MODIFIER)
3429 mod_mask = buf[2];
3430 len -= 3;
3431 if (len > 0)
3432 mch_memmove(buf, buf + 3, (size_t)len);
3433 continue;
3434 }
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00003435 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003436 }
3437#ifdef FEAT_MBYTE
3438 if (has_mbyte)
3439 {
3440 if (MB_BYTE2LEN(n) > len)
3441 continue; /* more bytes to get */
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003442 buf[len >= buflen ? buflen - 1 : len] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003443 n = (*mb_ptr2char)(buf);
3444 }
3445#endif
3446#ifdef UNIX
3447 if (n == intr_char)
3448 n = ESC;
3449#endif
3450 break;
3451 }
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003452 vim_free(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003453
3454 mapped_ctrl_c = save_mapped_ctrl_c;
3455 return n;
3456}
3457
3458/*
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003459 * Get a number from the user.
3460 * When "mouse_used" is not NULL allow using the mouse.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003461 */
3462 int
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003463get_number(colon, mouse_used)
3464 int colon; /* allow colon to abort */
3465 int *mouse_used;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003466{
3467 int n = 0;
3468 int c;
Bram Moolenaar3991dab2006-03-27 17:01:56 +00003469 int typed = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003470
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003471 if (mouse_used != NULL)
3472 *mouse_used = FALSE;
3473
Bram Moolenaar071d4272004-06-13 20:20:40 +00003474 /* When not printing messages, the user won't know what to type, return a
3475 * zero (as if CR was hit). */
3476 if (msg_silent != 0)
3477 return 0;
3478
3479#ifdef USE_ON_FLY_SCROLL
3480 dont_scroll = TRUE; /* disallow scrolling here */
3481#endif
3482 ++no_mapping;
3483 ++allow_keys; /* no mapping here, but recognize keys */
3484 for (;;)
3485 {
3486 windgoto(msg_row, msg_col);
3487 c = safe_vgetc();
3488 if (VIM_ISDIGIT(c))
3489 {
3490 n = n * 10 + c - '0';
3491 msg_putchar(c);
Bram Moolenaar3991dab2006-03-27 17:01:56 +00003492 ++typed;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003493 }
3494 else if (c == K_DEL || c == K_KDEL || c == K_BS || c == Ctrl_H)
3495 {
Bram Moolenaar3991dab2006-03-27 17:01:56 +00003496 if (typed > 0)
3497 {
3498 MSG_PUTS("\b \b");
3499 --typed;
3500 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003501 n /= 10;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003502 }
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003503#ifdef FEAT_MOUSE
3504 else if (mouse_used != NULL && c == K_LEFTMOUSE)
3505 {
3506 *mouse_used = TRUE;
3507 n = mouse_row + 1;
3508 break;
3509 }
3510#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003511 else if (n == 0 && c == ':' && colon)
3512 {
3513 stuffcharReadbuff(':');
3514 if (!exmode_active)
3515 cmdline_row = msg_row;
3516 skip_redraw = TRUE; /* skip redraw once */
3517 do_redraw = FALSE;
3518 break;
3519 }
3520 else if (c == CAR || c == NL || c == Ctrl_C || c == ESC)
3521 break;
3522 }
3523 --no_mapping;
3524 --allow_keys;
3525 return n;
3526}
3527
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003528/*
3529 * Ask the user to enter a number.
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003530 * When "mouse_used" is not NULL allow using the mouse and in that case return
3531 * the line number.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003532 */
3533 int
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003534prompt_for_number(mouse_used)
3535 int *mouse_used;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003536{
3537 int i;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003538 int save_cmdline_row;
3539 int save_State;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003540
3541 /* When using ":silent" assume that <CR> was entered. */
Bram Moolenaar42eeac32005-06-29 22:40:58 +00003542 if (mouse_used != NULL)
Bram Moolenaard812df62008-11-09 12:46:09 +00003543 MSG_PUTS(_("Type number and <Enter> or click with mouse (empty cancels): "));
Bram Moolenaar42eeac32005-06-29 22:40:58 +00003544 else
Bram Moolenaard812df62008-11-09 12:46:09 +00003545 MSG_PUTS(_("Type number and <Enter> (empty cancels): "));
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003546
Bram Moolenaar203335e2006-09-03 14:35:42 +00003547 /* Set the state such that text can be selected/copied/pasted and we still
3548 * get mouse events. */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003549 save_cmdline_row = cmdline_row;
Bram Moolenaar203335e2006-09-03 14:35:42 +00003550 cmdline_row = 0;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003551 save_State = State;
Bram Moolenaar203335e2006-09-03 14:35:42 +00003552 State = CMDLINE;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003553
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003554 i = get_number(TRUE, mouse_used);
3555 if (KeyTyped)
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003556 {
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003557 /* don't call wait_return() now */
3558 /* msg_putchar('\n'); */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003559 cmdline_row = msg_row - 1;
3560 need_wait_return = FALSE;
3561 msg_didany = FALSE;
Bram Moolenaarb2450162009-07-22 09:04:20 +00003562 msg_didout = FALSE;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003563 }
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003564 else
3565 cmdline_row = save_cmdline_row;
3566 State = save_State;
3567
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003568 return i;
3569}
3570
Bram Moolenaar071d4272004-06-13 20:20:40 +00003571 void
3572msgmore(n)
3573 long n;
3574{
3575 long pn;
3576
3577 if (global_busy /* no messages now, wait until global is finished */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003578 || !messaging()) /* 'lazyredraw' set, don't do messages now */
3579 return;
3580
Bram Moolenaar7df2d662005-01-25 22:18:08 +00003581 /* We don't want to overwrite another important message, but do overwrite
3582 * a previous "more lines" or "fewer lines" message, so that "5dd" and
3583 * then "put" reports the last action. */
3584 if (keep_msg != NULL && !keep_msg_more)
3585 return;
3586
Bram Moolenaar071d4272004-06-13 20:20:40 +00003587 if (n > 0)
3588 pn = n;
3589 else
3590 pn = -n;
3591
3592 if (pn > p_report)
3593 {
3594 if (pn == 1)
3595 {
3596 if (n > 0)
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003597 vim_strncpy(msg_buf, (char_u *)_("1 more line"),
3598 MSG_BUF_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003599 else
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003600 vim_strncpy(msg_buf, (char_u *)_("1 line less"),
3601 MSG_BUF_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003602 }
3603 else
3604 {
3605 if (n > 0)
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003606 vim_snprintf((char *)msg_buf, MSG_BUF_LEN,
3607 _("%ld more lines"), pn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003608 else
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003609 vim_snprintf((char *)msg_buf, MSG_BUF_LEN,
3610 _("%ld fewer lines"), pn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003611 }
3612 if (got_int)
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003613 vim_strcat(msg_buf, (char_u *)_(" (Interrupted)"), MSG_BUF_LEN);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003614 if (msg(msg_buf))
3615 {
Bram Moolenaar238a5642006-02-21 22:12:05 +00003616 set_keep_msg(msg_buf, 0);
Bram Moolenaar7df2d662005-01-25 22:18:08 +00003617 keep_msg_more = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003618 }
3619 }
3620}
3621
3622/*
3623 * flush map and typeahead buffers and give a warning for an error
3624 */
3625 void
3626beep_flush()
3627{
3628 if (emsg_silent == 0)
3629 {
3630 flush_buffers(FALSE);
3631 vim_beep();
3632 }
3633}
3634
3635/*
3636 * give a warning for an error
3637 */
3638 void
3639vim_beep()
3640{
3641 if (emsg_silent == 0)
3642 {
3643 if (p_vb
3644#ifdef FEAT_GUI
3645 /* While the GUI is starting up the termcap is set for the GUI
3646 * but the output still goes to a terminal. */
3647 && !(gui.in_use && gui.starting)
3648#endif
3649 )
3650 {
3651 out_str(T_VB);
3652 }
3653 else
3654 {
3655#ifdef MSDOS
3656 /*
3657 * The number of beeps outputted is reduced to avoid having to wait
3658 * for all the beeps to finish. This is only a problem on systems
3659 * where the beeps don't overlap.
3660 */
3661 if (beep_count == 0 || beep_count == 10)
3662 {
3663 out_char(BELL);
3664 beep_count = 1;
3665 }
3666 else
3667 ++beep_count;
3668#else
3669 out_char(BELL);
3670#endif
3671 }
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003672
3673 /* When 'verbose' is set and we are sourcing a script or executing a
3674 * function give the user a hint where the beep comes from. */
3675 if (vim_strchr(p_debug, 'e') != NULL)
3676 {
3677 msg_source(hl_attr(HLF_W));
3678 msg_attr((char_u *)_("Beep!"), hl_attr(HLF_W));
3679 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003680 }
3681}
3682
3683/*
3684 * To get the "real" home directory:
3685 * - get value of $HOME
3686 * For Unix:
3687 * - go to that directory
3688 * - do mch_dirname() to get the real name of that directory.
3689 * This also works with mounts and links.
3690 * Don't do this for MS-DOS, it will change the "current dir" for a drive.
3691 */
3692static char_u *homedir = NULL;
3693
3694 void
3695init_homedir()
3696{
3697 char_u *var;
3698
Bram Moolenaar05159a02005-02-26 23:04:13 +00003699 /* In case we are called a second time (when 'encoding' changes). */
3700 vim_free(homedir);
3701 homedir = NULL;
3702
Bram Moolenaar071d4272004-06-13 20:20:40 +00003703#ifdef VMS
3704 var = mch_getenv((char_u *)"SYS$LOGIN");
3705#else
3706 var = mch_getenv((char_u *)"HOME");
3707#endif
3708
3709 if (var != NULL && *var == NUL) /* empty is same as not set */
3710 var = NULL;
3711
3712#ifdef WIN3264
3713 /*
3714 * Weird but true: $HOME may contain an indirect reference to another
3715 * variable, esp. "%USERPROFILE%". Happens when $USERPROFILE isn't set
3716 * when $HOME is being set.
3717 */
3718 if (var != NULL && *var == '%')
3719 {
3720 char_u *p;
3721 char_u *exp;
3722
3723 p = vim_strchr(var + 1, '%');
3724 if (p != NULL)
3725 {
Bram Moolenaarce0842a2005-07-18 21:58:11 +00003726 vim_strncpy(NameBuff, var + 1, p - (var + 1));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003727 exp = mch_getenv(NameBuff);
3728 if (exp != NULL && *exp != NUL
3729 && STRLEN(exp) + STRLEN(p) < MAXPATHL)
3730 {
Bram Moolenaar555b2802005-05-19 21:08:39 +00003731 vim_snprintf((char *)NameBuff, MAXPATHL, "%s%s", exp, p + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003732 var = NameBuff;
3733 /* Also set $HOME, it's needed for _viminfo. */
3734 vim_setenv((char_u *)"HOME", NameBuff);
3735 }
3736 }
3737 }
3738
3739 /*
3740 * Typically, $HOME is not defined on Windows, unless the user has
3741 * specifically defined it for Vim's sake. However, on Windows NT
3742 * platforms, $HOMEDRIVE and $HOMEPATH are automatically defined for
3743 * each user. Try constructing $HOME from these.
3744 */
3745 if (var == NULL)
3746 {
3747 char_u *homedrive, *homepath;
3748
3749 homedrive = mch_getenv((char_u *)"HOMEDRIVE");
3750 homepath = mch_getenv((char_u *)"HOMEPATH");
Bram Moolenaar6f977012010-01-06 17:53:38 +01003751 if (homepath == NULL || *homepath == NUL)
3752 homepath = "\\";
3753 if (homedrive != NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00003754 && STRLEN(homedrive) + STRLEN(homepath) < MAXPATHL)
3755 {
3756 sprintf((char *)NameBuff, "%s%s", homedrive, homepath);
3757 if (NameBuff[0] != NUL)
3758 {
3759 var = NameBuff;
3760 /* Also set $HOME, it's needed for _viminfo. */
3761 vim_setenv((char_u *)"HOME", NameBuff);
3762 }
3763 }
3764 }
Bram Moolenaar05159a02005-02-26 23:04:13 +00003765
3766# if defined(FEAT_MBYTE)
3767 if (enc_utf8 && var != NULL)
3768 {
3769 int len;
Bram Moolenaarb453a532011-04-28 17:48:44 +02003770 char_u *pp = NULL;
Bram Moolenaar05159a02005-02-26 23:04:13 +00003771
3772 /* Convert from active codepage to UTF-8. Other conversions are
3773 * not done, because they would fail for non-ASCII characters. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003774 acp_to_enc(var, (int)STRLEN(var), &pp, &len);
Bram Moolenaar05159a02005-02-26 23:04:13 +00003775 if (pp != NULL)
3776 {
3777 homedir = pp;
3778 return;
3779 }
3780 }
3781# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003782#endif
3783
3784#if defined(OS2) || defined(MSDOS) || defined(MSWIN)
3785 /*
3786 * Default home dir is C:/
3787 * Best assumption we can make in such a situation.
3788 */
3789 if (var == NULL)
3790 var = "C:/";
3791#endif
3792 if (var != NULL)
3793 {
3794#ifdef UNIX
3795 /*
3796 * Change to the directory and get the actual path. This resolves
3797 * links. Don't do it when we can't return.
3798 */
3799 if (mch_dirname(NameBuff, MAXPATHL) == OK
3800 && mch_chdir((char *)NameBuff) == 0)
3801 {
3802 if (!mch_chdir((char *)var) && mch_dirname(IObuff, IOSIZE) == OK)
3803 var = IObuff;
3804 if (mch_chdir((char *)NameBuff) != 0)
3805 EMSG(_(e_prev_dir));
3806 }
3807#endif
3808 homedir = vim_strsave(var);
3809 }
3810}
3811
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003812#if defined(EXITFREE) || defined(PROTO)
3813 void
3814free_homedir()
3815{
3816 vim_free(homedir);
3817}
Bram Moolenaar24305862012-08-15 14:05:05 +02003818
3819# ifdef FEAT_CMDL_COMPL
3820 void
3821free_users()
3822{
3823 ga_clear_strings(&ga_users);
3824}
3825# endif
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003826#endif
3827
Bram Moolenaar071d4272004-06-13 20:20:40 +00003828/*
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003829 * Call expand_env() and store the result in an allocated string.
3830 * This is not very memory efficient, this expects the result to be freed
3831 * again soon.
3832 */
3833 char_u *
3834expand_env_save(src)
3835 char_u *src;
3836{
3837 return expand_env_save_opt(src, FALSE);
3838}
3839
3840/*
3841 * Idem, but when "one" is TRUE handle the string as one file name, only
3842 * expand "~" at the start.
3843 */
3844 char_u *
3845expand_env_save_opt(src, one)
3846 char_u *src;
3847 int one;
3848{
3849 char_u *p;
3850
3851 p = alloc(MAXPATHL);
3852 if (p != NULL)
3853 expand_env_esc(src, p, MAXPATHL, FALSE, one, NULL);
3854 return p;
3855}
3856
3857/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003858 * Expand environment variable with path name.
3859 * "~/" is also expanded, using $HOME. For Unix "~user/" is expanded.
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003860 * Skips over "\ ", "\~" and "\$" (not for Win32 though).
Bram Moolenaar071d4272004-06-13 20:20:40 +00003861 * If anything fails no expansion is done and dst equals src.
3862 */
3863 void
3864expand_env(src, dst, dstlen)
3865 char_u *src; /* input string e.g. "$HOME/vim.hlp" */
3866 char_u *dst; /* where to put the result */
3867 int dstlen; /* maximum length of the result */
3868{
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003869 expand_env_esc(src, dst, dstlen, FALSE, FALSE, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003870}
3871
3872 void
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003873expand_env_esc(srcp, dst, dstlen, esc, one, startstr)
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003874 char_u *srcp; /* input string e.g. "$HOME/vim.hlp" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003875 char_u *dst; /* where to put the result */
3876 int dstlen; /* maximum length of the result */
3877 int esc; /* escape spaces in expanded variables */
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003878 int one; /* "srcp" is one file name */
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003879 char_u *startstr; /* start again after this (can be NULL) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003880{
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003881 char_u *src;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003882 char_u *tail;
3883 int c;
3884 char_u *var;
3885 int copy_char;
3886 int mustfree; /* var was allocated, need to free it later */
3887 int at_start = TRUE; /* at start of a name */
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003888 int startstr_len = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003889
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003890 if (startstr != NULL)
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003891 startstr_len = (int)STRLEN(startstr);
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003892
3893 src = skipwhite(srcp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003894 --dstlen; /* leave one char space for "\," */
3895 while (*src && dstlen > 0)
3896 {
3897 copy_char = TRUE;
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003898 if ((*src == '$'
3899#ifdef VMS
3900 && at_start
3901#endif
3902 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003903#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3904 || *src == '%'
3905#endif
3906 || (*src == '~' && at_start))
3907 {
3908 mustfree = FALSE;
3909
3910 /*
3911 * The variable name is copied into dst temporarily, because it may
3912 * be a string in read-only memory and a NUL needs to be appended.
3913 */
3914 if (*src != '~') /* environment var */
3915 {
3916 tail = src + 1;
3917 var = dst;
3918 c = dstlen - 1;
3919
3920#ifdef UNIX
3921 /* Unix has ${var-name} type environment vars */
3922 if (*tail == '{' && !vim_isIDc('{'))
3923 {
3924 tail++; /* ignore '{' */
3925 while (c-- > 0 && *tail && *tail != '}')
3926 *var++ = *tail++;
3927 }
3928 else
3929#endif
3930 {
3931 while (c-- > 0 && *tail != NUL && ((vim_isIDc(*tail))
3932#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3933 || (*src == '%' && *tail != '%')
3934#endif
3935 ))
3936 {
3937#ifdef OS2 /* env vars only in uppercase */
3938 *var++ = TOUPPER_LOC(*tail);
3939 tail++; /* toupper() may be a macro! */
3940#else
3941 *var++ = *tail++;
3942#endif
3943 }
3944 }
3945
3946#if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
3947# ifdef UNIX
3948 if (src[1] == '{' && *tail != '}')
3949# else
3950 if (*src == '%' && *tail != '%')
3951# endif
3952 var = NULL;
3953 else
3954 {
3955# ifdef UNIX
3956 if (src[1] == '{')
3957# else
3958 if (*src == '%')
3959#endif
3960 ++tail;
3961#endif
3962 *var = NUL;
3963 var = vim_getenv(dst, &mustfree);
3964#if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
3965 }
3966#endif
3967 }
3968 /* home directory */
3969 else if ( src[1] == NUL
3970 || vim_ispathsep(src[1])
3971 || vim_strchr((char_u *)" ,\t\n", src[1]) != NULL)
3972 {
3973 var = homedir;
3974 tail = src + 1;
3975 }
3976 else /* user directory */
3977 {
3978#if defined(UNIX) || (defined(VMS) && defined(USER_HOME))
3979 /*
3980 * Copy ~user to dst[], so we can put a NUL after it.
3981 */
3982 tail = src;
3983 var = dst;
3984 c = dstlen - 1;
3985 while ( c-- > 0
3986 && *tail
3987 && vim_isfilec(*tail)
3988 && !vim_ispathsep(*tail))
3989 *var++ = *tail++;
3990 *var = NUL;
3991# ifdef UNIX
3992 /*
3993 * If the system supports getpwnam(), use it.
3994 * Otherwise, or if getpwnam() fails, the shell is used to
3995 * expand ~user. This is slower and may fail if the shell
3996 * does not support ~user (old versions of /bin/sh).
3997 */
3998# if defined(HAVE_GETPWNAM) && defined(HAVE_PWD_H)
3999 {
4000 struct passwd *pw;
4001
Bram Moolenaara40ceaf2006-01-13 22:35:40 +00004002 /* Note: memory allocated by getpwnam() is never freed.
4003 * Calling endpwent() apparently doesn't help. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004004 pw = getpwnam((char *)dst + 1);
4005 if (pw != NULL)
4006 var = (char_u *)pw->pw_dir;
4007 else
4008 var = NULL;
4009 }
4010 if (var == NULL)
4011# endif
4012 {
4013 expand_T xpc;
4014
4015 ExpandInit(&xpc);
4016 xpc.xp_context = EXPAND_FILES;
4017 var = ExpandOne(&xpc, dst, NULL,
4018 WILD_ADD_SLASH|WILD_SILENT, WILD_EXPAND_FREE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004019 mustfree = TRUE;
4020 }
4021
4022# else /* !UNIX, thus VMS */
4023 /*
4024 * USER_HOME is a comma-separated list of
4025 * directories to search for the user account in.
4026 */
4027 {
4028 char_u test[MAXPATHL], paths[MAXPATHL];
4029 char_u *path, *next_path, *ptr;
4030 struct stat st;
4031
4032 STRCPY(paths, USER_HOME);
4033 next_path = paths;
4034 while (*next_path)
4035 {
4036 for (path = next_path; *next_path && *next_path != ',';
4037 next_path++);
4038 if (*next_path)
4039 *next_path++ = NUL;
4040 STRCPY(test, path);
4041 STRCAT(test, "/");
4042 STRCAT(test, dst + 1);
4043 if (mch_stat(test, &st) == 0)
4044 {
4045 var = alloc(STRLEN(test) + 1);
4046 STRCPY(var, test);
4047 mustfree = TRUE;
4048 break;
4049 }
4050 }
4051 }
4052# endif /* UNIX */
4053#else
4054 /* cannot expand user's home directory, so don't try */
4055 var = NULL;
4056 tail = (char_u *)""; /* for gcc */
4057#endif /* UNIX || VMS */
4058 }
4059
4060#ifdef BACKSLASH_IN_FILENAME
4061 /* If 'shellslash' is set change backslashes to forward slashes.
4062 * Can't use slash_adjust(), p_ssl may be set temporarily. */
4063 if (p_ssl && var != NULL && vim_strchr(var, '\\') != NULL)
4064 {
4065 char_u *p = vim_strsave(var);
4066
4067 if (p != NULL)
4068 {
4069 if (mustfree)
4070 vim_free(var);
4071 var = p;
4072 mustfree = TRUE;
4073 forward_slash(var);
4074 }
4075 }
4076#endif
4077
4078 /* If "var" contains white space, escape it with a backslash.
4079 * Required for ":e ~/tt" when $HOME includes a space. */
4080 if (esc && var != NULL && vim_strpbrk(var, (char_u *)" \t") != NULL)
4081 {
4082 char_u *p = vim_strsave_escaped(var, (char_u *)" \t");
4083
4084 if (p != NULL)
4085 {
4086 if (mustfree)
4087 vim_free(var);
4088 var = p;
4089 mustfree = TRUE;
4090 }
4091 }
4092
4093 if (var != NULL && *var != NUL
4094 && (STRLEN(var) + STRLEN(tail) + 1 < (unsigned)dstlen))
4095 {
4096 STRCPY(dst, var);
4097 dstlen -= (int)STRLEN(var);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004098 c = (int)STRLEN(var);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004099 /* if var[] ends in a path separator and tail[] starts
4100 * with it, skip a character */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004101 if (*var != NUL && after_pathsep(dst, dst + c)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004102#if defined(BACKSLASH_IN_FILENAME) || defined(AMIGA)
4103 && dst[-1] != ':'
4104#endif
4105 && vim_ispathsep(*tail))
4106 ++tail;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004107 dst += c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004108 src = tail;
4109 copy_char = FALSE;
4110 }
4111 if (mustfree)
4112 vim_free(var);
4113 }
4114
4115 if (copy_char) /* copy at least one char */
4116 {
4117 /*
Bram Moolenaar25394022007-05-10 19:06:20 +00004118 * Recognize the start of a new name, for '~'.
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00004119 * Don't do this when "one" is TRUE, to avoid expanding "~" in
4120 * ":edit foo ~ foo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00004121 */
4122 at_start = FALSE;
4123 if (src[0] == '\\' && src[1] != NUL)
4124 {
4125 *dst++ = *src++;
4126 --dstlen;
4127 }
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00004128 else if ((src[0] == ' ' || src[0] == ',') && !one)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004129 at_start = TRUE;
4130 *dst++ = *src++;
4131 --dstlen;
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00004132
4133 if (startstr != NULL && src - startstr_len >= srcp
4134 && STRNCMP(src - startstr_len, startstr, startstr_len) == 0)
4135 at_start = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004136 }
4137 }
4138 *dst = NUL;
4139}
4140
4141/*
4142 * Vim's version of getenv().
4143 * Special handling of $HOME, $VIM and $VIMRUNTIME.
Bram Moolenaar2f6b0b82005-03-08 22:43:10 +00004144 * Also does ACP to 'enc' conversion for Win32.
Bram Moolenaarb453a532011-04-28 17:48:44 +02004145 * "mustfree" is set to TRUE when returned is allocated, it must be
4146 * initialized to FALSE by the caller.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004147 */
4148 char_u *
4149vim_getenv(name, mustfree)
4150 char_u *name;
Bram Moolenaarb453a532011-04-28 17:48:44 +02004151 int *mustfree;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004152{
4153 char_u *p;
4154 char_u *pend;
4155 int vimruntime;
4156
4157#if defined(OS2) || defined(MSDOS) || defined(MSWIN)
4158 /* use "C:/" when $HOME is not set */
4159 if (STRCMP(name, "HOME") == 0)
4160 return homedir;
4161#endif
4162
4163 p = mch_getenv(name);
4164 if (p != NULL && *p == NUL) /* empty is the same as not set */
4165 p = NULL;
4166
4167 if (p != NULL)
Bram Moolenaar05159a02005-02-26 23:04:13 +00004168 {
4169#if defined(FEAT_MBYTE) && defined(WIN3264)
4170 if (enc_utf8)
4171 {
4172 int len;
Bram Moolenaarb453a532011-04-28 17:48:44 +02004173 char_u *pp = NULL;
Bram Moolenaar05159a02005-02-26 23:04:13 +00004174
4175 /* Convert from active codepage to UTF-8. Other conversions are
4176 * not done, because they would fail for non-ASCII characters. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004177 acp_to_enc(p, (int)STRLEN(p), &pp, &len);
Bram Moolenaar05159a02005-02-26 23:04:13 +00004178 if (pp != NULL)
4179 {
4180 p = pp;
4181 *mustfree = TRUE;
4182 }
4183 }
4184#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004185 return p;
Bram Moolenaar05159a02005-02-26 23:04:13 +00004186 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004187
4188 vimruntime = (STRCMP(name, "VIMRUNTIME") == 0);
4189 if (!vimruntime && STRCMP(name, "VIM") != 0)
4190 return NULL;
4191
4192 /*
4193 * When expanding $VIMRUNTIME fails, try using $VIM/vim<version> or $VIM.
4194 * Don't do this when default_vimruntime_dir is non-empty.
4195 */
4196 if (vimruntime
4197#ifdef HAVE_PATHDEF
4198 && *default_vimruntime_dir == NUL
4199#endif
4200 )
4201 {
4202 p = mch_getenv((char_u *)"VIM");
4203 if (p != NULL && *p == NUL) /* empty is the same as not set */
4204 p = NULL;
4205 if (p != NULL)
4206 {
4207 p = vim_version_dir(p);
4208 if (p != NULL)
4209 *mustfree = TRUE;
4210 else
4211 p = mch_getenv((char_u *)"VIM");
Bram Moolenaar05159a02005-02-26 23:04:13 +00004212
4213#if defined(FEAT_MBYTE) && defined(WIN3264)
4214 if (enc_utf8)
4215 {
4216 int len;
Bram Moolenaarb453a532011-04-28 17:48:44 +02004217 char_u *pp = NULL;
Bram Moolenaar05159a02005-02-26 23:04:13 +00004218
4219 /* Convert from active codepage to UTF-8. Other conversions
4220 * are not done, because they would fail for non-ASCII
4221 * characters. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004222 acp_to_enc(p, (int)STRLEN(p), &pp, &len);
Bram Moolenaar05159a02005-02-26 23:04:13 +00004223 if (pp != NULL)
4224 {
Bram Moolenaarb453a532011-04-28 17:48:44 +02004225 if (*mustfree)
Bram Moolenaar05159a02005-02-26 23:04:13 +00004226 vim_free(p);
4227 p = pp;
4228 *mustfree = TRUE;
4229 }
4230 }
4231#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004232 }
4233 }
4234
4235 /*
4236 * When expanding $VIM or $VIMRUNTIME fails, try using:
4237 * - the directory name from 'helpfile' (unless it contains '$')
4238 * - the executable name from argv[0]
4239 */
4240 if (p == NULL)
4241 {
4242 if (p_hf != NULL && vim_strchr(p_hf, '$') == NULL)
4243 p = p_hf;
4244#ifdef USE_EXE_NAME
4245 /*
4246 * Use the name of the executable, obtained from argv[0].
4247 */
4248 else
4249 p = exe_name;
4250#endif
4251 if (p != NULL)
4252 {
4253 /* remove the file name */
4254 pend = gettail(p);
4255
4256 /* remove "doc/" from 'helpfile', if present */
4257 if (p == p_hf)
4258 pend = remove_tail(p, pend, (char_u *)"doc");
4259
4260#ifdef USE_EXE_NAME
4261# ifdef MACOS_X
Bram Moolenaar95e9b492006-03-15 23:04:43 +00004262 /* remove "MacOS" from exe_name and add "Resources/vim" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004263 if (p == exe_name)
4264 {
4265 char_u *pend1;
Bram Moolenaar95e9b492006-03-15 23:04:43 +00004266 char_u *pnew;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004267
Bram Moolenaar95e9b492006-03-15 23:04:43 +00004268 pend1 = remove_tail(p, pend, (char_u *)"MacOS");
4269 if (pend1 != pend)
4270 {
4271 pnew = alloc((unsigned)(pend1 - p) + 15);
4272 if (pnew != NULL)
4273 {
4274 STRNCPY(pnew, p, (pend1 - p));
4275 STRCPY(pnew + (pend1 - p), "Resources/vim");
4276 p = pnew;
4277 pend = p + STRLEN(p);
4278 }
4279 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004280 }
4281# endif
4282 /* remove "src/" from exe_name, if present */
4283 if (p == exe_name)
4284 pend = remove_tail(p, pend, (char_u *)"src");
4285#endif
4286
4287 /* for $VIM, remove "runtime/" or "vim54/", if present */
4288 if (!vimruntime)
4289 {
4290 pend = remove_tail(p, pend, (char_u *)RUNTIME_DIRNAME);
4291 pend = remove_tail(p, pend, (char_u *)VIM_VERSION_NODOT);
4292 }
4293
4294 /* remove trailing path separator */
4295#ifndef MACOS_CLASSIC
4296 /* With MacOS path (with colons) the final colon is required */
Bram Moolenaare21877a2008-02-13 09:58:14 +00004297 /* to avoid confusion between absolute and relative path */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004298 if (pend > p && after_pathsep(p, pend))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004299 --pend;
4300#endif
4301
Bram Moolenaar95e9b492006-03-15 23:04:43 +00004302#ifdef MACOS_X
4303 if (p == exe_name || p == p_hf)
4304#endif
4305 /* check that the result is a directory name */
4306 p = vim_strnsave(p, (int)(pend - p));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004307
4308 if (p != NULL && !mch_isdir(p))
4309 {
4310 vim_free(p);
4311 p = NULL;
4312 }
4313 else
4314 {
4315#ifdef USE_EXE_NAME
4316 /* may add "/vim54" or "/runtime" if it exists */
4317 if (vimruntime && (pend = vim_version_dir(p)) != NULL)
4318 {
4319 vim_free(p);
4320 p = pend;
4321 }
4322#endif
4323 *mustfree = TRUE;
4324 }
4325 }
4326 }
4327
4328#ifdef HAVE_PATHDEF
4329 /* When there is a pathdef.c file we can use default_vim_dir and
4330 * default_vimruntime_dir */
4331 if (p == NULL)
4332 {
4333 /* Only use default_vimruntime_dir when it is not empty */
4334 if (vimruntime && *default_vimruntime_dir != NUL)
4335 {
4336 p = default_vimruntime_dir;
4337 *mustfree = FALSE;
4338 }
4339 else if (*default_vim_dir != NUL)
4340 {
4341 if (vimruntime && (p = vim_version_dir(default_vim_dir)) != NULL)
4342 *mustfree = TRUE;
4343 else
4344 {
4345 p = default_vim_dir;
4346 *mustfree = FALSE;
4347 }
4348 }
4349 }
4350#endif
4351
4352 /*
4353 * Set the environment variable, so that the new value can be found fast
4354 * next time, and others can also use it (e.g. Perl).
4355 */
4356 if (p != NULL)
4357 {
4358 if (vimruntime)
4359 {
4360 vim_setenv((char_u *)"VIMRUNTIME", p);
4361 didset_vimruntime = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004362 }
4363 else
4364 {
4365 vim_setenv((char_u *)"VIM", p);
4366 didset_vim = TRUE;
4367 }
4368 }
4369 return p;
4370}
4371
4372/*
4373 * Check if the directory "vimdir/<version>" or "vimdir/runtime" exists.
4374 * Return NULL if not, return its name in allocated memory otherwise.
4375 */
4376 static char_u *
4377vim_version_dir(vimdir)
4378 char_u *vimdir;
4379{
4380 char_u *p;
4381
4382 if (vimdir == NULL || *vimdir == NUL)
4383 return NULL;
4384 p = concat_fnames(vimdir, (char_u *)VIM_VERSION_NODOT, TRUE);
4385 if (p != NULL && mch_isdir(p))
4386 return p;
4387 vim_free(p);
4388 p = concat_fnames(vimdir, (char_u *)RUNTIME_DIRNAME, TRUE);
4389 if (p != NULL && mch_isdir(p))
4390 return p;
4391 vim_free(p);
4392 return NULL;
4393}
4394
4395/*
4396 * If the string between "p" and "pend" ends in "name/", return "pend" minus
4397 * the length of "name/". Otherwise return "pend".
4398 */
4399 static char_u *
4400remove_tail(p, pend, name)
4401 char_u *p;
4402 char_u *pend;
4403 char_u *name;
4404{
4405 int len = (int)STRLEN(name) + 1;
4406 char_u *newend = pend - len;
4407
4408 if (newend >= p
4409 && fnamencmp(newend, name, len - 1) == 0
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004410 && (newend == p || after_pathsep(p, newend)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004411 return newend;
4412 return pend;
4413}
4414
Bram Moolenaar071d4272004-06-13 20:20:40 +00004415/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004416 * Our portable version of setenv.
4417 */
4418 void
4419vim_setenv(name, val)
4420 char_u *name;
4421 char_u *val;
4422{
4423#ifdef HAVE_SETENV
4424 mch_setenv((char *)name, (char *)val, 1);
4425#else
4426 char_u *envbuf;
4427
4428 /*
4429 * Putenv does not copy the string, it has to remain
4430 * valid. The allocated memory will never be freed.
4431 */
4432 envbuf = alloc((unsigned)(STRLEN(name) + STRLEN(val) + 2));
4433 if (envbuf != NULL)
4434 {
4435 sprintf((char *)envbuf, "%s=%s", name, val);
4436 putenv((char *)envbuf);
4437 }
4438#endif
Bram Moolenaar011a34d2012-02-29 13:49:09 +01004439#ifdef FEAT_GETTEXT
4440 /*
4441 * When setting $VIMRUNTIME adjust the directory to find message
4442 * translations to $VIMRUNTIME/lang.
4443 */
4444 if (*val != NUL && STRICMP(name, "VIMRUNTIME") == 0)
4445 {
4446 char_u *buf = concat_str(val, (char_u *)"/lang");
4447
4448 if (buf != NULL)
4449 {
4450 bindtextdomain(VIMPACKAGE, (char *)buf);
4451 vim_free(buf);
4452 }
4453 }
4454#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004455}
4456
4457#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
4458/*
4459 * Function given to ExpandGeneric() to obtain an environment variable name.
4460 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004461 char_u *
4462get_env_name(xp, idx)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00004463 expand_T *xp UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004464 int idx;
4465{
4466# if defined(AMIGA) || defined(__MRC__) || defined(__SC__)
4467 /*
4468 * No environ[] on the Amiga and on the Mac (using MPW).
4469 */
4470 return NULL;
4471# else
4472# ifndef __WIN32__
4473 /* Borland C++ 5.2 has this in a header file. */
4474 extern char **environ;
4475# endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00004476# define ENVNAMELEN 100
4477 static char_u name[ENVNAMELEN];
Bram Moolenaar071d4272004-06-13 20:20:40 +00004478 char_u *str;
4479 int n;
4480
4481 str = (char_u *)environ[idx];
4482 if (str == NULL)
4483 return NULL;
4484
Bram Moolenaar21cf8232004-07-16 20:18:37 +00004485 for (n = 0; n < ENVNAMELEN - 1; ++n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004486 {
4487 if (str[n] == '=' || str[n] == NUL)
4488 break;
4489 name[n] = str[n];
4490 }
4491 name[n] = NUL;
4492 return name;
4493# endif
4494}
Bram Moolenaar24305862012-08-15 14:05:05 +02004495
4496/*
4497 * Find all user names for user completion.
4498 * Done only once and then cached.
4499 */
4500 static void
Bram Moolenaar01b626c2013-06-16 22:49:14 +02004501init_users()
4502{
Bram Moolenaar24305862012-08-15 14:05:05 +02004503 static int lazy_init_done = FALSE;
4504
4505 if (lazy_init_done)
4506 return;
4507
4508 lazy_init_done = TRUE;
4509 ga_init2(&ga_users, sizeof(char_u *), 20);
4510
4511# if defined(HAVE_GETPWENT) && defined(HAVE_PWD_H)
4512 {
4513 char_u* user;
4514 struct passwd* pw;
4515
4516 setpwent();
4517 while ((pw = getpwent()) != NULL)
4518 /* pw->pw_name shouldn't be NULL but just in case... */
4519 if (pw->pw_name != NULL)
4520 {
4521 if (ga_grow(&ga_users, 1) == FAIL)
4522 break;
4523 user = vim_strsave((char_u*)pw->pw_name);
4524 if (user == NULL)
4525 break;
4526 ((char_u **)(ga_users.ga_data))[ga_users.ga_len++] = user;
4527 }
4528 endpwent();
4529 }
4530# endif
4531}
4532
4533/*
4534 * Function given to ExpandGeneric() to obtain an user names.
4535 */
4536 char_u*
4537get_users(xp, idx)
4538 expand_T *xp UNUSED;
4539 int idx;
4540{
4541 init_users();
4542 if (idx < ga_users.ga_len)
4543 return ((char_u **)ga_users.ga_data)[idx];
4544 return NULL;
4545}
4546
4547/*
4548 * Check whether name matches a user name. Return:
4549 * 0 if name does not match any user name.
4550 * 1 if name partially matches the beginning of a user name.
4551 * 2 is name fully matches a user name.
4552 */
4553int match_user(name)
4554 char_u* name;
4555{
4556 int i;
4557 int n = (int)STRLEN(name);
4558 int result = 0;
4559
4560 init_users();
4561 for (i = 0; i < ga_users.ga_len; i++)
4562 {
4563 if (STRCMP(((char_u **)ga_users.ga_data)[i], name) == 0)
4564 return 2; /* full match */
4565 if (STRNCMP(((char_u **)ga_users.ga_data)[i], name, n) == 0)
4566 result = 1; /* partial match */
4567 }
4568 return result;
4569}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004570#endif
4571
4572/*
4573 * Replace home directory by "~" in each space or comma separated file name in
4574 * 'src'.
4575 * If anything fails (except when out of space) dst equals src.
4576 */
4577 void
4578home_replace(buf, src, dst, dstlen, one)
4579 buf_T *buf; /* when not NULL, check for help files */
4580 char_u *src; /* input file name */
4581 char_u *dst; /* where to put the result */
4582 int dstlen; /* maximum length of the result */
4583 int one; /* if TRUE, only replace one file name, include
4584 spaces and commas in the file name. */
4585{
4586 size_t dirlen = 0, envlen = 0;
4587 size_t len;
Bram Moolenaar9158f9e2012-06-20 14:02:27 +02004588 char_u *homedir_env, *homedir_env_orig;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004589 char_u *p;
4590
4591 if (src == NULL)
4592 {
4593 *dst = NUL;
4594 return;
4595 }
4596
4597 /*
4598 * If the file is a help file, remove the path completely.
4599 */
4600 if (buf != NULL && buf->b_help)
4601 {
4602 STRCPY(dst, gettail(src));
4603 return;
4604 }
4605
4606 /*
4607 * We check both the value of the $HOME environment variable and the
4608 * "real" home directory.
4609 */
4610 if (homedir != NULL)
4611 dirlen = STRLEN(homedir);
4612
4613#ifdef VMS
Bram Moolenaar9158f9e2012-06-20 14:02:27 +02004614 homedir_env_orig = homedir_env = mch_getenv((char_u *)"SYS$LOGIN");
Bram Moolenaar071d4272004-06-13 20:20:40 +00004615#else
Bram Moolenaar9158f9e2012-06-20 14:02:27 +02004616 homedir_env_orig = homedir_env = mch_getenv((char_u *)"HOME");
4617#endif
Bram Moolenaarbef47902012-07-06 16:49:40 +02004618 /* Empty is the same as not set. */
4619 if (homedir_env != NULL && *homedir_env == NUL)
4620 homedir_env = NULL;
4621
Bram Moolenaare60c2e52013-06-05 19:35:38 +02004622#if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL)
Bram Moolenaarbef47902012-07-06 16:49:40 +02004623 if (homedir_env != NULL && vim_strchr(homedir_env, '~') != NULL)
Bram Moolenaar9158f9e2012-06-20 14:02:27 +02004624 {
4625 int usedlen = 0;
4626 int flen;
4627 char_u *fbuf = NULL;
4628
4629 flen = (int)STRLEN(homedir_env);
Bram Moolenaard12f8112012-06-20 17:56:09 +02004630 (void)modify_fname((char_u *)":p", &usedlen,
4631 &homedir_env, &fbuf, &flen);
Bram Moolenaar9158f9e2012-06-20 14:02:27 +02004632 flen = (int)STRLEN(homedir_env);
4633 if (flen > 0 && vim_ispathsep(homedir_env[flen - 1]))
4634 /* Remove the trailing / that is added to a directory. */
4635 homedir_env[flen - 1] = NUL;
4636 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004637#endif
4638
Bram Moolenaar071d4272004-06-13 20:20:40 +00004639 if (homedir_env != NULL)
4640 envlen = STRLEN(homedir_env);
4641
4642 if (!one)
4643 src = skipwhite(src);
4644 while (*src && dstlen > 0)
4645 {
4646 /*
4647 * Here we are at the beginning of a file name.
4648 * First, check to see if the beginning of the file name matches
4649 * $HOME or the "real" home directory. Check that there is a '/'
4650 * after the match (so that if e.g. the file is "/home/pieter/bla",
4651 * and the home directory is "/home/piet", the file does not end up
4652 * as "~er/bla" (which would seem to indicate the file "bla" in user
4653 * er's home directory)).
4654 */
4655 p = homedir;
4656 len = dirlen;
4657 for (;;)
4658 {
4659 if ( len
4660 && fnamencmp(src, p, len) == 0
4661 && (vim_ispathsep(src[len])
4662 || (!one && (src[len] == ',' || src[len] == ' '))
4663 || src[len] == NUL))
4664 {
4665 src += len;
4666 if (--dstlen > 0)
4667 *dst++ = '~';
4668
4669 /*
4670 * If it's just the home directory, add "/".
4671 */
4672 if (!vim_ispathsep(src[0]) && --dstlen > 0)
4673 *dst++ = '/';
4674 break;
4675 }
4676 if (p == homedir_env)
4677 break;
4678 p = homedir_env;
4679 len = envlen;
4680 }
4681
4682 /* if (!one) skip to separator: space or comma */
4683 while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
4684 *dst++ = *src++;
4685 /* skip separator */
4686 while ((*src == ' ' || *src == ',') && --dstlen > 0)
4687 *dst++ = *src++;
4688 }
4689 /* if (dstlen == 0) out of space, what to do??? */
4690
4691 *dst = NUL;
Bram Moolenaar9158f9e2012-06-20 14:02:27 +02004692
4693 if (homedir_env != homedir_env_orig)
4694 vim_free(homedir_env);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004695}
4696
4697/*
4698 * Like home_replace, store the replaced string in allocated memory.
4699 * When something fails, NULL is returned.
4700 */
4701 char_u *
4702home_replace_save(buf, src)
4703 buf_T *buf; /* when not NULL, check for help files */
4704 char_u *src; /* input file name */
4705{
4706 char_u *dst;
4707 unsigned len;
4708
4709 len = 3; /* space for "~/" and trailing NUL */
4710 if (src != NULL) /* just in case */
4711 len += (unsigned)STRLEN(src);
4712 dst = alloc(len);
4713 if (dst != NULL)
4714 home_replace(buf, src, dst, len, TRUE);
4715 return dst;
4716}
4717
4718/*
4719 * Compare two file names and return:
4720 * FPC_SAME if they both exist and are the same file.
4721 * FPC_SAMEX if they both don't exist and have the same file name.
4722 * FPC_DIFF if they both exist and are different files.
4723 * FPC_NOTX if they both don't exist.
4724 * FPC_DIFFX if one of them doesn't exist.
4725 * For the first name environment variables are expanded
4726 */
4727 int
4728fullpathcmp(s1, s2, checkname)
4729 char_u *s1, *s2;
4730 int checkname; /* when both don't exist, check file names */
4731{
4732#ifdef UNIX
4733 char_u exp1[MAXPATHL];
4734 char_u full1[MAXPATHL];
4735 char_u full2[MAXPATHL];
4736 struct stat st1, st2;
4737 int r1, r2;
4738
4739 expand_env(s1, exp1, MAXPATHL);
4740 r1 = mch_stat((char *)exp1, &st1);
4741 r2 = mch_stat((char *)s2, &st2);
4742 if (r1 != 0 && r2 != 0)
4743 {
4744 /* if mch_stat() doesn't work, may compare the names */
4745 if (checkname)
4746 {
4747 if (fnamecmp(exp1, s2) == 0)
4748 return FPC_SAMEX;
4749 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4750 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4751 if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
4752 return FPC_SAMEX;
4753 }
4754 return FPC_NOTX;
4755 }
4756 if (r1 != 0 || r2 != 0)
4757 return FPC_DIFFX;
4758 if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
4759 return FPC_SAME;
4760 return FPC_DIFF;
4761#else
4762 char_u *exp1; /* expanded s1 */
4763 char_u *full1; /* full path of s1 */
4764 char_u *full2; /* full path of s2 */
4765 int retval = FPC_DIFF;
4766 int r1, r2;
4767
4768 /* allocate one buffer to store three paths (alloc()/free() is slow!) */
4769 if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
4770 {
4771 full1 = exp1 + MAXPATHL;
4772 full2 = full1 + MAXPATHL;
4773
4774 expand_env(s1, exp1, MAXPATHL);
4775 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4776 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4777
4778 /* If vim_FullName() fails, the file probably doesn't exist. */
4779 if (r1 != OK && r2 != OK)
4780 {
4781 if (checkname && fnamecmp(exp1, s2) == 0)
4782 retval = FPC_SAMEX;
4783 else
4784 retval = FPC_NOTX;
4785 }
4786 else if (r1 != OK || r2 != OK)
4787 retval = FPC_DIFFX;
4788 else if (fnamecmp(full1, full2))
4789 retval = FPC_DIFF;
4790 else
4791 retval = FPC_SAME;
4792 vim_free(exp1);
4793 }
4794 return retval;
4795#endif
4796}
4797
4798/*
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004799 * Get the tail of a path: the file name.
Bram Moolenaar31710262010-08-13 13:36:15 +02004800 * When the path ends in a path separator the tail is the NUL after it.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004801 * Fail safe: never returns NULL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004802 */
4803 char_u *
4804gettail(fname)
4805 char_u *fname;
4806{
4807 char_u *p1, *p2;
4808
4809 if (fname == NULL)
4810 return (char_u *)"";
4811 for (p1 = p2 = fname; *p2; ) /* find last part of path */
4812 {
4813 if (vim_ispathsep(*p2))
4814 p1 = p2 + 1;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004815 mb_ptr_adv(p2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004816 }
4817 return p1;
4818}
4819
Bram Moolenaar31710262010-08-13 13:36:15 +02004820#if defined(FEAT_SEARCHPATH)
4821static char_u *gettail_dir __ARGS((char_u *fname));
4822
4823/*
4824 * Return the end of the directory name, on the first path
4825 * separator:
4826 * "/path/file", "/path/dir/", "/path//dir", "/file"
4827 * ^ ^ ^ ^
4828 */
4829 static char_u *
4830gettail_dir(fname)
4831 char_u *fname;
4832{
4833 char_u *dir_end = fname;
4834 char_u *next_dir_end = fname;
4835 int look_for_sep = TRUE;
4836 char_u *p;
4837
4838 for (p = fname; *p != NUL; )
4839 {
4840 if (vim_ispathsep(*p))
4841 {
4842 if (look_for_sep)
4843 {
4844 next_dir_end = p;
4845 look_for_sep = FALSE;
4846 }
4847 }
4848 else
4849 {
4850 if (!look_for_sep)
4851 dir_end = next_dir_end;
4852 look_for_sep = TRUE;
4853 }
4854 mb_ptr_adv(p);
4855 }
4856 return dir_end;
4857}
4858#endif
4859
Bram Moolenaar071d4272004-06-13 20:20:40 +00004860/*
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004861 * Get pointer to tail of "fname", including path separators. Putting a NUL
4862 * here leaves the directory name. Takes care of "c:/" and "//".
4863 * Always returns a valid pointer.
4864 */
4865 char_u *
4866gettail_sep(fname)
4867 char_u *fname;
4868{
4869 char_u *p;
4870 char_u *t;
4871
4872 p = get_past_head(fname); /* don't remove the '/' from "c:/file" */
4873 t = gettail(fname);
4874 while (t > p && after_pathsep(fname, t))
4875 --t;
4876#ifdef VMS
4877 /* path separator is part of the path */
4878 ++t;
4879#endif
4880 return t;
4881}
4882
4883/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004884 * get the next path component (just after the next path separator).
4885 */
4886 char_u *
4887getnextcomp(fname)
4888 char_u *fname;
4889{
4890 while (*fname && !vim_ispathsep(*fname))
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004891 mb_ptr_adv(fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004892 if (*fname)
4893 ++fname;
4894 return fname;
4895}
4896
Bram Moolenaar071d4272004-06-13 20:20:40 +00004897/*
4898 * Get a pointer to one character past the head of a path name.
4899 * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
4900 * If there is no head, path is returned.
4901 */
4902 char_u *
4903get_past_head(path)
4904 char_u *path;
4905{
4906 char_u *retval;
4907
4908#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
4909 /* may skip "c:" */
4910 if (isalpha(path[0]) && path[1] == ':')
4911 retval = path + 2;
4912 else
4913 retval = path;
4914#else
4915# if defined(AMIGA)
4916 /* may skip "label:" */
4917 retval = vim_strchr(path, ':');
4918 if (retval == NULL)
4919 retval = path;
4920# else /* Unix */
4921 retval = path;
4922# endif
4923#endif
4924
4925 while (vim_ispathsep(*retval))
4926 ++retval;
4927
4928 return retval;
4929}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004930
4931/*
4932 * return TRUE if 'c' is a path separator.
4933 */
4934 int
4935vim_ispathsep(c)
4936 int c;
4937{
Bram Moolenaare60acc12011-05-10 16:41:25 +02004938#ifdef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00004939 return (c == '/'); /* UNIX has ':' inside file names */
Bram Moolenaare60acc12011-05-10 16:41:25 +02004940#else
4941# ifdef BACKSLASH_IN_FILENAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00004942 return (c == ':' || c == '/' || c == '\\');
Bram Moolenaare60acc12011-05-10 16:41:25 +02004943# else
4944# ifdef VMS
Bram Moolenaar071d4272004-06-13 20:20:40 +00004945 /* server"user passwd"::device:[full.path.name]fname.extension;version" */
4946 return (c == ':' || c == '[' || c == ']' || c == '/'
4947 || c == '<' || c == '>' || c == '"' );
Bram Moolenaare60acc12011-05-10 16:41:25 +02004948# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004949 return (c == ':' || c == '/');
Bram Moolenaare60acc12011-05-10 16:41:25 +02004950# endif /* VMS */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004951# endif
Bram Moolenaare60acc12011-05-10 16:41:25 +02004952#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004953}
4954
4955#if defined(FEAT_SEARCHPATH) || defined(PROTO)
4956/*
4957 * return TRUE if 'c' is a path list separator.
4958 */
4959 int
4960vim_ispathlistsep(c)
4961 int c;
4962{
4963#ifdef UNIX
4964 return (c == ':');
4965#else
Bram Moolenaar25394022007-05-10 19:06:20 +00004966 return (c == ';'); /* might not be right for every system... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004967#endif
4968}
4969#endif
4970
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004971#if defined(FEAT_GUI_TABLINE) || defined(FEAT_WINDOWS) \
4972 || defined(FEAT_EVAL) || defined(PROTO)
4973/*
4974 * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
4975 * It's done in-place.
4976 */
4977 void
4978shorten_dir(str)
4979 char_u *str;
4980{
4981 char_u *tail, *s, *d;
4982 int skip = FALSE;
4983
4984 tail = gettail(str);
4985 d = str;
4986 for (s = str; ; ++s)
4987 {
4988 if (s >= tail) /* copy the whole tail */
4989 {
4990 *d++ = *s;
4991 if (*s == NUL)
4992 break;
4993 }
4994 else if (vim_ispathsep(*s)) /* copy '/' and next char */
4995 {
4996 *d++ = *s;
4997 skip = FALSE;
4998 }
4999 else if (!skip)
5000 {
5001 *d++ = *s; /* copy next char */
5002 if (*s != '~' && *s != '.') /* and leading "~" and "." */
5003 skip = TRUE;
5004# ifdef FEAT_MBYTE
5005 if (has_mbyte)
5006 {
5007 int l = mb_ptr2len(s);
5008
5009 while (--l > 0)
Bram Moolenaarb6baca52006-08-15 20:24:14 +00005010 *d++ = *++s;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005011 }
5012# endif
5013 }
5014 }
5015}
5016#endif
5017
Bram Moolenaar900b4d72005-12-12 22:05:50 +00005018/*
5019 * Return TRUE if the directory of "fname" exists, FALSE otherwise.
5020 * Also returns TRUE if there is no directory name.
5021 * "fname" must be writable!.
5022 */
5023 int
5024dir_of_file_exists(fname)
5025 char_u *fname;
5026{
5027 char_u *p;
5028 int c;
5029 int retval;
5030
5031 p = gettail_sep(fname);
5032 if (p == fname)
5033 return TRUE;
5034 c = *p;
5035 *p = NUL;
5036 retval = mch_isdir(fname);
5037 *p = c;
5038 return retval;
5039}
5040
Bram Moolenaar071d4272004-06-13 20:20:40 +00005041/*
Bram Moolenaar71afbfe2013-03-19 16:49:16 +01005042 * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally
5043 * and deal with 'fileignorecase'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005044 */
5045 int
5046vim_fnamecmp(x, y)
5047 char_u *x, *y;
5048{
Bram Moolenaar71afbfe2013-03-19 16:49:16 +01005049#ifdef BACKSLASH_IN_FILENAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00005050 return vim_fnamencmp(x, y, MAXPATHL);
Bram Moolenaar71afbfe2013-03-19 16:49:16 +01005051#else
5052 if (p_fic)
5053 return MB_STRICMP(x, y);
5054 return STRCMP(x, y);
5055#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005056}
5057
5058 int
5059vim_fnamencmp(x, y, len)
5060 char_u *x, *y;
5061 size_t len;
5062{
Bram Moolenaar71afbfe2013-03-19 16:49:16 +01005063#ifdef BACKSLASH_IN_FILENAME
Bram Moolenaard0e2d942013-03-19 18:31:49 +01005064 char_u *px = x;
5065 char_u *py = y;
5066 int cx = NUL;
5067 int cy = NUL;
5068
Bram Moolenaard0e2d942013-03-19 18:31:49 +01005069 while (len > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005070 {
Bram Moolenaard0e2d942013-03-19 18:31:49 +01005071 cx = PTR2CHAR(px);
5072 cy = PTR2CHAR(py);
5073 if (cx == NUL || cy == NUL
5074 || ((p_fic ? MB_TOLOWER(cx) != MB_TOLOWER(cy) : cx != cy)
5075 && !(cx == '/' && cy == '\\')
5076 && !(cx == '\\' && cy == '/')))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005077 break;
Bram Moolenaard0e2d942013-03-19 18:31:49 +01005078 len -= MB_PTR2LEN(px);
5079 px += MB_PTR2LEN(px);
5080 py += MB_PTR2LEN(py);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005081 }
5082 if (len == 0)
5083 return 0;
Bram Moolenaard0e2d942013-03-19 18:31:49 +01005084 return (cx - cy);
Bram Moolenaar71afbfe2013-03-19 16:49:16 +01005085#else
5086 if (p_fic)
5087 return MB_STRNICMP(x, y, len);
5088 return STRNCMP(x, y, len);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005089#endif
Bram Moolenaar71afbfe2013-03-19 16:49:16 +01005090}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005091
5092/*
5093 * Concatenate file names fname1 and fname2 into allocated memory.
Bram Moolenaar25394022007-05-10 19:06:20 +00005094 * Only add a '/' or '\\' when 'sep' is TRUE and it is necessary.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005095 */
5096 char_u *
5097concat_fnames(fname1, fname2, sep)
5098 char_u *fname1;
5099 char_u *fname2;
5100 int sep;
5101{
5102 char_u *dest;
5103
5104 dest = alloc((unsigned)(STRLEN(fname1) + STRLEN(fname2) + 3));
5105 if (dest != NULL)
5106 {
5107 STRCPY(dest, fname1);
5108 if (sep)
5109 add_pathsep(dest);
5110 STRCAT(dest, fname2);
5111 }
5112 return dest;
5113}
5114
Bram Moolenaard6754642005-01-17 22:18:45 +00005115/*
5116 * Concatenate two strings and return the result in allocated memory.
5117 * Returns NULL when out of memory.
5118 */
5119 char_u *
5120concat_str(str1, str2)
5121 char_u *str1;
5122 char_u *str2;
5123{
5124 char_u *dest;
5125 size_t l = STRLEN(str1);
5126
5127 dest = alloc((unsigned)(l + STRLEN(str2) + 1L));
5128 if (dest != NULL)
5129 {
5130 STRCPY(dest, str1);
5131 STRCPY(dest + l, str2);
5132 }
5133 return dest;
5134}
Bram Moolenaard6754642005-01-17 22:18:45 +00005135
Bram Moolenaar071d4272004-06-13 20:20:40 +00005136/*
5137 * Add a path separator to a file name, unless it already ends in a path
5138 * separator.
5139 */
5140 void
5141add_pathsep(p)
5142 char_u *p;
5143{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005144 if (*p != NUL && !after_pathsep(p, p + STRLEN(p)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005145 STRCAT(p, PATHSEPSTR);
5146}
5147
5148/*
5149 * FullName_save - Make an allocated copy of a full file name.
5150 * Returns NULL when out of memory.
5151 */
5152 char_u *
5153FullName_save(fname, force)
5154 char_u *fname;
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +02005155 int force; /* force expansion, even when it already looks
5156 * like a full path name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005157{
5158 char_u *buf;
5159 char_u *new_fname = NULL;
5160
5161 if (fname == NULL)
5162 return NULL;
5163
5164 buf = alloc((unsigned)MAXPATHL);
5165 if (buf != NULL)
5166 {
5167 if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
5168 new_fname = vim_strsave(buf);
5169 else
5170 new_fname = vim_strsave(fname);
5171 vim_free(buf);
5172 }
5173 return new_fname;
5174}
5175
5176#if defined(FEAT_CINDENT) || defined(FEAT_SYN_HL)
5177
5178static char_u *skip_string __ARGS((char_u *p));
5179
5180/*
5181 * Find the start of a comment, not knowing if we are in a comment right now.
5182 * Search starts at w_cursor.lnum and goes backwards.
5183 */
5184 pos_T *
5185find_start_comment(ind_maxcomment) /* XXX */
5186 int ind_maxcomment;
5187{
5188 pos_T *pos;
5189 char_u *line;
5190 char_u *p;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005191 int cur_maxcomment = ind_maxcomment;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005192
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005193 for (;;)
5194 {
5195 pos = findmatchlimit(NULL, '*', FM_BACKWARD, cur_maxcomment);
5196 if (pos == NULL)
5197 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005198
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005199 /*
5200 * Check if the comment start we found is inside a string.
5201 * If it is then restrict the search to below this line and try again.
5202 */
5203 line = ml_get(pos->lnum);
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00005204 for (p = line; *p && (colnr_T)(p - line) < pos->col; ++p)
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005205 p = skip_string(p);
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00005206 if ((colnr_T)(p - line) <= pos->col)
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005207 break;
5208 cur_maxcomment = curwin->w_cursor.lnum - pos->lnum - 1;
5209 if (cur_maxcomment <= 0)
5210 {
5211 pos = NULL;
5212 break;
5213 }
5214 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005215 return pos;
5216}
5217
5218/*
5219 * Skip to the end of a "string" and a 'c' character.
5220 * If there is no string or character, return argument unmodified.
5221 */
5222 static char_u *
5223skip_string(p)
5224 char_u *p;
5225{
5226 int i;
5227
5228 /*
5229 * We loop, because strings may be concatenated: "date""time".
5230 */
5231 for ( ; ; ++p)
5232 {
5233 if (p[0] == '\'') /* 'c' or '\n' or '\000' */
5234 {
5235 if (!p[1]) /* ' at end of line */
5236 break;
5237 i = 2;
5238 if (p[1] == '\\') /* '\n' or '\000' */
5239 {
5240 ++i;
5241 while (vim_isdigit(p[i - 1])) /* '\000' */
5242 ++i;
5243 }
5244 if (p[i] == '\'') /* check for trailing ' */
5245 {
5246 p += i;
5247 continue;
5248 }
5249 }
5250 else if (p[0] == '"') /* start of string */
5251 {
5252 for (++p; p[0]; ++p)
5253 {
5254 if (p[0] == '\\' && p[1] != NUL)
5255 ++p;
5256 else if (p[0] == '"') /* end of string */
5257 break;
5258 }
5259 if (p[0] == '"')
5260 continue;
5261 }
5262 break; /* no string found */
5263 }
5264 if (!*p)
5265 --p; /* backup from NUL */
5266 return p;
5267}
5268#endif /* FEAT_CINDENT || FEAT_SYN_HL */
5269
5270#if defined(FEAT_CINDENT) || defined(PROTO)
5271
5272/*
5273 * Do C or expression indenting on the current line.
5274 */
5275 void
5276do_c_expr_indent()
5277{
5278# ifdef FEAT_EVAL
5279 if (*curbuf->b_p_inde != NUL)
5280 fixthisline(get_expr_indent);
5281 else
5282# endif
5283 fixthisline(get_c_indent);
5284}
5285
5286/*
5287 * Functions for C-indenting.
5288 * Most of this originally comes from Eric Fischer.
5289 */
5290/*
5291 * Below "XXX" means that this function may unlock the current line.
5292 */
5293
5294static char_u *cin_skipcomment __ARGS((char_u *));
5295static int cin_nocode __ARGS((char_u *));
5296static pos_T *find_line_comment __ARGS((void));
5297static int cin_islabel_skip __ARGS((char_u **));
5298static int cin_isdefault __ARGS((char_u *));
5299static char_u *after_label __ARGS((char_u *l));
5300static int get_indent_nolabel __ARGS((linenr_T lnum));
5301static int skip_label __ARGS((linenr_T, char_u **pp, int ind_maxcomment));
5302static int cin_first_id_amount __ARGS((void));
5303static int cin_get_equal_amount __ARGS((linenr_T lnum));
5304static int cin_ispreproc __ARGS((char_u *));
5305static int cin_ispreproc_cont __ARGS((char_u **pp, linenr_T *lnump));
5306static int cin_iscomment __ARGS((char_u *));
5307static int cin_islinecomment __ARGS((char_u *));
5308static int cin_isterminated __ARGS((char_u *, int, int));
5309static int cin_isinit __ARGS((void));
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005310static int cin_isfuncdecl __ARGS((char_u **, linenr_T, linenr_T, int, int));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005311static int cin_isif __ARGS((char_u *));
5312static int cin_iselse __ARGS((char_u *));
5313static int cin_isdo __ARGS((char_u *));
5314static int cin_iswhileofdo __ARGS((char_u *, linenr_T, int));
Bram Moolenaarb345d492012-04-09 20:42:26 +02005315static int cin_is_if_for_while_before_offset __ARGS((char_u *line, int *poffset));
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005316static int cin_iswhileofdo_end __ARGS((int terminated, int ind_maxparen, int ind_maxcomment));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005317static int cin_isbreak __ARGS((char_u *));
Bram Moolenaare7c56862007-08-04 10:14:52 +00005318static int cin_is_cpp_baseclass __ARGS((colnr_T *col));
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005319static int get_baseclass_amount __ARGS((int col, int ind_maxparen, int ind_maxcomment, int ind_cpp_baseclass));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005320static int cin_ends_in __ARGS((char_u *, char_u *, char_u *));
Bram Moolenaar75342212013-03-07 13:13:52 +01005321static int cin_starts_with __ARGS((char_u *s, char *word));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005322static int cin_skip2pos __ARGS((pos_T *trypos));
5323static pos_T *find_start_brace __ARGS((int));
5324static pos_T *find_match_paren __ARGS((int, int));
5325static int corr_ind_maxparen __ARGS((int ind_maxparen, pos_T *startpos));
5326static int find_last_paren __ARGS((char_u *l, int start, int end));
5327static int find_match __ARGS((int lookfor, linenr_T ourscope, int ind_maxparen, int ind_maxcomment));
Bram Moolenaared38b0a2011-05-25 15:16:18 +02005328static int cin_is_cpp_namespace __ARGS((char_u *));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005329
Bram Moolenaar39353fd2007-03-27 09:02:11 +00005330static int ind_hash_comment = 0; /* # starts a comment */
5331
Bram Moolenaar071d4272004-06-13 20:20:40 +00005332/*
5333 * Skip over white space and C comments within the line.
Bram Moolenaar39353fd2007-03-27 09:02:11 +00005334 * Also skip over Perl/shell comments if desired.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005335 */
5336 static char_u *
5337cin_skipcomment(s)
5338 char_u *s;
5339{
5340 while (*s)
5341 {
Bram Moolenaar39353fd2007-03-27 09:02:11 +00005342 char_u *prev_s = s;
5343
Bram Moolenaar071d4272004-06-13 20:20:40 +00005344 s = skipwhite(s);
Bram Moolenaar39353fd2007-03-27 09:02:11 +00005345
5346 /* Perl/shell # comment comment continues until eol. Require a space
5347 * before # to avoid recognizing $#array. */
5348 if (ind_hash_comment != 0 && s != prev_s && *s == '#')
5349 {
5350 s += STRLEN(s);
5351 break;
5352 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005353 if (*s != '/')
5354 break;
5355 ++s;
5356 if (*s == '/') /* slash-slash comment continues till eol */
5357 {
5358 s += STRLEN(s);
5359 break;
5360 }
5361 if (*s != '*')
5362 break;
5363 for (++s; *s; ++s) /* skip slash-star comment */
5364 if (s[0] == '*' && s[1] == '/')
5365 {
5366 s += 2;
5367 break;
5368 }
5369 }
5370 return s;
5371}
5372
5373/*
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005374 * Return TRUE if there is no code at *s. White space and comments are
Bram Moolenaar071d4272004-06-13 20:20:40 +00005375 * not considered code.
5376 */
5377 static int
5378cin_nocode(s)
5379 char_u *s;
5380{
5381 return *cin_skipcomment(s) == NUL;
5382}
5383
5384/*
5385 * Check previous lines for a "//" line comment, skipping over blank lines.
5386 */
5387 static pos_T *
5388find_line_comment() /* XXX */
5389{
5390 static pos_T pos;
5391 char_u *line;
5392 char_u *p;
5393
5394 pos = curwin->w_cursor;
5395 while (--pos.lnum > 0)
5396 {
5397 line = ml_get(pos.lnum);
5398 p = skipwhite(line);
5399 if (cin_islinecomment(p))
5400 {
5401 pos.col = (int)(p - line);
5402 return &pos;
5403 }
5404 if (*p != NUL)
5405 break;
5406 }
5407 return NULL;
5408}
5409
5410/*
5411 * Check if string matches "label:"; move to character after ':' if true.
5412 */
5413 static int
5414cin_islabel_skip(s)
5415 char_u **s;
5416{
5417 if (!vim_isIDc(**s)) /* need at least one ID character */
5418 return FALSE;
5419
5420 while (vim_isIDc(**s))
5421 (*s)++;
5422
5423 *s = cin_skipcomment(*s);
5424
5425 /* "::" is not a label, it's C++ */
5426 return (**s == ':' && *++*s != ':');
5427}
5428
5429/*
5430 * Recognize a label: "label:".
5431 * Note: curwin->w_cursor must be where we are looking for the label.
5432 */
5433 int
5434cin_islabel(ind_maxcomment) /* XXX */
5435 int ind_maxcomment;
5436{
5437 char_u *s;
5438
5439 s = cin_skipcomment(ml_get_curline());
5440
5441 /*
5442 * Exclude "default" from labels, since it should be indented
5443 * like a switch label. Same for C++ scope declarations.
5444 */
5445 if (cin_isdefault(s))
5446 return FALSE;
5447 if (cin_isscopedecl(s))
5448 return FALSE;
5449
5450 if (cin_islabel_skip(&s))
5451 {
5452 /*
5453 * Only accept a label if the previous line is terminated or is a case
5454 * label.
5455 */
5456 pos_T cursor_save;
5457 pos_T *trypos;
5458 char_u *line;
5459
5460 cursor_save = curwin->w_cursor;
5461 while (curwin->w_cursor.lnum > 1)
5462 {
5463 --curwin->w_cursor.lnum;
5464
5465 /*
5466 * If we're in a comment now, skip to the start of the comment.
5467 */
5468 curwin->w_cursor.col = 0;
5469 if ((trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
5470 curwin->w_cursor = *trypos;
5471
5472 line = ml_get_curline();
5473 if (cin_ispreproc(line)) /* ignore #defines, #if, etc. */
5474 continue;
5475 if (*(line = cin_skipcomment(line)) == NUL)
5476 continue;
5477
5478 curwin->w_cursor = cursor_save;
5479 if (cin_isterminated(line, TRUE, FALSE)
5480 || cin_isscopedecl(line)
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005481 || cin_iscase(line, TRUE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005482 || (cin_islabel_skip(&line) && cin_nocode(line)))
5483 return TRUE;
5484 return FALSE;
5485 }
5486 curwin->w_cursor = cursor_save;
5487 return TRUE; /* label at start of file??? */
5488 }
5489 return FALSE;
5490}
5491
5492/*
Bram Moolenaar75342212013-03-07 13:13:52 +01005493 * Recognize structure initialization and enumerations:
5494 * "[typedef] [static|public|protected|private] enum"
5495 * "[typedef] [static|public|protected|private] = {"
Bram Moolenaar071d4272004-06-13 20:20:40 +00005496 */
5497 static int
5498cin_isinit(void)
5499{
5500 char_u *s;
Bram Moolenaar75342212013-03-07 13:13:52 +01005501 static char *skip[] = {"static", "public", "protected", "private"};
Bram Moolenaar071d4272004-06-13 20:20:40 +00005502
5503 s = cin_skipcomment(ml_get_curline());
5504
Bram Moolenaar75342212013-03-07 13:13:52 +01005505 if (cin_starts_with(s, "typedef"))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005506 s = cin_skipcomment(s + 7);
5507
Bram Moolenaar75342212013-03-07 13:13:52 +01005508 for (;;)
5509 {
5510 int i, l;
Bram Moolenaara5285652011-12-14 20:05:21 +01005511
Bram Moolenaar75342212013-03-07 13:13:52 +01005512 for (i = 0; i < (int)(sizeof(skip) / sizeof(char *)); ++i)
5513 {
Bram Moolenaarb3cb9822013-03-13 17:01:52 +01005514 l = (int)strlen(skip[i]);
Bram Moolenaar75342212013-03-07 13:13:52 +01005515 if (cin_starts_with(s, skip[i]))
5516 {
5517 s = cin_skipcomment(s + l);
5518 l = 0;
5519 break;
5520 }
5521 }
5522 if (l != 0)
5523 break;
5524 }
5525
5526 if (cin_starts_with(s, "enum"))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005527 return TRUE;
5528
5529 if (cin_ends_in(s, (char_u *)"=", (char_u *)"{"))
5530 return TRUE;
5531
5532 return FALSE;
5533}
5534
5535/*
5536 * Recognize a switch label: "case .*:" or "default:".
5537 */
5538 int
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005539cin_iscase(s, strict)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005540 char_u *s;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005541 int strict; /* Allow relaxed check of case statement for JS */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005542{
5543 s = cin_skipcomment(s);
Bram Moolenaar75342212013-03-07 13:13:52 +01005544 if (cin_starts_with(s, "case"))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005545 {
5546 for (s += 4; *s; ++s)
5547 {
5548 s = cin_skipcomment(s);
5549 if (*s == ':')
5550 {
5551 if (s[1] == ':') /* skip over "::" for C++ */
5552 ++s;
5553 else
5554 return TRUE;
5555 }
5556 if (*s == '\'' && s[1] && s[2] == '\'')
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005557 s += 2; /* skip over ':' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005558 else if (*s == '/' && (s[1] == '*' || s[1] == '/'))
5559 return FALSE; /* stop at comment */
5560 else if (*s == '"')
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005561 {
5562 /* JS etc. */
5563 if (strict)
5564 return FALSE; /* stop at string */
5565 else
5566 return TRUE;
5567 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005568 }
5569 return FALSE;
5570 }
5571
5572 if (cin_isdefault(s))
5573 return TRUE;
5574 return FALSE;
5575}
5576
5577/*
5578 * Recognize a "default" switch label.
5579 */
5580 static int
5581cin_isdefault(s)
5582 char_u *s;
5583{
5584 return (STRNCMP(s, "default", 7) == 0
5585 && *(s = cin_skipcomment(s + 7)) == ':'
5586 && s[1] != ':');
5587}
5588
5589/*
Bram Moolenaar1a509df2010-08-01 17:59:57 +02005590 * Recognize a "public/private/protected" scope declaration label.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005591 */
5592 int
5593cin_isscopedecl(s)
5594 char_u *s;
5595{
5596 int i;
5597
5598 s = cin_skipcomment(s);
5599 if (STRNCMP(s, "public", 6) == 0)
5600 i = 6;
5601 else if (STRNCMP(s, "protected", 9) == 0)
5602 i = 9;
5603 else if (STRNCMP(s, "private", 7) == 0)
5604 i = 7;
5605 else
5606 return FALSE;
5607 return (*(s = cin_skipcomment(s + i)) == ':' && s[1] != ':');
5608}
5609
Bram Moolenaared38b0a2011-05-25 15:16:18 +02005610/* Maximum number of lines to search back for a "namespace" line. */
5611#define FIND_NAMESPACE_LIM 20
5612
5613/*
5614 * Recognize a "namespace" scope declaration.
5615 */
5616 static int
5617cin_is_cpp_namespace(s)
5618 char_u *s;
5619{
5620 char_u *p;
5621 int has_name = FALSE;
5622
5623 s = cin_skipcomment(s);
5624 if (STRNCMP(s, "namespace", 9) == 0 && (s[9] == NUL || !vim_iswordc(s[9])))
5625 {
5626 p = cin_skipcomment(skipwhite(s + 9));
5627 while (*p != NUL)
5628 {
5629 if (vim_iswhite(*p))
5630 {
5631 has_name = TRUE; /* found end of a name */
5632 p = cin_skipcomment(skipwhite(p));
5633 }
5634 else if (*p == '{')
5635 {
5636 break;
5637 }
5638 else if (vim_iswordc(*p))
5639 {
5640 if (has_name)
5641 return FALSE; /* word character after skipping past name */
5642 ++p;
5643 }
5644 else
5645 {
5646 return FALSE;
5647 }
5648 }
5649 return TRUE;
5650 }
5651 return FALSE;
5652}
5653
Bram Moolenaar071d4272004-06-13 20:20:40 +00005654/*
5655 * Return a pointer to the first non-empty non-comment character after a ':'.
5656 * Return NULL if not found.
5657 * case 234: a = b;
5658 * ^
5659 */
5660 static char_u *
5661after_label(l)
5662 char_u *l;
5663{
5664 for ( ; *l; ++l)
5665 {
5666 if (*l == ':')
5667 {
5668 if (l[1] == ':') /* skip over "::" for C++ */
5669 ++l;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005670 else if (!cin_iscase(l + 1, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005671 break;
5672 }
5673 else if (*l == '\'' && l[1] && l[2] == '\'')
5674 l += 2; /* skip over 'x' */
5675 }
5676 if (*l == NUL)
5677 return NULL;
5678 l = cin_skipcomment(l + 1);
5679 if (*l == NUL)
5680 return NULL;
5681 return l;
5682}
5683
5684/*
5685 * Get indent of line "lnum", skipping a label.
5686 * Return 0 if there is nothing after the label.
5687 */
5688 static int
5689get_indent_nolabel(lnum) /* XXX */
5690 linenr_T lnum;
5691{
5692 char_u *l;
5693 pos_T fp;
5694 colnr_T col;
5695 char_u *p;
5696
5697 l = ml_get(lnum);
5698 p = after_label(l);
5699 if (p == NULL)
5700 return 0;
5701
5702 fp.col = (colnr_T)(p - l);
5703 fp.lnum = lnum;
5704 getvcol(curwin, &fp, &col, NULL, NULL);
5705 return (int)col;
5706}
5707
5708/*
5709 * Find indent for line "lnum", ignoring any case or jump label.
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005710 * Also return a pointer to the text (after the label) in "pp".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005711 * label: if (asdf && asdfasdf)
5712 * ^
5713 */
5714 static int
5715skip_label(lnum, pp, ind_maxcomment)
5716 linenr_T lnum;
5717 char_u **pp;
5718 int ind_maxcomment;
5719{
5720 char_u *l;
5721 int amount;
5722 pos_T cursor_save;
5723
5724 cursor_save = curwin->w_cursor;
5725 curwin->w_cursor.lnum = lnum;
5726 l = ml_get_curline();
5727 /* XXX */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005728 if (cin_iscase(l, FALSE) || cin_isscopedecl(l)
5729 || cin_islabel(ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005730 {
5731 amount = get_indent_nolabel(lnum);
5732 l = after_label(ml_get_curline());
5733 if (l == NULL) /* just in case */
5734 l = ml_get_curline();
5735 }
5736 else
5737 {
5738 amount = get_indent();
5739 l = ml_get_curline();
5740 }
5741 *pp = l;
5742
5743 curwin->w_cursor = cursor_save;
5744 return amount;
5745}
5746
5747/*
5748 * Return the indent of the first variable name after a type in a declaration.
5749 * int a, indent of "a"
5750 * static struct foo b, indent of "b"
5751 * enum bla c, indent of "c"
5752 * Returns zero when it doesn't look like a declaration.
5753 */
5754 static int
5755cin_first_id_amount()
5756{
5757 char_u *line, *p, *s;
5758 int len;
5759 pos_T fp;
5760 colnr_T col;
5761
5762 line = ml_get_curline();
5763 p = skipwhite(line);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005764 len = (int)(skiptowhite(p) - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005765 if (len == 6 && STRNCMP(p, "static", 6) == 0)
5766 {
5767 p = skipwhite(p + 6);
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00005768 len = (int)(skiptowhite(p) - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005769 }
5770 if (len == 6 && STRNCMP(p, "struct", 6) == 0)
5771 p = skipwhite(p + 6);
5772 else if (len == 4 && STRNCMP(p, "enum", 4) == 0)
5773 p = skipwhite(p + 4);
5774 else if ((len == 8 && STRNCMP(p, "unsigned", 8) == 0)
5775 || (len == 6 && STRNCMP(p, "signed", 6) == 0))
5776 {
5777 s = skipwhite(p + len);
5778 if ((STRNCMP(s, "int", 3) == 0 && vim_iswhite(s[3]))
5779 || (STRNCMP(s, "long", 4) == 0 && vim_iswhite(s[4]))
5780 || (STRNCMP(s, "short", 5) == 0 && vim_iswhite(s[5]))
5781 || (STRNCMP(s, "char", 4) == 0 && vim_iswhite(s[4])))
5782 p = s;
5783 }
5784 for (len = 0; vim_isIDc(p[len]); ++len)
5785 ;
5786 if (len == 0 || !vim_iswhite(p[len]) || cin_nocode(p))
5787 return 0;
5788
5789 p = skipwhite(p + len);
5790 fp.lnum = curwin->w_cursor.lnum;
5791 fp.col = (colnr_T)(p - line);
5792 getvcol(curwin, &fp, &col, NULL, NULL);
5793 return (int)col;
5794}
5795
5796/*
5797 * Return the indent of the first non-blank after an equal sign.
5798 * char *foo = "here";
5799 * Return zero if no (useful) equal sign found.
5800 * Return -1 if the line above "lnum" ends in a backslash.
5801 * foo = "asdf\
5802 * asdf\
5803 * here";
5804 */
5805 static int
5806cin_get_equal_amount(lnum)
5807 linenr_T lnum;
5808{
5809 char_u *line;
5810 char_u *s;
5811 colnr_T col;
5812 pos_T fp;
5813
5814 if (lnum > 1)
5815 {
5816 line = ml_get(lnum - 1);
5817 if (*line != NUL && line[STRLEN(line) - 1] == '\\')
5818 return -1;
5819 }
5820
5821 line = s = ml_get(lnum);
5822 while (*s != NUL && vim_strchr((char_u *)"=;{}\"'", *s) == NULL)
5823 {
5824 if (cin_iscomment(s)) /* ignore comments */
5825 s = cin_skipcomment(s);
5826 else
5827 ++s;
5828 }
5829 if (*s != '=')
5830 return 0;
5831
5832 s = skipwhite(s + 1);
5833 if (cin_nocode(s))
5834 return 0;
5835
5836 if (*s == '"') /* nice alignment for continued strings */
5837 ++s;
5838
5839 fp.lnum = lnum;
5840 fp.col = (colnr_T)(s - line);
5841 getvcol(curwin, &fp, &col, NULL, NULL);
5842 return (int)col;
5843}
5844
5845/*
5846 * Recognize a preprocessor statement: Any line that starts with '#'.
5847 */
5848 static int
5849cin_ispreproc(s)
5850 char_u *s;
5851{
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005852 if (*skipwhite(s) == '#')
Bram Moolenaar071d4272004-06-13 20:20:40 +00005853 return TRUE;
5854 return FALSE;
5855}
5856
5857/*
5858 * Return TRUE if line "*pp" at "*lnump" is a preprocessor statement or a
5859 * continuation line of a preprocessor statement. Decrease "*lnump" to the
5860 * start and return the line in "*pp".
5861 */
5862 static int
5863cin_ispreproc_cont(pp, lnump)
5864 char_u **pp;
5865 linenr_T *lnump;
5866{
5867 char_u *line = *pp;
5868 linenr_T lnum = *lnump;
5869 int retval = FALSE;
5870
Bram Moolenaard8e9bb22005-07-09 21:14:46 +00005871 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005872 {
5873 if (cin_ispreproc(line))
5874 {
5875 retval = TRUE;
5876 *lnump = lnum;
5877 break;
5878 }
5879 if (lnum == 1)
5880 break;
5881 line = ml_get(--lnum);
5882 if (*line == NUL || line[STRLEN(line) - 1] != '\\')
5883 break;
5884 }
5885
5886 if (lnum != *lnump)
5887 *pp = ml_get(*lnump);
5888 return retval;
5889}
5890
5891/*
5892 * Recognize the start of a C or C++ comment.
5893 */
5894 static int
5895cin_iscomment(p)
5896 char_u *p;
5897{
5898 return (p[0] == '/' && (p[1] == '*' || p[1] == '/'));
5899}
5900
5901/*
5902 * Recognize the start of a "//" comment.
5903 */
5904 static int
5905cin_islinecomment(p)
5906 char_u *p;
5907{
5908 return (p[0] == '/' && p[1] == '/');
5909}
5910
5911/*
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005912 * Recognize a line that starts with '{' or '}', or ends with ';', ',', '{' or
5913 * '}'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005914 * Don't consider "} else" a terminated line.
Bram Moolenaar496f9512011-05-19 16:35:09 +02005915 * If a line begins with an "else", only consider it terminated if no unmatched
5916 * opening braces follow (handle "else { foo();" correctly).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005917 * Return the character terminating the line (ending char's have precedence if
5918 * both apply in order to determine initializations).
5919 */
5920 static int
5921cin_isterminated(s, incl_open, incl_comma)
5922 char_u *s;
5923 int incl_open; /* include '{' at the end as terminator */
5924 int incl_comma; /* recognize a trailing comma */
5925{
Bram Moolenaar496f9512011-05-19 16:35:09 +02005926 char_u found_start = 0;
5927 unsigned n_open = 0;
5928 int is_else = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005929
5930 s = cin_skipcomment(s);
5931
5932 if (*s == '{' || (*s == '}' && !cin_iselse(s)))
5933 found_start = *s;
5934
Bram Moolenaar496f9512011-05-19 16:35:09 +02005935 if (!found_start)
5936 is_else = cin_iselse(s);
5937
Bram Moolenaar071d4272004-06-13 20:20:40 +00005938 while (*s)
5939 {
5940 /* skip over comments, "" strings and 'c'haracters */
5941 s = skip_string(cin_skipcomment(s));
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005942 if (*s == '}' && n_open > 0)
5943 --n_open;
Bram Moolenaar496f9512011-05-19 16:35:09 +02005944 if ((!is_else || n_open == 0)
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005945 && (*s == ';' || *s == '}' || (incl_comma && *s == ','))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005946 && cin_nocode(s + 1))
5947 return *s;
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005948 else if (*s == '{')
5949 {
5950 if (incl_open && cin_nocode(s + 1))
5951 return *s;
5952 else
5953 ++n_open;
5954 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005955
5956 if (*s)
5957 s++;
5958 }
5959 return found_start;
5960}
5961
5962/*
5963 * Recognize the basic picture of a function declaration -- it needs to
5964 * have an open paren somewhere and a close paren at the end of the line and
5965 * no semicolons anywhere.
5966 * When a line ends in a comma we continue looking in the next line.
5967 * "sp" points to a string with the line. When looking at other lines it must
5968 * be restored to the line. When it's NULL fetch lines here.
5969 * "lnum" is where we start looking.
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005970 * "min_lnum" is the line before which we will not be looking.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005971 */
5972 static int
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005973cin_isfuncdecl(sp, first_lnum, min_lnum, ind_maxparen, ind_maxcomment)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005974 char_u **sp;
5975 linenr_T first_lnum;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005976 linenr_T min_lnum;
5977 int ind_maxparen;
5978 int ind_maxcomment;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005979{
5980 char_u *s;
5981 linenr_T lnum = first_lnum;
5982 int retval = FALSE;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005983 pos_T *trypos;
5984 int just_started = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005985
5986 if (sp == NULL)
5987 s = ml_get(lnum);
5988 else
5989 s = *sp;
5990
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005991 if (find_last_paren(s, '(', ')')
5992 && (trypos = find_match_paren(ind_maxparen, ind_maxcomment)) != NULL)
5993 {
5994 lnum = trypos->lnum;
5995 if (lnum < min_lnum)
5996 return FALSE;
5997
5998 s = ml_get(lnum);
5999 }
6000
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02006001 /* Ignore line starting with #. */
6002 if (cin_ispreproc(s))
6003 return FALSE;
6004
Bram Moolenaar071d4272004-06-13 20:20:40 +00006005 while (*s && *s != '(' && *s != ';' && *s != '\'' && *s != '"')
6006 {
6007 if (cin_iscomment(s)) /* ignore comments */
6008 s = cin_skipcomment(s);
6009 else
6010 ++s;
6011 }
6012 if (*s != '(')
6013 return FALSE; /* ';', ' or " before any () or no '(' */
6014
6015 while (*s && *s != ';' && *s != '\'' && *s != '"')
6016 {
6017 if (*s == ')' && cin_nocode(s + 1))
6018 {
6019 /* ')' at the end: may have found a match
6020 * Check for he previous line not to end in a backslash:
6021 * #if defined(x) && \
6022 * defined(y)
6023 */
6024 lnum = first_lnum - 1;
6025 s = ml_get(lnum);
6026 if (*s == NUL || s[STRLEN(s) - 1] != '\\')
6027 retval = TRUE;
6028 goto done;
6029 }
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02006030 if ((*s == ',' && cin_nocode(s + 1)) || s[1] == NUL || cin_nocode(s))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006031 {
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02006032 int comma = (*s == ',');
6033
6034 /* ',' at the end: continue looking in the next line.
6035 * At the end: check for ',' in the next line, for this style:
6036 * func(arg1
6037 * , arg2) */
6038 for (;;)
6039 {
6040 if (lnum >= curbuf->b_ml.ml_line_count)
6041 break;
6042 s = ml_get(++lnum);
6043 if (!cin_ispreproc(s))
6044 break;
6045 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006046 if (lnum >= curbuf->b_ml.ml_line_count)
6047 break;
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02006048 /* Require a comma at end of the line or a comma or ')' at the
6049 * start of next line. */
6050 s = skipwhite(s);
Bram Moolenaarc367faa2011-12-14 20:21:35 +01006051 if (!just_started && (!comma && *s != ',' && *s != ')'))
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02006052 break;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01006053 just_started = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006054 }
6055 else if (cin_iscomment(s)) /* ignore comments */
6056 s = cin_skipcomment(s);
6057 else
Bram Moolenaarc367faa2011-12-14 20:21:35 +01006058 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006059 ++s;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01006060 just_started = FALSE;
6061 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006062 }
6063
6064done:
6065 if (lnum != first_lnum && sp != NULL)
6066 *sp = ml_get(first_lnum);
6067
6068 return retval;
6069}
6070
6071 static int
6072cin_isif(p)
6073 char_u *p;
6074{
6075 return (STRNCMP(p, "if", 2) == 0 && !vim_isIDc(p[2]));
6076}
6077
6078 static int
6079cin_iselse(p)
6080 char_u *p;
6081{
6082 if (*p == '}') /* accept "} else" */
6083 p = cin_skipcomment(p + 1);
6084 return (STRNCMP(p, "else", 4) == 0 && !vim_isIDc(p[4]));
6085}
6086
6087 static int
6088cin_isdo(p)
6089 char_u *p;
6090{
6091 return (STRNCMP(p, "do", 2) == 0 && !vim_isIDc(p[2]));
6092}
6093
6094/*
6095 * Check if this is a "while" that should have a matching "do".
6096 * We only accept a "while (condition) ;", with only white space between the
6097 * ')' and ';'. The condition may be spread over several lines.
6098 */
6099 static int
6100cin_iswhileofdo(p, lnum, ind_maxparen) /* XXX */
6101 char_u *p;
6102 linenr_T lnum;
6103 int ind_maxparen;
6104{
6105 pos_T cursor_save;
6106 pos_T *trypos;
6107 int retval = FALSE;
6108
6109 p = cin_skipcomment(p);
6110 if (*p == '}') /* accept "} while (cond);" */
6111 p = cin_skipcomment(p + 1);
Bram Moolenaar75342212013-03-07 13:13:52 +01006112 if (cin_starts_with(p, "while"))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006113 {
6114 cursor_save = curwin->w_cursor;
6115 curwin->w_cursor.lnum = lnum;
6116 curwin->w_cursor.col = 0;
6117 p = ml_get_curline();
6118 while (*p && *p != 'w') /* skip any '}', until the 'w' of the "while" */
6119 {
6120 ++p;
6121 ++curwin->w_cursor.col;
6122 }
6123 if ((trypos = findmatchlimit(NULL, 0, 0, ind_maxparen)) != NULL
6124 && *cin_skipcomment(ml_get_pos(trypos) + 1) == ';')
6125 retval = TRUE;
6126 curwin->w_cursor = cursor_save;
6127 }
6128 return retval;
6129}
6130
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006131/*
Bram Moolenaarb345d492012-04-09 20:42:26 +02006132 * Check whether in "p" there is an "if", "for" or "while" before "*poffset".
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006133 * Return 0 if there is none.
6134 * Otherwise return !0 and update "*poffset" to point to the place where the
6135 * string was found.
6136 */
6137 static int
Bram Moolenaarb345d492012-04-09 20:42:26 +02006138cin_is_if_for_while_before_offset(line, poffset)
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006139 char_u *line;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006140 int *poffset;
6141{
Bram Moolenaarb345d492012-04-09 20:42:26 +02006142 int offset = *poffset;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006143
6144 if (offset-- < 2)
6145 return 0;
6146 while (offset > 2 && vim_iswhite(line[offset]))
6147 --offset;
6148
6149 offset -= 1;
6150 if (!STRNCMP(line + offset, "if", 2))
6151 goto probablyFound;
6152
6153 if (offset >= 1)
6154 {
6155 offset -= 1;
6156 if (!STRNCMP(line + offset, "for", 3))
6157 goto probablyFound;
6158
6159 if (offset >= 2)
6160 {
6161 offset -= 2;
6162 if (!STRNCMP(line + offset, "while", 5))
6163 goto probablyFound;
6164 }
6165 }
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006166 return 0;
Bram Moolenaarb345d492012-04-09 20:42:26 +02006167
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006168probablyFound:
6169 if (!offset || !vim_isIDc(line[offset - 1]))
6170 {
6171 *poffset = offset;
6172 return 1;
6173 }
6174 return 0;
6175}
6176
6177/*
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006178 * Return TRUE if we are at the end of a do-while.
6179 * do
6180 * nothing;
6181 * while (foo
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00006182 * && bar); <-- here
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006183 * Adjust the cursor to the line with "while".
6184 */
6185 static int
6186cin_iswhileofdo_end(terminated, ind_maxparen, ind_maxcomment)
6187 int terminated;
6188 int ind_maxparen;
6189 int ind_maxcomment;
6190{
6191 char_u *line;
6192 char_u *p;
6193 char_u *s;
6194 pos_T *trypos;
6195 int i;
6196
6197 if (terminated != ';') /* there must be a ';' at the end */
6198 return FALSE;
6199
6200 p = line = ml_get_curline();
6201 while (*p != NUL)
6202 {
6203 p = cin_skipcomment(p);
6204 if (*p == ')')
6205 {
6206 s = skipwhite(p + 1);
6207 if (*s == ';' && cin_nocode(s + 1))
6208 {
6209 /* Found ");" at end of the line, now check there is "while"
6210 * before the matching '('. XXX */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006211 i = (int)(p - line);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006212 curwin->w_cursor.col = i;
6213 trypos = find_match_paren(ind_maxparen, ind_maxcomment);
6214 if (trypos != NULL)
6215 {
6216 s = cin_skipcomment(ml_get(trypos->lnum));
6217 if (*s == '}') /* accept "} while (cond);" */
6218 s = cin_skipcomment(s + 1);
Bram Moolenaar75342212013-03-07 13:13:52 +01006219 if (cin_starts_with(s, "while"))
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006220 {
6221 curwin->w_cursor.lnum = trypos->lnum;
6222 return TRUE;
6223 }
6224 }
6225
6226 /* Searching may have made "line" invalid, get it again. */
6227 line = ml_get_curline();
6228 p = line + i;
6229 }
6230 }
6231 if (*p != NUL)
6232 ++p;
6233 }
6234 return FALSE;
6235}
6236
Bram Moolenaar071d4272004-06-13 20:20:40 +00006237 static int
6238cin_isbreak(p)
6239 char_u *p;
6240{
6241 return (STRNCMP(p, "break", 5) == 0 && !vim_isIDc(p[5]));
6242}
6243
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006244/*
6245 * Find the position of a C++ base-class declaration or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006246 * constructor-initialization. eg:
6247 *
6248 * class MyClass :
6249 * baseClass <-- here
6250 * class MyClass : public baseClass,
6251 * anotherBaseClass <-- here (should probably lineup ??)
6252 * MyClass::MyClass(...) :
6253 * baseClass(...) <-- here (constructor-initialization)
Bram Moolenaar18144c82006-04-12 21:52:12 +00006254 *
6255 * This is a lot of guessing. Watch out for "cond ? func() : foo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00006256 */
6257 static int
Bram Moolenaare7c56862007-08-04 10:14:52 +00006258cin_is_cpp_baseclass(col)
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006259 colnr_T *col; /* return: column to align with */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006260{
6261 char_u *s;
6262 int class_or_struct, lookfor_ctor_init, cpp_base_class;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006263 linenr_T lnum = curwin->w_cursor.lnum;
Bram Moolenaare7c56862007-08-04 10:14:52 +00006264 char_u *line = ml_get_curline();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006265
6266 *col = 0;
6267
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006268 s = skipwhite(line);
6269 if (*s == '#') /* skip #define FOO x ? (x) : x */
6270 return FALSE;
6271 s = cin_skipcomment(s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006272 if (*s == NUL)
6273 return FALSE;
6274
6275 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
6276
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006277 /* Search for a line starting with '#', empty, ending in ';' or containing
6278 * '{' or '}' and start below it. This handles the following situations:
6279 * a = cond ?
6280 * func() :
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00006281 * asdf;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006282 * func::foo()
6283 * : something
6284 * {}
6285 * Foo::Foo (int one, int two)
6286 * : something(4),
6287 * somethingelse(3)
6288 * {}
6289 */
6290 while (lnum > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006291 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00006292 line = ml_get(lnum - 1);
6293 s = skipwhite(line);
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006294 if (*s == '#' || *s == NUL)
6295 break;
6296 while (*s != NUL)
6297 {
6298 s = cin_skipcomment(s);
6299 if (*s == '{' || *s == '}'
6300 || (*s == ';' && cin_nocode(s + 1)))
6301 break;
6302 if (*s != NUL)
6303 ++s;
6304 }
6305 if (*s != NUL)
6306 break;
6307 --lnum;
6308 }
6309
Bram Moolenaare7c56862007-08-04 10:14:52 +00006310 line = ml_get(lnum);
6311 s = cin_skipcomment(line);
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006312 for (;;)
6313 {
6314 if (*s == NUL)
6315 {
6316 if (lnum == curwin->w_cursor.lnum)
6317 break;
6318 /* Continue in the cursor line. */
Bram Moolenaare7c56862007-08-04 10:14:52 +00006319 line = ml_get(++lnum);
6320 s = cin_skipcomment(line);
6321 if (*s == NUL)
6322 continue;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006323 }
6324
Bram Moolenaaraede6ce2011-05-10 11:56:30 +02006325 if (s[0] == '"')
6326 s = skip_string(s) + 1;
6327 else if (s[0] == ':')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006328 {
6329 if (s[1] == ':')
6330 {
6331 /* skip double colon. It can't be a constructor
6332 * initialization any more */
6333 lookfor_ctor_init = FALSE;
6334 s = cin_skipcomment(s + 2);
6335 }
6336 else if (lookfor_ctor_init || class_or_struct)
6337 {
6338 /* we have something found, that looks like the start of
Bram Moolenaare21877a2008-02-13 09:58:14 +00006339 * cpp-base-class-declaration or constructor-initialization */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006340 cpp_base_class = TRUE;
6341 lookfor_ctor_init = class_or_struct = FALSE;
6342 *col = 0;
6343 s = cin_skipcomment(s + 1);
6344 }
6345 else
6346 s = cin_skipcomment(s + 1);
6347 }
6348 else if ((STRNCMP(s, "class", 5) == 0 && !vim_isIDc(s[5]))
6349 || (STRNCMP(s, "struct", 6) == 0 && !vim_isIDc(s[6])))
6350 {
6351 class_or_struct = TRUE;
6352 lookfor_ctor_init = FALSE;
6353
6354 if (*s == 'c')
6355 s = cin_skipcomment(s + 5);
6356 else
6357 s = cin_skipcomment(s + 6);
6358 }
6359 else
6360 {
6361 if (s[0] == '{' || s[0] == '}' || s[0] == ';')
6362 {
6363 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
6364 }
6365 else if (s[0] == ')')
6366 {
6367 /* Constructor-initialization is assumed if we come across
6368 * something like "):" */
6369 class_or_struct = FALSE;
6370 lookfor_ctor_init = TRUE;
6371 }
Bram Moolenaar18144c82006-04-12 21:52:12 +00006372 else if (s[0] == '?')
6373 {
6374 /* Avoid seeing '() :' after '?' as constructor init. */
6375 return FALSE;
6376 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006377 else if (!vim_isIDc(s[0]))
6378 {
6379 /* if it is not an identifier, we are wrong */
6380 class_or_struct = FALSE;
6381 lookfor_ctor_init = FALSE;
6382 }
6383 else if (*col == 0)
6384 {
6385 /* it can't be a constructor-initialization any more */
6386 lookfor_ctor_init = FALSE;
6387
6388 /* the first statement starts here: lineup with this one... */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006389 if (cpp_base_class)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006390 *col = (colnr_T)(s - line);
6391 }
6392
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006393 /* When the line ends in a comma don't align with it. */
6394 if (lnum == curwin->w_cursor.lnum && *s == ',' && cin_nocode(s + 1))
6395 *col = 0;
6396
Bram Moolenaar071d4272004-06-13 20:20:40 +00006397 s = cin_skipcomment(s + 1);
6398 }
6399 }
6400
6401 return cpp_base_class;
6402}
6403
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006404 static int
6405get_baseclass_amount(col, ind_maxparen, ind_maxcomment, ind_cpp_baseclass)
6406 int col;
6407 int ind_maxparen;
6408 int ind_maxcomment;
6409 int ind_cpp_baseclass;
6410{
6411 int amount;
6412 colnr_T vcol;
6413 pos_T *trypos;
6414
6415 if (col == 0)
6416 {
6417 amount = get_indent();
6418 if (find_last_paren(ml_get_curline(), '(', ')')
6419 && (trypos = find_match_paren(ind_maxparen,
6420 ind_maxcomment)) != NULL)
6421 amount = get_indent_lnum(trypos->lnum); /* XXX */
6422 if (!cin_ends_in(ml_get_curline(), (char_u *)",", NULL))
6423 amount += ind_cpp_baseclass;
6424 }
6425 else
6426 {
6427 curwin->w_cursor.col = col;
6428 getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
6429 amount = (int)vcol;
6430 }
6431 if (amount < ind_cpp_baseclass)
6432 amount = ind_cpp_baseclass;
6433 return amount;
6434}
6435
Bram Moolenaar071d4272004-06-13 20:20:40 +00006436/*
6437 * Return TRUE if string "s" ends with the string "find", possibly followed by
6438 * white space and comments. Skip strings and comments.
6439 * Ignore "ignore" after "find" if it's not NULL.
6440 */
6441 static int
6442cin_ends_in(s, find, ignore)
6443 char_u *s;
6444 char_u *find;
6445 char_u *ignore;
6446{
6447 char_u *p = s;
6448 char_u *r;
6449 int len = (int)STRLEN(find);
6450
6451 while (*p != NUL)
6452 {
6453 p = cin_skipcomment(p);
6454 if (STRNCMP(p, find, len) == 0)
6455 {
6456 r = skipwhite(p + len);
6457 if (ignore != NULL && STRNCMP(r, ignore, STRLEN(ignore)) == 0)
6458 r = skipwhite(r + STRLEN(ignore));
6459 if (cin_nocode(r))
6460 return TRUE;
6461 }
6462 if (*p != NUL)
6463 ++p;
6464 }
6465 return FALSE;
6466}
6467
6468/*
Bram Moolenaar75342212013-03-07 13:13:52 +01006469 * Return TRUE when "s" starts with "word" and then a non-ID character.
6470 */
6471 static int
6472cin_starts_with(s, word)
6473 char_u *s;
6474 char *word;
6475{
Bram Moolenaarb3cb9822013-03-13 17:01:52 +01006476 int l = (int)STRLEN(word);
Bram Moolenaar75342212013-03-07 13:13:52 +01006477
6478 return (STRNCMP(s, word, l) == 0 && !vim_isIDc(s[l]));
6479}
6480
6481/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006482 * Skip strings, chars and comments until at or past "trypos".
6483 * Return the column found.
6484 */
6485 static int
6486cin_skip2pos(trypos)
6487 pos_T *trypos;
6488{
6489 char_u *line;
6490 char_u *p;
6491
6492 p = line = ml_get(trypos->lnum);
6493 while (*p && (colnr_T)(p - line) < trypos->col)
6494 {
6495 if (cin_iscomment(p))
6496 p = cin_skipcomment(p);
6497 else
6498 {
6499 p = skip_string(p);
6500 ++p;
6501 }
6502 }
6503 return (int)(p - line);
6504}
6505
6506/*
6507 * Find the '{' at the start of the block we are in.
6508 * Return NULL if no match found.
6509 * Ignore a '{' that is in a comment, makes indenting the next three lines
6510 * work. */
6511/* foo() */
6512/* { */
6513/* } */
6514
6515 static pos_T *
6516find_start_brace(ind_maxcomment) /* XXX */
6517 int ind_maxcomment;
6518{
6519 pos_T cursor_save;
6520 pos_T *trypos;
6521 pos_T *pos;
6522 static pos_T pos_copy;
6523
6524 cursor_save = curwin->w_cursor;
6525 while ((trypos = findmatchlimit(NULL, '{', FM_BLOCKSTOP, 0)) != NULL)
6526 {
6527 pos_copy = *trypos; /* copy pos_T, next findmatch will change it */
6528 trypos = &pos_copy;
6529 curwin->w_cursor = *trypos;
6530 pos = NULL;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006531 /* ignore the { if it's in a // or / * * / comment */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006532 if ((colnr_T)cin_skip2pos(trypos) == trypos->col
6533 && (pos = find_start_comment(ind_maxcomment)) == NULL) /* XXX */
6534 break;
6535 if (pos != NULL)
6536 curwin->w_cursor.lnum = pos->lnum;
6537 }
6538 curwin->w_cursor = cursor_save;
6539 return trypos;
6540}
6541
6542/*
6543 * Find the matching '(', failing if it is in a comment.
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006544 * Return NULL if no match found.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006545 */
6546 static pos_T *
6547find_match_paren(ind_maxparen, ind_maxcomment) /* XXX */
6548 int ind_maxparen;
6549 int ind_maxcomment;
6550{
6551 pos_T cursor_save;
6552 pos_T *trypos;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006553 static pos_T pos_copy;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006554
6555 cursor_save = curwin->w_cursor;
6556 if ((trypos = findmatchlimit(NULL, '(', 0, ind_maxparen)) != NULL)
6557 {
6558 /* check if the ( is in a // comment */
6559 if ((colnr_T)cin_skip2pos(trypos) > trypos->col)
6560 trypos = NULL;
6561 else
6562 {
6563 pos_copy = *trypos; /* copy trypos, findmatch will change it */
6564 trypos = &pos_copy;
6565 curwin->w_cursor = *trypos;
6566 if (find_start_comment(ind_maxcomment) != NULL) /* XXX */
6567 trypos = NULL;
6568 }
6569 }
6570 curwin->w_cursor = cursor_save;
6571 return trypos;
6572}
6573
6574/*
6575 * Return ind_maxparen corrected for the difference in line number between the
6576 * cursor position and "startpos". This makes sure that searching for a
6577 * matching paren above the cursor line doesn't find a match because of
6578 * looking a few lines further.
6579 */
6580 static int
6581corr_ind_maxparen(ind_maxparen, startpos)
6582 int ind_maxparen;
6583 pos_T *startpos;
6584{
6585 long n = (long)startpos->lnum - (long)curwin->w_cursor.lnum;
6586
6587 if (n > 0 && n < ind_maxparen / 2)
6588 return ind_maxparen - (int)n;
6589 return ind_maxparen;
6590}
6591
6592/*
6593 * Set w_cursor.col to the column number of the last unmatched ')' or '{' in
Bram Moolenaar6d8f9c62011-11-30 13:03:28 +01006594 * line "l". "l" must point to the start of the line.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006595 */
6596 static int
6597find_last_paren(l, start, end)
6598 char_u *l;
6599 int start, end;
6600{
6601 int i;
6602 int retval = FALSE;
6603 int open_count = 0;
6604
6605 curwin->w_cursor.col = 0; /* default is start of line */
6606
Bram Moolenaar6d8f9c62011-11-30 13:03:28 +01006607 for (i = 0; l[i] != NUL; i++)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006608 {
6609 i = (int)(cin_skipcomment(l + i) - l); /* ignore parens in comments */
6610 i = (int)(skip_string(l + i) - l); /* ignore parens in quotes */
6611 if (l[i] == start)
6612 ++open_count;
6613 else if (l[i] == end)
6614 {
6615 if (open_count > 0)
6616 --open_count;
6617 else
6618 {
6619 curwin->w_cursor.col = i;
6620 retval = TRUE;
6621 }
6622 }
6623 }
6624 return retval;
6625}
6626
6627 int
6628get_c_indent()
6629{
Bram Moolenaar14f24742012-08-08 18:01:05 +02006630 int sw = (int)get_sw_value();
6631
Bram Moolenaar071d4272004-06-13 20:20:40 +00006632 /*
6633 * spaces from a block's opening brace the prevailing indent for that
6634 * block should be
6635 */
Bram Moolenaar14f24742012-08-08 18:01:05 +02006636
6637 int ind_level = sw;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006638
6639 /*
6640 * spaces from the edge of the line an open brace that's at the end of a
6641 * line is imagined to be.
6642 */
6643 int ind_open_imag = 0;
6644
6645 /*
Bram Moolenaar1a509df2010-08-01 17:59:57 +02006646 * spaces from the prevailing indent for a line that is not preceded by
Bram Moolenaar071d4272004-06-13 20:20:40 +00006647 * an opening brace.
6648 */
6649 int ind_no_brace = 0;
6650
6651 /*
6652 * column where the first { of a function should be located }
6653 */
6654 int ind_first_open = 0;
6655
6656 /*
6657 * spaces from the prevailing indent a leftmost open brace should be
6658 * located
6659 */
6660 int ind_open_extra = 0;
6661
6662 /*
6663 * spaces from the matching open brace (real location for one at the left
6664 * edge; imaginary location from one that ends a line) the matching close
6665 * brace should be located
6666 */
6667 int ind_close_extra = 0;
6668
6669 /*
6670 * spaces from the edge of the line an open brace sitting in the leftmost
6671 * column is imagined to be
6672 */
6673 int ind_open_left_imag = 0;
6674
6675 /*
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006676 * Spaces jump labels should be shifted to the left if N is non-negative,
6677 * otherwise the jump label will be put to column 1.
6678 */
6679 int ind_jump_label = -1;
6680
6681 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006682 * spaces from the switch() indent a "case xx" label should be located
6683 */
Bram Moolenaar14f24742012-08-08 18:01:05 +02006684 int ind_case = sw;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006685
6686 /*
6687 * spaces from the "case xx:" code after a switch() should be located
6688 */
Bram Moolenaar14f24742012-08-08 18:01:05 +02006689 int ind_case_code = sw;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006690
6691 /*
6692 * lineup break at end of case in switch() with case label
6693 */
6694 int ind_case_break = 0;
6695
6696 /*
6697 * spaces from the class declaration indent a scope declaration label
6698 * should be located
6699 */
Bram Moolenaar14f24742012-08-08 18:01:05 +02006700 int ind_scopedecl = sw;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006701
6702 /*
6703 * spaces from the scope declaration label code should be located
6704 */
Bram Moolenaar14f24742012-08-08 18:01:05 +02006705 int ind_scopedecl_code = sw;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006706
6707 /*
6708 * amount K&R-style parameters should be indented
6709 */
Bram Moolenaar14f24742012-08-08 18:01:05 +02006710 int ind_param = sw;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006711
6712 /*
6713 * amount a function type spec should be indented
6714 */
Bram Moolenaar14f24742012-08-08 18:01:05 +02006715 int ind_func_type = sw;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006716
6717 /*
6718 * amount a cpp base class declaration or constructor initialization
6719 * should be indented
6720 */
Bram Moolenaar14f24742012-08-08 18:01:05 +02006721 int ind_cpp_baseclass = sw;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006722
6723 /*
6724 * additional spaces beyond the prevailing indent a continuation line
6725 * should be located
6726 */
Bram Moolenaar14f24742012-08-08 18:01:05 +02006727 int ind_continuation = sw;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006728
6729 /*
6730 * spaces from the indent of the line with an unclosed parentheses
6731 */
Bram Moolenaar14f24742012-08-08 18:01:05 +02006732 int ind_unclosed = sw * 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006733
6734 /*
6735 * spaces from the indent of the line with an unclosed parentheses, which
6736 * itself is also unclosed
6737 */
Bram Moolenaar14f24742012-08-08 18:01:05 +02006738 int ind_unclosed2 = sw;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006739
6740 /*
6741 * suppress ignoring spaces from the indent of a line starting with an
6742 * unclosed parentheses.
6743 */
6744 int ind_unclosed_noignore = 0;
6745
6746 /*
6747 * If the opening paren is the last nonwhite character on the line, and
6748 * ind_unclosed_wrapped is nonzero, use this indent relative to the outer
6749 * context (for very long lines).
6750 */
6751 int ind_unclosed_wrapped = 0;
6752
6753 /*
6754 * suppress ignoring white space when lining up with the character after
6755 * an unclosed parentheses.
6756 */
6757 int ind_unclosed_whiteok = 0;
6758
6759 /*
6760 * indent a closing parentheses under the line start of the matching
6761 * opening parentheses.
6762 */
6763 int ind_matching_paren = 0;
6764
6765 /*
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006766 * indent a closing parentheses under the previous line.
6767 */
6768 int ind_paren_prev = 0;
6769
6770 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006771 * Extra indent for comments.
6772 */
6773 int ind_comment = 0;
6774
6775 /*
6776 * spaces from the comment opener when there is nothing after it.
6777 */
6778 int ind_in_comment = 3;
6779
6780 /*
6781 * boolean: if non-zero, use ind_in_comment even if there is something
6782 * after the comment opener.
6783 */
6784 int ind_in_comment2 = 0;
6785
6786 /*
6787 * max lines to search for an open paren
6788 */
6789 int ind_maxparen = 20;
6790
6791 /*
6792 * max lines to search for an open comment
6793 */
6794 int ind_maxcomment = 70;
6795
6796 /*
6797 * handle braces for java code
6798 */
6799 int ind_java = 0;
6800
6801 /*
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006802 * not to confuse JS object properties with labels
6803 */
6804 int ind_js = 0;
6805
6806 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006807 * handle blocked cases correctly
6808 */
6809 int ind_keep_case_label = 0;
6810
Bram Moolenaared38b0a2011-05-25 15:16:18 +02006811 /*
6812 * handle C++ namespace
6813 */
6814 int ind_cpp_namespace = 0;
6815
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006816 /*
6817 * handle continuation lines containing conditions of if(), for() and
6818 * while()
6819 */
6820 int ind_if_for_while = 0;
6821
Bram Moolenaar071d4272004-06-13 20:20:40 +00006822 pos_T cur_curpos;
6823 int amount;
6824 int scope_amount;
Bram Moolenaarb21e5842006-04-16 18:30:08 +00006825 int cur_amount = MAXCOL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006826 colnr_T col;
6827 char_u *theline;
6828 char_u *linecopy;
6829 pos_T *trypos;
6830 pos_T *tryposBrace = NULL;
6831 pos_T our_paren_pos;
6832 char_u *start;
6833 int start_brace;
Bram Moolenaare21877a2008-02-13 09:58:14 +00006834#define BRACE_IN_COL0 1 /* '{' is in column 0 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006835#define BRACE_AT_START 2 /* '{' is at start of line */
6836#define BRACE_AT_END 3 /* '{' is at end of line */
6837 linenr_T ourscope;
6838 char_u *l;
6839 char_u *look;
6840 char_u terminated;
6841 int lookfor;
6842#define LOOKFOR_INITIAL 0
6843#define LOOKFOR_IF 1
6844#define LOOKFOR_DO 2
6845#define LOOKFOR_CASE 3
6846#define LOOKFOR_ANY 4
6847#define LOOKFOR_TERM 5
6848#define LOOKFOR_UNTERM 6
6849#define LOOKFOR_SCOPEDECL 7
6850#define LOOKFOR_NOBREAK 8
6851#define LOOKFOR_CPP_BASECLASS 9
6852#define LOOKFOR_ENUM_OR_INIT 10
6853
6854 int whilelevel;
6855 linenr_T lnum;
6856 char_u *options;
Bram Moolenaar48d27922012-06-13 13:40:48 +02006857 char_u *digits;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006858 int fraction = 0; /* init for GCC */
6859 int divider;
6860 int n;
6861 int iscase;
6862 int lookfor_break;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02006863 int lookfor_cpp_namespace = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006864 int cont_amount = 0; /* amount for continuation line */
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006865 int original_line_islabel;
Bram Moolenaare79d1532011-10-04 18:03:47 +02006866 int added_to_amount = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006867
6868 for (options = curbuf->b_p_cino; *options; )
6869 {
6870 l = options++;
6871 if (*options == '-')
6872 ++options;
Bram Moolenaar48d27922012-06-13 13:40:48 +02006873 digits = options; /* remember where the digits start */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006874 n = getdigits(&options);
6875 divider = 0;
6876 if (*options == '.') /* ".5s" means a fraction */
6877 {
6878 fraction = atol((char *)++options);
6879 while (VIM_ISDIGIT(*options))
6880 {
6881 ++options;
6882 if (divider)
6883 divider *= 10;
6884 else
6885 divider = 10;
6886 }
6887 }
6888 if (*options == 's') /* "2s" means two times 'shiftwidth' */
6889 {
Bram Moolenaar48d27922012-06-13 13:40:48 +02006890 if (options == digits)
Bram Moolenaar14f24742012-08-08 18:01:05 +02006891 n = sw; /* just "s" is one 'shiftwidth' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006892 else
6893 {
Bram Moolenaar14f24742012-08-08 18:01:05 +02006894 n *= sw;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006895 if (divider)
Bram Moolenaar14f24742012-08-08 18:01:05 +02006896 n += (sw * fraction + divider / 2) / divider;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006897 }
6898 ++options;
6899 }
6900 if (l[1] == '-')
6901 n = -n;
6902 /* When adding an entry here, also update the default 'cinoptions' in
Bram Moolenaar39353fd2007-03-27 09:02:11 +00006903 * doc/indent.txt, and add explanation for it! */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006904 switch (*l)
6905 {
6906 case '>': ind_level = n; break;
6907 case 'e': ind_open_imag = n; break;
6908 case 'n': ind_no_brace = n; break;
6909 case 'f': ind_first_open = n; break;
6910 case '{': ind_open_extra = n; break;
6911 case '}': ind_close_extra = n; break;
6912 case '^': ind_open_left_imag = n; break;
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006913 case 'L': ind_jump_label = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006914 case ':': ind_case = n; break;
6915 case '=': ind_case_code = n; break;
6916 case 'b': ind_case_break = n; break;
6917 case 'p': ind_param = n; break;
6918 case 't': ind_func_type = n; break;
6919 case '/': ind_comment = n; break;
6920 case 'c': ind_in_comment = n; break;
6921 case 'C': ind_in_comment2 = n; break;
6922 case 'i': ind_cpp_baseclass = n; break;
6923 case '+': ind_continuation = n; break;
6924 case '(': ind_unclosed = n; break;
6925 case 'u': ind_unclosed2 = n; break;
6926 case 'U': ind_unclosed_noignore = n; break;
6927 case 'W': ind_unclosed_wrapped = n; break;
6928 case 'w': ind_unclosed_whiteok = n; break;
6929 case 'm': ind_matching_paren = n; break;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006930 case 'M': ind_paren_prev = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006931 case ')': ind_maxparen = n; break;
6932 case '*': ind_maxcomment = n; break;
6933 case 'g': ind_scopedecl = n; break;
6934 case 'h': ind_scopedecl_code = n; break;
6935 case 'j': ind_java = n; break;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006936 case 'J': ind_js = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006937 case 'l': ind_keep_case_label = n; break;
Bram Moolenaar39353fd2007-03-27 09:02:11 +00006938 case '#': ind_hash_comment = n; break;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02006939 case 'N': ind_cpp_namespace = n; break;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006940 case 'k': ind_if_for_while = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006941 }
Bram Moolenaardfdf3c42010-03-23 18:22:46 +01006942 if (*options == ',')
6943 ++options;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006944 }
6945
6946 /* remember where the cursor was when we started */
6947 cur_curpos = curwin->w_cursor;
6948
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006949 /* if we are at line 1 0 is fine, right? */
6950 if (cur_curpos.lnum == 1)
6951 return 0;
6952
Bram Moolenaar071d4272004-06-13 20:20:40 +00006953 /* Get a copy of the current contents of the line.
6954 * This is required, because only the most recent line obtained with
6955 * ml_get is valid! */
6956 linecopy = vim_strsave(ml_get(cur_curpos.lnum));
6957 if (linecopy == NULL)
6958 return 0;
6959
6960 /*
6961 * In insert mode and the cursor is on a ')' truncate the line at the
6962 * cursor position. We don't want to line up with the matching '(' when
6963 * inserting new stuff.
6964 * For unknown reasons the cursor might be past the end of the line, thus
6965 * check for that.
6966 */
6967 if ((State & INSERT)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006968 && curwin->w_cursor.col < (colnr_T)STRLEN(linecopy)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006969 && linecopy[curwin->w_cursor.col] == ')')
6970 linecopy[curwin->w_cursor.col] = NUL;
6971
6972 theline = skipwhite(linecopy);
6973
6974 /* move the cursor to the start of the line */
6975
6976 curwin->w_cursor.col = 0;
6977
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006978 original_line_islabel = cin_islabel(ind_maxcomment); /* XXX */
6979
Bram Moolenaar071d4272004-06-13 20:20:40 +00006980 /*
6981 * #defines and so on always go at the left when included in 'cinkeys'.
6982 */
6983 if (*theline == '#' && (*linecopy == '#' || in_cinkeys('#', ' ', TRUE)))
6984 {
6985 amount = 0;
6986 }
6987
6988 /*
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006989 * Is it a non-case label? Then that goes at the left margin too unless:
6990 * - JS flag is set.
6991 * - 'L' item has a positive value.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006992 */
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006993 else if (original_line_islabel && !ind_js && ind_jump_label < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006994 {
6995 amount = 0;
6996 }
6997
6998 /*
6999 * If we're inside a "//" comment and there is a "//" comment in a
7000 * previous line, lineup with that one.
7001 */
7002 else if (cin_islinecomment(theline)
7003 && (trypos = find_line_comment()) != NULL) /* XXX */
7004 {
7005 /* find how indented the line beginning the comment is */
7006 getvcol(curwin, trypos, &col, NULL, NULL);
7007 amount = col;
7008 }
7009
7010 /*
7011 * If we're inside a comment and not looking at the start of the
7012 * comment, try using the 'comments' option.
7013 */
7014 else if (!cin_iscomment(theline)
7015 && (trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
7016 {
7017 int lead_start_len = 2;
7018 int lead_middle_len = 1;
7019 char_u lead_start[COM_MAX_LEN]; /* start-comment string */
7020 char_u lead_middle[COM_MAX_LEN]; /* middle-comment string */
7021 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
7022 char_u *p;
7023 int start_align = 0;
7024 int start_off = 0;
7025 int done = FALSE;
7026
7027 /* find how indented the line beginning the comment is */
7028 getvcol(curwin, trypos, &col, NULL, NULL);
7029 amount = col;
Bram Moolenaar4aa97422011-04-11 14:27:38 +02007030 *lead_start = NUL;
7031 *lead_middle = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007032
7033 p = curbuf->b_p_com;
7034 while (*p != NUL)
7035 {
7036 int align = 0;
7037 int off = 0;
7038 int what = 0;
7039
7040 while (*p != NUL && *p != ':')
7041 {
7042 if (*p == COM_START || *p == COM_END || *p == COM_MIDDLE)
7043 what = *p++;
7044 else if (*p == COM_LEFT || *p == COM_RIGHT)
7045 align = *p++;
7046 else if (VIM_ISDIGIT(*p) || *p == '-')
7047 off = getdigits(&p);
7048 else
7049 ++p;
7050 }
7051
7052 if (*p == ':')
7053 ++p;
7054 (void)copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
7055 if (what == COM_START)
7056 {
7057 STRCPY(lead_start, lead_end);
7058 lead_start_len = (int)STRLEN(lead_start);
7059 start_off = off;
7060 start_align = align;
7061 }
7062 else if (what == COM_MIDDLE)
7063 {
7064 STRCPY(lead_middle, lead_end);
7065 lead_middle_len = (int)STRLEN(lead_middle);
7066 }
7067 else if (what == COM_END)
7068 {
7069 /* If our line starts with the middle comment string, line it
7070 * up with the comment opener per the 'comments' option. */
7071 if (STRNCMP(theline, lead_middle, lead_middle_len) == 0
7072 && STRNCMP(theline, lead_end, STRLEN(lead_end)) != 0)
7073 {
7074 done = TRUE;
7075 if (curwin->w_cursor.lnum > 1)
7076 {
7077 /* If the start comment string matches in the previous
Bram Moolenaare21877a2008-02-13 09:58:14 +00007078 * line, use the indent of that line plus offset. If
Bram Moolenaar071d4272004-06-13 20:20:40 +00007079 * the middle comment string matches in the previous
7080 * line, use the indent of that line. XXX */
7081 look = skipwhite(ml_get(curwin->w_cursor.lnum - 1));
7082 if (STRNCMP(look, lead_start, lead_start_len) == 0)
7083 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
7084 else if (STRNCMP(look, lead_middle,
7085 lead_middle_len) == 0)
7086 {
7087 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
7088 break;
7089 }
7090 /* If the start comment string doesn't match with the
7091 * start of the comment, skip this entry. XXX */
7092 else if (STRNCMP(ml_get(trypos->lnum) + trypos->col,
7093 lead_start, lead_start_len) != 0)
7094 continue;
7095 }
7096 if (start_off != 0)
7097 amount += start_off;
7098 else if (start_align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00007099 amount += vim_strsize(lead_start)
7100 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007101 break;
7102 }
7103
7104 /* If our line starts with the end comment string, line it up
7105 * with the middle comment */
7106 if (STRNCMP(theline, lead_middle, lead_middle_len) != 0
7107 && STRNCMP(theline, lead_end, STRLEN(lead_end)) == 0)
7108 {
7109 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
7110 /* XXX */
7111 if (off != 0)
7112 amount += off;
7113 else if (align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00007114 amount += vim_strsize(lead_start)
7115 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007116 done = TRUE;
7117 break;
7118 }
7119 }
7120 }
7121
7122 /* If our line starts with an asterisk, line up with the
7123 * asterisk in the comment opener; otherwise, line up
7124 * with the first character of the comment text.
7125 */
7126 if (done)
7127 ;
7128 else if (theline[0] == '*')
7129 amount += 1;
7130 else
7131 {
7132 /*
7133 * If we are more than one line away from the comment opener, take
7134 * the indent of the previous non-empty line. If 'cino' has "CO"
7135 * and we are just below the comment opener and there are any
7136 * white characters after it line up with the text after it;
7137 * otherwise, add the amount specified by "c" in 'cino'
7138 */
7139 amount = -1;
7140 for (lnum = cur_curpos.lnum - 1; lnum > trypos->lnum; --lnum)
7141 {
7142 if (linewhite(lnum)) /* skip blank lines */
7143 continue;
7144 amount = get_indent_lnum(lnum); /* XXX */
7145 break;
7146 }
7147 if (amount == -1) /* use the comment opener */
7148 {
7149 if (!ind_in_comment2)
7150 {
7151 start = ml_get(trypos->lnum);
7152 look = start + trypos->col + 2; /* skip / and * */
7153 if (*look != NUL) /* if something after it */
7154 trypos->col = (colnr_T)(skipwhite(look) - start);
7155 }
7156 getvcol(curwin, trypos, &col, NULL, NULL);
7157 amount = col;
7158 if (ind_in_comment2 || *look == NUL)
7159 amount += ind_in_comment;
7160 }
7161 }
7162 }
7163
7164 /*
7165 * Are we inside parentheses or braces?
7166 */ /* XXX */
7167 else if (((trypos = find_match_paren(ind_maxparen, ind_maxcomment)) != NULL
7168 && ind_java == 0)
7169 || (tryposBrace = find_start_brace(ind_maxcomment)) != NULL
7170 || trypos != NULL)
7171 {
7172 if (trypos != NULL && tryposBrace != NULL)
7173 {
7174 /* Both an unmatched '(' and '{' is found. Use the one which is
7175 * closer to the current cursor position, set the other to NULL. */
7176 if (trypos->lnum != tryposBrace->lnum
7177 ? trypos->lnum < tryposBrace->lnum
7178 : trypos->col < tryposBrace->col)
7179 trypos = NULL;
7180 else
7181 tryposBrace = NULL;
7182 }
7183
7184 if (trypos != NULL)
7185 {
7186 /*
7187 * If the matching paren is more than one line away, use the indent of
7188 * a previous non-empty line that matches the same paren.
7189 */
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007190 if (theline[0] == ')' && ind_paren_prev)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007191 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007192 /* Line up with the start of the matching paren line. */
7193 amount = get_indent_lnum(curwin->w_cursor.lnum - 1); /* XXX */
7194 }
7195 else
7196 {
7197 amount = -1;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007198 our_paren_pos = *trypos;
7199 for (lnum = cur_curpos.lnum - 1; lnum > our_paren_pos.lnum; --lnum)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007200 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007201 l = skipwhite(ml_get(lnum));
7202 if (cin_nocode(l)) /* skip comment lines */
7203 continue;
7204 if (cin_ispreproc_cont(&l, &lnum))
7205 continue; /* ignore #define, #if, etc. */
7206 curwin->w_cursor.lnum = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007207
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007208 /* Skip a comment. XXX */
7209 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
7210 {
7211 lnum = trypos->lnum + 1;
7212 continue;
7213 }
7214
7215 /* XXX */
7216 if ((trypos = find_match_paren(
7217 corr_ind_maxparen(ind_maxparen, &cur_curpos),
Bram Moolenaar071d4272004-06-13 20:20:40 +00007218 ind_maxcomment)) != NULL
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007219 && trypos->lnum == our_paren_pos.lnum
7220 && trypos->col == our_paren_pos.col)
7221 {
7222 amount = get_indent_lnum(lnum); /* XXX */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007223
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007224 if (theline[0] == ')')
7225 {
7226 if (our_paren_pos.lnum != lnum
7227 && cur_amount > amount)
7228 cur_amount = amount;
7229 amount = -1;
7230 }
7231 break;
7232 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007233 }
7234 }
7235
7236 /*
7237 * Line up with line where the matching paren is. XXX
7238 * If the line starts with a '(' or the indent for unclosed
7239 * parentheses is zero, line up with the unclosed parentheses.
7240 */
7241 if (amount == -1)
7242 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007243 int ignore_paren_col = 0;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007244 int is_if_for_while = 0;
7245
7246 if (ind_if_for_while)
7247 {
7248 /* Look for the outermost opening parenthesis on this line
7249 * and check whether it belongs to an "if", "for" or "while". */
7250
7251 pos_T cursor_save = curwin->w_cursor;
7252 pos_T outermost;
7253 char_u *line;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007254
7255 trypos = &our_paren_pos;
7256 do {
7257 outermost = *trypos;
7258 curwin->w_cursor.lnum = outermost.lnum;
7259 curwin->w_cursor.col = outermost.col;
7260
7261 trypos = find_match_paren(ind_maxparen, ind_maxcomment);
7262 } while (trypos && trypos->lnum == outermost.lnum);
7263
7264 curwin->w_cursor = cursor_save;
7265
7266 line = ml_get(outermost.lnum);
7267
7268 is_if_for_while =
Bram Moolenaarb345d492012-04-09 20:42:26 +02007269 cin_is_if_for_while_before_offset(line, &outermost.col);
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007270 }
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007271
Bram Moolenaar071d4272004-06-13 20:20:40 +00007272 amount = skip_label(our_paren_pos.lnum, &look, ind_maxcomment);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007273 look = skipwhite(look);
7274 if (*look == '(')
7275 {
7276 linenr_T save_lnum = curwin->w_cursor.lnum;
7277 char_u *line;
7278 int look_col;
7279
7280 /* Ignore a '(' in front of the line that has a match before
7281 * our matching '('. */
7282 curwin->w_cursor.lnum = our_paren_pos.lnum;
7283 line = ml_get_curline();
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007284 look_col = (int)(look - line);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007285 curwin->w_cursor.col = look_col + 1;
7286 if ((trypos = findmatchlimit(NULL, ')', 0, ind_maxparen))
7287 != NULL
7288 && trypos->lnum == our_paren_pos.lnum
7289 && trypos->col < our_paren_pos.col)
7290 ignore_paren_col = trypos->col + 1;
7291
7292 curwin->w_cursor.lnum = save_lnum;
7293 look = ml_get(our_paren_pos.lnum) + look_col;
7294 }
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007295 if (theline[0] == ')' || (ind_unclosed == 0 && is_if_for_while == 0)
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007296 || (!ind_unclosed_noignore && *look == '('
7297 && ignore_paren_col == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007298 {
7299 /*
7300 * If we're looking at a close paren, line up right there;
7301 * otherwise, line up with the next (non-white) character.
7302 * When ind_unclosed_wrapped is set and the matching paren is
7303 * the last nonwhite character of the line, use either the
7304 * indent of the current line or the indentation of the next
7305 * outer paren and add ind_unclosed_wrapped (for very long
7306 * lines).
7307 */
7308 if (theline[0] != ')')
7309 {
7310 cur_amount = MAXCOL;
7311 l = ml_get(our_paren_pos.lnum);
7312 if (ind_unclosed_wrapped
7313 && cin_ends_in(l, (char_u *)"(", NULL))
7314 {
7315 /* look for opening unmatched paren, indent one level
7316 * for each additional level */
7317 n = 1;
7318 for (col = 0; col < our_paren_pos.col; ++col)
7319 {
7320 switch (l[col])
7321 {
7322 case '(':
7323 case '{': ++n;
7324 break;
7325
7326 case ')':
7327 case '}': if (n > 1)
7328 --n;
7329 break;
7330 }
7331 }
7332
7333 our_paren_pos.col = 0;
7334 amount += n * ind_unclosed_wrapped;
7335 }
7336 else if (ind_unclosed_whiteok)
7337 our_paren_pos.col++;
7338 else
7339 {
7340 col = our_paren_pos.col + 1;
7341 while (vim_iswhite(l[col]))
7342 col++;
7343 if (l[col] != NUL) /* In case of trailing space */
7344 our_paren_pos.col = col;
7345 else
7346 our_paren_pos.col++;
7347 }
7348 }
7349
7350 /*
7351 * Find how indented the paren is, or the character after it
7352 * if we did the above "if".
7353 */
7354 if (our_paren_pos.col > 0)
7355 {
7356 getvcol(curwin, &our_paren_pos, &col, NULL, NULL);
7357 if (cur_amount > (int)col)
7358 cur_amount = col;
7359 }
7360 }
7361
7362 if (theline[0] == ')' && ind_matching_paren)
7363 {
7364 /* Line up with the start of the matching paren line. */
7365 }
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007366 else if ((ind_unclosed == 0 && is_if_for_while == 0)
7367 || (!ind_unclosed_noignore
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007368 && *look == '(' && ignore_paren_col == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007369 {
7370 if (cur_amount != MAXCOL)
7371 amount = cur_amount;
7372 }
7373 else
7374 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007375 /* Add ind_unclosed2 for each '(' before our matching one, but
7376 * ignore (void) before the line (ignore_paren_col). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007377 col = our_paren_pos.col;
Bram Moolenaarb21e5842006-04-16 18:30:08 +00007378 while ((int)our_paren_pos.col > ignore_paren_col)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007379 {
7380 --our_paren_pos.col;
7381 switch (*ml_get_pos(&our_paren_pos))
7382 {
7383 case '(': amount += ind_unclosed2;
7384 col = our_paren_pos.col;
7385 break;
7386 case ')': amount -= ind_unclosed2;
7387 col = MAXCOL;
7388 break;
7389 }
7390 }
7391
7392 /* Use ind_unclosed once, when the first '(' is not inside
7393 * braces */
7394 if (col == MAXCOL)
7395 amount += ind_unclosed;
7396 else
7397 {
7398 curwin->w_cursor.lnum = our_paren_pos.lnum;
7399 curwin->w_cursor.col = col;
Bram Moolenaar367bec82011-04-11 14:26:19 +02007400 if (find_match_paren(ind_maxparen, ind_maxcomment) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007401 amount += ind_unclosed2;
7402 else
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007403 {
7404 if (is_if_for_while)
7405 amount += ind_if_for_while;
7406 else
7407 amount += ind_unclosed;
7408 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007409 }
7410 /*
7411 * For a line starting with ')' use the minimum of the two
7412 * positions, to avoid giving it more indent than the previous
7413 * lines:
7414 * func_long_name( if (x
7415 * arg && yy
7416 * ) ^ not here ) ^ not here
7417 */
7418 if (cur_amount < amount)
7419 amount = cur_amount;
7420 }
7421 }
7422
7423 /* add extra indent for a comment */
7424 if (cin_iscomment(theline))
7425 amount += ind_comment;
7426 }
7427
7428 /*
7429 * Are we at least inside braces, then?
7430 */
7431 else
7432 {
7433 trypos = tryposBrace;
7434
7435 ourscope = trypos->lnum;
7436 start = ml_get(ourscope);
7437
7438 /*
7439 * Now figure out how indented the line is in general.
7440 * If the brace was at the start of the line, we use that;
7441 * otherwise, check out the indentation of the line as
7442 * a whole and then add the "imaginary indent" to that.
7443 */
7444 look = skipwhite(start);
7445 if (*look == '{')
7446 {
7447 getvcol(curwin, trypos, &col, NULL, NULL);
7448 amount = col;
7449 if (*start == '{')
7450 start_brace = BRACE_IN_COL0;
7451 else
7452 start_brace = BRACE_AT_START;
7453 }
7454 else
7455 {
7456 /*
7457 * that opening brace might have been on a continuation
7458 * line. if so, find the start of the line.
7459 */
7460 curwin->w_cursor.lnum = ourscope;
7461
7462 /*
7463 * position the cursor over the rightmost paren, so that
7464 * matching it will take us back to the start of the line.
7465 */
7466 lnum = ourscope;
7467 if (find_last_paren(start, '(', ')')
7468 && (trypos = find_match_paren(ind_maxparen,
7469 ind_maxcomment)) != NULL)
7470 lnum = trypos->lnum;
7471
7472 /*
7473 * It could have been something like
7474 * case 1: if (asdf &&
7475 * ldfd) {
7476 * }
7477 */
Bram Moolenaar6ec154b2011-06-12 21:51:08 +02007478 if (ind_js || (ind_keep_case_label
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007479 && cin_iscase(skipwhite(ml_get_curline()), FALSE)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007480 amount = get_indent();
7481 else
7482 amount = skip_label(lnum, &l, ind_maxcomment);
7483
7484 start_brace = BRACE_AT_END;
7485 }
7486
7487 /*
7488 * if we're looking at a closing brace, that's where
7489 * we want to be. otherwise, add the amount of room
7490 * that an indent is supposed to be.
7491 */
7492 if (theline[0] == '}')
7493 {
7494 /*
7495 * they may want closing braces to line up with something
7496 * other than the open brace. indulge them, if so.
7497 */
7498 amount += ind_close_extra;
7499 }
7500 else
7501 {
7502 /*
7503 * If we're looking at an "else", try to find an "if"
7504 * to match it with.
7505 * If we're looking at a "while", try to find a "do"
7506 * to match it with.
7507 */
7508 lookfor = LOOKFOR_INITIAL;
7509 if (cin_iselse(theline))
7510 lookfor = LOOKFOR_IF;
7511 else if (cin_iswhileofdo(theline, cur_curpos.lnum, ind_maxparen))
7512 /* XXX */
7513 lookfor = LOOKFOR_DO;
7514 if (lookfor != LOOKFOR_INITIAL)
7515 {
7516 curwin->w_cursor.lnum = cur_curpos.lnum;
7517 if (find_match(lookfor, ourscope, ind_maxparen,
7518 ind_maxcomment) == OK)
7519 {
7520 amount = get_indent(); /* XXX */
7521 goto theend;
7522 }
7523 }
7524
7525 /*
7526 * We get here if we are not on an "while-of-do" or "else" (or
7527 * failed to find a matching "if").
7528 * Search backwards for something to line up with.
7529 * First set amount for when we don't find anything.
7530 */
7531
7532 /*
7533 * if the '{' is _really_ at the left margin, use the imaginary
7534 * location of a left-margin brace. Otherwise, correct the
7535 * location for ind_open_extra.
7536 */
7537
7538 if (start_brace == BRACE_IN_COL0) /* '{' is in column 0 */
7539 {
7540 amount = ind_open_left_imag;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007541 lookfor_cpp_namespace = TRUE;
7542 }
7543 else if (start_brace == BRACE_AT_START &&
7544 lookfor_cpp_namespace) /* '{' is at start */
7545 {
7546
7547 lookfor_cpp_namespace = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007548 }
7549 else
7550 {
7551 if (start_brace == BRACE_AT_END) /* '{' is at end of line */
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007552 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007553 amount += ind_open_imag;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007554
7555 l = skipwhite(ml_get_curline());
7556 if (cin_is_cpp_namespace(l))
7557 amount += ind_cpp_namespace;
7558 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007559 else
7560 {
7561 /* Compensate for adding ind_open_extra later. */
7562 amount -= ind_open_extra;
7563 if (amount < 0)
7564 amount = 0;
7565 }
7566 }
7567
7568 lookfor_break = FALSE;
7569
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007570 if (cin_iscase(theline, FALSE)) /* it's a switch() label */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007571 {
7572 lookfor = LOOKFOR_CASE; /* find a previous switch() label */
7573 amount += ind_case;
7574 }
7575 else if (cin_isscopedecl(theline)) /* private:, ... */
7576 {
7577 lookfor = LOOKFOR_SCOPEDECL; /* class decl is this block */
7578 amount += ind_scopedecl;
7579 }
7580 else
7581 {
7582 if (ind_case_break && cin_isbreak(theline)) /* break; ... */
7583 lookfor_break = TRUE;
7584
7585 lookfor = LOOKFOR_INITIAL;
7586 amount += ind_level; /* ind_level from start of block */
7587 }
7588 scope_amount = amount;
7589 whilelevel = 0;
7590
7591 /*
7592 * Search backwards. If we find something we recognize, line up
7593 * with that.
7594 *
7595 * if we're looking at an open brace, indent
7596 * the usual amount relative to the conditional
7597 * that opens the block.
7598 */
7599 curwin->w_cursor = cur_curpos;
7600 for (;;)
7601 {
7602 curwin->w_cursor.lnum--;
7603 curwin->w_cursor.col = 0;
7604
7605 /*
7606 * If we went all the way back to the start of our scope, line
7607 * up with it.
7608 */
7609 if (curwin->w_cursor.lnum <= ourscope)
7610 {
7611 /* we reached end of scope:
7612 * if looking for a enum or structure initialization
7613 * go further back:
7614 * if it is an initializer (enum xxx or xxx =), then
7615 * don't add ind_continuation, otherwise it is a variable
7616 * declaration:
7617 * int x,
7618 * here; <-- add ind_continuation
7619 */
7620 if (lookfor == LOOKFOR_ENUM_OR_INIT)
7621 {
7622 if (curwin->w_cursor.lnum == 0
7623 || curwin->w_cursor.lnum
7624 < ourscope - ind_maxparen)
7625 {
7626 /* nothing found (abuse ind_maxparen as limit)
7627 * assume terminated line (i.e. a variable
7628 * initialization) */
7629 if (cont_amount > 0)
7630 amount = cont_amount;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007631 else if (!ind_js)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007632 amount += ind_continuation;
7633 break;
7634 }
7635
7636 l = ml_get_curline();
7637
7638 /*
7639 * If we're in a comment now, skip to the start of the
7640 * comment.
7641 */
7642 trypos = find_start_comment(ind_maxcomment);
7643 if (trypos != NULL)
7644 {
7645 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007646 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007647 continue;
7648 }
7649
7650 /*
7651 * Skip preprocessor directives and blank lines.
7652 */
7653 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7654 continue;
7655
7656 if (cin_nocode(l))
7657 continue;
7658
7659 terminated = cin_isterminated(l, FALSE, TRUE);
7660
7661 /*
7662 * If we are at top level and the line looks like a
7663 * function declaration, we are done
7664 * (it's a variable declaration).
7665 */
7666 if (start_brace != BRACE_IN_COL0
Bram Moolenaarc367faa2011-12-14 20:21:35 +01007667 || !cin_isfuncdecl(&l, curwin->w_cursor.lnum,
7668 0, ind_maxparen, ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007669 {
7670 /* if the line is terminated with another ','
7671 * it is a continued variable initialization.
7672 * don't add extra indent.
7673 * TODO: does not work, if a function
7674 * declaration is split over multiple lines:
7675 * cin_isfuncdecl returns FALSE then.
7676 */
7677 if (terminated == ',')
7678 break;
7679
7680 /* if it es a enum declaration or an assignment,
7681 * we are done.
7682 */
7683 if (terminated != ';' && cin_isinit())
7684 break;
7685
7686 /* nothing useful found */
7687 if (terminated == 0 || terminated == '{')
7688 continue;
7689 }
7690
7691 if (terminated != ';')
7692 {
7693 /* Skip parens and braces. Position the cursor
7694 * over the rightmost paren, so that matching it
7695 * will take us back to the start of the line.
7696 */ /* XXX */
7697 trypos = NULL;
7698 if (find_last_paren(l, '(', ')'))
7699 trypos = find_match_paren(ind_maxparen,
7700 ind_maxcomment);
7701
7702 if (trypos == NULL && find_last_paren(l, '{', '}'))
7703 trypos = find_start_brace(ind_maxcomment);
7704
7705 if (trypos != NULL)
7706 {
7707 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007708 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007709 continue;
7710 }
7711 }
7712
7713 /* it's a variable declaration, add indentation
7714 * like in
7715 * int a,
7716 * b;
7717 */
7718 if (cont_amount > 0)
7719 amount = cont_amount;
7720 else
7721 amount += ind_continuation;
7722 }
7723 else if (lookfor == LOOKFOR_UNTERM)
7724 {
7725 if (cont_amount > 0)
7726 amount = cont_amount;
7727 else
7728 amount += ind_continuation;
7729 }
Bram Moolenaare79d1532011-10-04 18:03:47 +02007730 else
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007731 {
Bram Moolenaare79d1532011-10-04 18:03:47 +02007732 if (lookfor != LOOKFOR_TERM
Bram Moolenaar071d4272004-06-13 20:20:40 +00007733 && lookfor != LOOKFOR_CPP_BASECLASS)
Bram Moolenaare79d1532011-10-04 18:03:47 +02007734 {
7735 amount = scope_amount;
7736 if (theline[0] == '{')
7737 {
7738 amount += ind_open_extra;
7739 added_to_amount = ind_open_extra;
7740 }
7741 }
7742
7743 if (lookfor_cpp_namespace)
7744 {
7745 /*
7746 * Looking for C++ namespace, need to look further
7747 * back.
7748 */
7749 if (curwin->w_cursor.lnum == ourscope)
7750 continue;
7751
7752 if (curwin->w_cursor.lnum == 0
7753 || curwin->w_cursor.lnum
7754 < ourscope - FIND_NAMESPACE_LIM)
7755 break;
7756
7757 l = ml_get_curline();
7758
7759 /* If we're in a comment now, skip to the start of
7760 * the comment. */
7761 trypos = find_start_comment(ind_maxcomment);
7762 if (trypos != NULL)
7763 {
7764 curwin->w_cursor.lnum = trypos->lnum + 1;
7765 curwin->w_cursor.col = 0;
7766 continue;
7767 }
7768
7769 /* Skip preprocessor directives and blank lines. */
7770 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7771 continue;
7772
7773 /* Finally the actual check for "namespace". */
7774 if (cin_is_cpp_namespace(l))
7775 {
7776 amount += ind_cpp_namespace - added_to_amount;
7777 break;
7778 }
7779
7780 if (cin_nocode(l))
7781 continue;
7782 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007783 }
7784 break;
7785 }
7786
7787 /*
7788 * If we're in a comment now, skip to the start of the comment.
7789 */ /* XXX */
7790 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
7791 {
7792 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007793 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007794 continue;
7795 }
7796
7797 l = ml_get_curline();
7798
7799 /*
7800 * If this is a switch() label, may line up relative to that.
Bram Moolenaar18144c82006-04-12 21:52:12 +00007801 * If this is a C++ scope declaration, do the same.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007802 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007803 iscase = cin_iscase(l, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007804 if (iscase || cin_isscopedecl(l))
7805 {
7806 /* we are only looking for cpp base class
7807 * declaration/initialization any longer */
7808 if (lookfor == LOOKFOR_CPP_BASECLASS)
7809 break;
7810
7811 /* When looking for a "do" we are not interested in
7812 * labels. */
7813 if (whilelevel > 0)
7814 continue;
7815
7816 /*
7817 * case xx:
7818 * c = 99 + <- this indent plus continuation
7819 *-> here;
7820 */
7821 if (lookfor == LOOKFOR_UNTERM
7822 || lookfor == LOOKFOR_ENUM_OR_INIT)
7823 {
7824 if (cont_amount > 0)
7825 amount = cont_amount;
7826 else
7827 amount += ind_continuation;
7828 break;
7829 }
7830
7831 /*
7832 * case xx: <- line up with this case
7833 * x = 333;
7834 * case yy:
7835 */
7836 if ( (iscase && lookfor == LOOKFOR_CASE)
7837 || (iscase && lookfor_break)
7838 || (!iscase && lookfor == LOOKFOR_SCOPEDECL))
7839 {
7840 /*
7841 * Check that this case label is not for another
7842 * switch()
7843 */ /* XXX */
7844 if ((trypos = find_start_brace(ind_maxcomment)) ==
7845 NULL || trypos->lnum == ourscope)
7846 {
7847 amount = get_indent(); /* XXX */
7848 break;
7849 }
7850 continue;
7851 }
7852
7853 n = get_indent_nolabel(curwin->w_cursor.lnum); /* XXX */
7854
7855 /*
7856 * case xx: if (cond) <- line up with this if
7857 * y = y + 1;
7858 * -> s = 99;
7859 *
7860 * case xx:
7861 * if (cond) <- line up with this line
7862 * y = y + 1;
7863 * -> s = 99;
7864 */
7865 if (lookfor == LOOKFOR_TERM)
7866 {
7867 if (n)
7868 amount = n;
7869
7870 if (!lookfor_break)
7871 break;
7872 }
7873
7874 /*
7875 * case xx: x = x + 1; <- line up with this x
7876 * -> y = y + 1;
7877 *
7878 * case xx: if (cond) <- line up with this if
7879 * -> y = y + 1;
7880 */
7881 if (n)
7882 {
7883 amount = n;
7884 l = after_label(ml_get_curline());
7885 if (l != NULL && cin_is_cinword(l))
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007886 {
7887 if (theline[0] == '{')
7888 amount += ind_open_extra;
7889 else
7890 amount += ind_level + ind_no_brace;
7891 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007892 break;
7893 }
7894
7895 /*
7896 * Try to get the indent of a statement before the switch
7897 * label. If nothing is found, line up relative to the
7898 * switch label.
7899 * break; <- may line up with this line
7900 * case xx:
7901 * -> y = 1;
7902 */
7903 scope_amount = get_indent() + (iscase /* XXX */
7904 ? ind_case_code : ind_scopedecl_code);
7905 lookfor = ind_case_break ? LOOKFOR_NOBREAK : LOOKFOR_ANY;
7906 continue;
7907 }
7908
7909 /*
7910 * Looking for a switch() label or C++ scope declaration,
7911 * ignore other lines, skip {}-blocks.
7912 */
7913 if (lookfor == LOOKFOR_CASE || lookfor == LOOKFOR_SCOPEDECL)
7914 {
7915 if (find_last_paren(l, '{', '}') && (trypos =
7916 find_start_brace(ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007917 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007918 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007919 curwin->w_cursor.col = 0;
7920 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007921 continue;
7922 }
7923
7924 /*
7925 * Ignore jump labels with nothing after them.
7926 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007927 if (!ind_js && cin_islabel(ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007928 {
7929 l = after_label(ml_get_curline());
7930 if (l == NULL || cin_nocode(l))
7931 continue;
7932 }
7933
7934 /*
7935 * Ignore #defines, #if, etc.
7936 * Ignore comment and empty lines.
7937 * (need to get the line again, cin_islabel() may have
7938 * unlocked it)
7939 */
7940 l = ml_get_curline();
7941 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum)
7942 || cin_nocode(l))
7943 continue;
7944
7945 /*
7946 * Are we at the start of a cpp base class declaration or
7947 * constructor initialization?
7948 */ /* XXX */
Bram Moolenaar18144c82006-04-12 21:52:12 +00007949 n = FALSE;
7950 if (lookfor != LOOKFOR_TERM && ind_cpp_baseclass > 0)
7951 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00007952 n = cin_is_cpp_baseclass(&col);
Bram Moolenaar18144c82006-04-12 21:52:12 +00007953 l = ml_get_curline();
7954 }
7955 if (n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007956 {
7957 if (lookfor == LOOKFOR_UNTERM)
7958 {
7959 if (cont_amount > 0)
7960 amount = cont_amount;
7961 else
7962 amount += ind_continuation;
7963 }
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007964 else if (theline[0] == '{')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007965 {
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007966 /* Need to find start of the declaration. */
7967 lookfor = LOOKFOR_UNTERM;
7968 ind_continuation = 0;
7969 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007970 }
7971 else
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007972 /* XXX */
7973 amount = get_baseclass_amount(col, ind_maxparen,
7974 ind_maxcomment, ind_cpp_baseclass);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007975 break;
7976 }
7977 else if (lookfor == LOOKFOR_CPP_BASECLASS)
7978 {
7979 /* only look, whether there is a cpp base class
Bram Moolenaar18144c82006-04-12 21:52:12 +00007980 * declaration or initialization before the opening brace.
7981 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007982 if (cin_isterminated(l, TRUE, FALSE))
7983 break;
7984 else
7985 continue;
7986 }
7987
7988 /*
7989 * What happens next depends on the line being terminated.
7990 * If terminated with a ',' only consider it terminating if
Bram Moolenaar25394022007-05-10 19:06:20 +00007991 * there is another unterminated statement behind, eg:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007992 * 123,
7993 * sizeof
7994 * here
7995 * Otherwise check whether it is a enumeration or structure
7996 * initialisation (not indented) or a variable declaration
7997 * (indented).
7998 */
7999 terminated = cin_isterminated(l, FALSE, TRUE);
8000
8001 if (terminated == 0 || (lookfor != LOOKFOR_UNTERM
8002 && terminated == ','))
8003 {
8004 /*
8005 * if we're in the middle of a paren thing,
8006 * go back to the line that starts it so
8007 * we can get the right prevailing indent
8008 * if ( foo &&
8009 * bar )
8010 */
8011 /*
8012 * position the cursor over the rightmost paren, so that
8013 * matching it will take us back to the start of the line.
8014 */
8015 (void)find_last_paren(l, '(', ')');
8016 trypos = find_match_paren(
8017 corr_ind_maxparen(ind_maxparen, &cur_curpos),
8018 ind_maxcomment);
8019
8020 /*
8021 * If we are looking for ',', we also look for matching
8022 * braces.
8023 */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00008024 if (trypos == NULL && terminated == ','
8025 && find_last_paren(l, '{', '}'))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008026 trypos = find_start_brace(ind_maxcomment);
8027
8028 if (trypos != NULL)
8029 {
8030 /*
8031 * Check if we are on a case label now. This is
8032 * handled above.
8033 * case xx: if ( asdf &&
8034 * asdf)
8035 */
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008036 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008037 l = ml_get_curline();
Bram Moolenaar3acfc302010-07-11 17:23:02 +02008038 if (cin_iscase(l, FALSE) || cin_isscopedecl(l))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008039 {
8040 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008041 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008042 continue;
8043 }
8044 }
8045
8046 /*
8047 * Skip over continuation lines to find the one to get the
8048 * indent from
8049 * char *usethis = "bla\
8050 * bla",
8051 * here;
8052 */
8053 if (terminated == ',')
8054 {
8055 while (curwin->w_cursor.lnum > 1)
8056 {
8057 l = ml_get(curwin->w_cursor.lnum - 1);
8058 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
8059 break;
8060 --curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008061 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008062 }
8063 }
8064
8065 /*
8066 * Get indent and pointer to text for current line,
8067 * ignoring any jump label. XXX
8068 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02008069 if (!ind_js)
8070 cur_amount = skip_label(curwin->w_cursor.lnum,
Bram Moolenaar071d4272004-06-13 20:20:40 +00008071 &l, ind_maxcomment);
Bram Moolenaar3acfc302010-07-11 17:23:02 +02008072 else
8073 cur_amount = get_indent();
Bram Moolenaar071d4272004-06-13 20:20:40 +00008074 /*
8075 * If this is just above the line we are indenting, and it
8076 * starts with a '{', line it up with this line.
8077 * while (not)
8078 * -> {
8079 * }
8080 */
8081 if (terminated != ',' && lookfor != LOOKFOR_TERM
8082 && theline[0] == '{')
8083 {
8084 amount = cur_amount;
8085 /*
8086 * Only add ind_open_extra when the current line
8087 * doesn't start with a '{', which must have a match
8088 * in the same line (scope is the same). Probably:
8089 * { 1, 2 },
8090 * -> { 3, 4 }
8091 */
8092 if (*skipwhite(l) != '{')
8093 amount += ind_open_extra;
8094
8095 if (ind_cpp_baseclass)
8096 {
8097 /* have to look back, whether it is a cpp base
8098 * class declaration or initialization */
8099 lookfor = LOOKFOR_CPP_BASECLASS;
8100 continue;
8101 }
8102 break;
8103 }
8104
8105 /*
8106 * Check if we are after an "if", "while", etc.
8107 * Also allow " } else".
8108 */
8109 if (cin_is_cinword(l) || cin_iselse(skipwhite(l)))
8110 {
8111 /*
8112 * Found an unterminated line after an if (), line up
8113 * with the last one.
8114 * if (cond)
8115 * 100 +
8116 * -> here;
8117 */
8118 if (lookfor == LOOKFOR_UNTERM
8119 || lookfor == LOOKFOR_ENUM_OR_INIT)
8120 {
8121 if (cont_amount > 0)
8122 amount = cont_amount;
8123 else
8124 amount += ind_continuation;
8125 break;
8126 }
8127
8128 /*
8129 * If this is just above the line we are indenting, we
8130 * are finished.
8131 * while (not)
8132 * -> here;
8133 * Otherwise this indent can be used when the line
8134 * before this is terminated.
8135 * yyy;
8136 * if (stat)
8137 * while (not)
8138 * xxx;
8139 * -> here;
8140 */
8141 amount = cur_amount;
8142 if (theline[0] == '{')
8143 amount += ind_open_extra;
8144 if (lookfor != LOOKFOR_TERM)
8145 {
8146 amount += ind_level + ind_no_brace;
8147 break;
8148 }
8149
8150 /*
8151 * Special trick: when expecting the while () after a
8152 * do, line up with the while()
8153 * do
8154 * x = 1;
8155 * -> here
8156 */
8157 l = skipwhite(ml_get_curline());
8158 if (cin_isdo(l))
8159 {
8160 if (whilelevel == 0)
8161 break;
8162 --whilelevel;
8163 }
8164
8165 /*
8166 * When searching for a terminated line, don't use the
Bram Moolenaar334adf02011-05-25 13:34:04 +02008167 * one between the "if" and the matching "else".
Bram Moolenaar071d4272004-06-13 20:20:40 +00008168 * Need to use the scope of this "else". XXX
8169 * If whilelevel != 0 continue looking for a "do {".
8170 */
Bram Moolenaar334adf02011-05-25 13:34:04 +02008171 if (cin_iselse(l) && whilelevel == 0)
8172 {
8173 /* If we're looking at "} else", let's make sure we
8174 * find the opening brace of the enclosing scope,
8175 * not the one from "if () {". */
8176 if (*l == '}')
8177 curwin->w_cursor.col =
Bram Moolenaar9b83c2f2011-05-25 17:29:44 +02008178 (colnr_T)(l - ml_get_curline()) + 1;
Bram Moolenaar334adf02011-05-25 13:34:04 +02008179
8180 if ((trypos = find_start_brace(ind_maxcomment))
8181 == NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00008182 || find_match(LOOKFOR_IF, trypos->lnum,
Bram Moolenaar334adf02011-05-25 13:34:04 +02008183 ind_maxparen, ind_maxcomment) == FAIL)
8184 break;
8185 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008186 }
8187
8188 /*
8189 * If we're below an unterminated line that is not an
8190 * "if" or something, we may line up with this line or
Bram Moolenaar25394022007-05-10 19:06:20 +00008191 * add something for a continuation line, depending on
Bram Moolenaar071d4272004-06-13 20:20:40 +00008192 * the line before this one.
8193 */
8194 else
8195 {
8196 /*
8197 * Found two unterminated lines on a row, line up with
8198 * the last one.
8199 * c = 99 +
8200 * 100 +
8201 * -> here;
8202 */
8203 if (lookfor == LOOKFOR_UNTERM)
8204 {
8205 /* When line ends in a comma add extra indent */
8206 if (terminated == ',')
8207 amount += ind_continuation;
8208 break;
8209 }
8210
8211 if (lookfor == LOOKFOR_ENUM_OR_INIT)
8212 {
8213 /* Found two lines ending in ',', lineup with the
8214 * lowest one, but check for cpp base class
8215 * declaration/initialization, if it is an
8216 * opening brace or we are looking just for
8217 * enumerations/initializations. */
8218 if (terminated == ',')
8219 {
8220 if (ind_cpp_baseclass == 0)
8221 break;
8222
8223 lookfor = LOOKFOR_CPP_BASECLASS;
8224 continue;
8225 }
8226
8227 /* Ignore unterminated lines in between, but
8228 * reduce indent. */
8229 if (amount > cur_amount)
8230 amount = cur_amount;
8231 }
8232 else
8233 {
8234 /*
8235 * Found first unterminated line on a row, may
8236 * line up with this line, remember its indent
8237 * 100 +
8238 * -> here;
8239 */
8240 amount = cur_amount;
8241
8242 /*
8243 * If previous line ends in ',', check whether we
8244 * are in an initialization or enum
8245 * struct xxx =
8246 * {
8247 * sizeof a,
8248 * 124 };
8249 * or a normal possible continuation line.
8250 * but only, of no other statement has been found
8251 * yet.
8252 */
8253 if (lookfor == LOOKFOR_INITIAL && terminated == ',')
8254 {
8255 lookfor = LOOKFOR_ENUM_OR_INIT;
8256 cont_amount = cin_first_id_amount();
8257 }
8258 else
8259 {
8260 if (lookfor == LOOKFOR_INITIAL
8261 && *l != NUL
8262 && l[STRLEN(l) - 1] == '\\')
8263 /* XXX */
8264 cont_amount = cin_get_equal_amount(
8265 curwin->w_cursor.lnum);
8266 if (lookfor != LOOKFOR_TERM)
8267 lookfor = LOOKFOR_UNTERM;
8268 }
8269 }
8270 }
8271 }
8272
8273 /*
8274 * Check if we are after a while (cond);
8275 * If so: Ignore until the matching "do".
8276 */
8277 /* XXX */
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00008278 else if (cin_iswhileofdo_end(terminated, ind_maxparen,
8279 ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008280 {
8281 /*
8282 * Found an unterminated line after a while ();, line up
8283 * with the last one.
8284 * while (cond);
8285 * 100 + <- line up with this one
8286 * -> here;
8287 */
8288 if (lookfor == LOOKFOR_UNTERM
8289 || lookfor == LOOKFOR_ENUM_OR_INIT)
8290 {
8291 if (cont_amount > 0)
8292 amount = cont_amount;
8293 else
8294 amount += ind_continuation;
8295 break;
8296 }
8297
8298 if (whilelevel == 0)
8299 {
8300 lookfor = LOOKFOR_TERM;
8301 amount = get_indent(); /* XXX */
8302 if (theline[0] == '{')
8303 amount += ind_open_extra;
8304 }
8305 ++whilelevel;
8306 }
8307
8308 /*
8309 * We are after a "normal" statement.
8310 * If we had another statement we can stop now and use the
8311 * indent of that other statement.
8312 * Otherwise the indent of the current statement may be used,
8313 * search backwards for the next "normal" statement.
8314 */
8315 else
8316 {
8317 /*
8318 * Skip single break line, if before a switch label. It
8319 * may be lined up with the case label.
8320 */
8321 if (lookfor == LOOKFOR_NOBREAK
8322 && cin_isbreak(skipwhite(ml_get_curline())))
8323 {
8324 lookfor = LOOKFOR_ANY;
8325 continue;
8326 }
8327
8328 /*
8329 * Handle "do {" line.
8330 */
8331 if (whilelevel > 0)
8332 {
8333 l = cin_skipcomment(ml_get_curline());
8334 if (cin_isdo(l))
8335 {
8336 amount = get_indent(); /* XXX */
8337 --whilelevel;
8338 continue;
8339 }
8340 }
8341
8342 /*
8343 * Found a terminated line above an unterminated line. Add
8344 * the amount for a continuation line.
8345 * x = 1;
8346 * y = foo +
8347 * -> here;
8348 * or
8349 * int x = 1;
8350 * int foo,
8351 * -> here;
8352 */
8353 if (lookfor == LOOKFOR_UNTERM
8354 || lookfor == LOOKFOR_ENUM_OR_INIT)
8355 {
8356 if (cont_amount > 0)
8357 amount = cont_amount;
8358 else
8359 amount += ind_continuation;
8360 break;
8361 }
8362
8363 /*
8364 * Found a terminated line above a terminated line or "if"
8365 * etc. line. Use the amount of the line below us.
8366 * x = 1; x = 1;
8367 * if (asdf) y = 2;
8368 * while (asdf) ->here;
8369 * here;
8370 * ->foo;
8371 */
8372 if (lookfor == LOOKFOR_TERM)
8373 {
8374 if (!lookfor_break && whilelevel == 0)
8375 break;
8376 }
8377
8378 /*
8379 * First line above the one we're indenting is terminated.
8380 * To know what needs to be done look further backward for
8381 * a terminated line.
8382 */
8383 else
8384 {
8385 /*
8386 * position the cursor over the rightmost paren, so
8387 * that matching it will take us back to the start of
8388 * the line. Helps for:
8389 * func(asdr,
8390 * asdfasdf);
8391 * here;
8392 */
8393term_again:
8394 l = ml_get_curline();
8395 if (find_last_paren(l, '(', ')')
8396 && (trypos = find_match_paren(ind_maxparen,
8397 ind_maxcomment)) != NULL)
8398 {
8399 /*
8400 * Check if we are on a case label now. This is
8401 * handled above.
8402 * case xx: if ( asdf &&
8403 * asdf)
8404 */
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008405 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008406 l = ml_get_curline();
Bram Moolenaar3acfc302010-07-11 17:23:02 +02008407 if (cin_iscase(l, FALSE) || cin_isscopedecl(l))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008408 {
8409 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008410 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008411 continue;
8412 }
8413 }
8414
8415 /* When aligning with the case statement, don't align
8416 * with a statement after it.
8417 * case 1: { <-- don't use this { position
8418 * stat;
8419 * }
8420 * case 2:
8421 * stat;
8422 * }
8423 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02008424 iscase = (ind_keep_case_label && cin_iscase(l, FALSE));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008425
8426 /*
8427 * Get indent and pointer to text for current line,
8428 * ignoring any jump label.
8429 */
8430 amount = skip_label(curwin->w_cursor.lnum,
8431 &l, ind_maxcomment);
8432
8433 if (theline[0] == '{')
8434 amount += ind_open_extra;
8435 /* See remark above: "Only add ind_open_extra.." */
Bram Moolenaar18144c82006-04-12 21:52:12 +00008436 l = skipwhite(l);
8437 if (*l == '{')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008438 amount -= ind_open_extra;
8439 lookfor = iscase ? LOOKFOR_ANY : LOOKFOR_TERM;
8440
8441 /*
Bram Moolenaar18144c82006-04-12 21:52:12 +00008442 * When a terminated line starts with "else" skip to
8443 * the matching "if":
8444 * else 3;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008445 * indent this;
Bram Moolenaar18144c82006-04-12 21:52:12 +00008446 * Need to use the scope of this "else". XXX
8447 * If whilelevel != 0 continue looking for a "do {".
8448 */
8449 if (lookfor == LOOKFOR_TERM
8450 && *l != '}'
8451 && cin_iselse(l)
8452 && whilelevel == 0)
8453 {
8454 if ((trypos = find_start_brace(ind_maxcomment))
8455 == NULL
8456 || find_match(LOOKFOR_IF, trypos->lnum,
8457 ind_maxparen, ind_maxcomment) == FAIL)
8458 break;
8459 continue;
8460 }
8461
8462 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008463 * If we're at the end of a block, skip to the start of
8464 * that block.
8465 */
Bram Moolenaar6d8f9c62011-11-30 13:03:28 +01008466 l = ml_get_curline();
Bram Moolenaar50f42ca2011-07-15 14:12:30 +02008467 if (find_last_paren(l, '{', '}')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008468 && (trypos = find_start_brace(ind_maxcomment))
8469 != NULL) /* XXX */
8470 {
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008471 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008472 /* if not "else {" check for terminated again */
8473 /* but skip block for "} else {" */
8474 l = cin_skipcomment(ml_get_curline());
8475 if (*l == '}' || !cin_iselse(l))
8476 goto term_again;
8477 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008478 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008479 }
8480 }
8481 }
8482 }
8483 }
8484 }
8485
8486 /* add extra indent for a comment */
8487 if (cin_iscomment(theline))
8488 amount += ind_comment;
Bram Moolenaar02c707a2010-07-17 17:12:06 +02008489
8490 /* subtract extra left-shift for jump labels */
8491 if (ind_jump_label > 0 && original_line_islabel)
8492 amount -= ind_jump_label;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008493 }
8494
8495 /*
8496 * ok -- we're not inside any sort of structure at all!
8497 *
8498 * this means we're at the top level, and everything should
8499 * basically just match where the previous line is, except
8500 * for the lines immediately following a function declaration,
8501 * which are K&R-style parameters and need to be indented.
8502 */
8503 else
8504 {
8505 /*
8506 * if our line starts with an open brace, forget about any
8507 * prevailing indent and make sure it looks like the start
8508 * of a function
8509 */
8510
8511 if (theline[0] == '{')
8512 {
8513 amount = ind_first_open;
8514 }
8515
8516 /*
8517 * If the NEXT line is a function declaration, the current
8518 * line needs to be indented as a function type spec.
Bram Moolenaar1a89bbe2010-03-02 12:38:22 +01008519 * Don't do this if the current line looks like a comment or if the
8520 * current line is terminated, ie. ends in ';', or if the current line
8521 * contains { or }: "void f() {\n if (1)"
Bram Moolenaar071d4272004-06-13 20:20:40 +00008522 */
8523 else if (cur_curpos.lnum < curbuf->b_ml.ml_line_count
8524 && !cin_nocode(theline)
Bram Moolenaar1a89bbe2010-03-02 12:38:22 +01008525 && vim_strchr(theline, '{') == NULL
8526 && vim_strchr(theline, '}') == NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00008527 && !cin_ends_in(theline, (char_u *)":", NULL)
8528 && !cin_ends_in(theline, (char_u *)",", NULL)
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008529 && cin_isfuncdecl(NULL, cur_curpos.lnum + 1,
8530 cur_curpos.lnum + 1,
8531 ind_maxparen, ind_maxcomment)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008532 && !cin_isterminated(theline, FALSE, TRUE))
8533 {
8534 amount = ind_func_type;
8535 }
8536 else
8537 {
8538 amount = 0;
8539 curwin->w_cursor = cur_curpos;
8540
8541 /* search backwards until we find something we recognize */
8542
8543 while (curwin->w_cursor.lnum > 1)
8544 {
8545 curwin->w_cursor.lnum--;
8546 curwin->w_cursor.col = 0;
8547
8548 l = ml_get_curline();
8549
8550 /*
8551 * If we're in a comment now, skip to the start of the comment.
8552 */ /* XXX */
8553 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
8554 {
8555 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008556 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008557 continue;
8558 }
8559
8560 /*
Bram Moolenaar18144c82006-04-12 21:52:12 +00008561 * Are we at the start of a cpp base class declaration or
8562 * constructor initialization?
Bram Moolenaar071d4272004-06-13 20:20:40 +00008563 */ /* XXX */
Bram Moolenaar18144c82006-04-12 21:52:12 +00008564 n = FALSE;
8565 if (ind_cpp_baseclass != 0 && theline[0] != '{')
8566 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00008567 n = cin_is_cpp_baseclass(&col);
Bram Moolenaar18144c82006-04-12 21:52:12 +00008568 l = ml_get_curline();
8569 }
8570 if (n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008571 {
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00008572 /* XXX */
8573 amount = get_baseclass_amount(col, ind_maxparen,
8574 ind_maxcomment, ind_cpp_baseclass);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008575 break;
8576 }
8577
8578 /*
8579 * Skip preprocessor directives and blank lines.
8580 */
8581 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
8582 continue;
8583
8584 if (cin_nocode(l))
8585 continue;
8586
8587 /*
8588 * If the previous line ends in ',', use one level of
8589 * indentation:
8590 * int foo,
8591 * bar;
8592 * do this before checking for '}' in case of eg.
8593 * enum foobar
8594 * {
8595 * ...
8596 * } foo,
8597 * bar;
8598 */
8599 n = 0;
8600 if (cin_ends_in(l, (char_u *)",", NULL)
8601 || (*l != NUL && (n = l[STRLEN(l) - 1]) == '\\'))
8602 {
8603 /* take us back to opening paren */
8604 if (find_last_paren(l, '(', ')')
8605 && (trypos = find_match_paren(ind_maxparen,
8606 ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008607 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008608
8609 /* For a line ending in ',' that is a continuation line go
8610 * back to the first line with a backslash:
8611 * char *foo = "bla\
8612 * bla",
8613 * here;
8614 */
8615 while (n == 0 && curwin->w_cursor.lnum > 1)
8616 {
8617 l = ml_get(curwin->w_cursor.lnum - 1);
8618 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
8619 break;
8620 --curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008621 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008622 }
8623
8624 amount = get_indent(); /* XXX */
8625
8626 if (amount == 0)
8627 amount = cin_first_id_amount();
8628 if (amount == 0)
8629 amount = ind_continuation;
8630 break;
8631 }
8632
8633 /*
8634 * If the line looks like a function declaration, and we're
8635 * not in a comment, put it the left margin.
8636 */
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008637 if (cin_isfuncdecl(NULL, cur_curpos.lnum, 0,
8638 ind_maxparen, ind_maxcomment)) /* XXX */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008639 break;
8640 l = ml_get_curline();
8641
8642 /*
8643 * Finding the closing '}' of a previous function. Put
8644 * current line at the left margin. For when 'cino' has "fs".
8645 */
8646 if (*skipwhite(l) == '}')
8647 break;
8648
8649 /* (matching {)
8650 * If the previous line ends on '};' (maybe followed by
8651 * comments) align at column 0. For example:
8652 * char *string_array[] = { "foo",
8653 * / * x * / "b};ar" }; / * foobar * /
8654 */
8655 if (cin_ends_in(l, (char_u *)"};", NULL))
8656 break;
8657
8658 /*
Bram Moolenaar3388bb42011-11-30 17:20:23 +01008659 * Find a line only has a semicolon that belongs to a previous
8660 * line ending in '}', e.g. before an #endif. Don't increase
8661 * indent then.
8662 */
8663 if (*(look = skipwhite(l)) == ';' && cin_nocode(look + 1))
8664 {
8665 pos_T curpos_save = curwin->w_cursor;
8666
8667 while (curwin->w_cursor.lnum > 1)
8668 {
8669 look = ml_get(--curwin->w_cursor.lnum);
8670 if (!(cin_nocode(look) || cin_ispreproc_cont(
8671 &look, &curwin->w_cursor.lnum)))
8672 break;
8673 }
8674 if (curwin->w_cursor.lnum > 0
8675 && cin_ends_in(look, (char_u *)"}", NULL))
8676 break;
8677
8678 curwin->w_cursor = curpos_save;
8679 }
8680
8681 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008682 * If the PREVIOUS line is a function declaration, the current
8683 * line (and the ones that follow) needs to be indented as
8684 * parameters.
8685 */
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008686 if (cin_isfuncdecl(&l, curwin->w_cursor.lnum, 0,
8687 ind_maxparen, ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008688 {
8689 amount = ind_param;
8690 break;
8691 }
8692
8693 /*
8694 * If the previous line ends in ';' and the line before the
8695 * previous line ends in ',' or '\', ident to column zero:
8696 * int foo,
8697 * bar;
8698 * indent_to_0 here;
8699 */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00008700 if (cin_ends_in(l, (char_u *)";", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008701 {
8702 l = ml_get(curwin->w_cursor.lnum - 1);
8703 if (cin_ends_in(l, (char_u *)",", NULL)
8704 || (*l != NUL && l[STRLEN(l) - 1] == '\\'))
8705 break;
8706 l = ml_get_curline();
8707 }
8708
8709 /*
8710 * Doesn't look like anything interesting -- so just
8711 * use the indent of this line.
8712 *
8713 * Position the cursor over the rightmost paren, so that
8714 * matching it will take us back to the start of the line.
8715 */
8716 find_last_paren(l, '(', ')');
8717
8718 if ((trypos = find_match_paren(ind_maxparen,
8719 ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008720 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008721 amount = get_indent(); /* XXX */
8722 break;
8723 }
8724
8725 /* add extra indent for a comment */
8726 if (cin_iscomment(theline))
8727 amount += ind_comment;
8728
8729 /* add extra indent if the previous line ended in a backslash:
8730 * "asdfasdf\
8731 * here";
8732 * char *foo = "asdf\
8733 * here";
8734 */
8735 if (cur_curpos.lnum > 1)
8736 {
8737 l = ml_get(cur_curpos.lnum - 1);
8738 if (*l != NUL && l[STRLEN(l) - 1] == '\\')
8739 {
8740 cur_amount = cin_get_equal_amount(cur_curpos.lnum - 1);
8741 if (cur_amount > 0)
8742 amount = cur_amount;
8743 else if (cur_amount == 0)
8744 amount += ind_continuation;
8745 }
8746 }
8747 }
8748 }
8749
8750theend:
8751 /* put the cursor back where it belongs */
8752 curwin->w_cursor = cur_curpos;
8753
8754 vim_free(linecopy);
8755
8756 if (amount < 0)
8757 return 0;
8758 return amount;
8759}
8760
8761 static int
8762find_match(lookfor, ourscope, ind_maxparen, ind_maxcomment)
8763 int lookfor;
8764 linenr_T ourscope;
8765 int ind_maxparen;
8766 int ind_maxcomment;
8767{
8768 char_u *look;
8769 pos_T *theirscope;
8770 char_u *mightbeif;
8771 int elselevel;
8772 int whilelevel;
8773
8774 if (lookfor == LOOKFOR_IF)
8775 {
8776 elselevel = 1;
8777 whilelevel = 0;
8778 }
8779 else
8780 {
8781 elselevel = 0;
8782 whilelevel = 1;
8783 }
8784
8785 curwin->w_cursor.col = 0;
8786
8787 while (curwin->w_cursor.lnum > ourscope + 1)
8788 {
8789 curwin->w_cursor.lnum--;
8790 curwin->w_cursor.col = 0;
8791
8792 look = cin_skipcomment(ml_get_curline());
8793 if (cin_iselse(look)
8794 || cin_isif(look)
8795 || cin_isdo(look) /* XXX */
8796 || cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
8797 {
8798 /*
8799 * if we've gone outside the braces entirely,
8800 * we must be out of scope...
8801 */
8802 theirscope = find_start_brace(ind_maxcomment); /* XXX */
8803 if (theirscope == NULL)
8804 break;
8805
8806 /*
8807 * and if the brace enclosing this is further
8808 * back than the one enclosing the else, we're
8809 * out of luck too.
8810 */
8811 if (theirscope->lnum < ourscope)
8812 break;
8813
8814 /*
8815 * and if they're enclosed in a *deeper* brace,
8816 * then we can ignore it because it's in a
8817 * different scope...
8818 */
8819 if (theirscope->lnum > ourscope)
8820 continue;
8821
8822 /*
8823 * if it was an "else" (that's not an "else if")
8824 * then we need to go back to another if, so
8825 * increment elselevel
8826 */
8827 look = cin_skipcomment(ml_get_curline());
8828 if (cin_iselse(look))
8829 {
8830 mightbeif = cin_skipcomment(look + 4);
8831 if (!cin_isif(mightbeif))
8832 ++elselevel;
8833 continue;
8834 }
8835
8836 /*
8837 * if it was a "while" then we need to go back to
8838 * another "do", so increment whilelevel. XXX
8839 */
8840 if (cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
8841 {
8842 ++whilelevel;
8843 continue;
8844 }
8845
8846 /* If it's an "if" decrement elselevel */
8847 look = cin_skipcomment(ml_get_curline());
8848 if (cin_isif(look))
8849 {
8850 elselevel--;
8851 /*
8852 * When looking for an "if" ignore "while"s that
8853 * get in the way.
8854 */
8855 if (elselevel == 0 && lookfor == LOOKFOR_IF)
8856 whilelevel = 0;
8857 }
8858
8859 /* If it's a "do" decrement whilelevel */
8860 if (cin_isdo(look))
8861 whilelevel--;
8862
8863 /*
8864 * if we've used up all the elses, then
8865 * this must be the if that we want!
8866 * match the indent level of that if.
8867 */
8868 if (elselevel <= 0 && whilelevel <= 0)
8869 {
8870 return OK;
8871 }
8872 }
8873 }
8874 return FAIL;
8875}
8876
8877# if defined(FEAT_EVAL) || defined(PROTO)
8878/*
8879 * Get indent level from 'indentexpr'.
8880 */
8881 int
8882get_expr_indent()
8883{
8884 int indent;
Bram Moolenaar8fe8d9e2013-02-13 16:10:17 +01008885 pos_T save_pos;
8886 colnr_T save_curswant;
8887 int save_set_curswant;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008888 int save_State;
Bram Moolenaard1f56e62006-02-22 21:25:37 +00008889 int use_sandbox = was_set_insecurely((char_u *)"indentexpr",
8890 OPT_LOCAL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008891
Bram Moolenaar8fe8d9e2013-02-13 16:10:17 +01008892 /* Save and restore cursor position and curswant, in case it was changed
8893 * via :normal commands */
8894 save_pos = curwin->w_cursor;
8895 save_curswant = curwin->w_curswant;
8896 save_set_curswant = curwin->w_set_curswant;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008897 set_vim_var_nr(VV_LNUM, curwin->w_cursor.lnum);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00008898 if (use_sandbox)
8899 ++sandbox;
8900 ++textlock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008901 indent = eval_to_number(curbuf->b_p_inde);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00008902 if (use_sandbox)
8903 --sandbox;
8904 --textlock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008905
8906 /* Restore the cursor position so that 'indentexpr' doesn't need to.
8907 * Pretend to be in Insert mode, allow cursor past end of line for "o"
8908 * command. */
8909 save_State = State;
8910 State = INSERT;
Bram Moolenaar8fe8d9e2013-02-13 16:10:17 +01008911 curwin->w_cursor = save_pos;
8912 curwin->w_curswant = save_curswant;
8913 curwin->w_set_curswant = save_set_curswant;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008914 check_cursor();
8915 State = save_State;
8916
8917 /* If there is an error, just keep the current indent. */
8918 if (indent < 0)
8919 indent = get_indent();
8920
8921 return indent;
8922}
8923# endif
8924
8925#endif /* FEAT_CINDENT */
8926
8927#if defined(FEAT_LISP) || defined(PROTO)
8928
8929static int lisp_match __ARGS((char_u *p));
8930
8931 static int
8932lisp_match(p)
8933 char_u *p;
8934{
8935 char_u buf[LSIZE];
8936 int len;
8937 char_u *word = p_lispwords;
8938
8939 while (*word != NUL)
8940 {
8941 (void)copy_option_part(&word, buf, LSIZE, ",");
8942 len = (int)STRLEN(buf);
8943 if (STRNCMP(buf, p, len) == 0 && p[len] == ' ')
8944 return TRUE;
8945 }
8946 return FALSE;
8947}
8948
8949/*
8950 * When 'p' is present in 'cpoptions, a Vi compatible method is used.
8951 * The incompatible newer method is quite a bit better at indenting
8952 * code in lisp-like languages than the traditional one; it's still
8953 * mostly heuristics however -- Dirk van Deun, dirk@rave.org
8954 *
8955 * TODO:
8956 * Findmatch() should be adapted for lisp, also to make showmatch
8957 * work correctly: now (v5.3) it seems all C/C++ oriented:
8958 * - it does not recognize the #\( and #\) notations as character literals
8959 * - it doesn't know about comments starting with a semicolon
8960 * - it incorrectly interprets '(' as a character literal
8961 * All this messes up get_lisp_indent in some rare cases.
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008962 * Update from Sergey Khorev:
8963 * I tried to fix the first two issues.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008964 */
8965 int
8966get_lisp_indent()
8967{
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008968 pos_T *pos, realpos, paren;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008969 int amount;
8970 char_u *that;
8971 colnr_T col;
8972 colnr_T firsttry;
8973 int parencount, quotecount;
8974 int vi_lisp;
8975
8976 /* Set vi_lisp to use the vi-compatible method */
8977 vi_lisp = (vim_strchr(p_cpo, CPO_LISP) != NULL);
8978
8979 realpos = curwin->w_cursor;
8980 curwin->w_cursor.col = 0;
8981
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008982 if ((pos = findmatch(NULL, '(')) == NULL)
8983 pos = findmatch(NULL, '[');
8984 else
8985 {
8986 paren = *pos;
8987 pos = findmatch(NULL, '[');
8988 if (pos == NULL || ltp(pos, &paren))
8989 pos = &paren;
8990 }
8991 if (pos != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008992 {
8993 /* Extra trick: Take the indent of the first previous non-white
8994 * line that is at the same () level. */
8995 amount = -1;
8996 parencount = 0;
8997
8998 while (--curwin->w_cursor.lnum >= pos->lnum)
8999 {
9000 if (linewhite(curwin->w_cursor.lnum))
9001 continue;
9002 for (that = ml_get_curline(); *that != NUL; ++that)
9003 {
9004 if (*that == ';')
9005 {
9006 while (*(that + 1) != NUL)
9007 ++that;
9008 continue;
9009 }
9010 if (*that == '\\')
9011 {
9012 if (*(that + 1) != NUL)
9013 ++that;
9014 continue;
9015 }
9016 if (*that == '"' && *(that + 1) != NUL)
9017 {
Bram Moolenaar15ff6c12006-09-15 18:18:09 +00009018 while (*++that && *that != '"')
9019 {
9020 /* skipping escaped characters in the string */
9021 if (*that == '\\')
9022 {
9023 if (*++that == NUL)
9024 break;
9025 if (that[1] == NUL)
9026 {
9027 ++that;
9028 break;
9029 }
9030 }
9031 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009032 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00009033 if (*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00009034 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00009035 else if (*that == ')' || *that == ']')
Bram Moolenaar071d4272004-06-13 20:20:40 +00009036 --parencount;
9037 }
9038 if (parencount == 0)
9039 {
9040 amount = get_indent();
9041 break;
9042 }
9043 }
9044
9045 if (amount == -1)
9046 {
9047 curwin->w_cursor.lnum = pos->lnum;
9048 curwin->w_cursor.col = pos->col;
9049 col = pos->col;
9050
9051 that = ml_get_curline();
9052
9053 if (vi_lisp && get_indent() == 0)
9054 amount = 2;
9055 else
9056 {
9057 amount = 0;
9058 while (*that && col)
9059 {
9060 amount += lbr_chartabsize_adv(&that, (colnr_T)amount);
9061 col--;
9062 }
9063
9064 /*
9065 * Some keywords require "body" indenting rules (the
9066 * non-standard-lisp ones are Scheme special forms):
9067 *
9068 * (let ((a 1)) instead (let ((a 1))
9069 * (...)) of (...))
9070 */
9071
Bram Moolenaar325b7a22004-07-05 15:58:32 +00009072 if (!vi_lisp && (*that == '(' || *that == '[')
9073 && lisp_match(that + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009074 amount += 2;
9075 else
9076 {
9077 that++;
9078 amount++;
9079 firsttry = amount;
9080
9081 while (vim_iswhite(*that))
9082 {
9083 amount += lbr_chartabsize(that, (colnr_T)amount);
9084 ++that;
9085 }
9086
9087 if (*that && *that != ';') /* not a comment line */
9088 {
Bram Moolenaare21877a2008-02-13 09:58:14 +00009089 /* test *that != '(' to accommodate first let/do
Bram Moolenaar071d4272004-06-13 20:20:40 +00009090 * argument if it is more than one line */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00009091 if (!vi_lisp && *that != '(' && *that != '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00009092 firsttry++;
9093
9094 parencount = 0;
9095 quotecount = 0;
9096
9097 if (vi_lisp
9098 || (*that != '"'
9099 && *that != '\''
9100 && *that != '#'
9101 && (*that < '0' || *that > '9')))
9102 {
9103 while (*that
9104 && (!vim_iswhite(*that)
9105 || quotecount
9106 || parencount)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00009107 && (!((*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00009108 && !quotecount
9109 && !parencount
9110 && vi_lisp)))
9111 {
9112 if (*that == '"')
9113 quotecount = !quotecount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00009114 if ((*that == '(' || *that == '[')
9115 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009116 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00009117 if ((*that == ')' || *that == ']')
9118 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009119 --parencount;
9120 if (*that == '\\' && *(that+1) != NUL)
9121 amount += lbr_chartabsize_adv(&that,
9122 (colnr_T)amount);
9123 amount += lbr_chartabsize_adv(&that,
9124 (colnr_T)amount);
9125 }
9126 }
9127 while (vim_iswhite(*that))
9128 {
9129 amount += lbr_chartabsize(that, (colnr_T)amount);
9130 that++;
9131 }
9132 if (!*that || *that == ';')
9133 amount = firsttry;
9134 }
9135 }
9136 }
9137 }
9138 }
9139 else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00009140 amount = 0; /* no matching '(' or '[' found, use zero indent */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009141
9142 curwin->w_cursor = realpos;
9143
9144 return amount;
9145}
9146#endif /* FEAT_LISP */
9147
9148 void
9149prepare_to_exit()
9150{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00009151#if defined(SIGHUP) && defined(SIG_IGN)
9152 /* Ignore SIGHUP, because a dropped connection causes a read error, which
9153 * makes Vim exit and then handling SIGHUP causes various reentrance
9154 * problems. */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00009155 signal(SIGHUP, SIG_IGN);
9156#endif
9157
Bram Moolenaar071d4272004-06-13 20:20:40 +00009158#ifdef FEAT_GUI
9159 if (gui.in_use)
9160 {
9161 gui.dying = TRUE;
9162 out_trash(); /* trash any pending output */
9163 }
9164 else
9165#endif
9166 {
9167 windgoto((int)Rows - 1, 0);
9168
9169 /*
9170 * Switch terminal mode back now, so messages end up on the "normal"
9171 * screen (if there are two screens).
9172 */
9173 settmode(TMODE_COOK);
9174#ifdef WIN3264
9175 if (can_end_termcap_mode(FALSE) == TRUE)
9176#endif
9177 stoptermcap();
9178 out_flush();
9179 }
9180}
9181
9182/*
9183 * Preserve files and exit.
9184 * When called IObuff must contain a message.
Bram Moolenaarbec9c202013-09-05 21:41:39 +02009185 * NOTE: This may be called from deathtrap() in a signal handler, avoid unsafe
9186 * functions, such as allocating memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009187 */
9188 void
9189preserve_exit()
9190{
9191 buf_T *buf;
9192
9193 prepare_to_exit();
9194
Bram Moolenaar4770d092006-01-12 23:22:24 +00009195 /* Setting this will prevent free() calls. That avoids calling free()
9196 * recursively when free() was invoked with a bad pointer. */
9197 really_exiting = TRUE;
9198
Bram Moolenaar071d4272004-06-13 20:20:40 +00009199 out_str(IObuff);
9200 screen_start(); /* don't know where cursor is now */
9201 out_flush();
9202
9203 ml_close_notmod(); /* close all not-modified buffers */
9204
9205 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
9206 {
9207 if (buf->b_ml.ml_mfp != NULL && buf->b_ml.ml_mfp->mf_fname != NULL)
9208 {
Bram Moolenaarbec9c202013-09-05 21:41:39 +02009209 OUT_STR("Vim: preserving files...\n");
Bram Moolenaar071d4272004-06-13 20:20:40 +00009210 screen_start(); /* don't know where cursor is now */
9211 out_flush();
9212 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
9213 break;
9214 }
9215 }
9216
9217 ml_close_all(FALSE); /* close all memfiles, without deleting */
9218
Bram Moolenaarbec9c202013-09-05 21:41:39 +02009219 OUT_STR("Vim: Finished.\n");
Bram Moolenaar071d4272004-06-13 20:20:40 +00009220
9221 getout(1);
9222}
9223
9224/*
9225 * return TRUE if "fname" exists.
9226 */
9227 int
9228vim_fexists(fname)
9229 char_u *fname;
9230{
9231 struct stat st;
9232
9233 if (mch_stat((char *)fname, &st))
9234 return FALSE;
9235 return TRUE;
9236}
9237
9238/*
9239 * Check for CTRL-C pressed, but only once in a while.
9240 * Should be used instead of ui_breakcheck() for functions that check for
9241 * each line in the file. Calling ui_breakcheck() each time takes too much
9242 * time, because it can be a system call.
9243 */
9244
9245#ifndef BREAKCHECK_SKIP
9246# ifdef FEAT_GUI /* assume the GUI only runs on fast computers */
9247# define BREAKCHECK_SKIP 200
9248# else
9249# define BREAKCHECK_SKIP 32
9250# endif
9251#endif
9252
9253static int breakcheck_count = 0;
9254
9255 void
9256line_breakcheck()
9257{
9258 if (++breakcheck_count >= BREAKCHECK_SKIP)
9259 {
9260 breakcheck_count = 0;
9261 ui_breakcheck();
9262 }
9263}
9264
9265/*
9266 * Like line_breakcheck() but check 10 times less often.
9267 */
9268 void
9269fast_breakcheck()
9270{
9271 if (++breakcheck_count >= BREAKCHECK_SKIP * 10)
9272 {
9273 breakcheck_count = 0;
9274 ui_breakcheck();
9275 }
9276}
9277
9278/*
Bram Moolenaard7834d32009-12-02 16:14:36 +00009279 * Invoke expand_wildcards() for one pattern.
9280 * Expand items like "%:h" before the expansion.
9281 * Returns OK or FAIL.
9282 */
9283 int
9284expand_wildcards_eval(pat, num_file, file, flags)
9285 char_u **pat; /* pointer to input pattern */
9286 int *num_file; /* resulting number of files */
9287 char_u ***file; /* array of resulting files */
9288 int flags; /* EW_DIR, etc. */
9289{
9290 int ret = FAIL;
9291 char_u *eval_pat = NULL;
9292 char_u *exp_pat = *pat;
9293 char_u *ignored_msg;
9294 int usedlen;
9295
9296 if (*exp_pat == '%' || *exp_pat == '#' || *exp_pat == '<')
9297 {
9298 ++emsg_off;
9299 eval_pat = eval_vars(exp_pat, exp_pat, &usedlen,
9300 NULL, &ignored_msg, NULL);
9301 --emsg_off;
9302 if (eval_pat != NULL)
9303 exp_pat = concat_str(eval_pat, exp_pat + usedlen);
9304 }
9305
9306 if (exp_pat != NULL)
9307 ret = expand_wildcards(1, &exp_pat, num_file, file, flags);
9308
9309 if (eval_pat != NULL)
9310 {
9311 vim_free(exp_pat);
9312 vim_free(eval_pat);
9313 }
9314
9315 return ret;
9316}
9317
9318/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00009319 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching
9320 * 'wildignore'.
Bram Moolenaar9e193ac2010-07-19 23:11:27 +02009321 * Returns OK or FAIL. When FAIL then "num_file" won't be set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009322 */
9323 int
9324expand_wildcards(num_pat, pat, num_file, file, flags)
9325 int num_pat; /* number of input patterns */
9326 char_u **pat; /* array of input patterns */
9327 int *num_file; /* resulting number of files */
9328 char_u ***file; /* array of resulting files */
9329 int flags; /* EW_DIR, etc. */
9330{
9331 int retval;
9332 int i, j;
9333 char_u *p;
9334 int non_suf_match; /* number without matching suffix */
9335
9336 retval = gen_expand_wildcards(num_pat, pat, num_file, file, flags);
9337
9338 /* When keeping all matches, return here */
Bram Moolenaar9e193ac2010-07-19 23:11:27 +02009339 if ((flags & EW_KEEPALL) || retval == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009340 return retval;
9341
9342#ifdef FEAT_WILDIGN
9343 /*
9344 * Remove names that match 'wildignore'.
9345 */
9346 if (*p_wig)
9347 {
9348 char_u *ffname;
9349
9350 /* check all files in (*file)[] */
9351 for (i = 0; i < *num_file; ++i)
9352 {
9353 ffname = FullName_save((*file)[i], FALSE);
9354 if (ffname == NULL) /* out of memory */
9355 break;
9356# ifdef VMS
9357 vms_remove_version(ffname);
9358# endif
9359 if (match_file_list(p_wig, (*file)[i], ffname))
9360 {
9361 /* remove this matching file from the list */
9362 vim_free((*file)[i]);
9363 for (j = i; j + 1 < *num_file; ++j)
9364 (*file)[j] = (*file)[j + 1];
9365 --*num_file;
9366 --i;
9367 }
9368 vim_free(ffname);
9369 }
9370 }
9371#endif
9372
9373 /*
9374 * Move the names where 'suffixes' match to the end.
9375 */
9376 if (*num_file > 1)
9377 {
9378 non_suf_match = 0;
9379 for (i = 0; i < *num_file; ++i)
9380 {
9381 if (!match_suffix((*file)[i]))
9382 {
9383 /*
9384 * Move the name without matching suffix to the front
9385 * of the list.
9386 */
9387 p = (*file)[i];
9388 for (j = i; j > non_suf_match; --j)
9389 (*file)[j] = (*file)[j - 1];
9390 (*file)[non_suf_match++] = p;
9391 }
9392 }
9393 }
9394
9395 return retval;
9396}
9397
9398/*
9399 * Return TRUE if "fname" matches with an entry in 'suffixes'.
9400 */
9401 int
9402match_suffix(fname)
9403 char_u *fname;
9404{
9405 int fnamelen, setsuflen;
9406 char_u *setsuf;
9407#define MAXSUFLEN 30 /* maximum length of a file suffix */
9408 char_u suf_buf[MAXSUFLEN];
9409
9410 fnamelen = (int)STRLEN(fname);
9411 setsuflen = 0;
9412 for (setsuf = p_su; *setsuf; )
9413 {
9414 setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
Bram Moolenaar055a2ba2009-07-14 19:40:21 +00009415 if (setsuflen == 0)
9416 {
9417 char_u *tail = gettail(fname);
9418
9419 /* empty entry: match name without a '.' */
9420 if (vim_strchr(tail, '.') == NULL)
9421 {
9422 setsuflen = 1;
9423 break;
9424 }
9425 }
9426 else
9427 {
9428 if (fnamelen >= setsuflen
9429 && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
9430 (size_t)setsuflen) == 0)
9431 break;
9432 setsuflen = 0;
9433 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009434 }
9435 return (setsuflen != 0);
9436}
9437
9438#if !defined(NO_EXPANDPATH) || defined(PROTO)
9439
9440# ifdef VIM_BACKTICK
9441static int vim_backtick __ARGS((char_u *p));
9442static int expand_backtick __ARGS((garray_T *gap, char_u *pat, int flags));
9443# endif
9444
9445# if defined(MSDOS) || defined(FEAT_GUI_W16) || defined(WIN3264)
9446/*
9447 * File name expansion code for MS-DOS, Win16 and Win32. It's here because
9448 * it's shared between these systems.
9449 */
9450# if defined(DJGPP) || defined(PROTO)
9451# define _cdecl /* DJGPP doesn't have this */
9452# else
9453# ifdef __BORLANDC__
9454# define _cdecl _RTLENTRYF
9455# endif
9456# endif
9457
9458/*
9459 * comparison function for qsort in dos_expandpath()
9460 */
9461 static int _cdecl
9462pstrcmp(const void *a, const void *b)
9463{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00009464 return (pathcmp(*(char **)a, *(char **)b, -1));
Bram Moolenaar071d4272004-06-13 20:20:40 +00009465}
9466
9467# ifndef WIN3264
9468 static void
9469namelowcpy(
9470 char_u *d,
9471 char_u *s)
9472{
9473# ifdef DJGPP
9474 if (USE_LONG_FNAME) /* don't lower case on Windows 95/NT systems */
9475 while (*s)
9476 *d++ = *s++;
9477 else
9478# endif
9479 while (*s)
9480 *d++ = TOLOWER_LOC(*s++);
9481 *d = NUL;
9482}
9483# endif
9484
9485/*
Bram Moolenaar231334e2005-07-25 20:46:57 +00009486 * Recursively expand one path component into all matching files and/or
9487 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009488 * Return the number of matches found.
9489 * "path" has backslashes before chars that are not to be expanded, starting
9490 * at "path[wildoff]".
Bram Moolenaar231334e2005-07-25 20:46:57 +00009491 * Return the number of matches found.
9492 * NOTE: much of this is identical to unix_expandpath(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00009493 */
9494 static int
9495dos_expandpath(
9496 garray_T *gap,
9497 char_u *path,
9498 int wildoff,
Bram Moolenaar231334e2005-07-25 20:46:57 +00009499 int flags, /* EW_* flags */
Bram Moolenaar25394022007-05-10 19:06:20 +00009500 int didstar) /* expanded "**" once already */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009501{
Bram Moolenaar231334e2005-07-25 20:46:57 +00009502 char_u *buf;
9503 char_u *path_end;
9504 char_u *p, *s, *e;
9505 int start_len = gap->ga_len;
9506 char_u *pat;
9507 regmatch_T regmatch;
9508 int starts_with_dot;
9509 int matches;
9510 int len;
9511 int starstar = FALSE;
9512 static int stardepth = 0; /* depth for "**" expansion */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009513#ifdef WIN3264
9514 WIN32_FIND_DATA fb;
9515 HANDLE hFind = (HANDLE)0;
9516# ifdef FEAT_MBYTE
9517 WIN32_FIND_DATAW wfb;
9518 WCHAR *wn = NULL; /* UCS-2 name, NULL when not used. */
9519# endif
9520#else
9521 struct ffblk fb;
9522#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009523 char_u *matchname;
Bram Moolenaar231334e2005-07-25 20:46:57 +00009524 int ok;
9525
9526 /* Expanding "**" may take a long time, check for CTRL-C. */
9527 if (stardepth > 0)
9528 {
9529 ui_breakcheck();
9530 if (got_int)
9531 return 0;
9532 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009533
9534 /* make room for file name */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009535 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009536 if (buf == NULL)
9537 return 0;
9538
9539 /*
9540 * Find the first part in the path name that contains a wildcard or a ~1.
9541 * Copy it into buf, including the preceding characters.
9542 */
9543 p = buf;
9544 s = buf;
9545 e = NULL;
9546 path_end = path;
9547 while (*path_end != NUL)
9548 {
9549 /* May ignore a wildcard that has a backslash before it; it will
9550 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
9551 if (path_end >= path + wildoff && rem_backslash(path_end))
9552 *p++ = *path_end++;
9553 else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
9554 {
9555 if (e != NULL)
9556 break;
9557 s = p + 1;
9558 }
9559 else if (path_end >= path + wildoff
9560 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
9561 e = p;
9562#ifdef FEAT_MBYTE
9563 if (has_mbyte)
9564 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00009565 len = (*mb_ptr2len)(path_end);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009566 STRNCPY(p, path_end, len);
9567 p += len;
9568 path_end += len;
9569 }
9570 else
9571#endif
9572 *p++ = *path_end++;
9573 }
9574 e = p;
9575 *e = NUL;
9576
9577 /* now we have one wildcard component between s and e */
9578 /* Remove backslashes between "wildoff" and the start of the wildcard
9579 * component. */
9580 for (p = buf + wildoff; p < s; ++p)
9581 if (rem_backslash(p))
9582 {
Bram Moolenaar8c8de832008-06-24 22:58:06 +00009583 STRMOVE(p, p + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009584 --e;
9585 --s;
9586 }
9587
Bram Moolenaar231334e2005-07-25 20:46:57 +00009588 /* Check for "**" between "s" and "e". */
9589 for (p = s; p < e; ++p)
9590 if (p[0] == '*' && p[1] == '*')
9591 starstar = TRUE;
9592
Bram Moolenaar071d4272004-06-13 20:20:40 +00009593 starts_with_dot = (*s == '.');
9594 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
9595 if (pat == NULL)
9596 {
9597 vim_free(buf);
9598 return 0;
9599 }
9600
9601 /* compile the regexp into a program */
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009602 if (flags & (EW_NOERROR | EW_NOTWILD))
Bram Moolenaarb5609832011-07-20 15:04:58 +02009603 ++emsg_silent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009604 regmatch.rm_ic = TRUE; /* Always ignore case */
9605 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009606 if (flags & (EW_NOERROR | EW_NOTWILD))
Bram Moolenaarb5609832011-07-20 15:04:58 +02009607 --emsg_silent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009608 vim_free(pat);
9609
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009610 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009611 {
9612 vim_free(buf);
9613 return 0;
9614 }
9615
9616 /* remember the pattern or file name being looked for */
9617 matchname = vim_strsave(s);
9618
Bram Moolenaar231334e2005-07-25 20:46:57 +00009619 /* If "**" is by itself, this is the first time we encounter it and more
9620 * is following then find matches without any directory. */
9621 if (!didstar && stardepth < 100 && starstar && e - s == 2
9622 && *path_end == '/')
9623 {
9624 STRCPY(s, path_end + 1);
9625 ++stardepth;
9626 (void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
9627 --stardepth;
9628 }
9629
Bram Moolenaar071d4272004-06-13 20:20:40 +00009630 /* Scan all files in the directory with "dir/ *.*" */
9631 STRCPY(s, "*.*");
9632#ifdef WIN3264
9633# ifdef FEAT_MBYTE
9634 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
9635 {
9636 /* The active codepage differs from 'encoding'. Attempt using the
9637 * wide function. If it fails because it is not implemented fall back
9638 * to the non-wide version (for Windows 98) */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009639 wn = enc_to_utf16(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009640 if (wn != NULL)
9641 {
9642 hFind = FindFirstFileW(wn, &wfb);
9643 if (hFind == INVALID_HANDLE_VALUE
9644 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
9645 {
9646 vim_free(wn);
9647 wn = NULL;
9648 }
9649 }
9650 }
9651
9652 if (wn == NULL)
9653# endif
9654 hFind = FindFirstFile(buf, &fb);
9655 ok = (hFind != INVALID_HANDLE_VALUE);
9656#else
9657 /* If we are expanding wildcards we try both files and directories */
9658 ok = (findfirst((char *)buf, &fb,
9659 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
9660#endif
9661
9662 while (ok)
9663 {
9664#ifdef WIN3264
9665# ifdef FEAT_MBYTE
9666 if (wn != NULL)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009667 p = utf16_to_enc(wfb.cFileName, NULL); /* p is allocated here */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009668 else
9669# endif
9670 p = (char_u *)fb.cFileName;
9671#else
9672 p = (char_u *)fb.ff_name;
9673#endif
9674 /* Ignore entries starting with a dot, unless when asked for. Accept
9675 * all entries found with "matchname". */
9676 if ((p[0] != '.' || starts_with_dot)
9677 && (matchname == NULL
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009678 || (regmatch.regprog != NULL
9679 && vim_regexec(&regmatch, p, (colnr_T)0))
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009680 || ((flags & EW_NOTWILD)
9681 && fnamencmp(path + (s - buf), p, e - s) == 0)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009682 {
9683#ifdef WIN3264
9684 STRCPY(s, p);
9685#else
9686 namelowcpy(s, p);
9687#endif
9688 len = (int)STRLEN(buf);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009689
9690 if (starstar && stardepth < 100)
9691 {
9692 /* For "**" in the pattern first go deeper in the tree to
9693 * find matches. */
9694 STRCPY(buf + len, "/**");
9695 STRCPY(buf + len + 3, path_end);
9696 ++stardepth;
9697 (void)dos_expandpath(gap, buf, len + 1, flags, TRUE);
9698 --stardepth;
9699 }
9700
Bram Moolenaar071d4272004-06-13 20:20:40 +00009701 STRCPY(buf + len, path_end);
9702 if (mch_has_exp_wildcard(path_end))
9703 {
9704 /* need to expand another component of the path */
9705 /* remove backslashes for the remaining components only */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009706 (void)dos_expandpath(gap, buf, len + 1, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009707 }
9708 else
9709 {
9710 /* no more wildcards, check if there is a match */
9711 /* remove backslashes for the remaining components only */
9712 if (*path_end != 0)
9713 backslash_halve(buf + len + 1);
9714 if (mch_getperm(buf) >= 0) /* add existing file */
9715 addfile(gap, buf, flags);
9716 }
9717 }
9718
9719#ifdef WIN3264
9720# ifdef FEAT_MBYTE
9721 if (wn != NULL)
9722 {
9723 vim_free(p);
9724 ok = FindNextFileW(hFind, &wfb);
9725 }
9726 else
9727# endif
9728 ok = FindNextFile(hFind, &fb);
9729#else
9730 ok = (findnext(&fb) == 0);
9731#endif
9732
9733 /* If no more matches and no match was used, try expanding the name
9734 * itself. Finds the long name of a short filename. */
9735 if (!ok && matchname != NULL && gap->ga_len == start_len)
9736 {
9737 STRCPY(s, matchname);
9738#ifdef WIN3264
9739 FindClose(hFind);
9740# ifdef FEAT_MBYTE
9741 if (wn != NULL)
9742 {
9743 vim_free(wn);
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009744 wn = enc_to_utf16(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009745 if (wn != NULL)
9746 hFind = FindFirstFileW(wn, &wfb);
9747 }
9748 if (wn == NULL)
9749# endif
9750 hFind = FindFirstFile(buf, &fb);
9751 ok = (hFind != INVALID_HANDLE_VALUE);
9752#else
9753 ok = (findfirst((char *)buf, &fb,
9754 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
9755#endif
9756 vim_free(matchname);
9757 matchname = NULL;
9758 }
9759 }
9760
9761#ifdef WIN3264
9762 FindClose(hFind);
9763# ifdef FEAT_MBYTE
9764 vim_free(wn);
9765# endif
9766#endif
9767 vim_free(buf);
Bram Moolenaar473de612013-06-08 18:19:48 +02009768 vim_regfree(regmatch.regprog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009769 vim_free(matchname);
9770
9771 matches = gap->ga_len - start_len;
9772 if (matches > 0)
9773 qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
9774 sizeof(char_u *), pstrcmp);
9775 return matches;
9776}
9777
9778 int
9779mch_expandpath(
9780 garray_T *gap,
9781 char_u *path,
9782 int flags) /* EW_* flags */
9783{
Bram Moolenaar231334e2005-07-25 20:46:57 +00009784 return dos_expandpath(gap, path, 0, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009785}
9786# endif /* MSDOS || FEAT_GUI_W16 || WIN3264 */
9787
Bram Moolenaar231334e2005-07-25 20:46:57 +00009788#if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
9789 || defined(PROTO)
9790/*
9791 * Unix style wildcard expansion code.
9792 * It's here because it's used both for Unix and Mac.
9793 */
9794static int pstrcmp __ARGS((const void *, const void *));
9795
9796 static int
9797pstrcmp(a, b)
9798 const void *a, *b;
9799{
9800 return (pathcmp(*(char **)a, *(char **)b, -1));
9801}
9802
9803/*
9804 * Recursively expand one path component into all matching files and/or
9805 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
9806 * "path" has backslashes before chars that are not to be expanded, starting
9807 * at "path + wildoff".
9808 * Return the number of matches found.
9809 * NOTE: much of this is identical to dos_expandpath(), keep in sync!
9810 */
9811 int
9812unix_expandpath(gap, path, wildoff, flags, didstar)
9813 garray_T *gap;
9814 char_u *path;
9815 int wildoff;
9816 int flags; /* EW_* flags */
9817 int didstar; /* expanded "**" once already */
9818{
9819 char_u *buf;
9820 char_u *path_end;
9821 char_u *p, *s, *e;
9822 int start_len = gap->ga_len;
9823 char_u *pat;
9824 regmatch_T regmatch;
9825 int starts_with_dot;
9826 int matches;
9827 int len;
9828 int starstar = FALSE;
9829 static int stardepth = 0; /* depth for "**" expansion */
9830
9831 DIR *dirp;
9832 struct dirent *dp;
9833
9834 /* Expanding "**" may take a long time, check for CTRL-C. */
9835 if (stardepth > 0)
9836 {
9837 ui_breakcheck();
9838 if (got_int)
9839 return 0;
9840 }
9841
9842 /* make room for file name */
9843 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
9844 if (buf == NULL)
9845 return 0;
9846
9847 /*
9848 * Find the first part in the path name that contains a wildcard.
Bram Moolenaar2d0b92f2012-04-30 21:09:43 +02009849 * When EW_ICASE is set every letter is considered to be a wildcard.
Bram Moolenaar231334e2005-07-25 20:46:57 +00009850 * Copy it into "buf", including the preceding characters.
9851 */
9852 p = buf;
9853 s = buf;
9854 e = NULL;
9855 path_end = path;
9856 while (*path_end != NUL)
9857 {
9858 /* May ignore a wildcard that has a backslash before it; it will
9859 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
9860 if (path_end >= path + wildoff && rem_backslash(path_end))
9861 *p++ = *path_end++;
9862 else if (*path_end == '/')
9863 {
9864 if (e != NULL)
9865 break;
9866 s = p + 1;
9867 }
9868 else if (path_end >= path + wildoff
Bram Moolenaar2d0b92f2012-04-30 21:09:43 +02009869 && (vim_strchr((char_u *)"*?[{~$", *path_end) != NULL
Bram Moolenaar71afbfe2013-03-19 16:49:16 +01009870 || (!p_fic && (flags & EW_ICASE)
9871 && isalpha(PTR2CHAR(path_end)))))
Bram Moolenaar231334e2005-07-25 20:46:57 +00009872 e = p;
9873#ifdef FEAT_MBYTE
9874 if (has_mbyte)
9875 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00009876 len = (*mb_ptr2len)(path_end);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009877 STRNCPY(p, path_end, len);
9878 p += len;
9879 path_end += len;
9880 }
9881 else
9882#endif
9883 *p++ = *path_end++;
9884 }
9885 e = p;
9886 *e = NUL;
9887
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009888 /* Now we have one wildcard component between "s" and "e". */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009889 /* Remove backslashes between "wildoff" and the start of the wildcard
9890 * component. */
9891 for (p = buf + wildoff; p < s; ++p)
9892 if (rem_backslash(p))
9893 {
Bram Moolenaar8c8de832008-06-24 22:58:06 +00009894 STRMOVE(p, p + 1);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009895 --e;
9896 --s;
9897 }
9898
9899 /* Check for "**" between "s" and "e". */
9900 for (p = s; p < e; ++p)
9901 if (p[0] == '*' && p[1] == '*')
9902 starstar = TRUE;
9903
9904 /* convert the file pattern to a regexp pattern */
9905 starts_with_dot = (*s == '.');
9906 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
9907 if (pat == NULL)
9908 {
9909 vim_free(buf);
9910 return 0;
9911 }
9912
9913 /* compile the regexp into a program */
Bram Moolenaar94950a92010-12-02 16:01:29 +01009914 if (flags & EW_ICASE)
9915 regmatch.rm_ic = TRUE; /* 'wildignorecase' set */
9916 else
Bram Moolenaar71afbfe2013-03-19 16:49:16 +01009917 regmatch.rm_ic = p_fic; /* ignore case when 'fileignorecase' is set */
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009918 if (flags & (EW_NOERROR | EW_NOTWILD))
9919 ++emsg_silent;
Bram Moolenaar231334e2005-07-25 20:46:57 +00009920 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009921 if (flags & (EW_NOERROR | EW_NOTWILD))
9922 --emsg_silent;
Bram Moolenaar231334e2005-07-25 20:46:57 +00009923 vim_free(pat);
9924
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009925 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
Bram Moolenaar231334e2005-07-25 20:46:57 +00009926 {
9927 vim_free(buf);
9928 return 0;
9929 }
9930
9931 /* If "**" is by itself, this is the first time we encounter it and more
9932 * is following then find matches without any directory. */
9933 if (!didstar && stardepth < 100 && starstar && e - s == 2
9934 && *path_end == '/')
9935 {
9936 STRCPY(s, path_end + 1);
9937 ++stardepth;
9938 (void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
9939 --stardepth;
9940 }
9941
9942 /* open the directory for scanning */
9943 *s = NUL;
9944 dirp = opendir(*buf == NUL ? "." : (char *)buf);
9945
9946 /* Find all matching entries */
9947 if (dirp != NULL)
9948 {
9949 for (;;)
9950 {
9951 dp = readdir(dirp);
9952 if (dp == NULL)
9953 break;
9954 if ((dp->d_name[0] != '.' || starts_with_dot)
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009955 && ((regmatch.regprog != NULL && vim_regexec(&regmatch,
9956 (char_u *)dp->d_name, (colnr_T)0))
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009957 || ((flags & EW_NOTWILD)
9958 && fnamencmp(path + (s - buf), dp->d_name, e - s) == 0)))
Bram Moolenaar231334e2005-07-25 20:46:57 +00009959 {
9960 STRCPY(s, dp->d_name);
9961 len = STRLEN(buf);
9962
9963 if (starstar && stardepth < 100)
9964 {
9965 /* For "**" in the pattern first go deeper in the tree to
9966 * find matches. */
9967 STRCPY(buf + len, "/**");
9968 STRCPY(buf + len + 3, path_end);
9969 ++stardepth;
9970 (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
9971 --stardepth;
9972 }
9973
9974 STRCPY(buf + len, path_end);
9975 if (mch_has_exp_wildcard(path_end)) /* handle more wildcards */
9976 {
9977 /* need to expand another component of the path */
9978 /* remove backslashes for the remaining components only */
9979 (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
9980 }
9981 else
9982 {
9983 /* no more wildcards, check if there is a match */
9984 /* remove backslashes for the remaining components only */
9985 if (*path_end != NUL)
9986 backslash_halve(buf + len + 1);
9987 if (mch_getperm(buf) >= 0) /* add existing file */
9988 {
Bram Moolenaar95e9b492006-03-15 23:04:43 +00009989#ifdef MACOS_CONVERT
Bram Moolenaar231334e2005-07-25 20:46:57 +00009990 size_t precomp_len = STRLEN(buf)+1;
9991 char_u *precomp_buf =
9992 mac_precompose_path(buf, precomp_len, &precomp_len);
Bram Moolenaar95e9b492006-03-15 23:04:43 +00009993
Bram Moolenaar231334e2005-07-25 20:46:57 +00009994 if (precomp_buf)
9995 {
9996 mch_memmove(buf, precomp_buf, precomp_len);
9997 vim_free(precomp_buf);
9998 }
9999#endif
10000 addfile(gap, buf, flags);
10001 }
10002 }
10003 }
10004 }
10005
10006 closedir(dirp);
10007 }
10008
10009 vim_free(buf);
Bram Moolenaar473de612013-06-08 18:19:48 +020010010 vim_regfree(regmatch.regprog);
Bram Moolenaar231334e2005-07-25 20:46:57 +000010011
10012 matches = gap->ga_len - start_len;
10013 if (matches > 0)
10014 qsort(((char_u **)gap->ga_data) + start_len, matches,
10015 sizeof(char_u *), pstrcmp);
10016 return matches;
10017}
10018#endif
10019
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010020#if defined(FEAT_SEARCHPATH)
10021static int find_previous_pathsep __ARGS((char_u *path, char_u **psep));
10022static int is_unique __ARGS((char_u *maybe_unique, garray_T *gap, int i));
Bram Moolenaar162bd912010-07-28 22:29:10 +020010023static void expand_path_option __ARGS((char_u *curdir, garray_T *gap));
10024static char_u *get_path_cutoff __ARGS((char_u *fname, garray_T *gap));
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010025static void uniquefy_paths __ARGS((garray_T *gap, char_u *pattern));
10026static int expand_in_path __ARGS((garray_T *gap, char_u *pattern, int flags));
10027
10028/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010029 * Moves "*psep" back to the previous path separator in "path".
10030 * Returns FAIL is "*psep" ends up at the beginning of "path".
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010031 */
10032 static int
10033find_previous_pathsep(path, psep)
10034 char_u *path;
10035 char_u **psep;
10036{
10037 /* skip the current separator */
10038 if (*psep > path && vim_ispathsep(**psep))
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010039 --*psep;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010040
10041 /* find the previous separator */
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010042 while (*psep > path)
10043 {
10044 if (vim_ispathsep(**psep))
10045 return OK;
10046 mb_ptr_back(path, *psep);
10047 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010048
10049 return FAIL;
10050}
10051
10052/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010053 * Returns TRUE if "maybe_unique" is unique wrt other_paths in "gap".
10054 * "maybe_unique" is the end portion of "((char_u **)gap->ga_data)[i]".
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010055 */
10056 static int
10057is_unique(maybe_unique, gap, i)
10058 char_u *maybe_unique;
10059 garray_T *gap;
10060 int i;
10061{
10062 int j;
10063 int candidate_len;
10064 int other_path_len;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010065 char_u **other_paths = (char_u **)gap->ga_data;
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010066 char_u *rival;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010067
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010068 for (j = 0; j < gap->ga_len; j++)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010069 {
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010070 if (j == i)
Bram Moolenaar162bd912010-07-28 22:29:10 +020010071 continue; /* don't compare it with itself */
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010072
Bram Moolenaar624c7aa2010-07-16 20:38:52 +020010073 candidate_len = (int)STRLEN(maybe_unique);
10074 other_path_len = (int)STRLEN(other_paths[j]);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010075 if (other_path_len < candidate_len)
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010076 continue; /* it's different when it's shorter */
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010077
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010078 rival = other_paths[j] + other_path_len - candidate_len;
Bram Moolenaarda9836c2010-08-16 21:53:27 +020010079 if (fnamecmp(maybe_unique, rival) == 0
10080 && (rival == other_paths[j] || vim_ispathsep(*(rival - 1))))
Bram Moolenaar162bd912010-07-28 22:29:10 +020010081 return FALSE; /* match */
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010082 }
10083
Bram Moolenaar162bd912010-07-28 22:29:10 +020010084 return TRUE; /* no match found */
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010085}
10086
10087/*
Bram Moolenaar1a509df2010-08-01 17:59:57 +020010088 * Split the 'path' option into an array of strings in garray_T. Relative
Bram Moolenaar162bd912010-07-28 22:29:10 +020010089 * paths are expanded to their equivalent fullpath. This includes the "."
10090 * (relative to current buffer directory) and empty path (relative to current
10091 * directory) notations.
10092 *
10093 * TODO: handle upward search (;) and path limiter (**N) notations by
10094 * expanding each into their equivalent path(s).
10095 */
10096 static void
10097expand_path_option(curdir, gap)
10098 char_u *curdir;
10099 garray_T *gap;
10100{
10101 char_u *path_option = *curbuf->b_p_path == NUL
10102 ? p_path : curbuf->b_p_path;
10103 char_u *buf;
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010104 char_u *p;
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010105 int len;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010106
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010107 if ((buf = alloc((int)MAXPATHL)) == NULL)
Bram Moolenaar162bd912010-07-28 22:29:10 +020010108 return;
10109
10110 while (*path_option != NUL)
10111 {
10112 copy_option_part(&path_option, buf, MAXPATHL, " ,");
10113
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010114 if (buf[0] == '.' && (buf[1] == NUL || vim_ispathsep(buf[1])))
Bram Moolenaar162bd912010-07-28 22:29:10 +020010115 {
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010116 /* Relative to current buffer:
10117 * "/path/file" + "." -> "/path/"
10118 * "/path/file" + "./subdir" -> "/path/subdir" */
Bram Moolenaar162bd912010-07-28 22:29:10 +020010119 if (curbuf->b_ffname == NULL)
10120 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010121 p = gettail(curbuf->b_ffname);
10122 len = (int)(p - curbuf->b_ffname);
10123 if (len + (int)STRLEN(buf) >= MAXPATHL)
10124 continue;
10125 if (buf[1] == NUL)
10126 buf[len] = NUL;
10127 else
10128 STRMOVE(buf + len, buf + 2);
10129 mch_memmove(buf, curbuf->b_ffname, len);
10130 simplify_filename(buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010131 }
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010132 else if (buf[0] == NUL)
10133 /* relative to current directory */
Bram Moolenaar162bd912010-07-28 22:29:10 +020010134 STRCPY(buf, curdir);
Bram Moolenaar84f888a2010-08-05 21:40:16 +020010135 else if (path_with_url(buf))
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010136 /* URL can't be used here */
Bram Moolenaar84f888a2010-08-05 21:40:16 +020010137 continue;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010138 else if (!mch_isFullName(buf))
10139 {
10140 /* Expand relative path to their full path equivalent */
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010141 len = (int)STRLEN(curdir);
10142 if (len + (int)STRLEN(buf) + 3 > MAXPATHL)
Bram Moolenaar162bd912010-07-28 22:29:10 +020010143 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010144 STRMOVE(buf + len + 1, buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010145 STRCPY(buf, curdir);
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010146 buf[len] = PATHSEP;
Bram Moolenaar57adda12010-08-03 22:11:29 +020010147 simplify_filename(buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010148 }
10149
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010150 if (ga_grow(gap, 1) == FAIL)
10151 break;
Bram Moolenaar811fe632013-04-24 17:34:20 +020010152
10153# if defined(MSWIN) || defined(MSDOS)
10154 /* Avoid the path ending in a backslash, it fails when a comma is
10155 * appended. */
Bram Moolenaar4e0d9742013-05-04 03:40:27 +020010156 len = (int)STRLEN(buf);
Bram Moolenaar811fe632013-04-24 17:34:20 +020010157 if (buf[len - 1] == '\\')
10158 buf[len - 1] = '/';
10159# endif
10160
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010161 p = vim_strsave(buf);
10162 if (p == NULL)
10163 break;
10164 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010165 }
10166
10167 vim_free(buf);
10168}
10169
10170/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010171 * Returns a pointer to the file or directory name in "fname" that matches the
10172 * longest path in "ga"p, or NULL if there is no match. For example:
Bram Moolenaar162bd912010-07-28 22:29:10 +020010173 *
10174 * path: /foo/bar/baz
10175 * fname: /foo/bar/baz/quux.txt
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010176 * returns: ^this
Bram Moolenaar162bd912010-07-28 22:29:10 +020010177 */
10178 static char_u *
10179get_path_cutoff(fname, gap)
10180 char_u *fname;
10181 garray_T *gap;
10182{
10183 int i;
10184 int maxlen = 0;
10185 char_u **path_part = (char_u **)gap->ga_data;
10186 char_u *cutoff = NULL;
10187
10188 for (i = 0; i < gap->ga_len; i++)
10189 {
10190 int j = 0;
10191
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010192 while ((fname[j] == path_part[i][j]
Bram Moolenaar2d7c47d2010-08-10 19:50:26 +020010193# if defined(MSWIN) || defined(MSDOS)
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010194 || (vim_ispathsep(fname[j]) && vim_ispathsep(path_part[i][j]))
10195#endif
10196 ) && fname[j] != NUL && path_part[i][j] != NUL)
Bram Moolenaar162bd912010-07-28 22:29:10 +020010197 j++;
10198 if (j > maxlen)
10199 {
10200 maxlen = j;
10201 cutoff = &fname[j];
10202 }
10203 }
10204
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010205 /* skip to the file or directory name */
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010206 if (cutoff != NULL)
Bram Moolenaar31710262010-08-13 13:36:15 +020010207 while (vim_ispathsep(*cutoff))
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010208 mb_ptr_adv(cutoff);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010209
10210 return cutoff;
10211}
10212
10213/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010214 * Sorts, removes duplicates and modifies all the fullpath names in "gap" so
10215 * that they are unique with respect to each other while conserving the part
10216 * that matches the pattern. Beware, this is at least O(n^2) wrt "gap->ga_len".
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010217 */
10218 static void
10219uniquefy_paths(gap, pattern)
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +020010220 garray_T *gap;
10221 char_u *pattern;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010222{
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +020010223 int i;
10224 int len;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010225 char_u **fnames = (char_u **)gap->ga_data;
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010226 int sort_again = FALSE;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010227 char_u *pat;
10228 char_u *file_pattern;
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010229 char_u *curdir;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010230 regmatch_T regmatch;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010231 garray_T path_ga;
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010232 char_u **in_curdir = NULL;
10233 char_u *short_name;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010234
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +020010235 remove_duplicates(gap);
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010236 ga_init2(&path_ga, (int)sizeof(char_u *), 1);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010237
10238 /*
10239 * We need to prepend a '*' at the beginning of file_pattern so that the
10240 * regex matches anywhere in the path. FIXME: is this valid for all
Bram Moolenaarb31e4382010-07-24 16:01:56 +020010241 * possible patterns?
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010242 */
Bram Moolenaar624c7aa2010-07-16 20:38:52 +020010243 len = (int)STRLEN(pattern);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010244 file_pattern = alloc(len + 2);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010245 if (file_pattern == NULL)
10246 return;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010247 file_pattern[0] = '*';
Bram Moolenaar162bd912010-07-28 22:29:10 +020010248 file_pattern[1] = NUL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010249 STRCAT(file_pattern, pattern);
10250 pat = file_pat_to_reg_pat(file_pattern, NULL, NULL, TRUE);
10251 vim_free(file_pattern);
Bram Moolenaarb31e4382010-07-24 16:01:56 +020010252 if (pat == NULL)
10253 return;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010254
Bram Moolenaarb31e4382010-07-24 16:01:56 +020010255 regmatch.rm_ic = TRUE; /* always ignore case */
10256 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
10257 vim_free(pat);
10258 if (regmatch.regprog == NULL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010259 return;
10260
Bram Moolenaar162bd912010-07-28 22:29:10 +020010261 if ((curdir = alloc((int)(MAXPATHL))) == NULL)
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010262 goto theend;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010263 mch_dirname(curdir, MAXPATHL);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010264 expand_path_option(curdir, &path_ga);
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010265
10266 in_curdir = (char_u **)alloc_clear(gap->ga_len * sizeof(char_u *));
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010267 if (in_curdir == NULL)
10268 goto theend;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010269
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010270 for (i = 0; i < gap->ga_len && !got_int; i++)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010271 {
Bram Moolenaar162bd912010-07-28 22:29:10 +020010272 char_u *path = fnames[i];
10273 int is_in_curdir;
Bram Moolenaar31710262010-08-13 13:36:15 +020010274 char_u *dir_end = gettail_dir(path);
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010275 char_u *pathsep_p;
10276 char_u *path_cutoff;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010277
Bram Moolenaar624c7aa2010-07-16 20:38:52 +020010278 len = (int)STRLEN(path);
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010279 is_in_curdir = fnamencmp(curdir, path, dir_end - path) == 0
Bram Moolenaar162bd912010-07-28 22:29:10 +020010280 && curdir[dir_end - path] == NUL;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010281 if (is_in_curdir)
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010282 in_curdir[i] = vim_strsave(path);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010283
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010284 /* Shorten the filename while maintaining its uniqueness */
10285 path_cutoff = get_path_cutoff(path, &path_ga);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010286
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010287 /* we start at the end of the path */
10288 pathsep_p = path + len - 1;
10289
10290 while (find_previous_pathsep(path, &pathsep_p))
10291 if (vim_regexec(&regmatch, pathsep_p + 1, (colnr_T)0)
10292 && is_unique(pathsep_p + 1, gap, i)
10293 && path_cutoff != NULL && pathsep_p + 1 >= path_cutoff)
10294 {
10295 sort_again = TRUE;
10296 mch_memmove(path, pathsep_p + 1, STRLEN(pathsep_p));
10297 break;
10298 }
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010299
10300 if (mch_isFullName(path))
10301 {
10302 /*
10303 * Last resort: shorten relative to curdir if possible.
10304 * 'possible' means:
10305 * 1. It is under the current directory.
10306 * 2. The result is actually shorter than the original.
10307 *
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010308 * Before curdir After
10309 * /foo/bar/file.txt /foo/bar ./file.txt
10310 * c:\foo\bar\file.txt c:\foo\bar .\file.txt
10311 * /file.txt / /file.txt
10312 * c:\file.txt c:\ .\file.txt
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010313 */
10314 short_name = shorten_fname(path, curdir);
Bram Moolenaar31710262010-08-13 13:36:15 +020010315 if (short_name != NULL && short_name > path + 1
10316#if defined(MSWIN) || defined(MSDOS)
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010317 /* On windows,
Bram Moolenaar31710262010-08-13 13:36:15 +020010318 * shorten_fname("c:\a\a.txt", "c:\a\b")
Bram Moolenaar31710262010-08-13 13:36:15 +020010319 * returns "\a\a.txt", which is not really the short
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010320 * name, hence: */
Bram Moolenaar31710262010-08-13 13:36:15 +020010321 && !vim_ispathsep(*short_name)
10322#endif
10323 )
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010324 {
10325 STRCPY(path, ".");
10326 add_pathsep(path);
Bram Moolenaarcda000e2010-08-14 13:34:39 +020010327 STRMOVE(path + STRLEN(path), short_name);
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010328 }
10329 }
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010330 ui_breakcheck();
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010331 }
10332
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010333 /* Shorten filenames in /in/current/directory/{filename} */
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010334 for (i = 0; i < gap->ga_len && !got_int; i++)
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010335 {
10336 char_u *rel_path;
10337 char_u *path = in_curdir[i];
10338
10339 if (path == NULL)
10340 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010341
10342 /* If the {filename} is not unique, change it to ./{filename}.
10343 * Else reduce it to {filename} */
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010344 short_name = shorten_fname(path, curdir);
10345 if (short_name == NULL)
10346 short_name = path;
10347 if (is_unique(short_name, gap, i))
10348 {
10349 STRCPY(fnames[i], short_name);
10350 continue;
10351 }
10352
10353 rel_path = alloc((int)(STRLEN(short_name) + STRLEN(PATHSEPSTR) + 2));
10354 if (rel_path == NULL)
10355 goto theend;
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010356 STRCPY(rel_path, ".");
10357 add_pathsep(rel_path);
10358 STRCAT(rel_path, short_name);
10359
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010360 vim_free(fnames[i]);
10361 fnames[i] = rel_path;
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010362 sort_again = TRUE;
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010363 ui_breakcheck();
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010364 }
10365
Bram Moolenaar162bd912010-07-28 22:29:10 +020010366theend:
10367 vim_free(curdir);
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010368 if (in_curdir != NULL)
10369 {
10370 for (i = 0; i < gap->ga_len; i++)
10371 vim_free(in_curdir[i]);
10372 vim_free(in_curdir);
10373 }
Bram Moolenaar162bd912010-07-28 22:29:10 +020010374 ga_clear_strings(&path_ga);
Bram Moolenaar473de612013-06-08 18:19:48 +020010375 vim_regfree(regmatch.regprog);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010376
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010377 if (sort_again)
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +020010378 remove_duplicates(gap);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010379}
10380
10381/*
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010382 * Calls globpath() with 'path' values for the given pattern and stores the
10383 * result in "gap".
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010384 * Returns the total number of matches.
10385 */
10386 static int
10387expand_in_path(gap, pattern, flags)
10388 garray_T *gap;
10389 char_u *pattern;
10390 int flags; /* EW_* flags */
10391{
Bram Moolenaar162bd912010-07-28 22:29:10 +020010392 char_u *curdir;
10393 garray_T path_ga;
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010394 char_u *files = NULL;
10395 char_u *s; /* start */
10396 char_u *e; /* end */
10397 char_u *paths = NULL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010398
Bram Moolenaar7f0f6212010-08-03 22:21:00 +020010399 if ((curdir = alloc((unsigned)MAXPATHL)) == NULL)
Bram Moolenaar162bd912010-07-28 22:29:10 +020010400 return 0;
10401 mch_dirname(curdir, MAXPATHL);
10402
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010403 ga_init2(&path_ga, (int)sizeof(char_u *), 1);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010404 expand_path_option(curdir, &path_ga);
10405 vim_free(curdir);
Bram Moolenaar006d2b02010-08-04 12:39:44 +020010406 if (path_ga.ga_len == 0)
10407 return 0;
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010408
10409 paths = ga_concat_strings(&path_ga);
10410 ga_clear_strings(&path_ga);
10411 if (paths == NULL)
Bram Moolenaar7f0f6212010-08-03 22:21:00 +020010412 return 0;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010413
Bram Moolenaar94950a92010-12-02 16:01:29 +010010414 files = globpath(paths, pattern, (flags & EW_ICASE) ? WILD_ICASE : 0);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010415 vim_free(paths);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010416 if (files == NULL)
10417 return 0;
10418
10419 /* Copy each path in files into gap */
10420 s = e = files;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010421 while (*s != NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010422 {
Bram Moolenaar162bd912010-07-28 22:29:10 +020010423 while (*e != '\n' && *e != NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010424 e++;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010425 if (*e == NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010426 {
10427 addfile(gap, s, flags);
10428 break;
10429 }
10430 else
10431 {
10432 /* *e is '\n' */
Bram Moolenaar162bd912010-07-28 22:29:10 +020010433 *e = NUL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010434 addfile(gap, s, flags);
10435 e++;
10436 s = e;
10437 }
10438 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010439 vim_free(files);
10440
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010441 return gap->ga_len;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010442}
10443#endif
10444
Bram Moolenaar1587a1e2010-07-29 20:59:59 +020010445#if defined(FEAT_SEARCHPATH) || defined(FEAT_CMDL_COMPL) || defined(PROTO)
10446/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010447 * Sort "gap" and remove duplicate entries. "gap" is expected to contain a
10448 * list of file names in allocated memory.
Bram Moolenaar1587a1e2010-07-29 20:59:59 +020010449 */
10450 void
10451remove_duplicates(gap)
10452 garray_T *gap;
10453{
10454 int i;
10455 int j;
10456 char_u **fnames = (char_u **)gap->ga_data;
10457
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010458 sort_strings(fnames, gap->ga_len);
Bram Moolenaar1587a1e2010-07-29 20:59:59 +020010459 for (i = gap->ga_len - 1; i > 0; --i)
10460 if (fnamecmp(fnames[i - 1], fnames[i]) == 0)
10461 {
10462 vim_free(fnames[i]);
10463 for (j = i + 1; j < gap->ga_len; ++j)
10464 fnames[j - 1] = fnames[j];
10465 --gap->ga_len;
10466 }
10467}
10468#endif
10469
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010470static int has_env_var __ARGS((char_u *p));
10471
10472/*
10473 * Return TRUE if "p" contains what looks like an environment variable.
10474 * Allowing for escaping.
10475 */
10476 static int
10477has_env_var(p)
10478 char_u *p;
10479{
10480 for ( ; *p; mb_ptr_adv(p))
10481 {
10482 if (*p == '\\' && p[1] != NUL)
10483 ++p;
10484 else if (vim_strchr((char_u *)
10485#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
10486 "$%"
10487#else
10488 "$"
10489#endif
10490 , *p) != NULL)
10491 return TRUE;
10492 }
10493 return FALSE;
10494}
10495
10496#ifdef SPECIAL_WILDCHAR
10497static int has_special_wildchar __ARGS((char_u *p));
10498
10499/*
10500 * Return TRUE if "p" contains a special wildcard character.
10501 * Allowing for escaping.
10502 */
10503 static int
10504has_special_wildchar(p)
10505 char_u *p;
10506{
10507 for ( ; *p; mb_ptr_adv(p))
10508 {
10509 if (*p == '\\' && p[1] != NUL)
10510 ++p;
10511 else if (vim_strchr((char_u *)SPECIAL_WILDCHAR, *p) != NULL)
10512 return TRUE;
10513 }
10514 return FALSE;
10515}
10516#endif
10517
Bram Moolenaar071d4272004-06-13 20:20:40 +000010518/*
10519 * Generic wildcard expansion code.
10520 *
10521 * Characters in "pat" that should not be expanded must be preceded with a
10522 * backslash. E.g., "/path\ with\ spaces/my\*star*"
10523 *
10524 * Return FAIL when no single file was found. In this case "num_file" is not
10525 * set, and "file" may contain an error message.
10526 * Return OK when some files found. "num_file" is set to the number of
10527 * matches, "file" to the array of matches. Call FreeWild() later.
10528 */
10529 int
10530gen_expand_wildcards(num_pat, pat, num_file, file, flags)
10531 int num_pat; /* number of input patterns */
10532 char_u **pat; /* array of input patterns */
10533 int *num_file; /* resulting number of files */
10534 char_u ***file; /* array of resulting files */
10535 int flags; /* EW_* flags */
10536{
10537 int i;
10538 garray_T ga;
10539 char_u *p;
10540 static int recursive = FALSE;
10541 int add_pat;
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010542#if defined(FEAT_SEARCHPATH)
10543 int did_expand_in_path = FALSE;
10544#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000010545
10546 /*
10547 * expand_env() is called to expand things like "~user". If this fails,
10548 * it calls ExpandOne(), which brings us back here. In this case, always
10549 * call the machine specific expansion function, if possible. Otherwise,
10550 * return FAIL.
10551 */
10552 if (recursive)
10553#ifdef SPECIAL_WILDCHAR
10554 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
10555#else
10556 return FAIL;
10557#endif
10558
10559#ifdef SPECIAL_WILDCHAR
10560 /*
10561 * If there are any special wildcard characters which we cannot handle
10562 * here, call machine specific function for all the expansion. This
10563 * avoids starting the shell for each argument separately.
10564 * For `=expr` do use the internal function.
10565 */
10566 for (i = 0; i < num_pat; i++)
10567 {
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010568 if (has_special_wildchar(pat[i])
Bram Moolenaar071d4272004-06-13 20:20:40 +000010569# ifdef VIM_BACKTICK
10570 && !(vim_backtick(pat[i]) && pat[i][1] == '=')
10571# endif
10572 )
10573 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
10574 }
10575#endif
10576
10577 recursive = TRUE;
10578
10579 /*
10580 * The matching file names are stored in a growarray. Init it empty.
10581 */
10582 ga_init2(&ga, (int)sizeof(char_u *), 30);
10583
10584 for (i = 0; i < num_pat; ++i)
10585 {
10586 add_pat = -1;
10587 p = pat[i];
10588
10589#ifdef VIM_BACKTICK
10590 if (vim_backtick(p))
10591 add_pat = expand_backtick(&ga, p, flags);
10592 else
10593#endif
10594 {
10595 /*
10596 * First expand environment variables, "~/" and "~user/".
10597 */
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010598 if (has_env_var(p) || *p == '~')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010599 {
Bram Moolenaar9f0545d2007-09-26 20:36:32 +000010600 p = expand_env_save_opt(p, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010601 if (p == NULL)
10602 p = pat[i];
10603#ifdef UNIX
10604 /*
10605 * On Unix, if expand_env() can't expand an environment
10606 * variable, use the shell to do that. Discard previously
10607 * found file names and start all over again.
10608 */
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010609 else if (has_env_var(p) || *p == '~')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010610 {
10611 vim_free(p);
Bram Moolenaar782027e2009-06-24 14:25:49 +000010612 ga_clear_strings(&ga);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010613 i = mch_expand_wildcards(num_pat, pat, num_file, file,
10614 flags);
10615 recursive = FALSE;
10616 return i;
10617 }
10618#endif
10619 }
10620
10621 /*
10622 * If there are wildcards: Expand file names and add each match to
10623 * the list. If there is no match, and EW_NOTFOUND is given, add
10624 * the pattern.
10625 * If there are no wildcards: Add the file name if it exists or
10626 * when EW_NOTFOUND is given.
10627 */
10628 if (mch_has_exp_wildcard(p))
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010629 {
10630#if defined(FEAT_SEARCHPATH)
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010631 if ((flags & EW_PATH)
10632 && !mch_isFullName(p)
10633 && !(p[0] == '.'
10634 && (vim_ispathsep(p[1])
10635 || (p[1] == '.' && vim_ispathsep(p[2]))))
10636 )
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010637 {
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010638 /* :find completion where 'path' is used.
10639 * Recursiveness is OK here. */
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010640 recursive = FALSE;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010641 add_pat = expand_in_path(&ga, p, flags);
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010642 recursive = TRUE;
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010643 did_expand_in_path = TRUE;
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010644 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010645 else
10646#endif
10647 add_pat = mch_expandpath(&ga, p, flags);
10648 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010649 }
10650
10651 if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
10652 {
10653 char_u *t = backslash_halve_save(p);
10654
10655#if defined(MACOS_CLASSIC)
10656 slash_to_colon(t);
10657#endif
10658 /* When EW_NOTFOUND is used, always add files and dirs. Makes
10659 * "vim c:/" work. */
10660 if (flags & EW_NOTFOUND)
10661 addfile(&ga, t, flags | EW_DIR | EW_FILE);
10662 else if (mch_getperm(t) >= 0)
10663 addfile(&ga, t, flags);
10664 vim_free(t);
10665 }
10666
Bram Moolenaarb28ebbc2010-07-14 16:59:57 +020010667#if defined(FEAT_SEARCHPATH)
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010668 if (did_expand_in_path && ga.ga_len > 0 && (flags & EW_PATH))
Bram Moolenaarb28ebbc2010-07-14 16:59:57 +020010669 uniquefy_paths(&ga, p);
10670#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000010671 if (p != pat[i])
10672 vim_free(p);
10673 }
10674
10675 *num_file = ga.ga_len;
10676 *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data : (char_u **)"";
10677
10678 recursive = FALSE;
10679
10680 return (ga.ga_data != NULL) ? OK : FAIL;
10681}
10682
10683# ifdef VIM_BACKTICK
10684
10685/*
10686 * Return TRUE if we can expand this backtick thing here.
10687 */
10688 static int
10689vim_backtick(p)
10690 char_u *p;
10691{
10692 return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
10693}
10694
10695/*
10696 * Expand an item in `backticks` by executing it as a command.
10697 * Currently only works when pat[] starts and ends with a `.
10698 * Returns number of file names found.
10699 */
10700 static int
10701expand_backtick(gap, pat, flags)
10702 garray_T *gap;
10703 char_u *pat;
10704 int flags; /* EW_* flags */
10705{
10706 char_u *p;
10707 char_u *cmd;
10708 char_u *buffer;
10709 int cnt = 0;
10710 int i;
10711
10712 /* Create the command: lop off the backticks. */
10713 cmd = vim_strnsave(pat + 1, (int)STRLEN(pat) - 2);
10714 if (cmd == NULL)
10715 return 0;
10716
10717#ifdef FEAT_EVAL
10718 if (*cmd == '=') /* `={expr}`: Expand expression */
Bram Moolenaar362e1a32006-03-06 23:29:24 +000010719 buffer = eval_to_string(cmd + 1, &p, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010720 else
10721#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010722 buffer = get_cmd_output(cmd, NULL,
10723 (flags & EW_SILENT) ? SHELL_SILENT : 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010724 vim_free(cmd);
10725 if (buffer == NULL)
10726 return 0;
10727
10728 cmd = buffer;
10729 while (*cmd != NUL)
10730 {
10731 cmd = skipwhite(cmd); /* skip over white space */
10732 p = cmd;
10733 while (*p != NUL && *p != '\r' && *p != '\n') /* skip over entry */
10734 ++p;
10735 /* add an entry if it is not empty */
10736 if (p > cmd)
10737 {
10738 i = *p;
10739 *p = NUL;
10740 addfile(gap, cmd, flags);
10741 *p = i;
10742 ++cnt;
10743 }
10744 cmd = p;
10745 while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
10746 ++cmd;
10747 }
10748
10749 vim_free(buffer);
10750 return cnt;
10751}
10752# endif /* VIM_BACKTICK */
10753
10754/*
10755 * Add a file to a file list. Accepted flags:
10756 * EW_DIR add directories
10757 * EW_FILE add files
Bram Moolenaar1f35bf92006-03-07 22:38:47 +000010758 * EW_EXEC add executable files
Bram Moolenaar071d4272004-06-13 20:20:40 +000010759 * EW_NOTFOUND add even when it doesn't exist
10760 * EW_ADDSLASH add slash after directory name
10761 */
10762 void
10763addfile(gap, f, flags)
10764 garray_T *gap;
10765 char_u *f; /* filename */
10766 int flags;
10767{
10768 char_u *p;
10769 int isdir;
10770
10771 /* if the file/dir doesn't exist, may not add it */
10772 if (!(flags & EW_NOTFOUND) && mch_getperm(f) < 0)
10773 return;
10774
10775#ifdef FNAME_ILLEGAL
10776 /* if the file/dir contains illegal characters, don't add it */
10777 if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
10778 return;
10779#endif
10780
10781 isdir = mch_isdir(f);
10782 if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
10783 return;
10784
Bram Moolenaar1f35bf92006-03-07 22:38:47 +000010785 /* If the file isn't executable, may not add it. Do accept directories. */
10786 if (!isdir && (flags & EW_EXEC) && !mch_can_exe(f))
10787 return;
10788
Bram Moolenaar071d4272004-06-13 20:20:40 +000010789 /* Make room for another item in the file list. */
10790 if (ga_grow(gap, 1) == FAIL)
10791 return;
10792
10793 p = alloc((unsigned)(STRLEN(f) + 1 + isdir));
10794 if (p == NULL)
10795 return;
10796
10797 STRCPY(p, f);
10798#ifdef BACKSLASH_IN_FILENAME
10799 slash_adjust(p);
10800#endif
10801 /*
10802 * Append a slash or backslash after directory names if none is present.
10803 */
10804#ifndef DONT_ADD_PATHSEP_TO_DIR
10805 if (isdir && (flags & EW_ADDSLASH))
10806 add_pathsep(p);
10807#endif
10808 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010809}
10810#endif /* !NO_EXPANDPATH */
10811
10812#if defined(VIM_BACKTICK) || defined(FEAT_EVAL) || defined(PROTO)
10813
10814#ifndef SEEK_SET
10815# define SEEK_SET 0
10816#endif
10817#ifndef SEEK_END
10818# define SEEK_END 2
10819#endif
10820
10821/*
10822 * Get the stdout of an external command.
10823 * Returns an allocated string, or NULL for error.
10824 */
10825 char_u *
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010826get_cmd_output(cmd, infile, flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010827 char_u *cmd;
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010828 char_u *infile; /* optional input file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010829 int flags; /* can be SHELL_SILENT */
10830{
10831 char_u *tempname;
10832 char_u *command;
10833 char_u *buffer = NULL;
10834 int len;
10835 int i = 0;
10836 FILE *fd;
10837
10838 if (check_restricted() || check_secure())
10839 return NULL;
10840
10841 /* get a name for the temp file */
10842 if ((tempname = vim_tempname('o')) == NULL)
10843 {
10844 EMSG(_(e_notmp));
10845 return NULL;
10846 }
10847
10848 /* Add the redirection stuff */
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010849 command = make_filter_cmd(cmd, infile, tempname);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010850 if (command == NULL)
10851 goto done;
10852
10853 /*
10854 * Call the shell to execute the command (errors are ignored).
10855 * Don't check timestamps here.
10856 */
10857 ++no_check_timestamps;
10858 call_shell(command, SHELL_DOOUT | SHELL_EXPAND | flags);
10859 --no_check_timestamps;
10860
10861 vim_free(command);
10862
10863 /*
10864 * read the names from the file into memory
10865 */
10866# ifdef VMS
Bram Moolenaar25394022007-05-10 19:06:20 +000010867 /* created temporary file is not always readable as binary */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010868 fd = mch_fopen((char *)tempname, "r");
10869# else
10870 fd = mch_fopen((char *)tempname, READBIN);
10871# endif
10872
10873 if (fd == NULL)
10874 {
10875 EMSG2(_(e_notopen), tempname);
10876 goto done;
10877 }
10878
10879 fseek(fd, 0L, SEEK_END);
10880 len = ftell(fd); /* get size of temp file */
10881 fseek(fd, 0L, SEEK_SET);
10882
10883 buffer = alloc(len + 1);
10884 if (buffer != NULL)
10885 i = (int)fread((char *)buffer, (size_t)1, (size_t)len, fd);
10886 fclose(fd);
10887 mch_remove(tempname);
10888 if (buffer == NULL)
10889 goto done;
10890#ifdef VMS
10891 len = i; /* VMS doesn't give us what we asked for... */
10892#endif
10893 if (i != len)
10894 {
10895 EMSG2(_(e_notread), tempname);
10896 vim_free(buffer);
10897 buffer = NULL;
10898 }
10899 else
Bram Moolenaarfb332a22013-08-03 14:10:50 +020010900 {
10901 /* Change NUL into SOH, otherwise the string is truncated. */
10902 for (i = 0; i < len; ++i)
Bram Moolenaarf40f4ab2013-08-03 17:31:28 +020010903 if (buffer[i] == NUL)
10904 buffer[i] = 1;
Bram Moolenaarfb332a22013-08-03 14:10:50 +020010905
Bram Moolenaar162bd912010-07-28 22:29:10 +020010906 buffer[len] = NUL; /* make sure the buffer is terminated */
Bram Moolenaarfb332a22013-08-03 14:10:50 +020010907 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010908
10909done:
10910 vim_free(tempname);
10911 return buffer;
10912}
10913#endif
10914
10915/*
10916 * Free the list of files returned by expand_wildcards() or other expansion
10917 * functions.
10918 */
10919 void
10920FreeWild(count, files)
10921 int count;
10922 char_u **files;
10923{
Bram Moolenaarfc1421e2006-04-20 22:17:20 +000010924 if (count <= 0 || files == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010925 return;
10926#if defined(__EMX__) && defined(__ALWAYS_HAS_TRAILING_NULL_POINTER) /* XXX */
10927 /*
10928 * Is this still OK for when other functions than expand_wildcards() have
10929 * been used???
10930 */
10931 _fnexplodefree((char **)files);
10932#else
10933 while (count--)
10934 vim_free(files[count]);
10935 vim_free(files);
10936#endif
10937}
10938
10939/*
Bram Moolenaara9dc3752010-07-11 20:46:53 +020010940 * Return TRUE when need to go to Insert mode because of 'insertmode'.
Bram Moolenaar071d4272004-06-13 20:20:40 +000010941 * Don't do this when still processing a command or a mapping.
10942 * Don't do this when inside a ":normal" command.
10943 */
10944 int
10945goto_im()
10946{
10947 return (p_im && stuff_empty() && typebuf_typed());
10948}