blob: 636fc4a07b6258ac6dac7d6d8ca15289fc98f0b9 [file] [log] [blame]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001/* vi:set ts=8 sts=4 sw=4:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * misc1.c: functions that didn't seem to fit elsewhere
12 */
13
14#include "vim.h"
15#include "version.h"
16
Bram Moolenaar071d4272004-06-13 20:20:40 +000017static char_u *vim_version_dir __ARGS((char_u *vimdir));
18static char_u *remove_tail __ARGS((char_u *p, char_u *pend, char_u *name));
Bram Moolenaar071d4272004-06-13 20:20:40 +000019static int copy_indent __ARGS((int size, char_u *src));
20
Bram Moolenaar24305862012-08-15 14:05:05 +020021/* All user names (for ~user completion as done by shell). */
22#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
23static garray_T ga_users;
24#endif
25
Bram Moolenaar071d4272004-06-13 20:20:40 +000026/*
27 * Count the size (in window cells) of the indent in the current line.
28 */
29 int
30get_indent()
31{
32 return get_indent_str(ml_get_curline(), (int)curbuf->b_p_ts);
33}
34
35/*
36 * Count the size (in window cells) of the indent in line "lnum".
37 */
38 int
39get_indent_lnum(lnum)
40 linenr_T lnum;
41{
42 return get_indent_str(ml_get(lnum), (int)curbuf->b_p_ts);
43}
44
45#if defined(FEAT_FOLDING) || defined(PROTO)
46/*
47 * Count the size (in window cells) of the indent in line "lnum" of buffer
48 * "buf".
49 */
50 int
51get_indent_buf(buf, lnum)
52 buf_T *buf;
53 linenr_T lnum;
54{
55 return get_indent_str(ml_get_buf(buf, lnum, FALSE), (int)buf->b_p_ts);
56}
57#endif
58
59/*
60 * count the size (in window cells) of the indent in line "ptr", with
61 * 'tabstop' at "ts"
62 */
Bram Moolenaar4399ef42005-02-12 14:29:27 +000063 int
Bram Moolenaar071d4272004-06-13 20:20:40 +000064get_indent_str(ptr, ts)
65 char_u *ptr;
66 int ts;
67{
68 int count = 0;
69
70 for ( ; *ptr; ++ptr)
71 {
72 if (*ptr == TAB) /* count a tab for what it is worth */
73 count += ts - (count % ts);
74 else if (*ptr == ' ')
75 ++count; /* count a space for one */
76 else
77 break;
78 }
Bram Moolenaar4399ef42005-02-12 14:29:27 +000079 return count;
Bram Moolenaar071d4272004-06-13 20:20:40 +000080}
81
82/*
83 * Set the indent of the current line.
84 * Leaves the cursor on the first non-blank in the line.
85 * Caller must take care of undo.
86 * "flags":
87 * SIN_CHANGED: call changed_bytes() if the line was changed.
88 * SIN_INSERT: insert the indent in front of the line.
89 * SIN_UNDO: save line for undo before changing it.
90 * Returns TRUE if the line was changed.
91 */
92 int
93set_indent(size, flags)
Bram Moolenaar5002c292007-07-24 13:26:15 +000094 int size; /* measured in spaces */
Bram Moolenaar071d4272004-06-13 20:20:40 +000095 int flags;
96{
97 char_u *p;
98 char_u *newline;
99 char_u *oldline;
100 char_u *s;
101 int todo;
Bram Moolenaar5002c292007-07-24 13:26:15 +0000102 int ind_len; /* measured in characters */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000103 int line_len;
104 int doit = FALSE;
Bram Moolenaar5002c292007-07-24 13:26:15 +0000105 int ind_done = 0; /* measured in spaces */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000106 int tab_pad;
Bram Moolenaar5409c052005-03-18 20:27:04 +0000107 int retval = FALSE;
Bram Moolenaar4d64b782007-08-14 20:16:42 +0000108 int orig_char_len = -1; /* number of initial whitespace chars when
Bram Moolenaar5002c292007-07-24 13:26:15 +0000109 'et' and 'pi' are both set */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000110
111 /*
112 * First check if there is anything to do and compute the number of
113 * characters needed for the indent.
114 */
115 todo = size;
116 ind_len = 0;
117 p = oldline = ml_get_curline();
118
119 /* Calculate the buffer size for the new indent, and check to see if it
120 * isn't already set */
121
Bram Moolenaar5002c292007-07-24 13:26:15 +0000122 /* if 'expandtab' isn't set: use TABs; if both 'expandtab' and
123 * 'preserveindent' are set count the number of characters at the
124 * beginning of the line to be copied */
125 if (!curbuf->b_p_et || (!(flags & SIN_INSERT) && curbuf->b_p_pi))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000126 {
127 /* If 'preserveindent' is set then reuse as much as possible of
128 * the existing indent structure for the new indent */
129 if (!(flags & SIN_INSERT) && curbuf->b_p_pi)
130 {
131 ind_done = 0;
132
133 /* count as many characters as we can use */
134 while (todo > 0 && vim_iswhite(*p))
135 {
136 if (*p == TAB)
137 {
138 tab_pad = (int)curbuf->b_p_ts
139 - (ind_done % (int)curbuf->b_p_ts);
140 /* stop if this tab will overshoot the target */
141 if (todo < tab_pad)
142 break;
143 todo -= tab_pad;
144 ++ind_len;
145 ind_done += tab_pad;
146 }
147 else
148 {
149 --todo;
150 ++ind_len;
151 ++ind_done;
152 }
153 ++p;
154 }
155
Bram Moolenaar5002c292007-07-24 13:26:15 +0000156 /* Set initial number of whitespace chars to copy if we are
157 * preserving indent but expandtab is set */
158 if (curbuf->b_p_et)
159 orig_char_len = ind_len;
160
Bram Moolenaar071d4272004-06-13 20:20:40 +0000161 /* Fill to next tabstop with a tab, if possible */
162 tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
Bram Moolenaar4d64b782007-08-14 20:16:42 +0000163 if (todo >= tab_pad && orig_char_len == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000164 {
165 doit = TRUE;
166 todo -= tab_pad;
167 ++ind_len;
168 /* ind_done += tab_pad; */
169 }
170 }
171
172 /* count tabs required for indent */
173 while (todo >= (int)curbuf->b_p_ts)
174 {
175 if (*p != TAB)
176 doit = TRUE;
177 else
178 ++p;
179 todo -= (int)curbuf->b_p_ts;
180 ++ind_len;
181 /* ind_done += (int)curbuf->b_p_ts; */
182 }
183 }
184 /* count spaces required for indent */
185 while (todo > 0)
186 {
187 if (*p != ' ')
188 doit = TRUE;
189 else
190 ++p;
191 --todo;
192 ++ind_len;
193 /* ++ind_done; */
194 }
195
196 /* Return if the indent is OK already. */
197 if (!doit && !vim_iswhite(*p) && !(flags & SIN_INSERT))
198 return FALSE;
199
200 /* Allocate memory for the new line. */
201 if (flags & SIN_INSERT)
202 p = oldline;
203 else
204 p = skipwhite(p);
205 line_len = (int)STRLEN(p) + 1;
Bram Moolenaar5002c292007-07-24 13:26:15 +0000206
207 /* If 'preserveindent' and 'expandtab' are both set keep the original
208 * characters and allocate accordingly. We will fill the rest with spaces
209 * after the if (!curbuf->b_p_et) below. */
Bram Moolenaar4d64b782007-08-14 20:16:42 +0000210 if (orig_char_len != -1)
Bram Moolenaar5002c292007-07-24 13:26:15 +0000211 {
212 newline = alloc(orig_char_len + size - ind_done + line_len);
213 if (newline == NULL)
214 return FALSE;
Bram Moolenaar4d64b782007-08-14 20:16:42 +0000215 todo = size - ind_done;
216 ind_len = orig_char_len + todo; /* Set total length of indent in
217 * characters, which may have been
218 * undercounted until now */
Bram Moolenaar5002c292007-07-24 13:26:15 +0000219 p = oldline;
220 s = newline;
221 while (orig_char_len > 0)
222 {
223 *s++ = *p++;
224 orig_char_len--;
225 }
Bram Moolenaar913626c2008-01-03 11:43:42 +0000226
Bram Moolenaar5002c292007-07-24 13:26:15 +0000227 /* Skip over any additional white space (useful when newindent is less
228 * than old) */
229 while (vim_iswhite(*p))
Bram Moolenaar913626c2008-01-03 11:43:42 +0000230 ++p;
Bram Moolenaarcc00b952007-08-11 12:32:57 +0000231
Bram Moolenaar5002c292007-07-24 13:26:15 +0000232 }
233 else
234 {
235 todo = size;
236 newline = alloc(ind_len + line_len);
237 if (newline == NULL)
238 return FALSE;
239 s = newline;
240 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000241
242 /* Put the characters in the new line. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000243 /* if 'expandtab' isn't set: use TABs */
244 if (!curbuf->b_p_et)
245 {
246 /* If 'preserveindent' is set then reuse as much as possible of
247 * the existing indent structure for the new indent */
248 if (!(flags & SIN_INSERT) && curbuf->b_p_pi)
249 {
250 p = oldline;
251 ind_done = 0;
252
253 while (todo > 0 && vim_iswhite(*p))
254 {
255 if (*p == TAB)
256 {
257 tab_pad = (int)curbuf->b_p_ts
258 - (ind_done % (int)curbuf->b_p_ts);
259 /* stop if this tab will overshoot the target */
260 if (todo < tab_pad)
261 break;
262 todo -= tab_pad;
263 ind_done += tab_pad;
264 }
265 else
266 {
267 --todo;
268 ++ind_done;
269 }
270 *s++ = *p++;
271 }
272
273 /* Fill to next tabstop with a tab, if possible */
274 tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
275 if (todo >= tab_pad)
276 {
277 *s++ = TAB;
278 todo -= tab_pad;
279 }
280
281 p = skipwhite(p);
282 }
283
284 while (todo >= (int)curbuf->b_p_ts)
285 {
286 *s++ = TAB;
287 todo -= (int)curbuf->b_p_ts;
288 }
289 }
290 while (todo > 0)
291 {
292 *s++ = ' ';
293 --todo;
294 }
295 mch_memmove(s, p, (size_t)line_len);
296
297 /* Replace the line (unless undo fails). */
298 if (!(flags & SIN_UNDO) || u_savesub(curwin->w_cursor.lnum) == OK)
299 {
300 ml_replace(curwin->w_cursor.lnum, newline, FALSE);
301 if (flags & SIN_CHANGED)
302 changed_bytes(curwin->w_cursor.lnum, 0);
303 /* Correct saved cursor position if it's after the indent. */
304 if (saved_cursor.lnum == curwin->w_cursor.lnum
305 && saved_cursor.col >= (colnr_T)(p - oldline))
Bram Moolenaara93fa7e2006-04-17 22:14:47 +0000306 saved_cursor.col += ind_len - (colnr_T)(p - oldline);
Bram Moolenaar5409c052005-03-18 20:27:04 +0000307 retval = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000308 }
309 else
310 vim_free(newline);
311
312 curwin->w_cursor.col = ind_len;
Bram Moolenaar5409c052005-03-18 20:27:04 +0000313 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000314}
315
316/*
317 * Copy the indent from ptr to the current line (and fill to size)
318 * Leaves the cursor on the first non-blank in the line.
319 * Returns TRUE if the line was changed.
320 */
321 static int
322copy_indent(size, src)
323 int size;
324 char_u *src;
325{
326 char_u *p = NULL;
327 char_u *line = NULL;
328 char_u *s;
329 int todo;
330 int ind_len;
331 int line_len = 0;
332 int tab_pad;
333 int ind_done;
334 int round;
335
336 /* Round 1: compute the number of characters needed for the indent
337 * Round 2: copy the characters. */
338 for (round = 1; round <= 2; ++round)
339 {
340 todo = size;
341 ind_len = 0;
342 ind_done = 0;
343 s = src;
344
345 /* Count/copy the usable portion of the source line */
346 while (todo > 0 && vim_iswhite(*s))
347 {
348 if (*s == TAB)
349 {
350 tab_pad = (int)curbuf->b_p_ts
351 - (ind_done % (int)curbuf->b_p_ts);
352 /* Stop if this tab will overshoot the target */
353 if (todo < tab_pad)
354 break;
355 todo -= tab_pad;
356 ind_done += tab_pad;
357 }
358 else
359 {
360 --todo;
361 ++ind_done;
362 }
363 ++ind_len;
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000364 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000365 *p++ = *s;
366 ++s;
367 }
368
369 /* Fill to next tabstop with a tab, if possible */
370 tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
Bram Moolenaarc42e7ed2011-09-07 19:58:09 +0200371 if (todo >= tab_pad && !curbuf->b_p_et)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000372 {
373 todo -= tab_pad;
374 ++ind_len;
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000375 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000376 *p++ = TAB;
377 }
378
379 /* Add tabs required for indent */
Bram Moolenaarc42e7ed2011-09-07 19:58:09 +0200380 while (todo >= (int)curbuf->b_p_ts && !curbuf->b_p_et)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000381 {
382 todo -= (int)curbuf->b_p_ts;
383 ++ind_len;
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000384 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000385 *p++ = TAB;
386 }
387
388 /* Count/add spaces required for indent */
389 while (todo > 0)
390 {
391 --todo;
392 ++ind_len;
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000393 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000394 *p++ = ' ';
395 }
396
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000397 if (p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000398 {
399 /* Allocate memory for the result: the copied indent, new indent
400 * and the rest of the line. */
401 line_len = (int)STRLEN(ml_get_curline()) + 1;
402 line = alloc(ind_len + line_len);
403 if (line == NULL)
404 return FALSE;
405 p = line;
406 }
407 }
408
409 /* Append the original line */
410 mch_memmove(p, ml_get_curline(), (size_t)line_len);
411
412 /* Replace the line */
413 ml_replace(curwin->w_cursor.lnum, line, FALSE);
414
415 /* Put the cursor after the indent. */
416 curwin->w_cursor.col = ind_len;
417 return TRUE;
418}
419
420/*
421 * Return the indent of the current line after a number. Return -1 if no
422 * number was found. Used for 'n' in 'formatoptions': numbered list.
Bram Moolenaar86b68352004-12-27 21:59:20 +0000423 * Since a pattern is used it can actually handle more than numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000424 */
425 int
426get_number_indent(lnum)
427 linenr_T lnum;
428{
Bram Moolenaar071d4272004-06-13 20:20:40 +0000429 colnr_T col;
430 pos_T pos;
431
Bram Moolenaar96b7ca52012-06-29 15:04:49 +0200432 regmatch_T regmatch;
433 int lead_len = 0; /* length of comment leader */
434
Bram Moolenaar071d4272004-06-13 20:20:40 +0000435 if (lnum > curbuf->b_ml.ml_line_count)
436 return -1;
Bram Moolenaar86b68352004-12-27 21:59:20 +0000437 pos.lnum = 0;
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200438
439#ifdef FEAT_COMMENTS
Bram Moolenaar96b7ca52012-06-29 15:04:49 +0200440 /* In format_lines() (i.e. not insert mode), fo+=q is needed too... */
441 if ((State & INSERT) || has_format_option(FO_Q_COMS))
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200442 lead_len = get_leader_len(ml_get(lnum), NULL, FALSE, TRUE);
Bram Moolenaar86b68352004-12-27 21:59:20 +0000443#endif
Bram Moolenaar96b7ca52012-06-29 15:04:49 +0200444 regmatch.regprog = vim_regcomp(curbuf->b_p_flp, RE_MAGIC);
445 if (regmatch.regprog != NULL)
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200446 {
Bram Moolenaar96b7ca52012-06-29 15:04:49 +0200447 regmatch.rm_ic = FALSE;
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200448
Bram Moolenaar96b7ca52012-06-29 15:04:49 +0200449 /* vim_regexec() expects a pointer to a line. This lets us
450 * start matching for the flp beyond any comment leader... */
451 if (vim_regexec(&regmatch, ml_get(lnum) + lead_len, (colnr_T)0))
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200452 {
Bram Moolenaar96b7ca52012-06-29 15:04:49 +0200453 pos.lnum = lnum;
454 pos.col = (colnr_T)(*regmatch.endp - ml_get(lnum));
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200455#ifdef FEAT_VIRTUALEDIT
Bram Moolenaar96b7ca52012-06-29 15:04:49 +0200456 pos.coladd = 0;
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200457#endif
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200458 }
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200459 }
Bram Moolenaar96b7ca52012-06-29 15:04:49 +0200460 vim_free(regmatch.regprog);
Bram Moolenaar86b68352004-12-27 21:59:20 +0000461
462 if (pos.lnum == 0 || *ml_get_pos(&pos) == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000463 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000464 getvcol(curwin, &pos, &col, NULL, NULL);
465 return (int)col;
466}
467
468#if defined(FEAT_CINDENT) || defined(FEAT_SMARTINDENT)
469
470static int cin_is_cinword __ARGS((char_u *line));
471
472/*
473 * Return TRUE if the string "line" starts with a word from 'cinwords'.
474 */
475 static int
476cin_is_cinword(line)
477 char_u *line;
478{
479 char_u *cinw;
480 char_u *cinw_buf;
481 int cinw_len;
482 int retval = FALSE;
483 int len;
484
485 cinw_len = (int)STRLEN(curbuf->b_p_cinw) + 1;
486 cinw_buf = alloc((unsigned)cinw_len);
487 if (cinw_buf != NULL)
488 {
489 line = skipwhite(line);
490 for (cinw = curbuf->b_p_cinw; *cinw; )
491 {
492 len = copy_option_part(&cinw, cinw_buf, cinw_len, ",");
493 if (STRNCMP(line, cinw_buf, len) == 0
494 && (!vim_iswordc(line[len]) || !vim_iswordc(line[len - 1])))
495 {
496 retval = TRUE;
497 break;
498 }
499 }
500 vim_free(cinw_buf);
501 }
502 return retval;
503}
504#endif
505
506/*
507 * open_line: Add a new line below or above the current line.
508 *
509 * For VREPLACE mode, we only add a new line when we get to the end of the
510 * file, otherwise we just start replacing the next line.
511 *
512 * Caller must take care of undo. Since VREPLACE may affect any number of
513 * lines however, it may call u_save_cursor() again when starting to change a
514 * new line.
515 * "flags": OPENLINE_DELSPACES delete spaces after cursor
516 * OPENLINE_DO_COM format comments
517 * OPENLINE_KEEPTRAIL keep trailing spaces
518 * OPENLINE_MARKFIX adjust mark positions after the line break
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200519 * OPENLINE_COM_LIST format comments with list or 2nd line indent
520 *
521 * "second_line_indent": indent for after ^^D in Insert mode or if flag
522 * OPENLINE_COM_LIST
Bram Moolenaar071d4272004-06-13 20:20:40 +0000523 *
524 * Return TRUE for success, FALSE for failure
525 */
526 int
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200527open_line(dir, flags, second_line_indent)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000528 int dir; /* FORWARD or BACKWARD */
529 int flags;
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200530 int second_line_indent;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000531{
532 char_u *saved_line; /* copy of the original line */
533 char_u *next_line = NULL; /* copy of the next line */
534 char_u *p_extra = NULL; /* what goes to next line */
535 int less_cols = 0; /* less columns for mark in new line */
536 int less_cols_off = 0; /* columns to skip for mark adjust */
537 pos_T old_cursor; /* old cursor position */
538 int newcol = 0; /* new cursor column */
539 int newindent = 0; /* auto-indent of the new line */
540 int n;
541 int trunc_line = FALSE; /* truncate current line afterwards */
542 int retval = FALSE; /* return value, default is FAIL */
543#ifdef FEAT_COMMENTS
544 int extra_len = 0; /* length of p_extra string */
545 int lead_len; /* length of comment leader */
546 char_u *lead_flags; /* position in 'comments' for comment leader */
547 char_u *leader = NULL; /* copy of comment leader */
548#endif
549 char_u *allocated = NULL; /* allocated memory */
550#if defined(FEAT_SMARTINDENT) || defined(FEAT_VREPLACE) || defined(FEAT_LISP) \
551 || defined(FEAT_CINDENT) || defined(FEAT_COMMENTS)
552 char_u *p;
553#endif
554 int saved_char = NUL; /* init for GCC */
555#if defined(FEAT_SMARTINDENT) || defined(FEAT_COMMENTS)
556 pos_T *pos;
557#endif
558#ifdef FEAT_SMARTINDENT
559 int do_si = (!p_paste && curbuf->b_p_si
560# ifdef FEAT_CINDENT
561 && !curbuf->b_p_cin
562# endif
563 );
564 int no_si = FALSE; /* reset did_si afterwards */
565 int first_char = NUL; /* init for GCC */
566#endif
567#if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
568 int vreplace_mode;
569#endif
570 int did_append; /* appended a new line */
571 int saved_pi = curbuf->b_p_pi; /* copy of preserveindent setting */
572
573 /*
574 * make a copy of the current line so we can mess with it
575 */
576 saved_line = vim_strsave(ml_get_curline());
577 if (saved_line == NULL) /* out of memory! */
578 return FALSE;
579
580#ifdef FEAT_VREPLACE
581 if (State & VREPLACE_FLAG)
582 {
583 /*
584 * With VREPLACE we make a copy of the next line, which we will be
585 * starting to replace. First make the new line empty and let vim play
586 * with the indenting and comment leader to its heart's content. Then
587 * we grab what it ended up putting on the new line, put back the
588 * original line, and call ins_char() to put each new character onto
589 * the line, replacing what was there before and pushing the right
590 * stuff onto the replace stack. -- webb.
591 */
592 if (curwin->w_cursor.lnum < orig_line_count)
593 next_line = vim_strsave(ml_get(curwin->w_cursor.lnum + 1));
594 else
595 next_line = vim_strsave((char_u *)"");
596 if (next_line == NULL) /* out of memory! */
597 goto theend;
598
599 /*
600 * In VREPLACE mode, a NL replaces the rest of the line, and starts
601 * replacing the next line, so push all of the characters left on the
602 * line onto the replace stack. We'll push any other characters that
603 * might be replaced at the start of the next line (due to autoindent
604 * etc) a bit later.
605 */
606 replace_push(NUL); /* Call twice because BS over NL expects it */
607 replace_push(NUL);
608 p = saved_line + curwin->w_cursor.col;
609 while (*p != NUL)
Bram Moolenaar2c994e82008-01-02 16:49:36 +0000610 {
611#ifdef FEAT_MBYTE
612 if (has_mbyte)
613 p += replace_push_mb(p);
614 else
615#endif
616 replace_push(*p++);
617 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000618 saved_line[curwin->w_cursor.col] = NUL;
619 }
620#endif
621
622 if ((State & INSERT)
623#ifdef FEAT_VREPLACE
624 && !(State & VREPLACE_FLAG)
625#endif
626 )
627 {
628 p_extra = saved_line + curwin->w_cursor.col;
629#ifdef FEAT_SMARTINDENT
630 if (do_si) /* need first char after new line break */
631 {
632 p = skipwhite(p_extra);
633 first_char = *p;
634 }
635#endif
636#ifdef FEAT_COMMENTS
637 extra_len = (int)STRLEN(p_extra);
638#endif
639 saved_char = *p_extra;
640 *p_extra = NUL;
641 }
642
643 u_clearline(); /* cannot do "U" command when adding lines */
644#ifdef FEAT_SMARTINDENT
645 did_si = FALSE;
646#endif
647 ai_col = 0;
648
649 /*
650 * If we just did an auto-indent, then we didn't type anything on
651 * the prior line, and it should be truncated. Do this even if 'ai' is not
652 * set because automatically inserting a comment leader also sets did_ai.
653 */
654 if (dir == FORWARD && did_ai)
655 trunc_line = TRUE;
656
657 /*
658 * If 'autoindent' and/or 'smartindent' is set, try to figure out what
659 * indent to use for the new line.
660 */
661 if (curbuf->b_p_ai
662#ifdef FEAT_SMARTINDENT
663 || do_si
664#endif
665 )
666 {
667 /*
668 * count white space on current line
669 */
670 newindent = get_indent_str(saved_line, (int)curbuf->b_p_ts);
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +0200671 if (newindent == 0 && !(flags & OPENLINE_COM_LIST))
672 newindent = second_line_indent; /* for ^^D command in insert mode */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000673
674#ifdef FEAT_SMARTINDENT
675 /*
676 * Do smart indenting.
677 * In insert/replace mode (only when dir == FORWARD)
678 * we may move some text to the next line. If it starts with '{'
679 * don't add an indent. Fixes inserting a NL before '{' in line
680 * "if (condition) {"
681 */
682 if (!trunc_line && do_si && *saved_line != NUL
683 && (p_extra == NULL || first_char != '{'))
684 {
685 char_u *ptr;
686 char_u last_char;
687
688 old_cursor = curwin->w_cursor;
689 ptr = saved_line;
690# ifdef FEAT_COMMENTS
691 if (flags & OPENLINE_DO_COM)
Bram Moolenaar81340392012-06-06 16:12:59 +0200692 lead_len = get_leader_len(ptr, NULL, FALSE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000693 else
694 lead_len = 0;
695# endif
696 if (dir == FORWARD)
697 {
698 /*
699 * Skip preprocessor directives, unless they are
700 * recognised as comments.
701 */
702 if (
703# ifdef FEAT_COMMENTS
704 lead_len == 0 &&
705# endif
706 ptr[0] == '#')
707 {
708 while (ptr[0] == '#' && curwin->w_cursor.lnum > 1)
709 ptr = ml_get(--curwin->w_cursor.lnum);
710 newindent = get_indent();
711 }
712# ifdef FEAT_COMMENTS
713 if (flags & OPENLINE_DO_COM)
Bram Moolenaar81340392012-06-06 16:12:59 +0200714 lead_len = get_leader_len(ptr, NULL, FALSE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000715 else
716 lead_len = 0;
717 if (lead_len > 0)
718 {
719 /*
720 * This case gets the following right:
721 * \*
722 * * A comment (read '\' as '/').
723 * *\
724 * #define IN_THE_WAY
725 * This should line up here;
726 */
727 p = skipwhite(ptr);
728 if (p[0] == '/' && p[1] == '*')
729 p++;
730 if (p[0] == '*')
731 {
732 for (p++; *p; p++)
733 {
734 if (p[0] == '/' && p[-1] == '*')
735 {
736 /*
737 * End of C comment, indent should line up
738 * with the line containing the start of
739 * the comment
740 */
741 curwin->w_cursor.col = (colnr_T)(p - ptr);
742 if ((pos = findmatch(NULL, NUL)) != NULL)
743 {
744 curwin->w_cursor.lnum = pos->lnum;
745 newindent = get_indent();
746 }
747 }
748 }
749 }
750 }
751 else /* Not a comment line */
752# endif
753 {
754 /* Find last non-blank in line */
755 p = ptr + STRLEN(ptr) - 1;
756 while (p > ptr && vim_iswhite(*p))
757 --p;
758 last_char = *p;
759
760 /*
761 * find the character just before the '{' or ';'
762 */
763 if (last_char == '{' || last_char == ';')
764 {
765 if (p > ptr)
766 --p;
767 while (p > ptr && vim_iswhite(*p))
768 --p;
769 }
770 /*
771 * Try to catch lines that are split over multiple
772 * lines. eg:
773 * if (condition &&
774 * condition) {
775 * Should line up here!
776 * }
777 */
778 if (*p == ')')
779 {
780 curwin->w_cursor.col = (colnr_T)(p - ptr);
781 if ((pos = findmatch(NULL, '(')) != NULL)
782 {
783 curwin->w_cursor.lnum = pos->lnum;
784 newindent = get_indent();
785 ptr = ml_get_curline();
786 }
787 }
788 /*
789 * If last character is '{' do indent, without
790 * checking for "if" and the like.
791 */
792 if (last_char == '{')
793 {
794 did_si = TRUE; /* do indent */
795 no_si = TRUE; /* don't delete it when '{' typed */
796 }
797 /*
798 * Look for "if" and the like, use 'cinwords'.
799 * Don't do this if the previous line ended in ';' or
800 * '}'.
801 */
802 else if (last_char != ';' && last_char != '}'
803 && cin_is_cinword(ptr))
804 did_si = TRUE;
805 }
806 }
807 else /* dir == BACKWARD */
808 {
809 /*
810 * Skip preprocessor directives, unless they are
811 * recognised as comments.
812 */
813 if (
814# ifdef FEAT_COMMENTS
815 lead_len == 0 &&
816# endif
817 ptr[0] == '#')
818 {
819 int was_backslashed = FALSE;
820
821 while ((ptr[0] == '#' || was_backslashed) &&
822 curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
823 {
824 if (*ptr && ptr[STRLEN(ptr) - 1] == '\\')
825 was_backslashed = TRUE;
826 else
827 was_backslashed = FALSE;
828 ptr = ml_get(++curwin->w_cursor.lnum);
829 }
830 if (was_backslashed)
831 newindent = 0; /* Got to end of file */
832 else
833 newindent = get_indent();
834 }
835 p = skipwhite(ptr);
836 if (*p == '}') /* if line starts with '}': do indent */
837 did_si = TRUE;
838 else /* can delete indent when '{' typed */
839 can_si_back = TRUE;
840 }
841 curwin->w_cursor = old_cursor;
842 }
843 if (do_si)
844 can_si = TRUE;
845#endif /* FEAT_SMARTINDENT */
846
847 did_ai = TRUE;
848 }
849
850#ifdef FEAT_COMMENTS
851 /*
852 * Find out if the current line starts with a comment leader.
853 * This may then be inserted in front of the new line.
854 */
855 end_comment_pending = NUL;
856 if (flags & OPENLINE_DO_COM)
Bram Moolenaar81340392012-06-06 16:12:59 +0200857 lead_len = get_leader_len(saved_line, &lead_flags, dir == BACKWARD, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000858 else
859 lead_len = 0;
860 if (lead_len > 0)
861 {
862 char_u *lead_repl = NULL; /* replaces comment leader */
863 int lead_repl_len = 0; /* length of *lead_repl */
864 char_u lead_middle[COM_MAX_LEN]; /* middle-comment string */
865 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
866 char_u *comment_end = NULL; /* where lead_end has been found */
867 int extra_space = FALSE; /* append extra space */
868 int current_flag;
869 int require_blank = FALSE; /* requires blank after middle */
870 char_u *p2;
871
872 /*
873 * If the comment leader has the start, middle or end flag, it may not
874 * be used or may be replaced with the middle leader.
875 */
876 for (p = lead_flags; *p && *p != ':'; ++p)
877 {
878 if (*p == COM_BLANK)
879 {
880 require_blank = TRUE;
881 continue;
882 }
883 if (*p == COM_START || *p == COM_MIDDLE)
884 {
885 current_flag = *p;
886 if (*p == COM_START)
887 {
888 /*
889 * Doing "O" on a start of comment does not insert leader.
890 */
891 if (dir == BACKWARD)
892 {
893 lead_len = 0;
894 break;
895 }
896
897 /* find start of middle part */
898 (void)copy_option_part(&p, lead_middle, COM_MAX_LEN, ",");
899 require_blank = FALSE;
900 }
901
902 /*
903 * Isolate the strings of the middle and end leader.
904 */
905 while (*p && p[-1] != ':') /* find end of middle flags */
906 {
907 if (*p == COM_BLANK)
908 require_blank = TRUE;
909 ++p;
910 }
911 (void)copy_option_part(&p, lead_middle, COM_MAX_LEN, ",");
912
913 while (*p && p[-1] != ':') /* find end of end flags */
914 {
915 /* Check whether we allow automatic ending of comments */
916 if (*p == COM_AUTO_END)
917 end_comment_pending = -1; /* means we want to set it */
918 ++p;
919 }
920 n = copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
921
922 if (end_comment_pending == -1) /* we can set it now */
923 end_comment_pending = lead_end[n - 1];
924
925 /*
926 * If the end of the comment is in the same line, don't use
927 * the comment leader.
928 */
929 if (dir == FORWARD)
930 {
931 for (p = saved_line + lead_len; *p; ++p)
932 if (STRNCMP(p, lead_end, n) == 0)
933 {
934 comment_end = p;
935 lead_len = 0;
936 break;
937 }
938 }
939
940 /*
941 * Doing "o" on a start of comment inserts the middle leader.
942 */
943 if (lead_len > 0)
944 {
945 if (current_flag == COM_START)
946 {
947 lead_repl = lead_middle;
948 lead_repl_len = (int)STRLEN(lead_middle);
949 }
950
951 /*
952 * If we have hit RETURN immediately after the start
953 * comment leader, then put a space after the middle
954 * comment leader on the next line.
955 */
956 if (!vim_iswhite(saved_line[lead_len - 1])
957 && ((p_extra != NULL
958 && (int)curwin->w_cursor.col == lead_len)
959 || (p_extra == NULL
960 && saved_line[lead_len] == NUL)
961 || require_blank))
962 extra_space = TRUE;
963 }
964 break;
965 }
966 if (*p == COM_END)
967 {
968 /*
969 * Doing "o" on the end of a comment does not insert leader.
970 * Remember where the end is, might want to use it to find the
971 * start (for C-comments).
972 */
973 if (dir == FORWARD)
974 {
975 comment_end = skipwhite(saved_line);
976 lead_len = 0;
977 break;
978 }
979
980 /*
981 * Doing "O" on the end of a comment inserts the middle leader.
982 * Find the string for the middle leader, searching backwards.
983 */
984 while (p > curbuf->b_p_com && *p != ',')
985 --p;
986 for (lead_repl = p; lead_repl > curbuf->b_p_com
987 && lead_repl[-1] != ':'; --lead_repl)
988 ;
989 lead_repl_len = (int)(p - lead_repl);
990
991 /* We can probably always add an extra space when doing "O" on
992 * the comment-end */
993 extra_space = TRUE;
994
995 /* Check whether we allow automatic ending of comments */
996 for (p2 = p; *p2 && *p2 != ':'; p2++)
997 {
998 if (*p2 == COM_AUTO_END)
999 end_comment_pending = -1; /* means we want to set it */
1000 }
1001 if (end_comment_pending == -1)
1002 {
1003 /* Find last character in end-comment string */
1004 while (*p2 && *p2 != ',')
1005 p2++;
1006 end_comment_pending = p2[-1];
1007 }
1008 break;
1009 }
1010 if (*p == COM_FIRST)
1011 {
1012 /*
1013 * Comment leader for first line only: Don't repeat leader
1014 * when using "O", blank out leader when using "o".
1015 */
1016 if (dir == BACKWARD)
1017 lead_len = 0;
1018 else
1019 {
1020 lead_repl = (char_u *)"";
1021 lead_repl_len = 0;
1022 }
1023 break;
1024 }
1025 }
1026 if (lead_len)
1027 {
Bram Moolenaardc7e85e2012-06-20 12:40:08 +02001028 /* allocate buffer (may concatenate p_extra later) */
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +02001029 leader = alloc(lead_len + lead_repl_len + extra_space + extra_len
Bram Moolenaardc7e85e2012-06-20 12:40:08 +02001030 + (second_line_indent > 0 ? second_line_indent : 0) + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001031 allocated = leader; /* remember to free it later */
1032
1033 if (leader == NULL)
1034 lead_len = 0;
1035 else
1036 {
Bram Moolenaarce0842a2005-07-18 21:58:11 +00001037 vim_strncpy(leader, saved_line, lead_len);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001038
1039 /*
1040 * Replace leader with lead_repl, right or left adjusted
1041 */
1042 if (lead_repl != NULL)
1043 {
1044 int c = 0;
1045 int off = 0;
1046
Bram Moolenaard7d5b472009-11-11 16:30:08 +00001047 for (p = lead_flags; *p != NUL && *p != ':'; )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001048 {
1049 if (*p == COM_RIGHT || *p == COM_LEFT)
Bram Moolenaard7d5b472009-11-11 16:30:08 +00001050 c = *p++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001051 else if (VIM_ISDIGIT(*p) || *p == '-')
1052 off = getdigits(&p);
Bram Moolenaard7d5b472009-11-11 16:30:08 +00001053 else
1054 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001055 }
1056 if (c == COM_RIGHT) /* right adjusted leader */
1057 {
1058 /* find last non-white in the leader to line up with */
1059 for (p = leader + lead_len - 1; p > leader
1060 && vim_iswhite(*p); --p)
1061 ;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001062 ++p;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001063
1064#ifdef FEAT_MBYTE
1065 /* Compute the length of the replaced characters in
1066 * screen characters, not bytes. */
1067 {
1068 int repl_size = vim_strnsize(lead_repl,
1069 lead_repl_len);
1070 int old_size = 0;
1071 char_u *endp = p;
1072 int l;
1073
1074 while (old_size < repl_size && p > leader)
1075 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001076 mb_ptr_back(leader, p);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001077 old_size += ptr2cells(p);
1078 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001079 l = lead_repl_len - (int)(endp - p);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001080 if (l != 0)
1081 mch_memmove(endp + l, endp,
1082 (size_t)((leader + lead_len) - endp));
1083 lead_len += l;
1084 }
1085#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001086 if (p < leader + lead_repl_len)
1087 p = leader;
1088 else
1089 p -= lead_repl_len;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001090#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001091 mch_memmove(p, lead_repl, (size_t)lead_repl_len);
1092 if (p + lead_repl_len > leader + lead_len)
1093 p[lead_repl_len] = NUL;
1094
1095 /* blank-out any other chars from the old leader. */
1096 while (--p >= leader)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001097 {
1098#ifdef FEAT_MBYTE
1099 int l = mb_head_off(leader, p);
1100
1101 if (l > 1)
1102 {
1103 p -= l;
1104 if (ptr2cells(p) > 1)
1105 {
1106 p[1] = ' ';
1107 --l;
1108 }
1109 mch_memmove(p + 1, p + l + 1,
1110 (size_t)((leader + lead_len) - (p + l + 1)));
1111 lead_len -= l;
1112 *p = ' ';
1113 }
1114 else
1115#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001116 if (!vim_iswhite(*p))
1117 *p = ' ';
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001118 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001119 }
1120 else /* left adjusted leader */
1121 {
1122 p = skipwhite(leader);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001123#ifdef FEAT_MBYTE
1124 /* Compute the length of the replaced characters in
1125 * screen characters, not bytes. Move the part that is
1126 * not to be overwritten. */
1127 {
1128 int repl_size = vim_strnsize(lead_repl,
1129 lead_repl_len);
1130 int i;
1131 int l;
1132
1133 for (i = 0; p[i] != NUL && i < lead_len; i += l)
1134 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00001135 l = (*mb_ptr2len)(p + i);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001136 if (vim_strnsize(p, i + l) > repl_size)
1137 break;
1138 }
1139 if (i != lead_repl_len)
1140 {
1141 mch_memmove(p + lead_repl_len, p + i,
Bram Moolenaar2d7ff052009-11-17 15:08:26 +00001142 (size_t)(lead_len - i - (p - leader)));
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001143 lead_len += lead_repl_len - i;
1144 }
1145 }
1146#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001147 mch_memmove(p, lead_repl, (size_t)lead_repl_len);
1148
1149 /* Replace any remaining non-white chars in the old
1150 * leader by spaces. Keep Tabs, the indent must
1151 * remain the same. */
1152 for (p += lead_repl_len; p < leader + lead_len; ++p)
1153 if (!vim_iswhite(*p))
1154 {
1155 /* Don't put a space before a TAB. */
1156 if (p + 1 < leader + lead_len && p[1] == TAB)
1157 {
1158 --lead_len;
1159 mch_memmove(p, p + 1,
1160 (leader + lead_len) - p);
1161 }
1162 else
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001163 {
1164#ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00001165 int l = (*mb_ptr2len)(p);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001166
1167 if (l > 1)
1168 {
1169 if (ptr2cells(p) > 1)
1170 {
1171 /* Replace a double-wide char with
1172 * two spaces */
1173 --l;
1174 *p++ = ' ';
1175 }
1176 mch_memmove(p + 1, p + l,
1177 (leader + lead_len) - p);
1178 lead_len -= l - 1;
1179 }
1180#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001181 *p = ' ';
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001182 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001183 }
1184 *p = NUL;
1185 }
1186
1187 /* Recompute the indent, it may have changed. */
1188 if (curbuf->b_p_ai
1189#ifdef FEAT_SMARTINDENT
1190 || do_si
1191#endif
1192 )
1193 newindent = get_indent_str(leader, (int)curbuf->b_p_ts);
1194
1195 /* Add the indent offset */
1196 if (newindent + off < 0)
1197 {
1198 off = -newindent;
1199 newindent = 0;
1200 }
1201 else
1202 newindent += off;
1203
1204 /* Correct trailing spaces for the shift, so that
1205 * alignment remains equal. */
1206 while (off > 0 && lead_len > 0
1207 && leader[lead_len - 1] == ' ')
1208 {
1209 /* Don't do it when there is a tab before the space */
1210 if (vim_strchr(skipwhite(leader), '\t') != NULL)
1211 break;
1212 --lead_len;
1213 --off;
1214 }
1215
1216 /* If the leader ends in white space, don't add an
1217 * extra space */
1218 if (lead_len > 0 && vim_iswhite(leader[lead_len - 1]))
1219 extra_space = FALSE;
1220 leader[lead_len] = NUL;
1221 }
1222
1223 if (extra_space)
1224 {
1225 leader[lead_len++] = ' ';
1226 leader[lead_len] = NUL;
1227 }
1228
1229 newcol = lead_len;
1230
1231 /*
1232 * if a new indent will be set below, remove the indent that
1233 * is in the comment leader
1234 */
1235 if (newindent
1236#ifdef FEAT_SMARTINDENT
1237 || did_si
1238#endif
1239 )
1240 {
1241 while (lead_len && vim_iswhite(*leader))
1242 {
1243 --lead_len;
1244 --newcol;
1245 ++leader;
1246 }
1247 }
1248
1249 }
1250#ifdef FEAT_SMARTINDENT
1251 did_si = can_si = FALSE;
1252#endif
1253 }
1254 else if (comment_end != NULL)
1255 {
1256 /*
1257 * We have finished a comment, so we don't use the leader.
1258 * If this was a C-comment and 'ai' or 'si' is set do a normal
1259 * indent to align with the line containing the start of the
1260 * comment.
1261 */
1262 if (comment_end[0] == '*' && comment_end[1] == '/' &&
1263 (curbuf->b_p_ai
1264#ifdef FEAT_SMARTINDENT
1265 || do_si
1266#endif
1267 ))
1268 {
1269 old_cursor = curwin->w_cursor;
1270 curwin->w_cursor.col = (colnr_T)(comment_end - saved_line);
1271 if ((pos = findmatch(NULL, NUL)) != NULL)
1272 {
1273 curwin->w_cursor.lnum = pos->lnum;
1274 newindent = get_indent();
1275 }
1276 curwin->w_cursor = old_cursor;
1277 }
1278 }
1279 }
1280#endif
1281
1282 /* (State == INSERT || State == REPLACE), only when dir == FORWARD */
1283 if (p_extra != NULL)
1284 {
1285 *p_extra = saved_char; /* restore char that NUL replaced */
1286
1287 /*
1288 * When 'ai' set or "flags" has OPENLINE_DELSPACES, skip to the first
1289 * non-blank.
1290 *
1291 * When in REPLACE mode, put the deleted blanks on the replace stack,
1292 * preceded by a NUL, so they can be put back when a BS is entered.
1293 */
1294 if (REPLACE_NORMAL(State))
1295 replace_push(NUL); /* end of extra blanks */
1296 if (curbuf->b_p_ai || (flags & OPENLINE_DELSPACES))
1297 {
1298 while ((*p_extra == ' ' || *p_extra == '\t')
1299#ifdef FEAT_MBYTE
1300 && (!enc_utf8
1301 || !utf_iscomposing(utf_ptr2char(p_extra + 1)))
1302#endif
1303 )
1304 {
1305 if (REPLACE_NORMAL(State))
1306 replace_push(*p_extra);
1307 ++p_extra;
1308 ++less_cols_off;
1309 }
1310 }
1311 if (*p_extra != NUL)
1312 did_ai = FALSE; /* append some text, don't truncate now */
1313
1314 /* columns for marks adjusted for removed columns */
1315 less_cols = (int)(p_extra - saved_line);
1316 }
1317
1318 if (p_extra == NULL)
1319 p_extra = (char_u *)""; /* append empty line */
1320
1321#ifdef FEAT_COMMENTS
1322 /* concatenate leader and p_extra, if there is a leader */
1323 if (lead_len)
1324 {
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +02001325 if (flags & OPENLINE_COM_LIST && second_line_indent > 0)
1326 {
1327 int i;
Bram Moolenaar36105782012-06-14 20:59:25 +02001328 int padding = second_line_indent
1329 - (newindent + (int)STRLEN(leader));
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +02001330
1331 /* Here whitespace is inserted after the comment char.
1332 * Below, set_indent(newindent, SIN_INSERT) will insert the
1333 * whitespace needed before the comment char. */
1334 for (i = 0; i < padding; i++)
1335 {
1336 STRCAT(leader, " ");
Bram Moolenaar5fb9ec52012-07-25 16:10:03 +02001337 less_cols--;
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +02001338 newcol++;
1339 }
1340 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001341 STRCAT(leader, p_extra);
1342 p_extra = leader;
1343 did_ai = TRUE; /* So truncating blanks works with comments */
1344 less_cols -= lead_len;
1345 }
1346 else
1347 end_comment_pending = NUL; /* turns out there was no leader */
1348#endif
1349
1350 old_cursor = curwin->w_cursor;
1351 if (dir == BACKWARD)
1352 --curwin->w_cursor.lnum;
1353#ifdef FEAT_VREPLACE
1354 if (!(State & VREPLACE_FLAG) || old_cursor.lnum >= orig_line_count)
1355#endif
1356 {
1357 if (ml_append(curwin->w_cursor.lnum, p_extra, (colnr_T)0, FALSE)
1358 == FAIL)
1359 goto theend;
1360 /* Postpone calling changed_lines(), because it would mess up folding
1361 * with markers. */
1362 mark_adjust(curwin->w_cursor.lnum + 1, (linenr_T)MAXLNUM, 1L, 0L);
1363 did_append = TRUE;
1364 }
1365#ifdef FEAT_VREPLACE
1366 else
1367 {
1368 /*
1369 * In VREPLACE mode we are starting to replace the next line.
1370 */
1371 curwin->w_cursor.lnum++;
1372 if (curwin->w_cursor.lnum >= Insstart.lnum + vr_lines_changed)
1373 {
1374 /* In case we NL to a new line, BS to the previous one, and NL
1375 * again, we don't want to save the new line for undo twice.
1376 */
1377 (void)u_save_cursor(); /* errors are ignored! */
1378 vr_lines_changed++;
1379 }
1380 ml_replace(curwin->w_cursor.lnum, p_extra, TRUE);
1381 changed_bytes(curwin->w_cursor.lnum, 0);
1382 curwin->w_cursor.lnum--;
1383 did_append = FALSE;
1384 }
1385#endif
1386
1387 if (newindent
1388#ifdef FEAT_SMARTINDENT
1389 || did_si
1390#endif
1391 )
1392 {
1393 ++curwin->w_cursor.lnum;
1394#ifdef FEAT_SMARTINDENT
1395 if (did_si)
1396 {
Bram Moolenaar14f24742012-08-08 18:01:05 +02001397 int sw = (int)get_sw_value();
1398
Bram Moolenaar071d4272004-06-13 20:20:40 +00001399 if (p_sr)
Bram Moolenaar14f24742012-08-08 18:01:05 +02001400 newindent -= newindent % sw;
1401 newindent += sw;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001402 }
1403#endif
Bram Moolenaar5002c292007-07-24 13:26:15 +00001404 /* Copy the indent */
1405 if (curbuf->b_p_ci)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001406 {
1407 (void)copy_indent(newindent, saved_line);
1408
1409 /*
1410 * Set the 'preserveindent' option so that any further screwing
1411 * with the line doesn't entirely destroy our efforts to preserve
1412 * it. It gets restored at the function end.
1413 */
1414 curbuf->b_p_pi = TRUE;
1415 }
1416 else
1417 (void)set_indent(newindent, SIN_INSERT);
1418 less_cols -= curwin->w_cursor.col;
1419
1420 ai_col = curwin->w_cursor.col;
1421
1422 /*
1423 * In REPLACE mode, for each character in the new indent, there must
1424 * be a NUL on the replace stack, for when it is deleted with BS
1425 */
1426 if (REPLACE_NORMAL(State))
1427 for (n = 0; n < (int)curwin->w_cursor.col; ++n)
1428 replace_push(NUL);
1429 newcol += curwin->w_cursor.col;
1430#ifdef FEAT_SMARTINDENT
1431 if (no_si)
1432 did_si = FALSE;
1433#endif
1434 }
1435
1436#ifdef FEAT_COMMENTS
1437 /*
1438 * In REPLACE mode, for each character in the extra leader, there must be
1439 * a NUL on the replace stack, for when it is deleted with BS.
1440 */
1441 if (REPLACE_NORMAL(State))
1442 while (lead_len-- > 0)
1443 replace_push(NUL);
1444#endif
1445
1446 curwin->w_cursor = old_cursor;
1447
1448 if (dir == FORWARD)
1449 {
1450 if (trunc_line || (State & INSERT))
1451 {
1452 /* truncate current line at cursor */
1453 saved_line[curwin->w_cursor.col] = NUL;
1454 /* Remove trailing white space, unless OPENLINE_KEEPTRAIL used. */
1455 if (trunc_line && !(flags & OPENLINE_KEEPTRAIL))
1456 truncate_spaces(saved_line);
1457 ml_replace(curwin->w_cursor.lnum, saved_line, FALSE);
1458 saved_line = NULL;
1459 if (did_append)
1460 {
1461 changed_lines(curwin->w_cursor.lnum, curwin->w_cursor.col,
1462 curwin->w_cursor.lnum + 1, 1L);
1463 did_append = FALSE;
1464
1465 /* Move marks after the line break to the new line. */
1466 if (flags & OPENLINE_MARKFIX)
1467 mark_col_adjust(curwin->w_cursor.lnum,
1468 curwin->w_cursor.col + less_cols_off,
1469 1L, (long)-less_cols);
1470 }
1471 else
1472 changed_bytes(curwin->w_cursor.lnum, curwin->w_cursor.col);
1473 }
1474
1475 /*
1476 * Put the cursor on the new line. Careful: the scrollup() above may
1477 * have moved w_cursor, we must use old_cursor.
1478 */
1479 curwin->w_cursor.lnum = old_cursor.lnum + 1;
1480 }
1481 if (did_append)
1482 changed_lines(curwin->w_cursor.lnum, 0, curwin->w_cursor.lnum, 1L);
1483
1484 curwin->w_cursor.col = newcol;
1485#ifdef FEAT_VIRTUALEDIT
1486 curwin->w_cursor.coladd = 0;
1487#endif
1488
1489#if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
1490 /*
1491 * In VREPLACE mode, we are handling the replace stack ourselves, so stop
1492 * fixthisline() from doing it (via change_indent()) by telling it we're in
1493 * normal INSERT mode.
1494 */
1495 if (State & VREPLACE_FLAG)
1496 {
1497 vreplace_mode = State; /* So we know to put things right later */
1498 State = INSERT;
1499 }
1500 else
1501 vreplace_mode = 0;
1502#endif
1503#ifdef FEAT_LISP
1504 /*
1505 * May do lisp indenting.
1506 */
1507 if (!p_paste
1508# ifdef FEAT_COMMENTS
1509 && leader == NULL
1510# endif
1511 && curbuf->b_p_lisp
1512 && curbuf->b_p_ai)
1513 {
1514 fixthisline(get_lisp_indent);
1515 p = ml_get_curline();
1516 ai_col = (colnr_T)(skipwhite(p) - p);
1517 }
1518#endif
1519#ifdef FEAT_CINDENT
1520 /*
1521 * May do indenting after opening a new line.
1522 */
1523 if (!p_paste
1524 && (curbuf->b_p_cin
1525# ifdef FEAT_EVAL
1526 || *curbuf->b_p_inde != NUL
1527# endif
1528 )
1529 && in_cinkeys(dir == FORWARD
1530 ? KEY_OPEN_FORW
1531 : KEY_OPEN_BACK, ' ', linewhite(curwin->w_cursor.lnum)))
1532 {
1533 do_c_expr_indent();
1534 p = ml_get_curline();
1535 ai_col = (colnr_T)(skipwhite(p) - p);
1536 }
1537#endif
1538#if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
1539 if (vreplace_mode != 0)
1540 State = vreplace_mode;
1541#endif
1542
1543#ifdef FEAT_VREPLACE
1544 /*
1545 * Finally, VREPLACE gets the stuff on the new line, then puts back the
1546 * original line, and inserts the new stuff char by char, pushing old stuff
1547 * onto the replace stack (via ins_char()).
1548 */
1549 if (State & VREPLACE_FLAG)
1550 {
1551 /* Put new line in p_extra */
1552 p_extra = vim_strsave(ml_get_curline());
1553 if (p_extra == NULL)
1554 goto theend;
1555
1556 /* Put back original line */
1557 ml_replace(curwin->w_cursor.lnum, next_line, FALSE);
1558
1559 /* Insert new stuff into line again */
1560 curwin->w_cursor.col = 0;
1561#ifdef FEAT_VIRTUALEDIT
1562 curwin->w_cursor.coladd = 0;
1563#endif
1564 ins_bytes(p_extra); /* will call changed_bytes() */
1565 vim_free(p_extra);
1566 next_line = NULL;
1567 }
1568#endif
1569
1570 retval = TRUE; /* success! */
1571theend:
1572 curbuf->b_p_pi = saved_pi;
1573 vim_free(saved_line);
1574 vim_free(next_line);
1575 vim_free(allocated);
1576 return retval;
1577}
1578
1579#if defined(FEAT_COMMENTS) || defined(PROTO)
1580/*
1581 * get_leader_len() returns the length of the prefix of the given string
1582 * which introduces a comment. If this string is not a comment then 0 is
1583 * returned.
1584 * When "flags" is not NULL, it is set to point to the flags of the recognized
1585 * comment leader.
1586 * "backward" must be true for the "O" command.
Bram Moolenaar81340392012-06-06 16:12:59 +02001587 * If "include_space" is set, include trailing whitespace while calculating the
1588 * length.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001589 */
1590 int
Bram Moolenaar81340392012-06-06 16:12:59 +02001591get_leader_len(line, flags, backward, include_space)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001592 char_u *line;
1593 char_u **flags;
1594 int backward;
Bram Moolenaar81340392012-06-06 16:12:59 +02001595 int include_space;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001596{
1597 int i, j;
Bram Moolenaar81340392012-06-06 16:12:59 +02001598 int result;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001599 int got_com = FALSE;
1600 int found_one;
1601 char_u part_buf[COM_MAX_LEN]; /* buffer for one option part */
1602 char_u *string; /* pointer to comment string */
1603 char_u *list;
Bram Moolenaara4271d52011-05-10 13:38:27 +02001604 int middle_match_len = 0;
1605 char_u *prev_list;
Bram Moolenaar05da4282011-05-10 14:44:11 +02001606 char_u *saved_flags = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001607
Bram Moolenaar81340392012-06-06 16:12:59 +02001608 result = i = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001609 while (vim_iswhite(line[i])) /* leading white space is ignored */
1610 ++i;
1611
1612 /*
1613 * Repeat to match several nested comment strings.
1614 */
Bram Moolenaara4271d52011-05-10 13:38:27 +02001615 while (line[i] != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001616 {
1617 /*
1618 * scan through the 'comments' option for a match
1619 */
1620 found_one = FALSE;
1621 for (list = curbuf->b_p_com; *list; )
1622 {
Bram Moolenaara4271d52011-05-10 13:38:27 +02001623 /* Get one option part into part_buf[]. Advance "list" to next
1624 * one. Put "string" at start of string. */
1625 if (!got_com && flags != NULL)
1626 *flags = list; /* remember where flags started */
1627 prev_list = list;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001628 (void)copy_option_part(&list, part_buf, COM_MAX_LEN, ",");
1629 string = vim_strchr(part_buf, ':');
1630 if (string == NULL) /* missing ':', ignore this part */
1631 continue;
1632 *string++ = NUL; /* isolate flags from string */
1633
Bram Moolenaara4271d52011-05-10 13:38:27 +02001634 /* If we found a middle match previously, use that match when this
1635 * is not a middle or end. */
1636 if (middle_match_len != 0
1637 && vim_strchr(part_buf, COM_MIDDLE) == NULL
1638 && vim_strchr(part_buf, COM_END) == NULL)
1639 break;
1640
1641 /* When we already found a nested comment, only accept further
1642 * nested comments. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001643 if (got_com && vim_strchr(part_buf, COM_NEST) == NULL)
1644 continue;
1645
Bram Moolenaara4271d52011-05-10 13:38:27 +02001646 /* When 'O' flag present and using "O" command skip this one. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001647 if (backward && vim_strchr(part_buf, COM_NOBACK) != NULL)
1648 continue;
1649
Bram Moolenaara4271d52011-05-10 13:38:27 +02001650 /* Line contents and string must match.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001651 * When string starts with white space, must have some white space
1652 * (but the amount does not need to match, there might be a mix of
Bram Moolenaara4271d52011-05-10 13:38:27 +02001653 * TABs and spaces). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001654 if (vim_iswhite(string[0]))
1655 {
1656 if (i == 0 || !vim_iswhite(line[i - 1]))
Bram Moolenaara4271d52011-05-10 13:38:27 +02001657 continue; /* missing shite space */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001658 while (vim_iswhite(string[0]))
1659 ++string;
1660 }
1661 for (j = 0; string[j] != NUL && string[j] == line[i + j]; ++j)
1662 ;
1663 if (string[j] != NUL)
Bram Moolenaara4271d52011-05-10 13:38:27 +02001664 continue; /* string doesn't match */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001665
Bram Moolenaara4271d52011-05-10 13:38:27 +02001666 /* When 'b' flag used, there must be white space or an
1667 * end-of-line after the string in the line. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001668 if (vim_strchr(part_buf, COM_BLANK) != NULL
1669 && !vim_iswhite(line[i + j]) && line[i + j] != NUL)
1670 continue;
1671
Bram Moolenaara4271d52011-05-10 13:38:27 +02001672 /* We have found a match, stop searching unless this is a middle
1673 * comment. The middle comment can be a substring of the end
1674 * comment in which case it's better to return the length of the
1675 * end comment and its flags. Thus we keep searching with middle
1676 * and end matches and use an end match if it matches better. */
1677 if (vim_strchr(part_buf, COM_MIDDLE) != NULL)
1678 {
1679 if (middle_match_len == 0)
1680 {
1681 middle_match_len = j;
1682 saved_flags = prev_list;
1683 }
1684 continue;
1685 }
1686 if (middle_match_len != 0 && j > middle_match_len)
1687 /* Use this match instead of the middle match, since it's a
1688 * longer thus better match. */
1689 middle_match_len = 0;
1690
1691 if (middle_match_len == 0)
1692 i += j;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001693 found_one = TRUE;
1694 break;
1695 }
1696
Bram Moolenaara4271d52011-05-10 13:38:27 +02001697 if (middle_match_len != 0)
1698 {
1699 /* Use the previously found middle match after failing to find a
1700 * match with an end. */
1701 if (!got_com && flags != NULL)
1702 *flags = saved_flags;
1703 i += middle_match_len;
1704 found_one = TRUE;
1705 }
1706
1707 /* No match found, stop scanning. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001708 if (!found_one)
1709 break;
1710
Bram Moolenaar81340392012-06-06 16:12:59 +02001711 result = i;
1712
Bram Moolenaara4271d52011-05-10 13:38:27 +02001713 /* Include any trailing white space. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001714 while (vim_iswhite(line[i]))
1715 ++i;
1716
Bram Moolenaar81340392012-06-06 16:12:59 +02001717 if (include_space)
1718 result = i;
1719
Bram Moolenaara4271d52011-05-10 13:38:27 +02001720 /* If this comment doesn't nest, stop here. */
1721 got_com = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001722 if (vim_strchr(part_buf, COM_NEST) == NULL)
1723 break;
1724 }
Bram Moolenaar81340392012-06-06 16:12:59 +02001725 return result;
1726}
Bram Moolenaara4271d52011-05-10 13:38:27 +02001727
Bram Moolenaar81340392012-06-06 16:12:59 +02001728/*
1729 * Return the offset at which the last comment in line starts. If there is no
1730 * comment in the whole line, -1 is returned.
1731 *
1732 * When "flags" is not null, it is set to point to the flags describing the
1733 * recognized comment leader.
1734 */
1735 int
1736get_last_leader_offset(line, flags)
1737 char_u *line;
1738 char_u **flags;
1739{
1740 int result = -1;
1741 int i, j;
1742 int lower_check_bound = 0;
1743 char_u *string;
1744 char_u *com_leader;
1745 char_u *com_flags;
1746 char_u *list;
1747 int found_one;
1748 char_u part_buf[COM_MAX_LEN]; /* buffer for one option part */
1749
1750 /*
1751 * Repeat to match several nested comment strings.
1752 */
1753 i = (int)STRLEN(line);
1754 while (--i >= lower_check_bound)
1755 {
1756 /*
1757 * scan through the 'comments' option for a match
1758 */
1759 found_one = FALSE;
1760 for (list = curbuf->b_p_com; *list; )
1761 {
1762 char_u *flags_save = list;
1763
1764 /*
1765 * Get one option part into part_buf[]. Advance list to next one.
1766 * put string at start of string.
1767 */
1768 (void)copy_option_part(&list, part_buf, COM_MAX_LEN, ",");
1769 string = vim_strchr(part_buf, ':');
1770 if (string == NULL) /* If everything is fine, this cannot actually
1771 * happen. */
1772 {
1773 continue;
1774 }
1775 *string++ = NUL; /* Isolate flags from string. */
1776 com_leader = string;
1777
1778 /*
1779 * Line contents and string must match.
1780 * When string starts with white space, must have some white space
1781 * (but the amount does not need to match, there might be a mix of
1782 * TABs and spaces).
1783 */
1784 if (vim_iswhite(string[0]))
1785 {
1786 if (i == 0 || !vim_iswhite(line[i - 1]))
1787 continue;
1788 while (vim_iswhite(string[0]))
1789 ++string;
1790 }
1791 for (j = 0; string[j] != NUL && string[j] == line[i + j]; ++j)
1792 /* do nothing */;
1793 if (string[j] != NUL)
1794 continue;
1795
1796 /*
1797 * When 'b' flag used, there must be white space or an
1798 * end-of-line after the string in the line.
1799 */
1800 if (vim_strchr(part_buf, COM_BLANK) != NULL
1801 && !vim_iswhite(line[i + j]) && line[i + j] != NUL)
1802 {
1803 continue;
1804 }
1805
1806 /*
1807 * We have found a match, stop searching.
1808 */
1809 found_one = TRUE;
1810
1811 if (flags)
1812 *flags = flags_save;
1813 com_flags = flags_save;
1814
1815 break;
1816 }
1817
1818 if (found_one)
1819 {
1820 char_u part_buf2[COM_MAX_LEN]; /* buffer for one option part */
1821 int len1, len2, off;
1822
1823 result = i;
1824 /*
1825 * If this comment nests, continue searching.
1826 */
1827 if (vim_strchr(part_buf, COM_NEST) != NULL)
1828 continue;
1829
1830 lower_check_bound = i;
1831
1832 /* Let's verify whether the comment leader found is a substring
1833 * of other comment leaders. If it is, let's adjust the
1834 * lower_check_bound so that we make sure that we have determined
1835 * the comment leader correctly.
1836 */
1837
1838 while (vim_iswhite(*com_leader))
1839 ++com_leader;
1840 len1 = (int)STRLEN(com_leader);
1841
1842 for (list = curbuf->b_p_com; *list; )
1843 {
1844 char_u *flags_save = list;
1845
1846 (void)copy_option_part(&list, part_buf2, COM_MAX_LEN, ",");
1847 if (flags_save == com_flags)
1848 continue;
1849 string = vim_strchr(part_buf2, ':');
1850 ++string;
1851 while (vim_iswhite(*string))
1852 ++string;
1853 len2 = (int)STRLEN(string);
1854 if (len2 == 0)
1855 continue;
1856
1857 /* Now we have to verify whether string ends with a substring
1858 * beginning the com_leader. */
1859 for (off = (len2 > i ? i : len2); off > 0 && off + len1 > len2;)
1860 {
1861 --off;
1862 if (!STRNCMP(string + off, com_leader, len2 - off))
1863 {
1864 if (i - off < lower_check_bound)
1865 lower_check_bound = i - off;
1866 }
1867 }
1868 }
1869 }
1870 }
1871 return result;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001872}
1873#endif
1874
1875/*
1876 * Return the number of window lines occupied by buffer line "lnum".
1877 */
1878 int
1879plines(lnum)
1880 linenr_T lnum;
1881{
1882 return plines_win(curwin, lnum, TRUE);
1883}
1884
1885 int
1886plines_win(wp, lnum, winheight)
1887 win_T *wp;
1888 linenr_T lnum;
1889 int winheight; /* when TRUE limit to window height */
1890{
1891#if defined(FEAT_DIFF) || defined(PROTO)
1892 /* Check for filler lines above this buffer line. When folded the result
1893 * is one line anyway. */
1894 return plines_win_nofill(wp, lnum, winheight) + diff_check_fill(wp, lnum);
1895}
1896
1897 int
1898plines_nofill(lnum)
1899 linenr_T lnum;
1900{
1901 return plines_win_nofill(curwin, lnum, TRUE);
1902}
1903
1904 int
1905plines_win_nofill(wp, lnum, winheight)
1906 win_T *wp;
1907 linenr_T lnum;
1908 int winheight; /* when TRUE limit to window height */
1909{
1910#endif
1911 int lines;
1912
1913 if (!wp->w_p_wrap)
1914 return 1;
1915
1916#ifdef FEAT_VERTSPLIT
1917 if (wp->w_width == 0)
1918 return 1;
1919#endif
1920
1921#ifdef FEAT_FOLDING
1922 /* A folded lines is handled just like an empty line. */
1923 /* NOTE: Caller must handle lines that are MAYBE folded. */
1924 if (lineFolded(wp, lnum) == TRUE)
1925 return 1;
1926#endif
1927
1928 lines = plines_win_nofold(wp, lnum);
1929 if (winheight > 0 && lines > wp->w_height)
1930 return (int)wp->w_height;
1931 return lines;
1932}
1933
1934/*
1935 * Return number of window lines physical line "lnum" will occupy in window
1936 * "wp". Does not care about folding, 'wrap' or 'diff'.
1937 */
1938 int
1939plines_win_nofold(wp, lnum)
1940 win_T *wp;
1941 linenr_T lnum;
1942{
1943 char_u *s;
1944 long col;
1945 int width;
1946
1947 s = ml_get_buf(wp->w_buffer, lnum, FALSE);
1948 if (*s == NUL) /* empty line */
1949 return 1;
1950 col = win_linetabsize(wp, s, (colnr_T)MAXCOL);
1951
1952 /*
1953 * If list mode is on, then the '$' at the end of the line may take up one
1954 * extra column.
1955 */
1956 if (wp->w_p_list && lcs_eol != NUL)
1957 col += 1;
1958
1959 /*
Bram Moolenaar64486672010-05-16 15:46:46 +02001960 * Add column offset for 'number', 'relativenumber' and 'foldcolumn'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001961 */
1962 width = W_WIDTH(wp) - win_col_off(wp);
1963 if (width <= 0)
1964 return 32000;
1965 if (col <= width)
1966 return 1;
1967 col -= width;
1968 width += win_col_off2(wp);
1969 return (col + (width - 1)) / width + 1;
1970}
1971
1972/*
1973 * Like plines_win(), but only reports the number of physical screen lines
1974 * used from the start of the line to the given column number.
1975 */
1976 int
1977plines_win_col(wp, lnum, column)
1978 win_T *wp;
1979 linenr_T lnum;
1980 long column;
1981{
1982 long col;
1983 char_u *s;
1984 int lines = 0;
1985 int width;
1986
1987#ifdef FEAT_DIFF
1988 /* Check for filler lines above this buffer line. When folded the result
1989 * is one line anyway. */
1990 lines = diff_check_fill(wp, lnum);
1991#endif
1992
1993 if (!wp->w_p_wrap)
1994 return lines + 1;
1995
1996#ifdef FEAT_VERTSPLIT
1997 if (wp->w_width == 0)
1998 return lines + 1;
1999#endif
2000
2001 s = ml_get_buf(wp->w_buffer, lnum, FALSE);
2002
2003 col = 0;
2004 while (*s != NUL && --column >= 0)
2005 {
2006 col += win_lbr_chartabsize(wp, s, (colnr_T)col, NULL);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002007 mb_ptr_adv(s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002008 }
2009
2010 /*
2011 * If *s is a TAB, and the TAB is not displayed as ^I, and we're not in
2012 * INSERT mode, then col must be adjusted so that it represents the last
2013 * screen position of the TAB. This only fixes an error when the TAB wraps
2014 * from one screen line to the next (when 'columns' is not a multiple of
2015 * 'ts') -- webb.
2016 */
2017 if (*s == TAB && (State & NORMAL) && (!wp->w_p_list || lcs_tab1))
2018 col += win_lbr_chartabsize(wp, s, (colnr_T)col, NULL) - 1;
2019
2020 /*
Bram Moolenaar64486672010-05-16 15:46:46 +02002021 * Add column offset for 'number', 'relativenumber', 'foldcolumn', etc.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002022 */
2023 width = W_WIDTH(wp) - win_col_off(wp);
Bram Moolenaar26470632006-10-24 19:12:40 +00002024 if (width <= 0)
2025 return 9999;
2026
2027 lines += 1;
2028 if (col > width)
2029 lines += (col - width) / (width + win_col_off2(wp)) + 1;
2030 return lines;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002031}
2032
2033 int
2034plines_m_win(wp, first, last)
2035 win_T *wp;
2036 linenr_T first, last;
2037{
2038 int count = 0;
2039
2040 while (first <= last)
2041 {
2042#ifdef FEAT_FOLDING
2043 int x;
2044
2045 /* Check if there are any really folded lines, but also included lines
2046 * that are maybe folded. */
2047 x = foldedCount(wp, first, NULL);
2048 if (x > 0)
2049 {
2050 ++count; /* count 1 for "+-- folded" line */
2051 first += x;
2052 }
2053 else
2054#endif
2055 {
2056#ifdef FEAT_DIFF
2057 if (first == wp->w_topline)
2058 count += plines_win_nofill(wp, first, TRUE) + wp->w_topfill;
2059 else
2060#endif
2061 count += plines_win(wp, first, TRUE);
2062 ++first;
2063 }
2064 }
2065 return (count);
2066}
2067
2068#if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) || defined(PROTO)
2069/*
2070 * Insert string "p" at the cursor position. Stops at a NUL byte.
2071 * Handles Replace mode and multi-byte characters.
2072 */
2073 void
2074ins_bytes(p)
2075 char_u *p;
2076{
2077 ins_bytes_len(p, (int)STRLEN(p));
2078}
2079#endif
2080
2081#if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) \
2082 || defined(FEAT_COMMENTS) || defined(FEAT_MBYTE) || defined(PROTO)
2083/*
2084 * Insert string "p" with length "len" at the cursor position.
2085 * Handles Replace mode and multi-byte characters.
2086 */
2087 void
2088ins_bytes_len(p, len)
2089 char_u *p;
2090 int len;
2091{
2092 int i;
2093# ifdef FEAT_MBYTE
2094 int n;
2095
Bram Moolenaar176dd1e2008-06-21 14:30:28 +00002096 if (has_mbyte)
2097 for (i = 0; i < len; i += n)
2098 {
2099 if (enc_utf8)
2100 /* avoid reading past p[len] */
2101 n = utfc_ptr2len_len(p + i, len - i);
2102 else
2103 n = (*mb_ptr2len)(p + i);
2104 ins_char_bytes(p + i, n);
2105 }
2106 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002107# endif
Bram Moolenaar176dd1e2008-06-21 14:30:28 +00002108 for (i = 0; i < len; ++i)
2109 ins_char(p[i]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002110}
2111#endif
2112
2113/*
2114 * Insert or replace a single character at the cursor position.
2115 * When in REPLACE or VREPLACE mode, replace any existing character.
2116 * Caller must have prepared for undo.
2117 * For multi-byte characters we get the whole character, the caller must
2118 * convert bytes to a character.
2119 */
2120 void
2121ins_char(c)
2122 int c;
2123{
2124#if defined(FEAT_MBYTE) || defined(PROTO)
Bram Moolenaar9a920d82012-06-01 15:21:02 +02002125 char_u buf[MB_MAXBYTES + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002126 int n;
2127
2128 n = (*mb_char2bytes)(c, buf);
2129
2130 /* When "c" is 0x100, 0x200, etc. we don't want to insert a NUL byte.
2131 * Happens for CTRL-Vu9900. */
2132 if (buf[0] == 0)
2133 buf[0] = '\n';
2134
2135 ins_char_bytes(buf, n);
2136}
2137
2138 void
2139ins_char_bytes(buf, charlen)
2140 char_u *buf;
2141 int charlen;
2142{
2143 int c = buf[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002144#endif
2145 int newlen; /* nr of bytes inserted */
2146 int oldlen; /* nr of bytes deleted (0 when not replacing) */
2147 char_u *p;
2148 char_u *newp;
2149 char_u *oldp;
2150 int linelen; /* length of old line including NUL */
2151 colnr_T col;
2152 linenr_T lnum = curwin->w_cursor.lnum;
2153 int i;
2154
2155#ifdef FEAT_VIRTUALEDIT
2156 /* Break tabs if needed. */
2157 if (virtual_active() && curwin->w_cursor.coladd > 0)
2158 coladvance_force(getviscol());
2159#endif
2160
2161 col = curwin->w_cursor.col;
2162 oldp = ml_get(lnum);
2163 linelen = (int)STRLEN(oldp) + 1;
2164
2165 /* The lengths default to the values for when not replacing. */
2166 oldlen = 0;
2167#ifdef FEAT_MBYTE
2168 newlen = charlen;
2169#else
2170 newlen = 1;
2171#endif
2172
2173 if (State & REPLACE_FLAG)
2174 {
2175#ifdef FEAT_VREPLACE
2176 if (State & VREPLACE_FLAG)
2177 {
2178 colnr_T new_vcol = 0; /* init for GCC */
2179 colnr_T vcol;
2180 int old_list;
2181#ifndef FEAT_MBYTE
2182 char_u buf[2];
2183#endif
2184
2185 /*
2186 * Disable 'list' temporarily, unless 'cpo' contains the 'L' flag.
2187 * Returns the old value of list, so when finished,
2188 * curwin->w_p_list should be set back to this.
2189 */
2190 old_list = curwin->w_p_list;
2191 if (old_list && vim_strchr(p_cpo, CPO_LISTWM) == NULL)
2192 curwin->w_p_list = FALSE;
2193
2194 /*
2195 * In virtual replace mode each character may replace one or more
2196 * characters (zero if it's a TAB). Count the number of bytes to
2197 * be deleted to make room for the new character, counting screen
2198 * cells. May result in adding spaces to fill a gap.
2199 */
2200 getvcol(curwin, &curwin->w_cursor, NULL, &vcol, NULL);
2201#ifndef FEAT_MBYTE
2202 buf[0] = c;
2203 buf[1] = NUL;
2204#endif
2205 new_vcol = vcol + chartabsize(buf, vcol);
2206 while (oldp[col + oldlen] != NUL && vcol < new_vcol)
2207 {
2208 vcol += chartabsize(oldp + col + oldlen, vcol);
2209 /* Don't need to remove a TAB that takes us to the right
2210 * position. */
2211 if (vcol > new_vcol && oldp[col + oldlen] == TAB)
2212 break;
2213#ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002214 oldlen += (*mb_ptr2len)(oldp + col + oldlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002215#else
2216 ++oldlen;
2217#endif
2218 /* Deleted a bit too much, insert spaces. */
2219 if (vcol > new_vcol)
2220 newlen += vcol - new_vcol;
2221 }
2222 curwin->w_p_list = old_list;
2223 }
2224 else
2225#endif
2226 if (oldp[col] != NUL)
2227 {
2228 /* normal replace */
2229#ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002230 oldlen = (*mb_ptr2len)(oldp + col);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002231#else
2232 oldlen = 1;
2233#endif
2234 }
2235
2236
2237 /* Push the replaced bytes onto the replace stack, so that they can be
2238 * put back when BS is used. The bytes of a multi-byte character are
2239 * done the other way around, so that the first byte is popped off
2240 * first (it tells the byte length of the character). */
2241 replace_push(NUL);
2242 for (i = 0; i < oldlen; ++i)
2243 {
2244#ifdef FEAT_MBYTE
Bram Moolenaar2c994e82008-01-02 16:49:36 +00002245 if (has_mbyte)
2246 i += replace_push_mb(oldp + col + i) - 1;
2247 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002248#endif
Bram Moolenaar2c994e82008-01-02 16:49:36 +00002249 replace_push(oldp[col + i]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002250 }
2251 }
2252
2253 newp = alloc_check((unsigned)(linelen + newlen - oldlen));
2254 if (newp == NULL)
2255 return;
2256
2257 /* Copy bytes before the cursor. */
2258 if (col > 0)
2259 mch_memmove(newp, oldp, (size_t)col);
2260
2261 /* Copy bytes after the changed character(s). */
2262 p = newp + col;
2263 mch_memmove(p + newlen, oldp + col + oldlen,
2264 (size_t)(linelen - col - oldlen));
2265
2266 /* Insert or overwrite the new character. */
2267#ifdef FEAT_MBYTE
2268 mch_memmove(p, buf, charlen);
2269 i = charlen;
2270#else
2271 *p = c;
2272 i = 1;
2273#endif
2274
2275 /* Fill with spaces when necessary. */
2276 while (i < newlen)
2277 p[i++] = ' ';
2278
2279 /* Replace the line in the buffer. */
2280 ml_replace(lnum, newp, FALSE);
2281
2282 /* mark the buffer as changed and prepare for displaying */
2283 changed_bytes(lnum, col);
2284
2285 /*
2286 * If we're in Insert or Replace mode and 'showmatch' is set, then briefly
2287 * show the match for right parens and braces.
2288 */
2289 if (p_sm && (State & INSERT)
2290 && msg_silent == 0
2291#ifdef FEAT_MBYTE
2292 && charlen == 1
2293#endif
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00002294#ifdef FEAT_INS_EXPAND
2295 && !ins_compl_active()
2296#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002297 )
2298 showmatch(c);
2299
2300#ifdef FEAT_RIGHTLEFT
2301 if (!p_ri || (State & REPLACE_FLAG))
2302#endif
2303 {
2304 /* Normal insert: move cursor right */
2305#ifdef FEAT_MBYTE
2306 curwin->w_cursor.col += charlen;
2307#else
2308 ++curwin->w_cursor.col;
2309#endif
2310 }
2311 /*
2312 * TODO: should try to update w_row here, to avoid recomputing it later.
2313 */
2314}
2315
2316/*
2317 * Insert a string at the cursor position.
2318 * Note: Does NOT handle Replace mode.
2319 * Caller must have prepared for undo.
2320 */
2321 void
2322ins_str(s)
2323 char_u *s;
2324{
2325 char_u *oldp, *newp;
2326 int newlen = (int)STRLEN(s);
2327 int oldlen;
2328 colnr_T col;
2329 linenr_T lnum = curwin->w_cursor.lnum;
2330
2331#ifdef FEAT_VIRTUALEDIT
2332 if (virtual_active() && curwin->w_cursor.coladd > 0)
2333 coladvance_force(getviscol());
2334#endif
2335
2336 col = curwin->w_cursor.col;
2337 oldp = ml_get(lnum);
2338 oldlen = (int)STRLEN(oldp);
2339
2340 newp = alloc_check((unsigned)(oldlen + newlen + 1));
2341 if (newp == NULL)
2342 return;
2343 if (col > 0)
2344 mch_memmove(newp, oldp, (size_t)col);
2345 mch_memmove(newp + col, s, (size_t)newlen);
2346 mch_memmove(newp + col + newlen, oldp + col, (size_t)(oldlen - col + 1));
2347 ml_replace(lnum, newp, FALSE);
2348 changed_bytes(lnum, col);
2349 curwin->w_cursor.col += newlen;
2350}
2351
2352/*
2353 * Delete one character under the cursor.
2354 * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
2355 * Caller must have prepared for undo.
2356 *
2357 * return FAIL for failure, OK otherwise
2358 */
2359 int
2360del_char(fixpos)
2361 int fixpos;
2362{
2363#ifdef FEAT_MBYTE
2364 if (has_mbyte)
2365 {
2366 /* Make sure the cursor is at the start of a character. */
2367 mb_adjust_cursor();
2368 if (*ml_get_cursor() == NUL)
2369 return FAIL;
2370 return del_chars(1L, fixpos);
2371 }
2372#endif
Bram Moolenaare3226be2005-12-18 22:10:00 +00002373 return del_bytes(1L, fixpos, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002374}
2375
2376#if defined(FEAT_MBYTE) || defined(PROTO)
2377/*
2378 * Like del_bytes(), but delete characters instead of bytes.
2379 */
2380 int
2381del_chars(count, fixpos)
2382 long count;
2383 int fixpos;
2384{
2385 long bytes = 0;
2386 long i;
2387 char_u *p;
2388 int l;
2389
2390 p = ml_get_cursor();
2391 for (i = 0; i < count && *p != NUL; ++i)
2392 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002393 l = (*mb_ptr2len)(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002394 bytes += l;
2395 p += l;
2396 }
Bram Moolenaare3226be2005-12-18 22:10:00 +00002397 return del_bytes(bytes, fixpos, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002398}
2399#endif
2400
2401/*
2402 * Delete "count" bytes under the cursor.
2403 * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
2404 * Caller must have prepared for undo.
2405 *
2406 * return FAIL for failure, OK otherwise
2407 */
2408 int
Bram Moolenaarca003e12006-03-17 23:19:38 +00002409del_bytes(count, fixpos_arg, use_delcombine)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002410 long count;
Bram Moolenaarca003e12006-03-17 23:19:38 +00002411 int fixpos_arg;
Bram Moolenaar78a15312009-05-15 19:33:18 +00002412 int use_delcombine UNUSED; /* 'delcombine' option applies */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002413{
2414 char_u *oldp, *newp;
2415 colnr_T oldlen;
2416 linenr_T lnum = curwin->w_cursor.lnum;
2417 colnr_T col = curwin->w_cursor.col;
2418 int was_alloced;
2419 long movelen;
Bram Moolenaarca003e12006-03-17 23:19:38 +00002420 int fixpos = fixpos_arg;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002421
2422 oldp = ml_get(lnum);
2423 oldlen = (int)STRLEN(oldp);
2424
2425 /*
2426 * Can't do anything when the cursor is on the NUL after the line.
2427 */
2428 if (col >= oldlen)
2429 return FAIL;
2430
2431#ifdef FEAT_MBYTE
2432 /* If 'delcombine' is set and deleting (less than) one character, only
2433 * delete the last combining character. */
Bram Moolenaare3226be2005-12-18 22:10:00 +00002434 if (p_deco && use_delcombine && enc_utf8
2435 && utfc_ptr2len(oldp + col) >= count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002436 {
Bram Moolenaar362e1a32006-03-06 23:29:24 +00002437 int cc[MAX_MCO];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002438 int n;
2439
Bram Moolenaar362e1a32006-03-06 23:29:24 +00002440 (void)utfc_ptr2char(oldp + col, cc);
2441 if (cc[0] != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002442 {
2443 /* Find the last composing char, there can be several. */
2444 n = col;
2445 do
2446 {
2447 col = n;
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002448 count = utf_ptr2len(oldp + n);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002449 n += count;
2450 } while (UTF_COMPOSINGLIKE(oldp + col, oldp + n));
2451 fixpos = 0;
2452 }
2453 }
2454#endif
2455
2456 /*
2457 * When count is too big, reduce it.
2458 */
2459 movelen = (long)oldlen - (long)col - count + 1; /* includes trailing NUL */
2460 if (movelen <= 1)
2461 {
2462 /*
2463 * If we just took off the last character of a non-blank line, and
Bram Moolenaarca003e12006-03-17 23:19:38 +00002464 * fixpos is TRUE, we don't want to end up positioned at the NUL,
2465 * unless "restart_edit" is set or 'virtualedit' contains "onemore".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002466 */
Bram Moolenaarca003e12006-03-17 23:19:38 +00002467 if (col > 0 && fixpos && restart_edit == 0
2468#ifdef FEAT_VIRTUALEDIT
2469 && (ve_flags & VE_ONEMORE) == 0
2470#endif
2471 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00002472 {
2473 --curwin->w_cursor.col;
2474#ifdef FEAT_VIRTUALEDIT
2475 curwin->w_cursor.coladd = 0;
2476#endif
2477#ifdef FEAT_MBYTE
2478 if (has_mbyte)
2479 curwin->w_cursor.col -=
2480 (*mb_head_off)(oldp, oldp + curwin->w_cursor.col);
2481#endif
2482 }
2483 count = oldlen - col;
2484 movelen = 1;
2485 }
2486
2487 /*
2488 * If the old line has been allocated the deletion can be done in the
2489 * existing line. Otherwise a new line has to be allocated
Bram Moolenaare21877a2008-02-13 09:58:14 +00002490 * Can't do this when using Netbeans, because we would need to invoke
2491 * netbeans_removed(), which deallocates the line. Let ml_replace() take
Bram Moolenaar1a509df2010-08-01 17:59:57 +02002492 * care of notifying Netbeans.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002493 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002494#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02002495 if (netbeans_active())
Bram Moolenaare21877a2008-02-13 09:58:14 +00002496 was_alloced = FALSE;
2497 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002498#endif
Bram Moolenaare21877a2008-02-13 09:58:14 +00002499 was_alloced = ml_line_alloced(); /* check if oldp was allocated */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002500 if (was_alloced)
2501 newp = oldp; /* use same allocated memory */
2502 else
2503 { /* need to allocate a new line */
2504 newp = alloc((unsigned)(oldlen + 1 - count));
2505 if (newp == NULL)
2506 return FAIL;
2507 mch_memmove(newp, oldp, (size_t)col);
2508 }
2509 mch_memmove(newp + col, oldp + col + count, (size_t)movelen);
2510 if (!was_alloced)
2511 ml_replace(lnum, newp, FALSE);
2512
2513 /* mark the buffer as changed and prepare for displaying */
2514 changed_bytes(lnum, curwin->w_cursor.col);
2515
2516 return OK;
2517}
2518
2519/*
2520 * Delete from cursor to end of line.
2521 * Caller must have prepared for undo.
2522 *
2523 * return FAIL for failure, OK otherwise
2524 */
2525 int
2526truncate_line(fixpos)
2527 int fixpos; /* if TRUE fix the cursor position when done */
2528{
2529 char_u *newp;
2530 linenr_T lnum = curwin->w_cursor.lnum;
2531 colnr_T col = curwin->w_cursor.col;
2532
2533 if (col == 0)
2534 newp = vim_strsave((char_u *)"");
2535 else
2536 newp = vim_strnsave(ml_get(lnum), col);
2537
2538 if (newp == NULL)
2539 return FAIL;
2540
2541 ml_replace(lnum, newp, FALSE);
2542
2543 /* mark the buffer as changed and prepare for displaying */
2544 changed_bytes(lnum, curwin->w_cursor.col);
2545
2546 /*
2547 * If "fixpos" is TRUE we don't want to end up positioned at the NUL.
2548 */
2549 if (fixpos && curwin->w_cursor.col > 0)
2550 --curwin->w_cursor.col;
2551
2552 return OK;
2553}
2554
2555/*
2556 * Delete "nlines" lines at the cursor.
2557 * Saves the lines for undo first if "undo" is TRUE.
2558 */
2559 void
2560del_lines(nlines, undo)
2561 long nlines; /* number of lines to delete */
2562 int undo; /* if TRUE, prepare for undo */
2563{
2564 long n;
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002565 linenr_T first = curwin->w_cursor.lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002566
2567 if (nlines <= 0)
2568 return;
2569
2570 /* save the deleted lines for undo */
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002571 if (undo && u_savedel(first, nlines) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002572 return;
2573
2574 for (n = 0; n < nlines; )
2575 {
2576 if (curbuf->b_ml.ml_flags & ML_EMPTY) /* nothing to delete */
2577 break;
2578
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002579 ml_delete(first, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002580 ++n;
2581
2582 /* If we delete the last line in the file, stop */
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002583 if (first > curbuf->b_ml.ml_line_count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002584 break;
2585 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002586
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002587 /* Correct the cursor position before calling deleted_lines_mark(), it may
2588 * trigger a callback to display the cursor. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002589 curwin->w_cursor.col = 0;
2590 check_cursor_lnum();
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002591
2592 /* adjust marks, mark the buffer as changed and prepare for displaying */
2593 deleted_lines_mark(first, n);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002594}
2595
2596 int
2597gchar_pos(pos)
2598 pos_T *pos;
2599{
2600 char_u *ptr = ml_get_pos(pos);
2601
2602#ifdef FEAT_MBYTE
2603 if (has_mbyte)
2604 return (*mb_ptr2char)(ptr);
2605#endif
2606 return (int)*ptr;
2607}
2608
2609 int
2610gchar_cursor()
2611{
2612#ifdef FEAT_MBYTE
2613 if (has_mbyte)
2614 return (*mb_ptr2char)(ml_get_cursor());
2615#endif
2616 return (int)*ml_get_cursor();
2617}
2618
2619/*
2620 * Write a character at the current cursor position.
2621 * It is directly written into the block.
2622 */
2623 void
2624pchar_cursor(c)
2625 int c;
2626{
2627 *(ml_get_buf(curbuf, curwin->w_cursor.lnum, TRUE)
2628 + curwin->w_cursor.col) = c;
2629}
2630
Bram Moolenaar071d4272004-06-13 20:20:40 +00002631/*
2632 * When extra == 0: Return TRUE if the cursor is before or on the first
2633 * non-blank in the line.
2634 * When extra == 1: Return TRUE if the cursor is before the first non-blank in
2635 * the line.
2636 */
2637 int
2638inindent(extra)
2639 int extra;
2640{
2641 char_u *ptr;
2642 colnr_T col;
2643
2644 for (col = 0, ptr = ml_get_curline(); vim_iswhite(*ptr); ++col)
2645 ++ptr;
2646 if (col >= curwin->w_cursor.col + extra)
2647 return TRUE;
2648 else
2649 return FALSE;
2650}
2651
2652/*
2653 * Skip to next part of an option argument: Skip space and comma.
2654 */
2655 char_u *
2656skip_to_option_part(p)
2657 char_u *p;
2658{
2659 if (*p == ',')
2660 ++p;
2661 while (*p == ' ')
2662 ++p;
2663 return p;
2664}
2665
2666/*
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002667 * Call this function when something in the current buffer is changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002668 *
2669 * Most often called through changed_bytes() and changed_lines(), which also
2670 * mark the area of the display to be redrawn.
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002671 *
2672 * Careful: may trigger autocommands that reload the buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002673 */
2674 void
2675changed()
2676{
2677#if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
2678 /* The text of the preediting area is inserted, but this doesn't
2679 * mean a change of the buffer yet. That is delayed until the
2680 * text is committed. (this means preedit becomes empty) */
2681 if (im_is_preediting() && !xim_changed_while_preediting)
2682 return;
2683 xim_changed_while_preediting = FALSE;
2684#endif
2685
2686 if (!curbuf->b_changed)
2687 {
2688 int save_msg_scroll = msg_scroll;
2689
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002690 /* Give a warning about changing a read-only file. This may also
2691 * check-out the file, thus change "curbuf"! */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002692 change_warning(0);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002693
Bram Moolenaar071d4272004-06-13 20:20:40 +00002694 /* Create a swap file if that is wanted.
2695 * Don't do this for "nofile" and "nowrite" buffer types. */
2696 if (curbuf->b_may_swap
2697#ifdef FEAT_QUICKFIX
2698 && !bt_dontwrite(curbuf)
2699#endif
2700 )
2701 {
2702 ml_open_file(curbuf);
2703
2704 /* The ml_open_file() can cause an ATTENTION message.
2705 * Wait two seconds, to make sure the user reads this unexpected
2706 * message. Since we could be anywhere, call wait_return() now,
2707 * and don't let the emsg() set msg_scroll. */
2708 if (need_wait_return && emsg_silent == 0)
2709 {
2710 out_flush();
2711 ui_delay(2000L, TRUE);
2712 wait_return(TRUE);
2713 msg_scroll = save_msg_scroll;
2714 }
2715 }
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02002716 changed_int();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002717 }
2718 ++curbuf->b_changedtick;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002719}
2720
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02002721/*
2722 * Internal part of changed(), no user interaction.
2723 */
2724 void
2725changed_int()
2726{
2727 curbuf->b_changed = TRUE;
2728 ml_setflags(curbuf);
2729#ifdef FEAT_WINDOWS
2730 check_status(curbuf);
2731 redraw_tabline = TRUE;
2732#endif
2733#ifdef FEAT_TITLE
2734 need_maketitle = TRUE; /* set window title later */
2735#endif
2736}
2737
Bram Moolenaardba8a912005-04-24 22:08:39 +00002738static void changedOneline __ARGS((buf_T *buf, linenr_T lnum));
2739static void changed_lines_buf __ARGS((buf_T *buf, linenr_T lnum, linenr_T lnume, long xtra));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002740static void changed_common __ARGS((linenr_T lnum, colnr_T col, linenr_T lnume, long xtra));
2741
2742/*
2743 * Changed bytes within a single line for the current buffer.
2744 * - marks the windows on this buffer to be redisplayed
2745 * - marks the buffer changed by calling changed()
2746 * - invalidates cached values
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002747 * Careful: may trigger autocommands that reload the buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002748 */
2749 void
2750changed_bytes(lnum, col)
2751 linenr_T lnum;
2752 colnr_T col;
2753{
Bram Moolenaardba8a912005-04-24 22:08:39 +00002754 changedOneline(curbuf, lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002755 changed_common(lnum, col, lnum + 1, 0L);
Bram Moolenaardba8a912005-04-24 22:08:39 +00002756
2757#ifdef FEAT_DIFF
2758 /* Diff highlighting in other diff windows may need to be updated too. */
2759 if (curwin->w_p_diff)
2760 {
2761 win_T *wp;
2762 linenr_T wlnum;
2763
2764 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2765 if (wp->w_p_diff && wp != curwin)
2766 {
2767 redraw_win_later(wp, VALID);
2768 wlnum = diff_lnum_win(lnum, wp);
2769 if (wlnum > 0)
2770 changedOneline(wp->w_buffer, wlnum);
2771 }
2772 }
2773#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002774}
2775
2776 static void
Bram Moolenaardba8a912005-04-24 22:08:39 +00002777changedOneline(buf, lnum)
2778 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002779 linenr_T lnum;
2780{
Bram Moolenaardba8a912005-04-24 22:08:39 +00002781 if (buf->b_mod_set)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002782 {
2783 /* find the maximum area that must be redisplayed */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002784 if (lnum < buf->b_mod_top)
2785 buf->b_mod_top = lnum;
2786 else if (lnum >= buf->b_mod_bot)
2787 buf->b_mod_bot = lnum + 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002788 }
2789 else
2790 {
2791 /* set the area that must be redisplayed to one line */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002792 buf->b_mod_set = TRUE;
2793 buf->b_mod_top = lnum;
2794 buf->b_mod_bot = lnum + 1;
2795 buf->b_mod_xlines = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002796 }
2797}
2798
2799/*
2800 * Appended "count" lines below line "lnum" in the current buffer.
2801 * Must be called AFTER the change and after mark_adjust().
2802 * Takes care of marking the buffer to be redrawn and sets the changed flag.
2803 */
2804 void
2805appended_lines(lnum, count)
2806 linenr_T lnum;
2807 long count;
2808{
2809 changed_lines(lnum + 1, 0, lnum + 1, count);
2810}
2811
2812/*
2813 * Like appended_lines(), but adjust marks first.
2814 */
2815 void
2816appended_lines_mark(lnum, count)
2817 linenr_T lnum;
2818 long count;
2819{
2820 mark_adjust(lnum + 1, (linenr_T)MAXLNUM, count, 0L);
2821 changed_lines(lnum + 1, 0, lnum + 1, count);
2822}
2823
2824/*
2825 * Deleted "count" lines at line "lnum" in the current buffer.
2826 * Must be called AFTER the change and after mark_adjust().
2827 * Takes care of marking the buffer to be redrawn and sets the changed flag.
2828 */
2829 void
2830deleted_lines(lnum, count)
2831 linenr_T lnum;
2832 long count;
2833{
2834 changed_lines(lnum, 0, lnum + count, -count);
2835}
2836
2837/*
2838 * Like deleted_lines(), but adjust marks first.
Bram Moolenaarcdcaa582009-07-09 18:06:49 +00002839 * Make sure the cursor is on a valid line before calling, a GUI callback may
2840 * be triggered to display the cursor.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002841 */
2842 void
2843deleted_lines_mark(lnum, count)
2844 linenr_T lnum;
2845 long count;
2846{
2847 mark_adjust(lnum, (linenr_T)(lnum + count - 1), (long)MAXLNUM, -count);
2848 changed_lines(lnum, 0, lnum + count, -count);
2849}
2850
2851/*
2852 * Changed lines for the current buffer.
2853 * Must be called AFTER the change and after mark_adjust().
2854 * - mark the buffer changed by calling changed()
2855 * - mark the windows on this buffer to be redisplayed
2856 * - invalidate cached values
2857 * "lnum" is the first line that needs displaying, "lnume" the first line
2858 * below the changed lines (BEFORE the change).
2859 * When only inserting lines, "lnum" and "lnume" are equal.
2860 * Takes care of calling changed() and updating b_mod_*.
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002861 * Careful: may trigger autocommands that reload the buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002862 */
2863 void
2864changed_lines(lnum, col, lnume, xtra)
2865 linenr_T lnum; /* first line with change */
2866 colnr_T col; /* column in first line with change */
2867 linenr_T lnume; /* line below last changed line */
2868 long xtra; /* number of extra lines (negative when deleting) */
2869{
Bram Moolenaardba8a912005-04-24 22:08:39 +00002870 changed_lines_buf(curbuf, lnum, lnume, xtra);
2871
2872#ifdef FEAT_DIFF
2873 if (xtra == 0 && curwin->w_p_diff)
2874 {
2875 /* When the number of lines doesn't change then mark_adjust() isn't
2876 * called and other diff buffers still need to be marked for
2877 * displaying. */
2878 win_T *wp;
2879 linenr_T wlnum;
2880
2881 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2882 if (wp->w_p_diff && wp != curwin)
2883 {
2884 redraw_win_later(wp, VALID);
2885 wlnum = diff_lnum_win(lnum, wp);
2886 if (wlnum > 0)
2887 changed_lines_buf(wp->w_buffer, wlnum,
2888 lnume - lnum + wlnum, 0L);
2889 }
2890 }
2891#endif
2892
2893 changed_common(lnum, col, lnume, xtra);
2894}
2895
2896 static void
2897changed_lines_buf(buf, lnum, lnume, xtra)
2898 buf_T *buf;
2899 linenr_T lnum; /* first line with change */
2900 linenr_T lnume; /* line below last changed line */
2901 long xtra; /* number of extra lines (negative when deleting) */
2902{
2903 if (buf->b_mod_set)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002904 {
2905 /* find the maximum area that must be redisplayed */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002906 if (lnum < buf->b_mod_top)
2907 buf->b_mod_top = lnum;
2908 if (lnum < buf->b_mod_bot)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002909 {
2910 /* adjust old bot position for xtra lines */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002911 buf->b_mod_bot += xtra;
2912 if (buf->b_mod_bot < lnum)
2913 buf->b_mod_bot = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002914 }
Bram Moolenaardba8a912005-04-24 22:08:39 +00002915 if (lnume + xtra > buf->b_mod_bot)
2916 buf->b_mod_bot = lnume + xtra;
2917 buf->b_mod_xlines += xtra;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002918 }
2919 else
2920 {
2921 /* set the area that must be redisplayed */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002922 buf->b_mod_set = TRUE;
2923 buf->b_mod_top = lnum;
2924 buf->b_mod_bot = lnume + xtra;
2925 buf->b_mod_xlines = xtra;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002926 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002927}
2928
Bram Moolenaarb0b50882010-07-07 18:26:28 +02002929/*
2930 * Common code for when a change is was made.
2931 * See changed_lines() for the arguments.
2932 * Careful: may trigger autocommands that reload the buffer.
2933 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002934 static void
2935changed_common(lnum, col, lnume, xtra)
2936 linenr_T lnum;
2937 colnr_T col;
2938 linenr_T lnume;
2939 long xtra;
2940{
2941 win_T *wp;
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00002942#ifdef FEAT_WINDOWS
2943 tabpage_T *tp;
2944#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002945 int i;
2946#ifdef FEAT_JUMPLIST
2947 int cols;
2948 pos_T *p;
2949 int add;
2950#endif
2951
2952 /* mark the buffer as modified */
2953 changed();
2954
2955 /* set the '. mark */
2956 if (!cmdmod.keepjumps)
2957 {
2958 curbuf->b_last_change.lnum = lnum;
2959 curbuf->b_last_change.col = col;
2960
2961#ifdef FEAT_JUMPLIST
2962 /* Create a new entry if a new undo-able change was started or we
2963 * don't have an entry yet. */
2964 if (curbuf->b_new_change || curbuf->b_changelistlen == 0)
2965 {
2966 if (curbuf->b_changelistlen == 0)
2967 add = TRUE;
2968 else
2969 {
2970 /* Don't create a new entry when the line number is the same
2971 * as the last one and the column is not too far away. Avoids
2972 * creating many entries for typing "xxxxx". */
2973 p = &curbuf->b_changelist[curbuf->b_changelistlen - 1];
2974 if (p->lnum != lnum)
2975 add = TRUE;
2976 else
2977 {
2978 cols = comp_textwidth(FALSE);
2979 if (cols == 0)
2980 cols = 79;
2981 add = (p->col + cols < col || col + cols < p->col);
2982 }
2983 }
2984 if (add)
2985 {
2986 /* This is the first of a new sequence of undo-able changes
2987 * and it's at some distance of the last change. Use a new
2988 * position in the changelist. */
2989 curbuf->b_new_change = FALSE;
2990
2991 if (curbuf->b_changelistlen == JUMPLISTSIZE)
2992 {
2993 /* changelist is full: remove oldest entry */
2994 curbuf->b_changelistlen = JUMPLISTSIZE - 1;
2995 mch_memmove(curbuf->b_changelist, curbuf->b_changelist + 1,
2996 sizeof(pos_T) * (JUMPLISTSIZE - 1));
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00002997 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002998 {
2999 /* Correct position in changelist for other windows on
3000 * this buffer. */
3001 if (wp->w_buffer == curbuf && wp->w_changelistidx > 0)
3002 --wp->w_changelistidx;
3003 }
3004 }
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00003005 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003006 {
3007 /* For other windows, if the position in the changelist is
3008 * at the end it stays at the end. */
3009 if (wp->w_buffer == curbuf
3010 && wp->w_changelistidx == curbuf->b_changelistlen)
3011 ++wp->w_changelistidx;
3012 }
3013 ++curbuf->b_changelistlen;
3014 }
3015 }
3016 curbuf->b_changelist[curbuf->b_changelistlen - 1] =
3017 curbuf->b_last_change;
3018 /* The current window is always after the last change, so that "g,"
3019 * takes you back to it. */
3020 curwin->w_changelistidx = curbuf->b_changelistlen;
3021#endif
3022 }
3023
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00003024 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003025 {
3026 if (wp->w_buffer == curbuf)
3027 {
3028 /* Mark this window to be redrawn later. */
3029 if (wp->w_redr_type < VALID)
3030 wp->w_redr_type = VALID;
3031
3032 /* Check if a change in the buffer has invalidated the cached
3033 * values for the cursor. */
3034#ifdef FEAT_FOLDING
3035 /*
3036 * Update the folds for this window. Can't postpone this, because
3037 * a following operator might work on the whole fold: ">>dd".
3038 */
3039 foldUpdate(wp, lnum, lnume + xtra - 1);
3040
3041 /* The change may cause lines above or below the change to become
3042 * included in a fold. Set lnum/lnume to the first/last line that
3043 * might be displayed differently.
3044 * Set w_cline_folded here as an efficient way to update it when
3045 * inserting lines just above a closed fold. */
3046 i = hasFoldingWin(wp, lnum, &lnum, NULL, FALSE, NULL);
3047 if (wp->w_cursor.lnum == lnum)
3048 wp->w_cline_folded = i;
3049 i = hasFoldingWin(wp, lnume, NULL, &lnume, FALSE, NULL);
3050 if (wp->w_cursor.lnum == lnume)
3051 wp->w_cline_folded = i;
3052
3053 /* If the changed line is in a range of previously folded lines,
3054 * compare with the first line in that range. */
3055 if (wp->w_cursor.lnum <= lnum)
3056 {
3057 i = find_wl_entry(wp, lnum);
3058 if (i >= 0 && wp->w_cursor.lnum > wp->w_lines[i].wl_lnum)
3059 changed_line_abv_curs_win(wp);
3060 }
3061#endif
3062
3063 if (wp->w_cursor.lnum > lnum)
3064 changed_line_abv_curs_win(wp);
3065 else if (wp->w_cursor.lnum == lnum && wp->w_cursor.col >= col)
3066 changed_cline_bef_curs_win(wp);
3067 if (wp->w_botline >= lnum)
3068 {
3069 /* Assume that botline doesn't change (inserted lines make
3070 * other lines scroll down below botline). */
3071 approximate_botline_win(wp);
3072 }
3073
3074 /* Check if any w_lines[] entries have become invalid.
3075 * For entries below the change: Correct the lnums for
3076 * inserted/deleted lines. Makes it possible to stop displaying
3077 * after the change. */
3078 for (i = 0; i < wp->w_lines_valid; ++i)
3079 if (wp->w_lines[i].wl_valid)
3080 {
3081 if (wp->w_lines[i].wl_lnum >= lnum)
3082 {
3083 if (wp->w_lines[i].wl_lnum < lnume)
3084 {
3085 /* line included in change */
3086 wp->w_lines[i].wl_valid = FALSE;
3087 }
3088 else if (xtra != 0)
3089 {
3090 /* line below change */
3091 wp->w_lines[i].wl_lnum += xtra;
3092#ifdef FEAT_FOLDING
3093 wp->w_lines[i].wl_lastlnum += xtra;
3094#endif
3095 }
3096 }
3097#ifdef FEAT_FOLDING
3098 else if (wp->w_lines[i].wl_lastlnum >= lnum)
3099 {
3100 /* change somewhere inside this range of folded lines,
3101 * may need to be redrawn */
3102 wp->w_lines[i].wl_valid = FALSE;
3103 }
3104#endif
3105 }
Bram Moolenaar3234cc62009-11-03 17:47:12 +00003106
3107#ifdef FEAT_FOLDING
3108 /* Take care of side effects for setting w_topline when folds have
3109 * changed. Esp. when the buffer was changed in another window. */
3110 if (hasAnyFolding(wp))
3111 set_topline(wp, wp->w_topline);
3112#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003113 }
3114 }
3115
3116 /* Call update_screen() later, which checks out what needs to be redrawn,
3117 * since it notices b_mod_set and then uses b_mod_*. */
3118 if (must_redraw < VALID)
3119 must_redraw = VALID;
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00003120
3121#ifdef FEAT_AUTOCMD
3122 /* when the cursor line is changed always trigger CursorMoved */
Bram Moolenaare163f1c2006-10-17 09:12:21 +00003123 if (lnum <= curwin->w_cursor.lnum
3124 && lnume + (xtra < 0 ? -xtra : xtra) > curwin->w_cursor.lnum)
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00003125 last_cursormoved.lnum = 0;
3126#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003127}
3128
3129/*
3130 * unchanged() is called when the changed flag must be reset for buffer 'buf'
3131 */
3132 void
3133unchanged(buf, ff)
3134 buf_T *buf;
3135 int ff; /* also reset 'fileformat' */
3136{
Bram Moolenaar164c60f2011-01-22 00:11:50 +01003137 if (buf->b_changed || (ff && file_ff_differs(buf, FALSE)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003138 {
3139 buf->b_changed = 0;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003140 ml_setflags(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003141 if (ff)
3142 save_file_ff(buf);
3143#ifdef FEAT_WINDOWS
3144 check_status(buf);
Bram Moolenaar997fb4b2006-02-17 21:53:23 +00003145 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003146#endif
3147#ifdef FEAT_TITLE
3148 need_maketitle = TRUE; /* set window title later */
3149#endif
3150 }
3151 ++buf->b_changedtick;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003152#ifdef FEAT_NETBEANS_INTG
3153 netbeans_unmodified(buf);
3154#endif
3155}
3156
3157#if defined(FEAT_WINDOWS) || defined(PROTO)
3158/*
3159 * check_status: called when the status bars for the buffer 'buf'
3160 * need to be updated
3161 */
3162 void
3163check_status(buf)
3164 buf_T *buf;
3165{
3166 win_T *wp;
3167
3168 for (wp = firstwin; wp != NULL; wp = wp->w_next)
3169 if (wp->w_buffer == buf && wp->w_status_height)
3170 {
3171 wp->w_redr_status = TRUE;
3172 if (must_redraw < VALID)
3173 must_redraw = VALID;
3174 }
3175}
3176#endif
3177
3178/*
3179 * If the file is readonly, give a warning message with the first change.
3180 * Don't do this for autocommands.
3181 * Don't use emsg(), because it flushes the macro buffer.
Bram Moolenaard5cdbeb2005-10-10 20:59:28 +00003182 * If we have undone all changes b_changed will be FALSE, but "b_did_warn"
Bram Moolenaar071d4272004-06-13 20:20:40 +00003183 * will be TRUE.
Bram Moolenaarb0b50882010-07-07 18:26:28 +02003184 * Careful: may trigger autocommands that reload the buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003185 */
3186 void
3187change_warning(col)
3188 int col; /* column for message; non-zero when in insert
3189 mode and 'showmode' is on */
3190{
Bram Moolenaar496c5262009-03-18 14:42:00 +00003191 static char *w_readonly = N_("W10: Warning: Changing a readonly file");
3192
Bram Moolenaar071d4272004-06-13 20:20:40 +00003193 if (curbuf->b_did_warn == FALSE
3194 && curbufIsChanged() == 0
3195#ifdef FEAT_AUTOCMD
3196 && !autocmd_busy
3197#endif
3198 && curbuf->b_p_ro)
3199 {
3200#ifdef FEAT_AUTOCMD
Bram Moolenaar910f66f2006-04-05 20:41:53 +00003201 ++curbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003202 apply_autocmds(EVENT_FILECHANGEDRO, NULL, NULL, FALSE, curbuf);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00003203 --curbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003204 if (!curbuf->b_p_ro)
3205 return;
3206#endif
3207 /*
3208 * Do what msg() does, but with a column offset if the warning should
3209 * be after the mode message.
3210 */
3211 msg_start();
3212 if (msg_row == Rows - 1)
3213 msg_col = col;
Bram Moolenaar2df6dcc2004-07-12 15:53:54 +00003214 msg_source(hl_attr(HLF_W));
Bram Moolenaar496c5262009-03-18 14:42:00 +00003215 MSG_PUTS_ATTR(_(w_readonly), hl_attr(HLF_W) | MSG_HIST);
3216#ifdef FEAT_EVAL
3217 set_vim_var_string(VV_WARNINGMSG, (char_u *)_(w_readonly), -1);
3218#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003219 msg_clr_eos();
3220 (void)msg_end();
3221 if (msg_silent == 0 && !silent_mode)
3222 {
3223 out_flush();
3224 ui_delay(1000L, TRUE); /* give the user time to think about it */
3225 }
3226 curbuf->b_did_warn = TRUE;
3227 redraw_cmdline = FALSE; /* don't redraw and erase the message */
3228 if (msg_row < Rows - 1)
3229 showmode();
3230 }
3231}
3232
3233/*
3234 * Ask for a reply from the user, a 'y' or a 'n'.
3235 * No other characters are accepted, the message is repeated until a valid
3236 * reply is entered or CTRL-C is hit.
3237 * If direct is TRUE, don't use vgetc() but ui_inchar(), don't get characters
3238 * from any buffers but directly from the user.
3239 *
3240 * return the 'y' or 'n'
3241 */
3242 int
3243ask_yesno(str, direct)
3244 char_u *str;
3245 int direct;
3246{
3247 int r = ' ';
3248 int save_State = State;
3249
3250 if (exiting) /* put terminal in raw mode for this question */
3251 settmode(TMODE_RAW);
3252 ++no_wait_return;
3253#ifdef USE_ON_FLY_SCROLL
3254 dont_scroll = TRUE; /* disallow scrolling here */
3255#endif
3256 State = CONFIRM; /* mouse behaves like with :confirm */
3257#ifdef FEAT_MOUSE
3258 setmouse(); /* disables mouse for xterm */
3259#endif
3260 ++no_mapping;
3261 ++allow_keys; /* no mapping here, but recognize keys */
3262
3263 while (r != 'y' && r != 'n')
3264 {
3265 /* same highlighting as for wait_return */
3266 smsg_attr(hl_attr(HLF_R), (char_u *)"%s (y/n)?", str);
3267 if (direct)
3268 r = get_keystroke();
3269 else
Bram Moolenaar913626c2008-01-03 11:43:42 +00003270 r = plain_vgetc();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003271 if (r == Ctrl_C || r == ESC)
3272 r = 'n';
3273 msg_putchar(r); /* show what you typed */
3274 out_flush();
3275 }
3276 --no_wait_return;
3277 State = save_State;
3278#ifdef FEAT_MOUSE
3279 setmouse();
3280#endif
3281 --no_mapping;
3282 --allow_keys;
3283
3284 return r;
3285}
3286
3287/*
3288 * Get a key stroke directly from the user.
3289 * Ignores mouse clicks and scrollbar events, except a click for the left
3290 * button (used at the more prompt).
3291 * Doesn't use vgetc(), because it syncs undo and eats mapped characters.
3292 * Disadvantage: typeahead is ignored.
3293 * Translates the interrupt character for unix to ESC.
3294 */
3295 int
3296get_keystroke()
3297{
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003298 char_u *buf = NULL;
3299 int buflen = 150;
3300 int maxlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003301 int len = 0;
3302 int n;
3303 int save_mapped_ctrl_c = mapped_ctrl_c;
Bram Moolenaar4395a712006-09-05 18:57:57 +00003304 int waited = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003305
3306 mapped_ctrl_c = FALSE; /* mappings are not used here */
3307 for (;;)
3308 {
3309 cursor_on();
3310 out_flush();
3311
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003312 /* Leave some room for check_termcode() to insert a key code into (max
3313 * 5 chars plus NUL). And fix_input_buffer() can triple the number of
3314 * bytes. */
3315 maxlen = (buflen - 6 - len) / 3;
3316 if (buf == NULL)
3317 buf = alloc(buflen);
3318 else if (maxlen < 10)
3319 {
Bram Moolenaardc7e85e2012-06-20 12:40:08 +02003320 /* Need some more space. This might happen when receiving a long
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003321 * escape sequence. */
3322 buflen += 100;
3323 buf = vim_realloc(buf, buflen);
3324 maxlen = (buflen - 6 - len) / 3;
3325 }
3326 if (buf == NULL)
3327 {
3328 do_outofmem_msg((long_u)buflen);
3329 return ESC; /* panic! */
3330 }
3331
Bram Moolenaar071d4272004-06-13 20:20:40 +00003332 /* First time: blocking wait. Second time: wait up to 100ms for a
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003333 * terminal code to complete. */
3334 n = ui_inchar(buf + len, maxlen, len == 0 ? -1L : 100L, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003335 if (n > 0)
3336 {
3337 /* Replace zero and CSI by a special key code. */
3338 n = fix_input_buffer(buf + len, n, FALSE);
3339 len += n;
Bram Moolenaar4395a712006-09-05 18:57:57 +00003340 waited = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003341 }
Bram Moolenaar4395a712006-09-05 18:57:57 +00003342 else if (len > 0)
3343 ++waited; /* keep track of the waiting time */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003344
Bram Moolenaar4395a712006-09-05 18:57:57 +00003345 /* Incomplete termcode and not timed out yet: get more characters */
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003346 if ((n = check_termcode(1, buf, buflen, &len)) < 0
Bram Moolenaar4395a712006-09-05 18:57:57 +00003347 && (!p_ttimeout || waited * 100L < (p_ttm < 0 ? p_tm : p_ttm)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003348 continue;
Bram Moolenaar4395a712006-09-05 18:57:57 +00003349
Bram Moolenaar946ffd42010-12-30 12:30:31 +01003350 if (n == KEYLEN_REMOVED) /* key code removed */
Bram Moolenaar6eb634e2011-03-03 15:04:08 +01003351 {
Bram Moolenaarfd30cd42011-03-22 13:07:26 +01003352 if (must_redraw != 0 && !need_wait_return && (State & CMDLINE) == 0)
Bram Moolenaar6eb634e2011-03-03 15:04:08 +01003353 {
3354 /* Redrawing was postponed, do it now. */
3355 update_screen(0);
3356 setcursor(); /* put cursor back where it belongs */
3357 }
Bram Moolenaar946ffd42010-12-30 12:30:31 +01003358 continue;
Bram Moolenaar6eb634e2011-03-03 15:04:08 +01003359 }
Bram Moolenaar946ffd42010-12-30 12:30:31 +01003360 if (n > 0) /* found a termcode: adjust length */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003361 len = n;
Bram Moolenaar946ffd42010-12-30 12:30:31 +01003362 if (len == 0) /* nothing typed yet */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003363 continue;
3364
3365 /* Handle modifier and/or special key code. */
3366 n = buf[0];
3367 if (n == K_SPECIAL)
3368 {
3369 n = TO_SPECIAL(buf[1], buf[2]);
3370 if (buf[1] == KS_MODIFIER
3371 || n == K_IGNORE
3372#ifdef FEAT_MOUSE
3373 || n == K_LEFTMOUSE_NM
3374 || n == K_LEFTDRAG
3375 || n == K_LEFTRELEASE
3376 || n == K_LEFTRELEASE_NM
3377 || n == K_MIDDLEMOUSE
3378 || n == K_MIDDLEDRAG
3379 || n == K_MIDDLERELEASE
3380 || n == K_RIGHTMOUSE
3381 || n == K_RIGHTDRAG
3382 || n == K_RIGHTRELEASE
3383 || n == K_MOUSEDOWN
3384 || n == K_MOUSEUP
Bram Moolenaar8d9b40e2010-07-25 15:49:07 +02003385 || n == K_MOUSELEFT
3386 || n == K_MOUSERIGHT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003387 || n == K_X1MOUSE
3388 || n == K_X1DRAG
3389 || n == K_X1RELEASE
3390 || n == K_X2MOUSE
3391 || n == K_X2DRAG
3392 || n == K_X2RELEASE
3393# ifdef FEAT_GUI
3394 || n == K_VER_SCROLLBAR
3395 || n == K_HOR_SCROLLBAR
3396# endif
3397#endif
3398 )
3399 {
3400 if (buf[1] == KS_MODIFIER)
3401 mod_mask = buf[2];
3402 len -= 3;
3403 if (len > 0)
3404 mch_memmove(buf, buf + 3, (size_t)len);
3405 continue;
3406 }
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00003407 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003408 }
3409#ifdef FEAT_MBYTE
3410 if (has_mbyte)
3411 {
3412 if (MB_BYTE2LEN(n) > len)
3413 continue; /* more bytes to get */
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003414 buf[len >= buflen ? buflen - 1 : len] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003415 n = (*mb_ptr2char)(buf);
3416 }
3417#endif
3418#ifdef UNIX
3419 if (n == intr_char)
3420 n = ESC;
3421#endif
3422 break;
3423 }
Bram Moolenaara8c8a682012-02-05 22:05:48 +01003424 vim_free(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003425
3426 mapped_ctrl_c = save_mapped_ctrl_c;
3427 return n;
3428}
3429
3430/*
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003431 * Get a number from the user.
3432 * When "mouse_used" is not NULL allow using the mouse.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003433 */
3434 int
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003435get_number(colon, mouse_used)
3436 int colon; /* allow colon to abort */
3437 int *mouse_used;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003438{
3439 int n = 0;
3440 int c;
Bram Moolenaar3991dab2006-03-27 17:01:56 +00003441 int typed = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003442
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003443 if (mouse_used != NULL)
3444 *mouse_used = FALSE;
3445
Bram Moolenaar071d4272004-06-13 20:20:40 +00003446 /* When not printing messages, the user won't know what to type, return a
3447 * zero (as if CR was hit). */
3448 if (msg_silent != 0)
3449 return 0;
3450
3451#ifdef USE_ON_FLY_SCROLL
3452 dont_scroll = TRUE; /* disallow scrolling here */
3453#endif
3454 ++no_mapping;
3455 ++allow_keys; /* no mapping here, but recognize keys */
3456 for (;;)
3457 {
3458 windgoto(msg_row, msg_col);
3459 c = safe_vgetc();
3460 if (VIM_ISDIGIT(c))
3461 {
3462 n = n * 10 + c - '0';
3463 msg_putchar(c);
Bram Moolenaar3991dab2006-03-27 17:01:56 +00003464 ++typed;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003465 }
3466 else if (c == K_DEL || c == K_KDEL || c == K_BS || c == Ctrl_H)
3467 {
Bram Moolenaar3991dab2006-03-27 17:01:56 +00003468 if (typed > 0)
3469 {
3470 MSG_PUTS("\b \b");
3471 --typed;
3472 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003473 n /= 10;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003474 }
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003475#ifdef FEAT_MOUSE
3476 else if (mouse_used != NULL && c == K_LEFTMOUSE)
3477 {
3478 *mouse_used = TRUE;
3479 n = mouse_row + 1;
3480 break;
3481 }
3482#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003483 else if (n == 0 && c == ':' && colon)
3484 {
3485 stuffcharReadbuff(':');
3486 if (!exmode_active)
3487 cmdline_row = msg_row;
3488 skip_redraw = TRUE; /* skip redraw once */
3489 do_redraw = FALSE;
3490 break;
3491 }
3492 else if (c == CAR || c == NL || c == Ctrl_C || c == ESC)
3493 break;
3494 }
3495 --no_mapping;
3496 --allow_keys;
3497 return n;
3498}
3499
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003500/*
3501 * Ask the user to enter a number.
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003502 * When "mouse_used" is not NULL allow using the mouse and in that case return
3503 * the line number.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003504 */
3505 int
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003506prompt_for_number(mouse_used)
3507 int *mouse_used;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003508{
3509 int i;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003510 int save_cmdline_row;
3511 int save_State;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003512
3513 /* When using ":silent" assume that <CR> was entered. */
Bram Moolenaar42eeac32005-06-29 22:40:58 +00003514 if (mouse_used != NULL)
Bram Moolenaard812df62008-11-09 12:46:09 +00003515 MSG_PUTS(_("Type number and <Enter> or click with mouse (empty cancels): "));
Bram Moolenaar42eeac32005-06-29 22:40:58 +00003516 else
Bram Moolenaard812df62008-11-09 12:46:09 +00003517 MSG_PUTS(_("Type number and <Enter> (empty cancels): "));
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003518
Bram Moolenaar203335e2006-09-03 14:35:42 +00003519 /* Set the state such that text can be selected/copied/pasted and we still
3520 * get mouse events. */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003521 save_cmdline_row = cmdline_row;
Bram Moolenaar203335e2006-09-03 14:35:42 +00003522 cmdline_row = 0;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003523 save_State = State;
Bram Moolenaar203335e2006-09-03 14:35:42 +00003524 State = CMDLINE;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003525
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003526 i = get_number(TRUE, mouse_used);
3527 if (KeyTyped)
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003528 {
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003529 /* don't call wait_return() now */
3530 /* msg_putchar('\n'); */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003531 cmdline_row = msg_row - 1;
3532 need_wait_return = FALSE;
3533 msg_didany = FALSE;
Bram Moolenaarb2450162009-07-22 09:04:20 +00003534 msg_didout = FALSE;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003535 }
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003536 else
3537 cmdline_row = save_cmdline_row;
3538 State = save_State;
3539
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003540 return i;
3541}
3542
Bram Moolenaar071d4272004-06-13 20:20:40 +00003543 void
3544msgmore(n)
3545 long n;
3546{
3547 long pn;
3548
3549 if (global_busy /* no messages now, wait until global is finished */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003550 || !messaging()) /* 'lazyredraw' set, don't do messages now */
3551 return;
3552
Bram Moolenaar7df2d662005-01-25 22:18:08 +00003553 /* We don't want to overwrite another important message, but do overwrite
3554 * a previous "more lines" or "fewer lines" message, so that "5dd" and
3555 * then "put" reports the last action. */
3556 if (keep_msg != NULL && !keep_msg_more)
3557 return;
3558
Bram Moolenaar071d4272004-06-13 20:20:40 +00003559 if (n > 0)
3560 pn = n;
3561 else
3562 pn = -n;
3563
3564 if (pn > p_report)
3565 {
3566 if (pn == 1)
3567 {
3568 if (n > 0)
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003569 vim_strncpy(msg_buf, (char_u *)_("1 more line"),
3570 MSG_BUF_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003571 else
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003572 vim_strncpy(msg_buf, (char_u *)_("1 line less"),
3573 MSG_BUF_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003574 }
3575 else
3576 {
3577 if (n > 0)
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003578 vim_snprintf((char *)msg_buf, MSG_BUF_LEN,
3579 _("%ld more lines"), pn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003580 else
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003581 vim_snprintf((char *)msg_buf, MSG_BUF_LEN,
3582 _("%ld fewer lines"), pn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003583 }
3584 if (got_int)
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02003585 vim_strcat(msg_buf, (char_u *)_(" (Interrupted)"), MSG_BUF_LEN);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003586 if (msg(msg_buf))
3587 {
Bram Moolenaar238a5642006-02-21 22:12:05 +00003588 set_keep_msg(msg_buf, 0);
Bram Moolenaar7df2d662005-01-25 22:18:08 +00003589 keep_msg_more = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003590 }
3591 }
3592}
3593
3594/*
3595 * flush map and typeahead buffers and give a warning for an error
3596 */
3597 void
3598beep_flush()
3599{
3600 if (emsg_silent == 0)
3601 {
3602 flush_buffers(FALSE);
3603 vim_beep();
3604 }
3605}
3606
3607/*
3608 * give a warning for an error
3609 */
3610 void
3611vim_beep()
3612{
3613 if (emsg_silent == 0)
3614 {
3615 if (p_vb
3616#ifdef FEAT_GUI
3617 /* While the GUI is starting up the termcap is set for the GUI
3618 * but the output still goes to a terminal. */
3619 && !(gui.in_use && gui.starting)
3620#endif
3621 )
3622 {
3623 out_str(T_VB);
3624 }
3625 else
3626 {
3627#ifdef MSDOS
3628 /*
3629 * The number of beeps outputted is reduced to avoid having to wait
3630 * for all the beeps to finish. This is only a problem on systems
3631 * where the beeps don't overlap.
3632 */
3633 if (beep_count == 0 || beep_count == 10)
3634 {
3635 out_char(BELL);
3636 beep_count = 1;
3637 }
3638 else
3639 ++beep_count;
3640#else
3641 out_char(BELL);
3642#endif
3643 }
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003644
3645 /* When 'verbose' is set and we are sourcing a script or executing a
3646 * function give the user a hint where the beep comes from. */
3647 if (vim_strchr(p_debug, 'e') != NULL)
3648 {
3649 msg_source(hl_attr(HLF_W));
3650 msg_attr((char_u *)_("Beep!"), hl_attr(HLF_W));
3651 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003652 }
3653}
3654
3655/*
3656 * To get the "real" home directory:
3657 * - get value of $HOME
3658 * For Unix:
3659 * - go to that directory
3660 * - do mch_dirname() to get the real name of that directory.
3661 * This also works with mounts and links.
3662 * Don't do this for MS-DOS, it will change the "current dir" for a drive.
3663 */
3664static char_u *homedir = NULL;
3665
3666 void
3667init_homedir()
3668{
3669 char_u *var;
3670
Bram Moolenaar05159a02005-02-26 23:04:13 +00003671 /* In case we are called a second time (when 'encoding' changes). */
3672 vim_free(homedir);
3673 homedir = NULL;
3674
Bram Moolenaar071d4272004-06-13 20:20:40 +00003675#ifdef VMS
3676 var = mch_getenv((char_u *)"SYS$LOGIN");
3677#else
3678 var = mch_getenv((char_u *)"HOME");
3679#endif
3680
3681 if (var != NULL && *var == NUL) /* empty is same as not set */
3682 var = NULL;
3683
3684#ifdef WIN3264
3685 /*
3686 * Weird but true: $HOME may contain an indirect reference to another
3687 * variable, esp. "%USERPROFILE%". Happens when $USERPROFILE isn't set
3688 * when $HOME is being set.
3689 */
3690 if (var != NULL && *var == '%')
3691 {
3692 char_u *p;
3693 char_u *exp;
3694
3695 p = vim_strchr(var + 1, '%');
3696 if (p != NULL)
3697 {
Bram Moolenaarce0842a2005-07-18 21:58:11 +00003698 vim_strncpy(NameBuff, var + 1, p - (var + 1));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003699 exp = mch_getenv(NameBuff);
3700 if (exp != NULL && *exp != NUL
3701 && STRLEN(exp) + STRLEN(p) < MAXPATHL)
3702 {
Bram Moolenaar555b2802005-05-19 21:08:39 +00003703 vim_snprintf((char *)NameBuff, MAXPATHL, "%s%s", exp, p + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003704 var = NameBuff;
3705 /* Also set $HOME, it's needed for _viminfo. */
3706 vim_setenv((char_u *)"HOME", NameBuff);
3707 }
3708 }
3709 }
3710
3711 /*
3712 * Typically, $HOME is not defined on Windows, unless the user has
3713 * specifically defined it for Vim's sake. However, on Windows NT
3714 * platforms, $HOMEDRIVE and $HOMEPATH are automatically defined for
3715 * each user. Try constructing $HOME from these.
3716 */
3717 if (var == NULL)
3718 {
3719 char_u *homedrive, *homepath;
3720
3721 homedrive = mch_getenv((char_u *)"HOMEDRIVE");
3722 homepath = mch_getenv((char_u *)"HOMEPATH");
Bram Moolenaar6f977012010-01-06 17:53:38 +01003723 if (homepath == NULL || *homepath == NUL)
3724 homepath = "\\";
3725 if (homedrive != NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00003726 && STRLEN(homedrive) + STRLEN(homepath) < MAXPATHL)
3727 {
3728 sprintf((char *)NameBuff, "%s%s", homedrive, homepath);
3729 if (NameBuff[0] != NUL)
3730 {
3731 var = NameBuff;
3732 /* Also set $HOME, it's needed for _viminfo. */
3733 vim_setenv((char_u *)"HOME", NameBuff);
3734 }
3735 }
3736 }
Bram Moolenaar05159a02005-02-26 23:04:13 +00003737
3738# if defined(FEAT_MBYTE)
3739 if (enc_utf8 && var != NULL)
3740 {
3741 int len;
Bram Moolenaarb453a532011-04-28 17:48:44 +02003742 char_u *pp = NULL;
Bram Moolenaar05159a02005-02-26 23:04:13 +00003743
3744 /* Convert from active codepage to UTF-8. Other conversions are
3745 * not done, because they would fail for non-ASCII characters. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003746 acp_to_enc(var, (int)STRLEN(var), &pp, &len);
Bram Moolenaar05159a02005-02-26 23:04:13 +00003747 if (pp != NULL)
3748 {
3749 homedir = pp;
3750 return;
3751 }
3752 }
3753# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003754#endif
3755
3756#if defined(OS2) || defined(MSDOS) || defined(MSWIN)
3757 /*
3758 * Default home dir is C:/
3759 * Best assumption we can make in such a situation.
3760 */
3761 if (var == NULL)
3762 var = "C:/";
3763#endif
3764 if (var != NULL)
3765 {
3766#ifdef UNIX
3767 /*
3768 * Change to the directory and get the actual path. This resolves
3769 * links. Don't do it when we can't return.
3770 */
3771 if (mch_dirname(NameBuff, MAXPATHL) == OK
3772 && mch_chdir((char *)NameBuff) == 0)
3773 {
3774 if (!mch_chdir((char *)var) && mch_dirname(IObuff, IOSIZE) == OK)
3775 var = IObuff;
3776 if (mch_chdir((char *)NameBuff) != 0)
3777 EMSG(_(e_prev_dir));
3778 }
3779#endif
3780 homedir = vim_strsave(var);
3781 }
3782}
3783
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003784#if defined(EXITFREE) || defined(PROTO)
3785 void
3786free_homedir()
3787{
3788 vim_free(homedir);
3789}
Bram Moolenaar24305862012-08-15 14:05:05 +02003790
3791# ifdef FEAT_CMDL_COMPL
3792 void
3793free_users()
3794{
3795 ga_clear_strings(&ga_users);
3796}
3797# endif
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003798#endif
3799
Bram Moolenaar071d4272004-06-13 20:20:40 +00003800/*
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003801 * Call expand_env() and store the result in an allocated string.
3802 * This is not very memory efficient, this expects the result to be freed
3803 * again soon.
3804 */
3805 char_u *
3806expand_env_save(src)
3807 char_u *src;
3808{
3809 return expand_env_save_opt(src, FALSE);
3810}
3811
3812/*
3813 * Idem, but when "one" is TRUE handle the string as one file name, only
3814 * expand "~" at the start.
3815 */
3816 char_u *
3817expand_env_save_opt(src, one)
3818 char_u *src;
3819 int one;
3820{
3821 char_u *p;
3822
3823 p = alloc(MAXPATHL);
3824 if (p != NULL)
3825 expand_env_esc(src, p, MAXPATHL, FALSE, one, NULL);
3826 return p;
3827}
3828
3829/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003830 * Expand environment variable with path name.
3831 * "~/" is also expanded, using $HOME. For Unix "~user/" is expanded.
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003832 * Skips over "\ ", "\~" and "\$" (not for Win32 though).
Bram Moolenaar071d4272004-06-13 20:20:40 +00003833 * If anything fails no expansion is done and dst equals src.
3834 */
3835 void
3836expand_env(src, dst, dstlen)
3837 char_u *src; /* input string e.g. "$HOME/vim.hlp" */
3838 char_u *dst; /* where to put the result */
3839 int dstlen; /* maximum length of the result */
3840{
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003841 expand_env_esc(src, dst, dstlen, FALSE, FALSE, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003842}
3843
3844 void
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003845expand_env_esc(srcp, dst, dstlen, esc, one, startstr)
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003846 char_u *srcp; /* input string e.g. "$HOME/vim.hlp" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003847 char_u *dst; /* where to put the result */
3848 int dstlen; /* maximum length of the result */
3849 int esc; /* escape spaces in expanded variables */
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00003850 int one; /* "srcp" is one file name */
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003851 char_u *startstr; /* start again after this (can be NULL) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003852{
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003853 char_u *src;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003854 char_u *tail;
3855 int c;
3856 char_u *var;
3857 int copy_char;
3858 int mustfree; /* var was allocated, need to free it later */
3859 int at_start = TRUE; /* at start of a name */
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003860 int startstr_len = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003861
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003862 if (startstr != NULL)
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003863 startstr_len = (int)STRLEN(startstr);
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003864
3865 src = skipwhite(srcp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003866 --dstlen; /* leave one char space for "\," */
3867 while (*src && dstlen > 0)
3868 {
3869 copy_char = TRUE;
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003870 if ((*src == '$'
3871#ifdef VMS
3872 && at_start
3873#endif
3874 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003875#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3876 || *src == '%'
3877#endif
3878 || (*src == '~' && at_start))
3879 {
3880 mustfree = FALSE;
3881
3882 /*
3883 * The variable name is copied into dst temporarily, because it may
3884 * be a string in read-only memory and a NUL needs to be appended.
3885 */
3886 if (*src != '~') /* environment var */
3887 {
3888 tail = src + 1;
3889 var = dst;
3890 c = dstlen - 1;
3891
3892#ifdef UNIX
3893 /* Unix has ${var-name} type environment vars */
3894 if (*tail == '{' && !vim_isIDc('{'))
3895 {
3896 tail++; /* ignore '{' */
3897 while (c-- > 0 && *tail && *tail != '}')
3898 *var++ = *tail++;
3899 }
3900 else
3901#endif
3902 {
3903 while (c-- > 0 && *tail != NUL && ((vim_isIDc(*tail))
3904#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3905 || (*src == '%' && *tail != '%')
3906#endif
3907 ))
3908 {
3909#ifdef OS2 /* env vars only in uppercase */
3910 *var++ = TOUPPER_LOC(*tail);
3911 tail++; /* toupper() may be a macro! */
3912#else
3913 *var++ = *tail++;
3914#endif
3915 }
3916 }
3917
3918#if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
3919# ifdef UNIX
3920 if (src[1] == '{' && *tail != '}')
3921# else
3922 if (*src == '%' && *tail != '%')
3923# endif
3924 var = NULL;
3925 else
3926 {
3927# ifdef UNIX
3928 if (src[1] == '{')
3929# else
3930 if (*src == '%')
3931#endif
3932 ++tail;
3933#endif
3934 *var = NUL;
3935 var = vim_getenv(dst, &mustfree);
3936#if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
3937 }
3938#endif
3939 }
3940 /* home directory */
3941 else if ( src[1] == NUL
3942 || vim_ispathsep(src[1])
3943 || vim_strchr((char_u *)" ,\t\n", src[1]) != NULL)
3944 {
3945 var = homedir;
3946 tail = src + 1;
3947 }
3948 else /* user directory */
3949 {
3950#if defined(UNIX) || (defined(VMS) && defined(USER_HOME))
3951 /*
3952 * Copy ~user to dst[], so we can put a NUL after it.
3953 */
3954 tail = src;
3955 var = dst;
3956 c = dstlen - 1;
3957 while ( c-- > 0
3958 && *tail
3959 && vim_isfilec(*tail)
3960 && !vim_ispathsep(*tail))
3961 *var++ = *tail++;
3962 *var = NUL;
3963# ifdef UNIX
3964 /*
3965 * If the system supports getpwnam(), use it.
3966 * Otherwise, or if getpwnam() fails, the shell is used to
3967 * expand ~user. This is slower and may fail if the shell
3968 * does not support ~user (old versions of /bin/sh).
3969 */
3970# if defined(HAVE_GETPWNAM) && defined(HAVE_PWD_H)
3971 {
3972 struct passwd *pw;
3973
Bram Moolenaara40ceaf2006-01-13 22:35:40 +00003974 /* Note: memory allocated by getpwnam() is never freed.
3975 * Calling endpwent() apparently doesn't help. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003976 pw = getpwnam((char *)dst + 1);
3977 if (pw != NULL)
3978 var = (char_u *)pw->pw_dir;
3979 else
3980 var = NULL;
3981 }
3982 if (var == NULL)
3983# endif
3984 {
3985 expand_T xpc;
3986
3987 ExpandInit(&xpc);
3988 xpc.xp_context = EXPAND_FILES;
3989 var = ExpandOne(&xpc, dst, NULL,
3990 WILD_ADD_SLASH|WILD_SILENT, WILD_EXPAND_FREE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003991 mustfree = TRUE;
3992 }
3993
3994# else /* !UNIX, thus VMS */
3995 /*
3996 * USER_HOME is a comma-separated list of
3997 * directories to search for the user account in.
3998 */
3999 {
4000 char_u test[MAXPATHL], paths[MAXPATHL];
4001 char_u *path, *next_path, *ptr;
4002 struct stat st;
4003
4004 STRCPY(paths, USER_HOME);
4005 next_path = paths;
4006 while (*next_path)
4007 {
4008 for (path = next_path; *next_path && *next_path != ',';
4009 next_path++);
4010 if (*next_path)
4011 *next_path++ = NUL;
4012 STRCPY(test, path);
4013 STRCAT(test, "/");
4014 STRCAT(test, dst + 1);
4015 if (mch_stat(test, &st) == 0)
4016 {
4017 var = alloc(STRLEN(test) + 1);
4018 STRCPY(var, test);
4019 mustfree = TRUE;
4020 break;
4021 }
4022 }
4023 }
4024# endif /* UNIX */
4025#else
4026 /* cannot expand user's home directory, so don't try */
4027 var = NULL;
4028 tail = (char_u *)""; /* for gcc */
4029#endif /* UNIX || VMS */
4030 }
4031
4032#ifdef BACKSLASH_IN_FILENAME
4033 /* If 'shellslash' is set change backslashes to forward slashes.
4034 * Can't use slash_adjust(), p_ssl may be set temporarily. */
4035 if (p_ssl && var != NULL && vim_strchr(var, '\\') != NULL)
4036 {
4037 char_u *p = vim_strsave(var);
4038
4039 if (p != NULL)
4040 {
4041 if (mustfree)
4042 vim_free(var);
4043 var = p;
4044 mustfree = TRUE;
4045 forward_slash(var);
4046 }
4047 }
4048#endif
4049
4050 /* If "var" contains white space, escape it with a backslash.
4051 * Required for ":e ~/tt" when $HOME includes a space. */
4052 if (esc && var != NULL && vim_strpbrk(var, (char_u *)" \t") != NULL)
4053 {
4054 char_u *p = vim_strsave_escaped(var, (char_u *)" \t");
4055
4056 if (p != NULL)
4057 {
4058 if (mustfree)
4059 vim_free(var);
4060 var = p;
4061 mustfree = TRUE;
4062 }
4063 }
4064
4065 if (var != NULL && *var != NUL
4066 && (STRLEN(var) + STRLEN(tail) + 1 < (unsigned)dstlen))
4067 {
4068 STRCPY(dst, var);
4069 dstlen -= (int)STRLEN(var);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004070 c = (int)STRLEN(var);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004071 /* if var[] ends in a path separator and tail[] starts
4072 * with it, skip a character */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004073 if (*var != NUL && after_pathsep(dst, dst + c)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004074#if defined(BACKSLASH_IN_FILENAME) || defined(AMIGA)
4075 && dst[-1] != ':'
4076#endif
4077 && vim_ispathsep(*tail))
4078 ++tail;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004079 dst += c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004080 src = tail;
4081 copy_char = FALSE;
4082 }
4083 if (mustfree)
4084 vim_free(var);
4085 }
4086
4087 if (copy_char) /* copy at least one char */
4088 {
4089 /*
Bram Moolenaar25394022007-05-10 19:06:20 +00004090 * Recognize the start of a new name, for '~'.
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00004091 * Don't do this when "one" is TRUE, to avoid expanding "~" in
4092 * ":edit foo ~ foo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00004093 */
4094 at_start = FALSE;
4095 if (src[0] == '\\' && src[1] != NUL)
4096 {
4097 *dst++ = *src++;
4098 --dstlen;
4099 }
Bram Moolenaar9f0545d2007-09-26 20:36:32 +00004100 else if ((src[0] == ' ' || src[0] == ',') && !one)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004101 at_start = TRUE;
4102 *dst++ = *src++;
4103 --dstlen;
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00004104
4105 if (startstr != NULL && src - startstr_len >= srcp
4106 && STRNCMP(src - startstr_len, startstr, startstr_len) == 0)
4107 at_start = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004108 }
4109 }
4110 *dst = NUL;
4111}
4112
4113/*
4114 * Vim's version of getenv().
4115 * Special handling of $HOME, $VIM and $VIMRUNTIME.
Bram Moolenaar2f6b0b82005-03-08 22:43:10 +00004116 * Also does ACP to 'enc' conversion for Win32.
Bram Moolenaarb453a532011-04-28 17:48:44 +02004117 * "mustfree" is set to TRUE when returned is allocated, it must be
4118 * initialized to FALSE by the caller.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004119 */
4120 char_u *
4121vim_getenv(name, mustfree)
4122 char_u *name;
Bram Moolenaarb453a532011-04-28 17:48:44 +02004123 int *mustfree;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004124{
4125 char_u *p;
4126 char_u *pend;
4127 int vimruntime;
4128
4129#if defined(OS2) || defined(MSDOS) || defined(MSWIN)
4130 /* use "C:/" when $HOME is not set */
4131 if (STRCMP(name, "HOME") == 0)
4132 return homedir;
4133#endif
4134
4135 p = mch_getenv(name);
4136 if (p != NULL && *p == NUL) /* empty is the same as not set */
4137 p = NULL;
4138
4139 if (p != NULL)
Bram Moolenaar05159a02005-02-26 23:04:13 +00004140 {
4141#if defined(FEAT_MBYTE) && defined(WIN3264)
4142 if (enc_utf8)
4143 {
4144 int len;
Bram Moolenaarb453a532011-04-28 17:48:44 +02004145 char_u *pp = NULL;
Bram Moolenaar05159a02005-02-26 23:04:13 +00004146
4147 /* Convert from active codepage to UTF-8. Other conversions are
4148 * not done, because they would fail for non-ASCII characters. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004149 acp_to_enc(p, (int)STRLEN(p), &pp, &len);
Bram Moolenaar05159a02005-02-26 23:04:13 +00004150 if (pp != NULL)
4151 {
4152 p = pp;
4153 *mustfree = TRUE;
4154 }
4155 }
4156#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004157 return p;
Bram Moolenaar05159a02005-02-26 23:04:13 +00004158 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004159
4160 vimruntime = (STRCMP(name, "VIMRUNTIME") == 0);
4161 if (!vimruntime && STRCMP(name, "VIM") != 0)
4162 return NULL;
4163
4164 /*
4165 * When expanding $VIMRUNTIME fails, try using $VIM/vim<version> or $VIM.
4166 * Don't do this when default_vimruntime_dir is non-empty.
4167 */
4168 if (vimruntime
4169#ifdef HAVE_PATHDEF
4170 && *default_vimruntime_dir == NUL
4171#endif
4172 )
4173 {
4174 p = mch_getenv((char_u *)"VIM");
4175 if (p != NULL && *p == NUL) /* empty is the same as not set */
4176 p = NULL;
4177 if (p != NULL)
4178 {
4179 p = vim_version_dir(p);
4180 if (p != NULL)
4181 *mustfree = TRUE;
4182 else
4183 p = mch_getenv((char_u *)"VIM");
Bram Moolenaar05159a02005-02-26 23:04:13 +00004184
4185#if defined(FEAT_MBYTE) && defined(WIN3264)
4186 if (enc_utf8)
4187 {
4188 int len;
Bram Moolenaarb453a532011-04-28 17:48:44 +02004189 char_u *pp = NULL;
Bram Moolenaar05159a02005-02-26 23:04:13 +00004190
4191 /* Convert from active codepage to UTF-8. Other conversions
4192 * are not done, because they would fail for non-ASCII
4193 * characters. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004194 acp_to_enc(p, (int)STRLEN(p), &pp, &len);
Bram Moolenaar05159a02005-02-26 23:04:13 +00004195 if (pp != NULL)
4196 {
Bram Moolenaarb453a532011-04-28 17:48:44 +02004197 if (*mustfree)
Bram Moolenaar05159a02005-02-26 23:04:13 +00004198 vim_free(p);
4199 p = pp;
4200 *mustfree = TRUE;
4201 }
4202 }
4203#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004204 }
4205 }
4206
4207 /*
4208 * When expanding $VIM or $VIMRUNTIME fails, try using:
4209 * - the directory name from 'helpfile' (unless it contains '$')
4210 * - the executable name from argv[0]
4211 */
4212 if (p == NULL)
4213 {
4214 if (p_hf != NULL && vim_strchr(p_hf, '$') == NULL)
4215 p = p_hf;
4216#ifdef USE_EXE_NAME
4217 /*
4218 * Use the name of the executable, obtained from argv[0].
4219 */
4220 else
4221 p = exe_name;
4222#endif
4223 if (p != NULL)
4224 {
4225 /* remove the file name */
4226 pend = gettail(p);
4227
4228 /* remove "doc/" from 'helpfile', if present */
4229 if (p == p_hf)
4230 pend = remove_tail(p, pend, (char_u *)"doc");
4231
4232#ifdef USE_EXE_NAME
4233# ifdef MACOS_X
Bram Moolenaar95e9b492006-03-15 23:04:43 +00004234 /* remove "MacOS" from exe_name and add "Resources/vim" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004235 if (p == exe_name)
4236 {
4237 char_u *pend1;
Bram Moolenaar95e9b492006-03-15 23:04:43 +00004238 char_u *pnew;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004239
Bram Moolenaar95e9b492006-03-15 23:04:43 +00004240 pend1 = remove_tail(p, pend, (char_u *)"MacOS");
4241 if (pend1 != pend)
4242 {
4243 pnew = alloc((unsigned)(pend1 - p) + 15);
4244 if (pnew != NULL)
4245 {
4246 STRNCPY(pnew, p, (pend1 - p));
4247 STRCPY(pnew + (pend1 - p), "Resources/vim");
4248 p = pnew;
4249 pend = p + STRLEN(p);
4250 }
4251 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004252 }
4253# endif
4254 /* remove "src/" from exe_name, if present */
4255 if (p == exe_name)
4256 pend = remove_tail(p, pend, (char_u *)"src");
4257#endif
4258
4259 /* for $VIM, remove "runtime/" or "vim54/", if present */
4260 if (!vimruntime)
4261 {
4262 pend = remove_tail(p, pend, (char_u *)RUNTIME_DIRNAME);
4263 pend = remove_tail(p, pend, (char_u *)VIM_VERSION_NODOT);
4264 }
4265
4266 /* remove trailing path separator */
4267#ifndef MACOS_CLASSIC
4268 /* With MacOS path (with colons) the final colon is required */
Bram Moolenaare21877a2008-02-13 09:58:14 +00004269 /* to avoid confusion between absolute and relative path */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004270 if (pend > p && after_pathsep(p, pend))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004271 --pend;
4272#endif
4273
Bram Moolenaar95e9b492006-03-15 23:04:43 +00004274#ifdef MACOS_X
4275 if (p == exe_name || p == p_hf)
4276#endif
4277 /* check that the result is a directory name */
4278 p = vim_strnsave(p, (int)(pend - p));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004279
4280 if (p != NULL && !mch_isdir(p))
4281 {
4282 vim_free(p);
4283 p = NULL;
4284 }
4285 else
4286 {
4287#ifdef USE_EXE_NAME
4288 /* may add "/vim54" or "/runtime" if it exists */
4289 if (vimruntime && (pend = vim_version_dir(p)) != NULL)
4290 {
4291 vim_free(p);
4292 p = pend;
4293 }
4294#endif
4295 *mustfree = TRUE;
4296 }
4297 }
4298 }
4299
4300#ifdef HAVE_PATHDEF
4301 /* When there is a pathdef.c file we can use default_vim_dir and
4302 * default_vimruntime_dir */
4303 if (p == NULL)
4304 {
4305 /* Only use default_vimruntime_dir when it is not empty */
4306 if (vimruntime && *default_vimruntime_dir != NUL)
4307 {
4308 p = default_vimruntime_dir;
4309 *mustfree = FALSE;
4310 }
4311 else if (*default_vim_dir != NUL)
4312 {
4313 if (vimruntime && (p = vim_version_dir(default_vim_dir)) != NULL)
4314 *mustfree = TRUE;
4315 else
4316 {
4317 p = default_vim_dir;
4318 *mustfree = FALSE;
4319 }
4320 }
4321 }
4322#endif
4323
4324 /*
4325 * Set the environment variable, so that the new value can be found fast
4326 * next time, and others can also use it (e.g. Perl).
4327 */
4328 if (p != NULL)
4329 {
4330 if (vimruntime)
4331 {
4332 vim_setenv((char_u *)"VIMRUNTIME", p);
4333 didset_vimruntime = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004334 }
4335 else
4336 {
4337 vim_setenv((char_u *)"VIM", p);
4338 didset_vim = TRUE;
4339 }
4340 }
4341 return p;
4342}
4343
4344/*
4345 * Check if the directory "vimdir/<version>" or "vimdir/runtime" exists.
4346 * Return NULL if not, return its name in allocated memory otherwise.
4347 */
4348 static char_u *
4349vim_version_dir(vimdir)
4350 char_u *vimdir;
4351{
4352 char_u *p;
4353
4354 if (vimdir == NULL || *vimdir == NUL)
4355 return NULL;
4356 p = concat_fnames(vimdir, (char_u *)VIM_VERSION_NODOT, TRUE);
4357 if (p != NULL && mch_isdir(p))
4358 return p;
4359 vim_free(p);
4360 p = concat_fnames(vimdir, (char_u *)RUNTIME_DIRNAME, TRUE);
4361 if (p != NULL && mch_isdir(p))
4362 return p;
4363 vim_free(p);
4364 return NULL;
4365}
4366
4367/*
4368 * If the string between "p" and "pend" ends in "name/", return "pend" minus
4369 * the length of "name/". Otherwise return "pend".
4370 */
4371 static char_u *
4372remove_tail(p, pend, name)
4373 char_u *p;
4374 char_u *pend;
4375 char_u *name;
4376{
4377 int len = (int)STRLEN(name) + 1;
4378 char_u *newend = pend - len;
4379
4380 if (newend >= p
4381 && fnamencmp(newend, name, len - 1) == 0
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004382 && (newend == p || after_pathsep(p, newend)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004383 return newend;
4384 return pend;
4385}
4386
Bram Moolenaar071d4272004-06-13 20:20:40 +00004387/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004388 * Our portable version of setenv.
4389 */
4390 void
4391vim_setenv(name, val)
4392 char_u *name;
4393 char_u *val;
4394{
4395#ifdef HAVE_SETENV
4396 mch_setenv((char *)name, (char *)val, 1);
4397#else
4398 char_u *envbuf;
4399
4400 /*
4401 * Putenv does not copy the string, it has to remain
4402 * valid. The allocated memory will never be freed.
4403 */
4404 envbuf = alloc((unsigned)(STRLEN(name) + STRLEN(val) + 2));
4405 if (envbuf != NULL)
4406 {
4407 sprintf((char *)envbuf, "%s=%s", name, val);
4408 putenv((char *)envbuf);
4409 }
4410#endif
Bram Moolenaar011a34d2012-02-29 13:49:09 +01004411#ifdef FEAT_GETTEXT
4412 /*
4413 * When setting $VIMRUNTIME adjust the directory to find message
4414 * translations to $VIMRUNTIME/lang.
4415 */
4416 if (*val != NUL && STRICMP(name, "VIMRUNTIME") == 0)
4417 {
4418 char_u *buf = concat_str(val, (char_u *)"/lang");
4419
4420 if (buf != NULL)
4421 {
4422 bindtextdomain(VIMPACKAGE, (char *)buf);
4423 vim_free(buf);
4424 }
4425 }
4426#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004427}
4428
4429#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
4430/*
4431 * Function given to ExpandGeneric() to obtain an environment variable name.
4432 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004433 char_u *
4434get_env_name(xp, idx)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00004435 expand_T *xp UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004436 int idx;
4437{
4438# if defined(AMIGA) || defined(__MRC__) || defined(__SC__)
4439 /*
4440 * No environ[] on the Amiga and on the Mac (using MPW).
4441 */
4442 return NULL;
4443# else
4444# ifndef __WIN32__
4445 /* Borland C++ 5.2 has this in a header file. */
4446 extern char **environ;
4447# endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00004448# define ENVNAMELEN 100
4449 static char_u name[ENVNAMELEN];
Bram Moolenaar071d4272004-06-13 20:20:40 +00004450 char_u *str;
4451 int n;
4452
4453 str = (char_u *)environ[idx];
4454 if (str == NULL)
4455 return NULL;
4456
Bram Moolenaar21cf8232004-07-16 20:18:37 +00004457 for (n = 0; n < ENVNAMELEN - 1; ++n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004458 {
4459 if (str[n] == '=' || str[n] == NUL)
4460 break;
4461 name[n] = str[n];
4462 }
4463 name[n] = NUL;
4464 return name;
4465# endif
4466}
Bram Moolenaar24305862012-08-15 14:05:05 +02004467
4468/*
4469 * Find all user names for user completion.
4470 * Done only once and then cached.
4471 */
4472 static void
4473init_users() {
4474 static int lazy_init_done = FALSE;
4475
4476 if (lazy_init_done)
4477 return;
4478
4479 lazy_init_done = TRUE;
4480 ga_init2(&ga_users, sizeof(char_u *), 20);
4481
4482# if defined(HAVE_GETPWENT) && defined(HAVE_PWD_H)
4483 {
4484 char_u* user;
4485 struct passwd* pw;
4486
4487 setpwent();
4488 while ((pw = getpwent()) != NULL)
4489 /* pw->pw_name shouldn't be NULL but just in case... */
4490 if (pw->pw_name != NULL)
4491 {
4492 if (ga_grow(&ga_users, 1) == FAIL)
4493 break;
4494 user = vim_strsave((char_u*)pw->pw_name);
4495 if (user == NULL)
4496 break;
4497 ((char_u **)(ga_users.ga_data))[ga_users.ga_len++] = user;
4498 }
4499 endpwent();
4500 }
4501# endif
4502}
4503
4504/*
4505 * Function given to ExpandGeneric() to obtain an user names.
4506 */
4507 char_u*
4508get_users(xp, idx)
4509 expand_T *xp UNUSED;
4510 int idx;
4511{
4512 init_users();
4513 if (idx < ga_users.ga_len)
4514 return ((char_u **)ga_users.ga_data)[idx];
4515 return NULL;
4516}
4517
4518/*
4519 * Check whether name matches a user name. Return:
4520 * 0 if name does not match any user name.
4521 * 1 if name partially matches the beginning of a user name.
4522 * 2 is name fully matches a user name.
4523 */
4524int match_user(name)
4525 char_u* name;
4526{
4527 int i;
4528 int n = (int)STRLEN(name);
4529 int result = 0;
4530
4531 init_users();
4532 for (i = 0; i < ga_users.ga_len; i++)
4533 {
4534 if (STRCMP(((char_u **)ga_users.ga_data)[i], name) == 0)
4535 return 2; /* full match */
4536 if (STRNCMP(((char_u **)ga_users.ga_data)[i], name, n) == 0)
4537 result = 1; /* partial match */
4538 }
4539 return result;
4540}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004541#endif
4542
4543/*
4544 * Replace home directory by "~" in each space or comma separated file name in
4545 * 'src'.
4546 * If anything fails (except when out of space) dst equals src.
4547 */
4548 void
4549home_replace(buf, src, dst, dstlen, one)
4550 buf_T *buf; /* when not NULL, check for help files */
4551 char_u *src; /* input file name */
4552 char_u *dst; /* where to put the result */
4553 int dstlen; /* maximum length of the result */
4554 int one; /* if TRUE, only replace one file name, include
4555 spaces and commas in the file name. */
4556{
4557 size_t dirlen = 0, envlen = 0;
4558 size_t len;
Bram Moolenaar9158f9e2012-06-20 14:02:27 +02004559 char_u *homedir_env, *homedir_env_orig;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004560 char_u *p;
4561
4562 if (src == NULL)
4563 {
4564 *dst = NUL;
4565 return;
4566 }
4567
4568 /*
4569 * If the file is a help file, remove the path completely.
4570 */
4571 if (buf != NULL && buf->b_help)
4572 {
4573 STRCPY(dst, gettail(src));
4574 return;
4575 }
4576
4577 /*
4578 * We check both the value of the $HOME environment variable and the
4579 * "real" home directory.
4580 */
4581 if (homedir != NULL)
4582 dirlen = STRLEN(homedir);
4583
4584#ifdef VMS
Bram Moolenaar9158f9e2012-06-20 14:02:27 +02004585 homedir_env_orig = homedir_env = mch_getenv((char_u *)"SYS$LOGIN");
Bram Moolenaar071d4272004-06-13 20:20:40 +00004586#else
Bram Moolenaar9158f9e2012-06-20 14:02:27 +02004587 homedir_env_orig = homedir_env = mch_getenv((char_u *)"HOME");
4588#endif
Bram Moolenaarbef47902012-07-06 16:49:40 +02004589 /* Empty is the same as not set. */
4590 if (homedir_env != NULL && *homedir_env == NUL)
4591 homedir_env = NULL;
4592
Bram Moolenaar9158f9e2012-06-20 14:02:27 +02004593#if defined(FEAT_MODIFY_FNAME) || defined(WIN3264)
Bram Moolenaarbef47902012-07-06 16:49:40 +02004594 if (homedir_env != NULL && vim_strchr(homedir_env, '~') != NULL)
Bram Moolenaar9158f9e2012-06-20 14:02:27 +02004595 {
4596 int usedlen = 0;
4597 int flen;
4598 char_u *fbuf = NULL;
4599
4600 flen = (int)STRLEN(homedir_env);
Bram Moolenaard12f8112012-06-20 17:56:09 +02004601 (void)modify_fname((char_u *)":p", &usedlen,
4602 &homedir_env, &fbuf, &flen);
Bram Moolenaar9158f9e2012-06-20 14:02:27 +02004603 flen = (int)STRLEN(homedir_env);
4604 if (flen > 0 && vim_ispathsep(homedir_env[flen - 1]))
4605 /* Remove the trailing / that is added to a directory. */
4606 homedir_env[flen - 1] = NUL;
4607 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004608#endif
4609
Bram Moolenaar071d4272004-06-13 20:20:40 +00004610 if (homedir_env != NULL)
4611 envlen = STRLEN(homedir_env);
4612
4613 if (!one)
4614 src = skipwhite(src);
4615 while (*src && dstlen > 0)
4616 {
4617 /*
4618 * Here we are at the beginning of a file name.
4619 * First, check to see if the beginning of the file name matches
4620 * $HOME or the "real" home directory. Check that there is a '/'
4621 * after the match (so that if e.g. the file is "/home/pieter/bla",
4622 * and the home directory is "/home/piet", the file does not end up
4623 * as "~er/bla" (which would seem to indicate the file "bla" in user
4624 * er's home directory)).
4625 */
4626 p = homedir;
4627 len = dirlen;
4628 for (;;)
4629 {
4630 if ( len
4631 && fnamencmp(src, p, len) == 0
4632 && (vim_ispathsep(src[len])
4633 || (!one && (src[len] == ',' || src[len] == ' '))
4634 || src[len] == NUL))
4635 {
4636 src += len;
4637 if (--dstlen > 0)
4638 *dst++ = '~';
4639
4640 /*
4641 * If it's just the home directory, add "/".
4642 */
4643 if (!vim_ispathsep(src[0]) && --dstlen > 0)
4644 *dst++ = '/';
4645 break;
4646 }
4647 if (p == homedir_env)
4648 break;
4649 p = homedir_env;
4650 len = envlen;
4651 }
4652
4653 /* if (!one) skip to separator: space or comma */
4654 while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
4655 *dst++ = *src++;
4656 /* skip separator */
4657 while ((*src == ' ' || *src == ',') && --dstlen > 0)
4658 *dst++ = *src++;
4659 }
4660 /* if (dstlen == 0) out of space, what to do??? */
4661
4662 *dst = NUL;
Bram Moolenaar9158f9e2012-06-20 14:02:27 +02004663
4664 if (homedir_env != homedir_env_orig)
4665 vim_free(homedir_env);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004666}
4667
4668/*
4669 * Like home_replace, store the replaced string in allocated memory.
4670 * When something fails, NULL is returned.
4671 */
4672 char_u *
4673home_replace_save(buf, src)
4674 buf_T *buf; /* when not NULL, check for help files */
4675 char_u *src; /* input file name */
4676{
4677 char_u *dst;
4678 unsigned len;
4679
4680 len = 3; /* space for "~/" and trailing NUL */
4681 if (src != NULL) /* just in case */
4682 len += (unsigned)STRLEN(src);
4683 dst = alloc(len);
4684 if (dst != NULL)
4685 home_replace(buf, src, dst, len, TRUE);
4686 return dst;
4687}
4688
4689/*
4690 * Compare two file names and return:
4691 * FPC_SAME if they both exist and are the same file.
4692 * FPC_SAMEX if they both don't exist and have the same file name.
4693 * FPC_DIFF if they both exist and are different files.
4694 * FPC_NOTX if they both don't exist.
4695 * FPC_DIFFX if one of them doesn't exist.
4696 * For the first name environment variables are expanded
4697 */
4698 int
4699fullpathcmp(s1, s2, checkname)
4700 char_u *s1, *s2;
4701 int checkname; /* when both don't exist, check file names */
4702{
4703#ifdef UNIX
4704 char_u exp1[MAXPATHL];
4705 char_u full1[MAXPATHL];
4706 char_u full2[MAXPATHL];
4707 struct stat st1, st2;
4708 int r1, r2;
4709
4710 expand_env(s1, exp1, MAXPATHL);
4711 r1 = mch_stat((char *)exp1, &st1);
4712 r2 = mch_stat((char *)s2, &st2);
4713 if (r1 != 0 && r2 != 0)
4714 {
4715 /* if mch_stat() doesn't work, may compare the names */
4716 if (checkname)
4717 {
4718 if (fnamecmp(exp1, s2) == 0)
4719 return FPC_SAMEX;
4720 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4721 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4722 if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
4723 return FPC_SAMEX;
4724 }
4725 return FPC_NOTX;
4726 }
4727 if (r1 != 0 || r2 != 0)
4728 return FPC_DIFFX;
4729 if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
4730 return FPC_SAME;
4731 return FPC_DIFF;
4732#else
4733 char_u *exp1; /* expanded s1 */
4734 char_u *full1; /* full path of s1 */
4735 char_u *full2; /* full path of s2 */
4736 int retval = FPC_DIFF;
4737 int r1, r2;
4738
4739 /* allocate one buffer to store three paths (alloc()/free() is slow!) */
4740 if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
4741 {
4742 full1 = exp1 + MAXPATHL;
4743 full2 = full1 + MAXPATHL;
4744
4745 expand_env(s1, exp1, MAXPATHL);
4746 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4747 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4748
4749 /* If vim_FullName() fails, the file probably doesn't exist. */
4750 if (r1 != OK && r2 != OK)
4751 {
4752 if (checkname && fnamecmp(exp1, s2) == 0)
4753 retval = FPC_SAMEX;
4754 else
4755 retval = FPC_NOTX;
4756 }
4757 else if (r1 != OK || r2 != OK)
4758 retval = FPC_DIFFX;
4759 else if (fnamecmp(full1, full2))
4760 retval = FPC_DIFF;
4761 else
4762 retval = FPC_SAME;
4763 vim_free(exp1);
4764 }
4765 return retval;
4766#endif
4767}
4768
4769/*
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004770 * Get the tail of a path: the file name.
Bram Moolenaar31710262010-08-13 13:36:15 +02004771 * When the path ends in a path separator the tail is the NUL after it.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004772 * Fail safe: never returns NULL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004773 */
4774 char_u *
4775gettail(fname)
4776 char_u *fname;
4777{
4778 char_u *p1, *p2;
4779
4780 if (fname == NULL)
4781 return (char_u *)"";
4782 for (p1 = p2 = fname; *p2; ) /* find last part of path */
4783 {
4784 if (vim_ispathsep(*p2))
4785 p1 = p2 + 1;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004786 mb_ptr_adv(p2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004787 }
4788 return p1;
4789}
4790
Bram Moolenaar31710262010-08-13 13:36:15 +02004791#if defined(FEAT_SEARCHPATH)
4792static char_u *gettail_dir __ARGS((char_u *fname));
4793
4794/*
4795 * Return the end of the directory name, on the first path
4796 * separator:
4797 * "/path/file", "/path/dir/", "/path//dir", "/file"
4798 * ^ ^ ^ ^
4799 */
4800 static char_u *
4801gettail_dir(fname)
4802 char_u *fname;
4803{
4804 char_u *dir_end = fname;
4805 char_u *next_dir_end = fname;
4806 int look_for_sep = TRUE;
4807 char_u *p;
4808
4809 for (p = fname; *p != NUL; )
4810 {
4811 if (vim_ispathsep(*p))
4812 {
4813 if (look_for_sep)
4814 {
4815 next_dir_end = p;
4816 look_for_sep = FALSE;
4817 }
4818 }
4819 else
4820 {
4821 if (!look_for_sep)
4822 dir_end = next_dir_end;
4823 look_for_sep = TRUE;
4824 }
4825 mb_ptr_adv(p);
4826 }
4827 return dir_end;
4828}
4829#endif
4830
Bram Moolenaar071d4272004-06-13 20:20:40 +00004831/*
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004832 * Get pointer to tail of "fname", including path separators. Putting a NUL
4833 * here leaves the directory name. Takes care of "c:/" and "//".
4834 * Always returns a valid pointer.
4835 */
4836 char_u *
4837gettail_sep(fname)
4838 char_u *fname;
4839{
4840 char_u *p;
4841 char_u *t;
4842
4843 p = get_past_head(fname); /* don't remove the '/' from "c:/file" */
4844 t = gettail(fname);
4845 while (t > p && after_pathsep(fname, t))
4846 --t;
4847#ifdef VMS
4848 /* path separator is part of the path */
4849 ++t;
4850#endif
4851 return t;
4852}
4853
4854/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004855 * get the next path component (just after the next path separator).
4856 */
4857 char_u *
4858getnextcomp(fname)
4859 char_u *fname;
4860{
4861 while (*fname && !vim_ispathsep(*fname))
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004862 mb_ptr_adv(fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004863 if (*fname)
4864 ++fname;
4865 return fname;
4866}
4867
Bram Moolenaar071d4272004-06-13 20:20:40 +00004868/*
4869 * Get a pointer to one character past the head of a path name.
4870 * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
4871 * If there is no head, path is returned.
4872 */
4873 char_u *
4874get_past_head(path)
4875 char_u *path;
4876{
4877 char_u *retval;
4878
4879#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
4880 /* may skip "c:" */
4881 if (isalpha(path[0]) && path[1] == ':')
4882 retval = path + 2;
4883 else
4884 retval = path;
4885#else
4886# if defined(AMIGA)
4887 /* may skip "label:" */
4888 retval = vim_strchr(path, ':');
4889 if (retval == NULL)
4890 retval = path;
4891# else /* Unix */
4892 retval = path;
4893# endif
4894#endif
4895
4896 while (vim_ispathsep(*retval))
4897 ++retval;
4898
4899 return retval;
4900}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004901
4902/*
4903 * return TRUE if 'c' is a path separator.
4904 */
4905 int
4906vim_ispathsep(c)
4907 int c;
4908{
Bram Moolenaare60acc12011-05-10 16:41:25 +02004909#ifdef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00004910 return (c == '/'); /* UNIX has ':' inside file names */
Bram Moolenaare60acc12011-05-10 16:41:25 +02004911#else
4912# ifdef BACKSLASH_IN_FILENAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00004913 return (c == ':' || c == '/' || c == '\\');
Bram Moolenaare60acc12011-05-10 16:41:25 +02004914# else
4915# ifdef VMS
Bram Moolenaar071d4272004-06-13 20:20:40 +00004916 /* server"user passwd"::device:[full.path.name]fname.extension;version" */
4917 return (c == ':' || c == '[' || c == ']' || c == '/'
4918 || c == '<' || c == '>' || c == '"' );
Bram Moolenaare60acc12011-05-10 16:41:25 +02004919# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004920 return (c == ':' || c == '/');
Bram Moolenaare60acc12011-05-10 16:41:25 +02004921# endif /* VMS */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004922# endif
Bram Moolenaare60acc12011-05-10 16:41:25 +02004923#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004924}
4925
4926#if defined(FEAT_SEARCHPATH) || defined(PROTO)
4927/*
4928 * return TRUE if 'c' is a path list separator.
4929 */
4930 int
4931vim_ispathlistsep(c)
4932 int c;
4933{
4934#ifdef UNIX
4935 return (c == ':');
4936#else
Bram Moolenaar25394022007-05-10 19:06:20 +00004937 return (c == ';'); /* might not be right for every system... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004938#endif
4939}
4940#endif
4941
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004942#if defined(FEAT_GUI_TABLINE) || defined(FEAT_WINDOWS) \
4943 || defined(FEAT_EVAL) || defined(PROTO)
4944/*
4945 * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
4946 * It's done in-place.
4947 */
4948 void
4949shorten_dir(str)
4950 char_u *str;
4951{
4952 char_u *tail, *s, *d;
4953 int skip = FALSE;
4954
4955 tail = gettail(str);
4956 d = str;
4957 for (s = str; ; ++s)
4958 {
4959 if (s >= tail) /* copy the whole tail */
4960 {
4961 *d++ = *s;
4962 if (*s == NUL)
4963 break;
4964 }
4965 else if (vim_ispathsep(*s)) /* copy '/' and next char */
4966 {
4967 *d++ = *s;
4968 skip = FALSE;
4969 }
4970 else if (!skip)
4971 {
4972 *d++ = *s; /* copy next char */
4973 if (*s != '~' && *s != '.') /* and leading "~" and "." */
4974 skip = TRUE;
4975# ifdef FEAT_MBYTE
4976 if (has_mbyte)
4977 {
4978 int l = mb_ptr2len(s);
4979
4980 while (--l > 0)
Bram Moolenaarb6baca52006-08-15 20:24:14 +00004981 *d++ = *++s;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004982 }
4983# endif
4984 }
4985 }
4986}
4987#endif
4988
Bram Moolenaar900b4d72005-12-12 22:05:50 +00004989/*
4990 * Return TRUE if the directory of "fname" exists, FALSE otherwise.
4991 * Also returns TRUE if there is no directory name.
4992 * "fname" must be writable!.
4993 */
4994 int
4995dir_of_file_exists(fname)
4996 char_u *fname;
4997{
4998 char_u *p;
4999 int c;
5000 int retval;
5001
5002 p = gettail_sep(fname);
5003 if (p == fname)
5004 return TRUE;
5005 c = *p;
5006 *p = NUL;
5007 retval = mch_isdir(fname);
5008 *p = c;
5009 return retval;
5010}
5011
Bram Moolenaar071d4272004-06-13 20:20:40 +00005012#if (defined(CASE_INSENSITIVE_FILENAME) && defined(BACKSLASH_IN_FILENAME)) \
5013 || defined(PROTO)
5014/*
5015 * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally.
5016 */
5017 int
5018vim_fnamecmp(x, y)
5019 char_u *x, *y;
5020{
5021 return vim_fnamencmp(x, y, MAXPATHL);
5022}
5023
5024 int
5025vim_fnamencmp(x, y, len)
5026 char_u *x, *y;
5027 size_t len;
5028{
5029 while (len > 0 && *x && *y)
5030 {
5031 if (TOLOWER_LOC(*x) != TOLOWER_LOC(*y)
5032 && !(*x == '/' && *y == '\\')
5033 && !(*x == '\\' && *y == '/'))
5034 break;
5035 ++x;
5036 ++y;
5037 --len;
5038 }
5039 if (len == 0)
5040 return 0;
5041 return (*x - *y);
5042}
5043#endif
5044
5045/*
5046 * Concatenate file names fname1 and fname2 into allocated memory.
Bram Moolenaar25394022007-05-10 19:06:20 +00005047 * Only add a '/' or '\\' when 'sep' is TRUE and it is necessary.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005048 */
5049 char_u *
5050concat_fnames(fname1, fname2, sep)
5051 char_u *fname1;
5052 char_u *fname2;
5053 int sep;
5054{
5055 char_u *dest;
5056
5057 dest = alloc((unsigned)(STRLEN(fname1) + STRLEN(fname2) + 3));
5058 if (dest != NULL)
5059 {
5060 STRCPY(dest, fname1);
5061 if (sep)
5062 add_pathsep(dest);
5063 STRCAT(dest, fname2);
5064 }
5065 return dest;
5066}
5067
Bram Moolenaard6754642005-01-17 22:18:45 +00005068/*
5069 * Concatenate two strings and return the result in allocated memory.
5070 * Returns NULL when out of memory.
5071 */
5072 char_u *
5073concat_str(str1, str2)
5074 char_u *str1;
5075 char_u *str2;
5076{
5077 char_u *dest;
5078 size_t l = STRLEN(str1);
5079
5080 dest = alloc((unsigned)(l + STRLEN(str2) + 1L));
5081 if (dest != NULL)
5082 {
5083 STRCPY(dest, str1);
5084 STRCPY(dest + l, str2);
5085 }
5086 return dest;
5087}
Bram Moolenaard6754642005-01-17 22:18:45 +00005088
Bram Moolenaar071d4272004-06-13 20:20:40 +00005089/*
5090 * Add a path separator to a file name, unless it already ends in a path
5091 * separator.
5092 */
5093 void
5094add_pathsep(p)
5095 char_u *p;
5096{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005097 if (*p != NUL && !after_pathsep(p, p + STRLEN(p)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005098 STRCAT(p, PATHSEPSTR);
5099}
5100
5101/*
5102 * FullName_save - Make an allocated copy of a full file name.
5103 * Returns NULL when out of memory.
5104 */
5105 char_u *
5106FullName_save(fname, force)
5107 char_u *fname;
Bram Moolenaarbfe3bf82012-06-13 17:28:55 +02005108 int force; /* force expansion, even when it already looks
5109 * like a full path name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005110{
5111 char_u *buf;
5112 char_u *new_fname = NULL;
5113
5114 if (fname == NULL)
5115 return NULL;
5116
5117 buf = alloc((unsigned)MAXPATHL);
5118 if (buf != NULL)
5119 {
5120 if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
5121 new_fname = vim_strsave(buf);
5122 else
5123 new_fname = vim_strsave(fname);
5124 vim_free(buf);
5125 }
5126 return new_fname;
5127}
5128
5129#if defined(FEAT_CINDENT) || defined(FEAT_SYN_HL)
5130
5131static char_u *skip_string __ARGS((char_u *p));
5132
5133/*
5134 * Find the start of a comment, not knowing if we are in a comment right now.
5135 * Search starts at w_cursor.lnum and goes backwards.
5136 */
5137 pos_T *
5138find_start_comment(ind_maxcomment) /* XXX */
5139 int ind_maxcomment;
5140{
5141 pos_T *pos;
5142 char_u *line;
5143 char_u *p;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005144 int cur_maxcomment = ind_maxcomment;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005145
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005146 for (;;)
5147 {
5148 pos = findmatchlimit(NULL, '*', FM_BACKWARD, cur_maxcomment);
5149 if (pos == NULL)
5150 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005151
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005152 /*
5153 * Check if the comment start we found is inside a string.
5154 * If it is then restrict the search to below this line and try again.
5155 */
5156 line = ml_get(pos->lnum);
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00005157 for (p = line; *p && (colnr_T)(p - line) < pos->col; ++p)
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005158 p = skip_string(p);
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00005159 if ((colnr_T)(p - line) <= pos->col)
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005160 break;
5161 cur_maxcomment = curwin->w_cursor.lnum - pos->lnum - 1;
5162 if (cur_maxcomment <= 0)
5163 {
5164 pos = NULL;
5165 break;
5166 }
5167 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005168 return pos;
5169}
5170
5171/*
5172 * Skip to the end of a "string" and a 'c' character.
5173 * If there is no string or character, return argument unmodified.
5174 */
5175 static char_u *
5176skip_string(p)
5177 char_u *p;
5178{
5179 int i;
5180
5181 /*
5182 * We loop, because strings may be concatenated: "date""time".
5183 */
5184 for ( ; ; ++p)
5185 {
5186 if (p[0] == '\'') /* 'c' or '\n' or '\000' */
5187 {
5188 if (!p[1]) /* ' at end of line */
5189 break;
5190 i = 2;
5191 if (p[1] == '\\') /* '\n' or '\000' */
5192 {
5193 ++i;
5194 while (vim_isdigit(p[i - 1])) /* '\000' */
5195 ++i;
5196 }
5197 if (p[i] == '\'') /* check for trailing ' */
5198 {
5199 p += i;
5200 continue;
5201 }
5202 }
5203 else if (p[0] == '"') /* start of string */
5204 {
5205 for (++p; p[0]; ++p)
5206 {
5207 if (p[0] == '\\' && p[1] != NUL)
5208 ++p;
5209 else if (p[0] == '"') /* end of string */
5210 break;
5211 }
5212 if (p[0] == '"')
5213 continue;
5214 }
5215 break; /* no string found */
5216 }
5217 if (!*p)
5218 --p; /* backup from NUL */
5219 return p;
5220}
5221#endif /* FEAT_CINDENT || FEAT_SYN_HL */
5222
5223#if defined(FEAT_CINDENT) || defined(PROTO)
5224
5225/*
5226 * Do C or expression indenting on the current line.
5227 */
5228 void
5229do_c_expr_indent()
5230{
5231# ifdef FEAT_EVAL
5232 if (*curbuf->b_p_inde != NUL)
5233 fixthisline(get_expr_indent);
5234 else
5235# endif
5236 fixthisline(get_c_indent);
5237}
5238
5239/*
5240 * Functions for C-indenting.
5241 * Most of this originally comes from Eric Fischer.
5242 */
5243/*
5244 * Below "XXX" means that this function may unlock the current line.
5245 */
5246
5247static char_u *cin_skipcomment __ARGS((char_u *));
5248static int cin_nocode __ARGS((char_u *));
5249static pos_T *find_line_comment __ARGS((void));
5250static int cin_islabel_skip __ARGS((char_u **));
5251static int cin_isdefault __ARGS((char_u *));
5252static char_u *after_label __ARGS((char_u *l));
5253static int get_indent_nolabel __ARGS((linenr_T lnum));
5254static int skip_label __ARGS((linenr_T, char_u **pp, int ind_maxcomment));
5255static int cin_first_id_amount __ARGS((void));
5256static int cin_get_equal_amount __ARGS((linenr_T lnum));
5257static int cin_ispreproc __ARGS((char_u *));
5258static int cin_ispreproc_cont __ARGS((char_u **pp, linenr_T *lnump));
5259static int cin_iscomment __ARGS((char_u *));
5260static int cin_islinecomment __ARGS((char_u *));
5261static int cin_isterminated __ARGS((char_u *, int, int));
5262static int cin_isinit __ARGS((void));
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005263static int cin_isfuncdecl __ARGS((char_u **, linenr_T, linenr_T, int, int));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005264static int cin_isif __ARGS((char_u *));
5265static int cin_iselse __ARGS((char_u *));
5266static int cin_isdo __ARGS((char_u *));
5267static int cin_iswhileofdo __ARGS((char_u *, linenr_T, int));
Bram Moolenaarb345d492012-04-09 20:42:26 +02005268static int cin_is_if_for_while_before_offset __ARGS((char_u *line, int *poffset));
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005269static int cin_iswhileofdo_end __ARGS((int terminated, int ind_maxparen, int ind_maxcomment));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005270static int cin_isbreak __ARGS((char_u *));
Bram Moolenaare7c56862007-08-04 10:14:52 +00005271static int cin_is_cpp_baseclass __ARGS((colnr_T *col));
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005272static int get_baseclass_amount __ARGS((int col, int ind_maxparen, int ind_maxcomment, int ind_cpp_baseclass));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005273static int cin_ends_in __ARGS((char_u *, char_u *, char_u *));
5274static int cin_skip2pos __ARGS((pos_T *trypos));
5275static pos_T *find_start_brace __ARGS((int));
5276static pos_T *find_match_paren __ARGS((int, int));
5277static int corr_ind_maxparen __ARGS((int ind_maxparen, pos_T *startpos));
5278static int find_last_paren __ARGS((char_u *l, int start, int end));
5279static int find_match __ARGS((int lookfor, linenr_T ourscope, int ind_maxparen, int ind_maxcomment));
Bram Moolenaared38b0a2011-05-25 15:16:18 +02005280static int cin_is_cpp_namespace __ARGS((char_u *));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005281
Bram Moolenaar39353fd2007-03-27 09:02:11 +00005282static int ind_hash_comment = 0; /* # starts a comment */
5283
Bram Moolenaar071d4272004-06-13 20:20:40 +00005284/*
5285 * Skip over white space and C comments within the line.
Bram Moolenaar39353fd2007-03-27 09:02:11 +00005286 * Also skip over Perl/shell comments if desired.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005287 */
5288 static char_u *
5289cin_skipcomment(s)
5290 char_u *s;
5291{
5292 while (*s)
5293 {
Bram Moolenaar39353fd2007-03-27 09:02:11 +00005294 char_u *prev_s = s;
5295
Bram Moolenaar071d4272004-06-13 20:20:40 +00005296 s = skipwhite(s);
Bram Moolenaar39353fd2007-03-27 09:02:11 +00005297
5298 /* Perl/shell # comment comment continues until eol. Require a space
5299 * before # to avoid recognizing $#array. */
5300 if (ind_hash_comment != 0 && s != prev_s && *s == '#')
5301 {
5302 s += STRLEN(s);
5303 break;
5304 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005305 if (*s != '/')
5306 break;
5307 ++s;
5308 if (*s == '/') /* slash-slash comment continues till eol */
5309 {
5310 s += STRLEN(s);
5311 break;
5312 }
5313 if (*s != '*')
5314 break;
5315 for (++s; *s; ++s) /* skip slash-star comment */
5316 if (s[0] == '*' && s[1] == '/')
5317 {
5318 s += 2;
5319 break;
5320 }
5321 }
5322 return s;
5323}
5324
5325/*
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005326 * Return TRUE if there is no code at *s. White space and comments are
Bram Moolenaar071d4272004-06-13 20:20:40 +00005327 * not considered code.
5328 */
5329 static int
5330cin_nocode(s)
5331 char_u *s;
5332{
5333 return *cin_skipcomment(s) == NUL;
5334}
5335
5336/*
5337 * Check previous lines for a "//" line comment, skipping over blank lines.
5338 */
5339 static pos_T *
5340find_line_comment() /* XXX */
5341{
5342 static pos_T pos;
5343 char_u *line;
5344 char_u *p;
5345
5346 pos = curwin->w_cursor;
5347 while (--pos.lnum > 0)
5348 {
5349 line = ml_get(pos.lnum);
5350 p = skipwhite(line);
5351 if (cin_islinecomment(p))
5352 {
5353 pos.col = (int)(p - line);
5354 return &pos;
5355 }
5356 if (*p != NUL)
5357 break;
5358 }
5359 return NULL;
5360}
5361
5362/*
5363 * Check if string matches "label:"; move to character after ':' if true.
5364 */
5365 static int
5366cin_islabel_skip(s)
5367 char_u **s;
5368{
5369 if (!vim_isIDc(**s)) /* need at least one ID character */
5370 return FALSE;
5371
5372 while (vim_isIDc(**s))
5373 (*s)++;
5374
5375 *s = cin_skipcomment(*s);
5376
5377 /* "::" is not a label, it's C++ */
5378 return (**s == ':' && *++*s != ':');
5379}
5380
5381/*
5382 * Recognize a label: "label:".
5383 * Note: curwin->w_cursor must be where we are looking for the label.
5384 */
5385 int
5386cin_islabel(ind_maxcomment) /* XXX */
5387 int ind_maxcomment;
5388{
5389 char_u *s;
5390
5391 s = cin_skipcomment(ml_get_curline());
5392
5393 /*
5394 * Exclude "default" from labels, since it should be indented
5395 * like a switch label. Same for C++ scope declarations.
5396 */
5397 if (cin_isdefault(s))
5398 return FALSE;
5399 if (cin_isscopedecl(s))
5400 return FALSE;
5401
5402 if (cin_islabel_skip(&s))
5403 {
5404 /*
5405 * Only accept a label if the previous line is terminated or is a case
5406 * label.
5407 */
5408 pos_T cursor_save;
5409 pos_T *trypos;
5410 char_u *line;
5411
5412 cursor_save = curwin->w_cursor;
5413 while (curwin->w_cursor.lnum > 1)
5414 {
5415 --curwin->w_cursor.lnum;
5416
5417 /*
5418 * If we're in a comment now, skip to the start of the comment.
5419 */
5420 curwin->w_cursor.col = 0;
5421 if ((trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
5422 curwin->w_cursor = *trypos;
5423
5424 line = ml_get_curline();
5425 if (cin_ispreproc(line)) /* ignore #defines, #if, etc. */
5426 continue;
5427 if (*(line = cin_skipcomment(line)) == NUL)
5428 continue;
5429
5430 curwin->w_cursor = cursor_save;
5431 if (cin_isterminated(line, TRUE, FALSE)
5432 || cin_isscopedecl(line)
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005433 || cin_iscase(line, TRUE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005434 || (cin_islabel_skip(&line) && cin_nocode(line)))
5435 return TRUE;
5436 return FALSE;
5437 }
5438 curwin->w_cursor = cursor_save;
5439 return TRUE; /* label at start of file??? */
5440 }
5441 return FALSE;
5442}
5443
5444/*
5445 * Recognize structure initialization and enumerations.
5446 * Q&D-Implementation:
5447 * check for "=" at end or "[typedef] enum" at beginning of line.
5448 */
5449 static int
5450cin_isinit(void)
5451{
5452 char_u *s;
5453
5454 s = cin_skipcomment(ml_get_curline());
5455
5456 if (STRNCMP(s, "typedef", 7) == 0 && !vim_isIDc(s[7]))
5457 s = cin_skipcomment(s + 7);
5458
Bram Moolenaara5285652011-12-14 20:05:21 +01005459 if (STRNCMP(s, "static", 6) == 0 && !vim_isIDc(s[6]))
5460 s = cin_skipcomment(s + 6);
5461
Bram Moolenaar071d4272004-06-13 20:20:40 +00005462 if (STRNCMP(s, "enum", 4) == 0 && !vim_isIDc(s[4]))
5463 return TRUE;
5464
5465 if (cin_ends_in(s, (char_u *)"=", (char_u *)"{"))
5466 return TRUE;
5467
5468 return FALSE;
5469}
5470
5471/*
5472 * Recognize a switch label: "case .*:" or "default:".
5473 */
5474 int
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005475cin_iscase(s, strict)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005476 char_u *s;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005477 int strict; /* Allow relaxed check of case statement for JS */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005478{
5479 s = cin_skipcomment(s);
5480 if (STRNCMP(s, "case", 4) == 0 && !vim_isIDc(s[4]))
5481 {
5482 for (s += 4; *s; ++s)
5483 {
5484 s = cin_skipcomment(s);
5485 if (*s == ':')
5486 {
5487 if (s[1] == ':') /* skip over "::" for C++ */
5488 ++s;
5489 else
5490 return TRUE;
5491 }
5492 if (*s == '\'' && s[1] && s[2] == '\'')
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005493 s += 2; /* skip over ':' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005494 else if (*s == '/' && (s[1] == '*' || s[1] == '/'))
5495 return FALSE; /* stop at comment */
5496 else if (*s == '"')
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005497 {
5498 /* JS etc. */
5499 if (strict)
5500 return FALSE; /* stop at string */
5501 else
5502 return TRUE;
5503 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005504 }
5505 return FALSE;
5506 }
5507
5508 if (cin_isdefault(s))
5509 return TRUE;
5510 return FALSE;
5511}
5512
5513/*
5514 * Recognize a "default" switch label.
5515 */
5516 static int
5517cin_isdefault(s)
5518 char_u *s;
5519{
5520 return (STRNCMP(s, "default", 7) == 0
5521 && *(s = cin_skipcomment(s + 7)) == ':'
5522 && s[1] != ':');
5523}
5524
5525/*
Bram Moolenaar1a509df2010-08-01 17:59:57 +02005526 * Recognize a "public/private/protected" scope declaration label.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005527 */
5528 int
5529cin_isscopedecl(s)
5530 char_u *s;
5531{
5532 int i;
5533
5534 s = cin_skipcomment(s);
5535 if (STRNCMP(s, "public", 6) == 0)
5536 i = 6;
5537 else if (STRNCMP(s, "protected", 9) == 0)
5538 i = 9;
5539 else if (STRNCMP(s, "private", 7) == 0)
5540 i = 7;
5541 else
5542 return FALSE;
5543 return (*(s = cin_skipcomment(s + i)) == ':' && s[1] != ':');
5544}
5545
Bram Moolenaared38b0a2011-05-25 15:16:18 +02005546/* Maximum number of lines to search back for a "namespace" line. */
5547#define FIND_NAMESPACE_LIM 20
5548
5549/*
5550 * Recognize a "namespace" scope declaration.
5551 */
5552 static int
5553cin_is_cpp_namespace(s)
5554 char_u *s;
5555{
5556 char_u *p;
5557 int has_name = FALSE;
5558
5559 s = cin_skipcomment(s);
5560 if (STRNCMP(s, "namespace", 9) == 0 && (s[9] == NUL || !vim_iswordc(s[9])))
5561 {
5562 p = cin_skipcomment(skipwhite(s + 9));
5563 while (*p != NUL)
5564 {
5565 if (vim_iswhite(*p))
5566 {
5567 has_name = TRUE; /* found end of a name */
5568 p = cin_skipcomment(skipwhite(p));
5569 }
5570 else if (*p == '{')
5571 {
5572 break;
5573 }
5574 else if (vim_iswordc(*p))
5575 {
5576 if (has_name)
5577 return FALSE; /* word character after skipping past name */
5578 ++p;
5579 }
5580 else
5581 {
5582 return FALSE;
5583 }
5584 }
5585 return TRUE;
5586 }
5587 return FALSE;
5588}
5589
Bram Moolenaar071d4272004-06-13 20:20:40 +00005590/*
5591 * Return a pointer to the first non-empty non-comment character after a ':'.
5592 * Return NULL if not found.
5593 * case 234: a = b;
5594 * ^
5595 */
5596 static char_u *
5597after_label(l)
5598 char_u *l;
5599{
5600 for ( ; *l; ++l)
5601 {
5602 if (*l == ':')
5603 {
5604 if (l[1] == ':') /* skip over "::" for C++ */
5605 ++l;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005606 else if (!cin_iscase(l + 1, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005607 break;
5608 }
5609 else if (*l == '\'' && l[1] && l[2] == '\'')
5610 l += 2; /* skip over 'x' */
5611 }
5612 if (*l == NUL)
5613 return NULL;
5614 l = cin_skipcomment(l + 1);
5615 if (*l == NUL)
5616 return NULL;
5617 return l;
5618}
5619
5620/*
5621 * Get indent of line "lnum", skipping a label.
5622 * Return 0 if there is nothing after the label.
5623 */
5624 static int
5625get_indent_nolabel(lnum) /* XXX */
5626 linenr_T lnum;
5627{
5628 char_u *l;
5629 pos_T fp;
5630 colnr_T col;
5631 char_u *p;
5632
5633 l = ml_get(lnum);
5634 p = after_label(l);
5635 if (p == NULL)
5636 return 0;
5637
5638 fp.col = (colnr_T)(p - l);
5639 fp.lnum = lnum;
5640 getvcol(curwin, &fp, &col, NULL, NULL);
5641 return (int)col;
5642}
5643
5644/*
5645 * Find indent for line "lnum", ignoring any case or jump label.
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005646 * Also return a pointer to the text (after the label) in "pp".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005647 * label: if (asdf && asdfasdf)
5648 * ^
5649 */
5650 static int
5651skip_label(lnum, pp, ind_maxcomment)
5652 linenr_T lnum;
5653 char_u **pp;
5654 int ind_maxcomment;
5655{
5656 char_u *l;
5657 int amount;
5658 pos_T cursor_save;
5659
5660 cursor_save = curwin->w_cursor;
5661 curwin->w_cursor.lnum = lnum;
5662 l = ml_get_curline();
5663 /* XXX */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02005664 if (cin_iscase(l, FALSE) || cin_isscopedecl(l)
5665 || cin_islabel(ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005666 {
5667 amount = get_indent_nolabel(lnum);
5668 l = after_label(ml_get_curline());
5669 if (l == NULL) /* just in case */
5670 l = ml_get_curline();
5671 }
5672 else
5673 {
5674 amount = get_indent();
5675 l = ml_get_curline();
5676 }
5677 *pp = l;
5678
5679 curwin->w_cursor = cursor_save;
5680 return amount;
5681}
5682
5683/*
5684 * Return the indent of the first variable name after a type in a declaration.
5685 * int a, indent of "a"
5686 * static struct foo b, indent of "b"
5687 * enum bla c, indent of "c"
5688 * Returns zero when it doesn't look like a declaration.
5689 */
5690 static int
5691cin_first_id_amount()
5692{
5693 char_u *line, *p, *s;
5694 int len;
5695 pos_T fp;
5696 colnr_T col;
5697
5698 line = ml_get_curline();
5699 p = skipwhite(line);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005700 len = (int)(skiptowhite(p) - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005701 if (len == 6 && STRNCMP(p, "static", 6) == 0)
5702 {
5703 p = skipwhite(p + 6);
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00005704 len = (int)(skiptowhite(p) - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005705 }
5706 if (len == 6 && STRNCMP(p, "struct", 6) == 0)
5707 p = skipwhite(p + 6);
5708 else if (len == 4 && STRNCMP(p, "enum", 4) == 0)
5709 p = skipwhite(p + 4);
5710 else if ((len == 8 && STRNCMP(p, "unsigned", 8) == 0)
5711 || (len == 6 && STRNCMP(p, "signed", 6) == 0))
5712 {
5713 s = skipwhite(p + len);
5714 if ((STRNCMP(s, "int", 3) == 0 && vim_iswhite(s[3]))
5715 || (STRNCMP(s, "long", 4) == 0 && vim_iswhite(s[4]))
5716 || (STRNCMP(s, "short", 5) == 0 && vim_iswhite(s[5]))
5717 || (STRNCMP(s, "char", 4) == 0 && vim_iswhite(s[4])))
5718 p = s;
5719 }
5720 for (len = 0; vim_isIDc(p[len]); ++len)
5721 ;
5722 if (len == 0 || !vim_iswhite(p[len]) || cin_nocode(p))
5723 return 0;
5724
5725 p = skipwhite(p + len);
5726 fp.lnum = curwin->w_cursor.lnum;
5727 fp.col = (colnr_T)(p - line);
5728 getvcol(curwin, &fp, &col, NULL, NULL);
5729 return (int)col;
5730}
5731
5732/*
5733 * Return the indent of the first non-blank after an equal sign.
5734 * char *foo = "here";
5735 * Return zero if no (useful) equal sign found.
5736 * Return -1 if the line above "lnum" ends in a backslash.
5737 * foo = "asdf\
5738 * asdf\
5739 * here";
5740 */
5741 static int
5742cin_get_equal_amount(lnum)
5743 linenr_T lnum;
5744{
5745 char_u *line;
5746 char_u *s;
5747 colnr_T col;
5748 pos_T fp;
5749
5750 if (lnum > 1)
5751 {
5752 line = ml_get(lnum - 1);
5753 if (*line != NUL && line[STRLEN(line) - 1] == '\\')
5754 return -1;
5755 }
5756
5757 line = s = ml_get(lnum);
5758 while (*s != NUL && vim_strchr((char_u *)"=;{}\"'", *s) == NULL)
5759 {
5760 if (cin_iscomment(s)) /* ignore comments */
5761 s = cin_skipcomment(s);
5762 else
5763 ++s;
5764 }
5765 if (*s != '=')
5766 return 0;
5767
5768 s = skipwhite(s + 1);
5769 if (cin_nocode(s))
5770 return 0;
5771
5772 if (*s == '"') /* nice alignment for continued strings */
5773 ++s;
5774
5775 fp.lnum = lnum;
5776 fp.col = (colnr_T)(s - line);
5777 getvcol(curwin, &fp, &col, NULL, NULL);
5778 return (int)col;
5779}
5780
5781/*
5782 * Recognize a preprocessor statement: Any line that starts with '#'.
5783 */
5784 static int
5785cin_ispreproc(s)
5786 char_u *s;
5787{
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005788 if (*skipwhite(s) == '#')
Bram Moolenaar071d4272004-06-13 20:20:40 +00005789 return TRUE;
5790 return FALSE;
5791}
5792
5793/*
5794 * Return TRUE if line "*pp" at "*lnump" is a preprocessor statement or a
5795 * continuation line of a preprocessor statement. Decrease "*lnump" to the
5796 * start and return the line in "*pp".
5797 */
5798 static int
5799cin_ispreproc_cont(pp, lnump)
5800 char_u **pp;
5801 linenr_T *lnump;
5802{
5803 char_u *line = *pp;
5804 linenr_T lnum = *lnump;
5805 int retval = FALSE;
5806
Bram Moolenaard8e9bb22005-07-09 21:14:46 +00005807 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005808 {
5809 if (cin_ispreproc(line))
5810 {
5811 retval = TRUE;
5812 *lnump = lnum;
5813 break;
5814 }
5815 if (lnum == 1)
5816 break;
5817 line = ml_get(--lnum);
5818 if (*line == NUL || line[STRLEN(line) - 1] != '\\')
5819 break;
5820 }
5821
5822 if (lnum != *lnump)
5823 *pp = ml_get(*lnump);
5824 return retval;
5825}
5826
5827/*
5828 * Recognize the start of a C or C++ comment.
5829 */
5830 static int
5831cin_iscomment(p)
5832 char_u *p;
5833{
5834 return (p[0] == '/' && (p[1] == '*' || p[1] == '/'));
5835}
5836
5837/*
5838 * Recognize the start of a "//" comment.
5839 */
5840 static int
5841cin_islinecomment(p)
5842 char_u *p;
5843{
5844 return (p[0] == '/' && p[1] == '/');
5845}
5846
5847/*
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005848 * Recognize a line that starts with '{' or '}', or ends with ';', ',', '{' or
5849 * '}'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005850 * Don't consider "} else" a terminated line.
Bram Moolenaar496f9512011-05-19 16:35:09 +02005851 * If a line begins with an "else", only consider it terminated if no unmatched
5852 * opening braces follow (handle "else { foo();" correctly).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005853 * Return the character terminating the line (ending char's have precedence if
5854 * both apply in order to determine initializations).
5855 */
5856 static int
5857cin_isterminated(s, incl_open, incl_comma)
5858 char_u *s;
5859 int incl_open; /* include '{' at the end as terminator */
5860 int incl_comma; /* recognize a trailing comma */
5861{
Bram Moolenaar496f9512011-05-19 16:35:09 +02005862 char_u found_start = 0;
5863 unsigned n_open = 0;
5864 int is_else = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005865
5866 s = cin_skipcomment(s);
5867
5868 if (*s == '{' || (*s == '}' && !cin_iselse(s)))
5869 found_start = *s;
5870
Bram Moolenaar496f9512011-05-19 16:35:09 +02005871 if (!found_start)
5872 is_else = cin_iselse(s);
5873
Bram Moolenaar071d4272004-06-13 20:20:40 +00005874 while (*s)
5875 {
5876 /* skip over comments, "" strings and 'c'haracters */
5877 s = skip_string(cin_skipcomment(s));
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005878 if (*s == '}' && n_open > 0)
5879 --n_open;
Bram Moolenaar496f9512011-05-19 16:35:09 +02005880 if ((!is_else || n_open == 0)
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005881 && (*s == ';' || *s == '}' || (incl_comma && *s == ','))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005882 && cin_nocode(s + 1))
5883 return *s;
Bram Moolenaar4ae06c12011-05-10 11:39:19 +02005884 else if (*s == '{')
5885 {
5886 if (incl_open && cin_nocode(s + 1))
5887 return *s;
5888 else
5889 ++n_open;
5890 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005891
5892 if (*s)
5893 s++;
5894 }
5895 return found_start;
5896}
5897
5898/*
5899 * Recognize the basic picture of a function declaration -- it needs to
5900 * have an open paren somewhere and a close paren at the end of the line and
5901 * no semicolons anywhere.
5902 * When a line ends in a comma we continue looking in the next line.
5903 * "sp" points to a string with the line. When looking at other lines it must
5904 * be restored to the line. When it's NULL fetch lines here.
5905 * "lnum" is where we start looking.
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005906 * "min_lnum" is the line before which we will not be looking.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005907 */
5908 static int
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005909cin_isfuncdecl(sp, first_lnum, min_lnum, ind_maxparen, ind_maxcomment)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005910 char_u **sp;
5911 linenr_T first_lnum;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005912 linenr_T min_lnum;
5913 int ind_maxparen;
5914 int ind_maxcomment;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005915{
5916 char_u *s;
5917 linenr_T lnum = first_lnum;
5918 int retval = FALSE;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005919 pos_T *trypos;
5920 int just_started = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005921
5922 if (sp == NULL)
5923 s = ml_get(lnum);
5924 else
5925 s = *sp;
5926
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005927 if (find_last_paren(s, '(', ')')
5928 && (trypos = find_match_paren(ind_maxparen, ind_maxcomment)) != NULL)
5929 {
5930 lnum = trypos->lnum;
5931 if (lnum < min_lnum)
5932 return FALSE;
5933
5934 s = ml_get(lnum);
5935 }
5936
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005937 /* Ignore line starting with #. */
5938 if (cin_ispreproc(s))
5939 return FALSE;
5940
Bram Moolenaar071d4272004-06-13 20:20:40 +00005941 while (*s && *s != '(' && *s != ';' && *s != '\'' && *s != '"')
5942 {
5943 if (cin_iscomment(s)) /* ignore comments */
5944 s = cin_skipcomment(s);
5945 else
5946 ++s;
5947 }
5948 if (*s != '(')
5949 return FALSE; /* ';', ' or " before any () or no '(' */
5950
5951 while (*s && *s != ';' && *s != '\'' && *s != '"')
5952 {
5953 if (*s == ')' && cin_nocode(s + 1))
5954 {
5955 /* ')' at the end: may have found a match
5956 * Check for he previous line not to end in a backslash:
5957 * #if defined(x) && \
5958 * defined(y)
5959 */
5960 lnum = first_lnum - 1;
5961 s = ml_get(lnum);
5962 if (*s == NUL || s[STRLEN(s) - 1] != '\\')
5963 retval = TRUE;
5964 goto done;
5965 }
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005966 if ((*s == ',' && cin_nocode(s + 1)) || s[1] == NUL || cin_nocode(s))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005967 {
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005968 int comma = (*s == ',');
5969
5970 /* ',' at the end: continue looking in the next line.
5971 * At the end: check for ',' in the next line, for this style:
5972 * func(arg1
5973 * , arg2) */
5974 for (;;)
5975 {
5976 if (lnum >= curbuf->b_ml.ml_line_count)
5977 break;
5978 s = ml_get(++lnum);
5979 if (!cin_ispreproc(s))
5980 break;
5981 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005982 if (lnum >= curbuf->b_ml.ml_line_count)
5983 break;
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005984 /* Require a comma at end of the line or a comma or ')' at the
5985 * start of next line. */
5986 s = skipwhite(s);
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005987 if (!just_started && (!comma && *s != ',' && *s != ')'))
Bram Moolenaar8d2d71d2011-04-28 13:02:09 +02005988 break;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005989 just_started = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005990 }
5991 else if (cin_iscomment(s)) /* ignore comments */
5992 s = cin_skipcomment(s);
5993 else
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005994 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005995 ++s;
Bram Moolenaarc367faa2011-12-14 20:21:35 +01005996 just_started = FALSE;
5997 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005998 }
5999
6000done:
6001 if (lnum != first_lnum && sp != NULL)
6002 *sp = ml_get(first_lnum);
6003
6004 return retval;
6005}
6006
6007 static int
6008cin_isif(p)
6009 char_u *p;
6010{
6011 return (STRNCMP(p, "if", 2) == 0 && !vim_isIDc(p[2]));
6012}
6013
6014 static int
6015cin_iselse(p)
6016 char_u *p;
6017{
6018 if (*p == '}') /* accept "} else" */
6019 p = cin_skipcomment(p + 1);
6020 return (STRNCMP(p, "else", 4) == 0 && !vim_isIDc(p[4]));
6021}
6022
6023 static int
6024cin_isdo(p)
6025 char_u *p;
6026{
6027 return (STRNCMP(p, "do", 2) == 0 && !vim_isIDc(p[2]));
6028}
6029
6030/*
6031 * Check if this is a "while" that should have a matching "do".
6032 * We only accept a "while (condition) ;", with only white space between the
6033 * ')' and ';'. The condition may be spread over several lines.
6034 */
6035 static int
6036cin_iswhileofdo(p, lnum, ind_maxparen) /* XXX */
6037 char_u *p;
6038 linenr_T lnum;
6039 int ind_maxparen;
6040{
6041 pos_T cursor_save;
6042 pos_T *trypos;
6043 int retval = FALSE;
6044
6045 p = cin_skipcomment(p);
6046 if (*p == '}') /* accept "} while (cond);" */
6047 p = cin_skipcomment(p + 1);
6048 if (STRNCMP(p, "while", 5) == 0 && !vim_isIDc(p[5]))
6049 {
6050 cursor_save = curwin->w_cursor;
6051 curwin->w_cursor.lnum = lnum;
6052 curwin->w_cursor.col = 0;
6053 p = ml_get_curline();
6054 while (*p && *p != 'w') /* skip any '}', until the 'w' of the "while" */
6055 {
6056 ++p;
6057 ++curwin->w_cursor.col;
6058 }
6059 if ((trypos = findmatchlimit(NULL, 0, 0, ind_maxparen)) != NULL
6060 && *cin_skipcomment(ml_get_pos(trypos) + 1) == ';')
6061 retval = TRUE;
6062 curwin->w_cursor = cursor_save;
6063 }
6064 return retval;
6065}
6066
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006067/*
Bram Moolenaarb345d492012-04-09 20:42:26 +02006068 * Check whether in "p" there is an "if", "for" or "while" before "*poffset".
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006069 * Return 0 if there is none.
6070 * Otherwise return !0 and update "*poffset" to point to the place where the
6071 * string was found.
6072 */
6073 static int
Bram Moolenaarb345d492012-04-09 20:42:26 +02006074cin_is_if_for_while_before_offset(line, poffset)
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006075 char_u *line;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006076 int *poffset;
6077{
Bram Moolenaarb345d492012-04-09 20:42:26 +02006078 int offset = *poffset;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006079
6080 if (offset-- < 2)
6081 return 0;
6082 while (offset > 2 && vim_iswhite(line[offset]))
6083 --offset;
6084
6085 offset -= 1;
6086 if (!STRNCMP(line + offset, "if", 2))
6087 goto probablyFound;
6088
6089 if (offset >= 1)
6090 {
6091 offset -= 1;
6092 if (!STRNCMP(line + offset, "for", 3))
6093 goto probablyFound;
6094
6095 if (offset >= 2)
6096 {
6097 offset -= 2;
6098 if (!STRNCMP(line + offset, "while", 5))
6099 goto probablyFound;
6100 }
6101 }
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006102 return 0;
Bram Moolenaarb345d492012-04-09 20:42:26 +02006103
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006104probablyFound:
6105 if (!offset || !vim_isIDc(line[offset - 1]))
6106 {
6107 *poffset = offset;
6108 return 1;
6109 }
6110 return 0;
6111}
6112
6113/*
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006114 * Return TRUE if we are at the end of a do-while.
6115 * do
6116 * nothing;
6117 * while (foo
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00006118 * && bar); <-- here
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006119 * Adjust the cursor to the line with "while".
6120 */
6121 static int
6122cin_iswhileofdo_end(terminated, ind_maxparen, ind_maxcomment)
6123 int terminated;
6124 int ind_maxparen;
6125 int ind_maxcomment;
6126{
6127 char_u *line;
6128 char_u *p;
6129 char_u *s;
6130 pos_T *trypos;
6131 int i;
6132
6133 if (terminated != ';') /* there must be a ';' at the end */
6134 return FALSE;
6135
6136 p = line = ml_get_curline();
6137 while (*p != NUL)
6138 {
6139 p = cin_skipcomment(p);
6140 if (*p == ')')
6141 {
6142 s = skipwhite(p + 1);
6143 if (*s == ';' && cin_nocode(s + 1))
6144 {
6145 /* Found ");" at end of the line, now check there is "while"
6146 * before the matching '('. XXX */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006147 i = (int)(p - line);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006148 curwin->w_cursor.col = i;
6149 trypos = find_match_paren(ind_maxparen, ind_maxcomment);
6150 if (trypos != NULL)
6151 {
6152 s = cin_skipcomment(ml_get(trypos->lnum));
6153 if (*s == '}') /* accept "} while (cond);" */
6154 s = cin_skipcomment(s + 1);
6155 if (STRNCMP(s, "while", 5) == 0 && !vim_isIDc(s[5]))
6156 {
6157 curwin->w_cursor.lnum = trypos->lnum;
6158 return TRUE;
6159 }
6160 }
6161
6162 /* Searching may have made "line" invalid, get it again. */
6163 line = ml_get_curline();
6164 p = line + i;
6165 }
6166 }
6167 if (*p != NUL)
6168 ++p;
6169 }
6170 return FALSE;
6171}
6172
Bram Moolenaar071d4272004-06-13 20:20:40 +00006173 static int
6174cin_isbreak(p)
6175 char_u *p;
6176{
6177 return (STRNCMP(p, "break", 5) == 0 && !vim_isIDc(p[5]));
6178}
6179
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006180/*
6181 * Find the position of a C++ base-class declaration or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006182 * constructor-initialization. eg:
6183 *
6184 * class MyClass :
6185 * baseClass <-- here
6186 * class MyClass : public baseClass,
6187 * anotherBaseClass <-- here (should probably lineup ??)
6188 * MyClass::MyClass(...) :
6189 * baseClass(...) <-- here (constructor-initialization)
Bram Moolenaar18144c82006-04-12 21:52:12 +00006190 *
6191 * This is a lot of guessing. Watch out for "cond ? func() : foo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00006192 */
6193 static int
Bram Moolenaare7c56862007-08-04 10:14:52 +00006194cin_is_cpp_baseclass(col)
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006195 colnr_T *col; /* return: column to align with */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006196{
6197 char_u *s;
6198 int class_or_struct, lookfor_ctor_init, cpp_base_class;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006199 linenr_T lnum = curwin->w_cursor.lnum;
Bram Moolenaare7c56862007-08-04 10:14:52 +00006200 char_u *line = ml_get_curline();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006201
6202 *col = 0;
6203
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006204 s = skipwhite(line);
6205 if (*s == '#') /* skip #define FOO x ? (x) : x */
6206 return FALSE;
6207 s = cin_skipcomment(s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006208 if (*s == NUL)
6209 return FALSE;
6210
6211 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
6212
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006213 /* Search for a line starting with '#', empty, ending in ';' or containing
6214 * '{' or '}' and start below it. This handles the following situations:
6215 * a = cond ?
6216 * func() :
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00006217 * asdf;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006218 * func::foo()
6219 * : something
6220 * {}
6221 * Foo::Foo (int one, int two)
6222 * : something(4),
6223 * somethingelse(3)
6224 * {}
6225 */
6226 while (lnum > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006227 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00006228 line = ml_get(lnum - 1);
6229 s = skipwhite(line);
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006230 if (*s == '#' || *s == NUL)
6231 break;
6232 while (*s != NUL)
6233 {
6234 s = cin_skipcomment(s);
6235 if (*s == '{' || *s == '}'
6236 || (*s == ';' && cin_nocode(s + 1)))
6237 break;
6238 if (*s != NUL)
6239 ++s;
6240 }
6241 if (*s != NUL)
6242 break;
6243 --lnum;
6244 }
6245
Bram Moolenaare7c56862007-08-04 10:14:52 +00006246 line = ml_get(lnum);
6247 s = cin_skipcomment(line);
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006248 for (;;)
6249 {
6250 if (*s == NUL)
6251 {
6252 if (lnum == curwin->w_cursor.lnum)
6253 break;
6254 /* Continue in the cursor line. */
Bram Moolenaare7c56862007-08-04 10:14:52 +00006255 line = ml_get(++lnum);
6256 s = cin_skipcomment(line);
6257 if (*s == NUL)
6258 continue;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006259 }
6260
Bram Moolenaaraede6ce2011-05-10 11:56:30 +02006261 if (s[0] == '"')
6262 s = skip_string(s) + 1;
6263 else if (s[0] == ':')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006264 {
6265 if (s[1] == ':')
6266 {
6267 /* skip double colon. It can't be a constructor
6268 * initialization any more */
6269 lookfor_ctor_init = FALSE;
6270 s = cin_skipcomment(s + 2);
6271 }
6272 else if (lookfor_ctor_init || class_or_struct)
6273 {
6274 /* we have something found, that looks like the start of
Bram Moolenaare21877a2008-02-13 09:58:14 +00006275 * cpp-base-class-declaration or constructor-initialization */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006276 cpp_base_class = TRUE;
6277 lookfor_ctor_init = class_or_struct = FALSE;
6278 *col = 0;
6279 s = cin_skipcomment(s + 1);
6280 }
6281 else
6282 s = cin_skipcomment(s + 1);
6283 }
6284 else if ((STRNCMP(s, "class", 5) == 0 && !vim_isIDc(s[5]))
6285 || (STRNCMP(s, "struct", 6) == 0 && !vim_isIDc(s[6])))
6286 {
6287 class_or_struct = TRUE;
6288 lookfor_ctor_init = FALSE;
6289
6290 if (*s == 'c')
6291 s = cin_skipcomment(s + 5);
6292 else
6293 s = cin_skipcomment(s + 6);
6294 }
6295 else
6296 {
6297 if (s[0] == '{' || s[0] == '}' || s[0] == ';')
6298 {
6299 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
6300 }
6301 else if (s[0] == ')')
6302 {
6303 /* Constructor-initialization is assumed if we come across
6304 * something like "):" */
6305 class_or_struct = FALSE;
6306 lookfor_ctor_init = TRUE;
6307 }
Bram Moolenaar18144c82006-04-12 21:52:12 +00006308 else if (s[0] == '?')
6309 {
6310 /* Avoid seeing '() :' after '?' as constructor init. */
6311 return FALSE;
6312 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006313 else if (!vim_isIDc(s[0]))
6314 {
6315 /* if it is not an identifier, we are wrong */
6316 class_or_struct = FALSE;
6317 lookfor_ctor_init = FALSE;
6318 }
6319 else if (*col == 0)
6320 {
6321 /* it can't be a constructor-initialization any more */
6322 lookfor_ctor_init = FALSE;
6323
6324 /* the first statement starts here: lineup with this one... */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006325 if (cpp_base_class)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006326 *col = (colnr_T)(s - line);
6327 }
6328
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006329 /* When the line ends in a comma don't align with it. */
6330 if (lnum == curwin->w_cursor.lnum && *s == ',' && cin_nocode(s + 1))
6331 *col = 0;
6332
Bram Moolenaar071d4272004-06-13 20:20:40 +00006333 s = cin_skipcomment(s + 1);
6334 }
6335 }
6336
6337 return cpp_base_class;
6338}
6339
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00006340 static int
6341get_baseclass_amount(col, ind_maxparen, ind_maxcomment, ind_cpp_baseclass)
6342 int col;
6343 int ind_maxparen;
6344 int ind_maxcomment;
6345 int ind_cpp_baseclass;
6346{
6347 int amount;
6348 colnr_T vcol;
6349 pos_T *trypos;
6350
6351 if (col == 0)
6352 {
6353 amount = get_indent();
6354 if (find_last_paren(ml_get_curline(), '(', ')')
6355 && (trypos = find_match_paren(ind_maxparen,
6356 ind_maxcomment)) != NULL)
6357 amount = get_indent_lnum(trypos->lnum); /* XXX */
6358 if (!cin_ends_in(ml_get_curline(), (char_u *)",", NULL))
6359 amount += ind_cpp_baseclass;
6360 }
6361 else
6362 {
6363 curwin->w_cursor.col = col;
6364 getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
6365 amount = (int)vcol;
6366 }
6367 if (amount < ind_cpp_baseclass)
6368 amount = ind_cpp_baseclass;
6369 return amount;
6370}
6371
Bram Moolenaar071d4272004-06-13 20:20:40 +00006372/*
6373 * Return TRUE if string "s" ends with the string "find", possibly followed by
6374 * white space and comments. Skip strings and comments.
6375 * Ignore "ignore" after "find" if it's not NULL.
6376 */
6377 static int
6378cin_ends_in(s, find, ignore)
6379 char_u *s;
6380 char_u *find;
6381 char_u *ignore;
6382{
6383 char_u *p = s;
6384 char_u *r;
6385 int len = (int)STRLEN(find);
6386
6387 while (*p != NUL)
6388 {
6389 p = cin_skipcomment(p);
6390 if (STRNCMP(p, find, len) == 0)
6391 {
6392 r = skipwhite(p + len);
6393 if (ignore != NULL && STRNCMP(r, ignore, STRLEN(ignore)) == 0)
6394 r = skipwhite(r + STRLEN(ignore));
6395 if (cin_nocode(r))
6396 return TRUE;
6397 }
6398 if (*p != NUL)
6399 ++p;
6400 }
6401 return FALSE;
6402}
6403
6404/*
6405 * Skip strings, chars and comments until at or past "trypos".
6406 * Return the column found.
6407 */
6408 static int
6409cin_skip2pos(trypos)
6410 pos_T *trypos;
6411{
6412 char_u *line;
6413 char_u *p;
6414
6415 p = line = ml_get(trypos->lnum);
6416 while (*p && (colnr_T)(p - line) < trypos->col)
6417 {
6418 if (cin_iscomment(p))
6419 p = cin_skipcomment(p);
6420 else
6421 {
6422 p = skip_string(p);
6423 ++p;
6424 }
6425 }
6426 return (int)(p - line);
6427}
6428
6429/*
6430 * Find the '{' at the start of the block we are in.
6431 * Return NULL if no match found.
6432 * Ignore a '{' that is in a comment, makes indenting the next three lines
6433 * work. */
6434/* foo() */
6435/* { */
6436/* } */
6437
6438 static pos_T *
6439find_start_brace(ind_maxcomment) /* XXX */
6440 int ind_maxcomment;
6441{
6442 pos_T cursor_save;
6443 pos_T *trypos;
6444 pos_T *pos;
6445 static pos_T pos_copy;
6446
6447 cursor_save = curwin->w_cursor;
6448 while ((trypos = findmatchlimit(NULL, '{', FM_BLOCKSTOP, 0)) != NULL)
6449 {
6450 pos_copy = *trypos; /* copy pos_T, next findmatch will change it */
6451 trypos = &pos_copy;
6452 curwin->w_cursor = *trypos;
6453 pos = NULL;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006454 /* ignore the { if it's in a // or / * * / comment */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006455 if ((colnr_T)cin_skip2pos(trypos) == trypos->col
6456 && (pos = find_start_comment(ind_maxcomment)) == NULL) /* XXX */
6457 break;
6458 if (pos != NULL)
6459 curwin->w_cursor.lnum = pos->lnum;
6460 }
6461 curwin->w_cursor = cursor_save;
6462 return trypos;
6463}
6464
6465/*
6466 * Find the matching '(', failing if it is in a comment.
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006467 * Return NULL if no match found.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006468 */
6469 static pos_T *
6470find_match_paren(ind_maxparen, ind_maxcomment) /* XXX */
6471 int ind_maxparen;
6472 int ind_maxcomment;
6473{
6474 pos_T cursor_save;
6475 pos_T *trypos;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006476 static pos_T pos_copy;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006477
6478 cursor_save = curwin->w_cursor;
6479 if ((trypos = findmatchlimit(NULL, '(', 0, ind_maxparen)) != NULL)
6480 {
6481 /* check if the ( is in a // comment */
6482 if ((colnr_T)cin_skip2pos(trypos) > trypos->col)
6483 trypos = NULL;
6484 else
6485 {
6486 pos_copy = *trypos; /* copy trypos, findmatch will change it */
6487 trypos = &pos_copy;
6488 curwin->w_cursor = *trypos;
6489 if (find_start_comment(ind_maxcomment) != NULL) /* XXX */
6490 trypos = NULL;
6491 }
6492 }
6493 curwin->w_cursor = cursor_save;
6494 return trypos;
6495}
6496
6497/*
6498 * Return ind_maxparen corrected for the difference in line number between the
6499 * cursor position and "startpos". This makes sure that searching for a
6500 * matching paren above the cursor line doesn't find a match because of
6501 * looking a few lines further.
6502 */
6503 static int
6504corr_ind_maxparen(ind_maxparen, startpos)
6505 int ind_maxparen;
6506 pos_T *startpos;
6507{
6508 long n = (long)startpos->lnum - (long)curwin->w_cursor.lnum;
6509
6510 if (n > 0 && n < ind_maxparen / 2)
6511 return ind_maxparen - (int)n;
6512 return ind_maxparen;
6513}
6514
6515/*
6516 * Set w_cursor.col to the column number of the last unmatched ')' or '{' in
Bram Moolenaar6d8f9c62011-11-30 13:03:28 +01006517 * line "l". "l" must point to the start of the line.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006518 */
6519 static int
6520find_last_paren(l, start, end)
6521 char_u *l;
6522 int start, end;
6523{
6524 int i;
6525 int retval = FALSE;
6526 int open_count = 0;
6527
6528 curwin->w_cursor.col = 0; /* default is start of line */
6529
Bram Moolenaar6d8f9c62011-11-30 13:03:28 +01006530 for (i = 0; l[i] != NUL; i++)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006531 {
6532 i = (int)(cin_skipcomment(l + i) - l); /* ignore parens in comments */
6533 i = (int)(skip_string(l + i) - l); /* ignore parens in quotes */
6534 if (l[i] == start)
6535 ++open_count;
6536 else if (l[i] == end)
6537 {
6538 if (open_count > 0)
6539 --open_count;
6540 else
6541 {
6542 curwin->w_cursor.col = i;
6543 retval = TRUE;
6544 }
6545 }
6546 }
6547 return retval;
6548}
6549
6550 int
6551get_c_indent()
6552{
Bram Moolenaar14f24742012-08-08 18:01:05 +02006553 int sw = (int)get_sw_value();
6554
Bram Moolenaar071d4272004-06-13 20:20:40 +00006555 /*
6556 * spaces from a block's opening brace the prevailing indent for that
6557 * block should be
6558 */
Bram Moolenaar14f24742012-08-08 18:01:05 +02006559
6560 int ind_level = sw;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006561
6562 /*
6563 * spaces from the edge of the line an open brace that's at the end of a
6564 * line is imagined to be.
6565 */
6566 int ind_open_imag = 0;
6567
6568 /*
Bram Moolenaar1a509df2010-08-01 17:59:57 +02006569 * spaces from the prevailing indent for a line that is not preceded by
Bram Moolenaar071d4272004-06-13 20:20:40 +00006570 * an opening brace.
6571 */
6572 int ind_no_brace = 0;
6573
6574 /*
6575 * column where the first { of a function should be located }
6576 */
6577 int ind_first_open = 0;
6578
6579 /*
6580 * spaces from the prevailing indent a leftmost open brace should be
6581 * located
6582 */
6583 int ind_open_extra = 0;
6584
6585 /*
6586 * spaces from the matching open brace (real location for one at the left
6587 * edge; imaginary location from one that ends a line) the matching close
6588 * brace should be located
6589 */
6590 int ind_close_extra = 0;
6591
6592 /*
6593 * spaces from the edge of the line an open brace sitting in the leftmost
6594 * column is imagined to be
6595 */
6596 int ind_open_left_imag = 0;
6597
6598 /*
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006599 * Spaces jump labels should be shifted to the left if N is non-negative,
6600 * otherwise the jump label will be put to column 1.
6601 */
6602 int ind_jump_label = -1;
6603
6604 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006605 * spaces from the switch() indent a "case xx" label should be located
6606 */
Bram Moolenaar14f24742012-08-08 18:01:05 +02006607 int ind_case = sw;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006608
6609 /*
6610 * spaces from the "case xx:" code after a switch() should be located
6611 */
Bram Moolenaar14f24742012-08-08 18:01:05 +02006612 int ind_case_code = sw;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006613
6614 /*
6615 * lineup break at end of case in switch() with case label
6616 */
6617 int ind_case_break = 0;
6618
6619 /*
6620 * spaces from the class declaration indent a scope declaration label
6621 * should be located
6622 */
Bram Moolenaar14f24742012-08-08 18:01:05 +02006623 int ind_scopedecl = sw;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006624
6625 /*
6626 * spaces from the scope declaration label code should be located
6627 */
Bram Moolenaar14f24742012-08-08 18:01:05 +02006628 int ind_scopedecl_code = sw;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006629
6630 /*
6631 * amount K&R-style parameters should be indented
6632 */
Bram Moolenaar14f24742012-08-08 18:01:05 +02006633 int ind_param = sw;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006634
6635 /*
6636 * amount a function type spec should be indented
6637 */
Bram Moolenaar14f24742012-08-08 18:01:05 +02006638 int ind_func_type = sw;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006639
6640 /*
6641 * amount a cpp base class declaration or constructor initialization
6642 * should be indented
6643 */
Bram Moolenaar14f24742012-08-08 18:01:05 +02006644 int ind_cpp_baseclass = sw;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006645
6646 /*
6647 * additional spaces beyond the prevailing indent a continuation line
6648 * should be located
6649 */
Bram Moolenaar14f24742012-08-08 18:01:05 +02006650 int ind_continuation = sw;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006651
6652 /*
6653 * spaces from the indent of the line with an unclosed parentheses
6654 */
Bram Moolenaar14f24742012-08-08 18:01:05 +02006655 int ind_unclosed = sw * 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006656
6657 /*
6658 * spaces from the indent of the line with an unclosed parentheses, which
6659 * itself is also unclosed
6660 */
Bram Moolenaar14f24742012-08-08 18:01:05 +02006661 int ind_unclosed2 = sw;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006662
6663 /*
6664 * suppress ignoring spaces from the indent of a line starting with an
6665 * unclosed parentheses.
6666 */
6667 int ind_unclosed_noignore = 0;
6668
6669 /*
6670 * If the opening paren is the last nonwhite character on the line, and
6671 * ind_unclosed_wrapped is nonzero, use this indent relative to the outer
6672 * context (for very long lines).
6673 */
6674 int ind_unclosed_wrapped = 0;
6675
6676 /*
6677 * suppress ignoring white space when lining up with the character after
6678 * an unclosed parentheses.
6679 */
6680 int ind_unclosed_whiteok = 0;
6681
6682 /*
6683 * indent a closing parentheses under the line start of the matching
6684 * opening parentheses.
6685 */
6686 int ind_matching_paren = 0;
6687
6688 /*
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006689 * indent a closing parentheses under the previous line.
6690 */
6691 int ind_paren_prev = 0;
6692
6693 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006694 * Extra indent for comments.
6695 */
6696 int ind_comment = 0;
6697
6698 /*
6699 * spaces from the comment opener when there is nothing after it.
6700 */
6701 int ind_in_comment = 3;
6702
6703 /*
6704 * boolean: if non-zero, use ind_in_comment even if there is something
6705 * after the comment opener.
6706 */
6707 int ind_in_comment2 = 0;
6708
6709 /*
6710 * max lines to search for an open paren
6711 */
6712 int ind_maxparen = 20;
6713
6714 /*
6715 * max lines to search for an open comment
6716 */
6717 int ind_maxcomment = 70;
6718
6719 /*
6720 * handle braces for java code
6721 */
6722 int ind_java = 0;
6723
6724 /*
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006725 * not to confuse JS object properties with labels
6726 */
6727 int ind_js = 0;
6728
6729 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006730 * handle blocked cases correctly
6731 */
6732 int ind_keep_case_label = 0;
6733
Bram Moolenaared38b0a2011-05-25 15:16:18 +02006734 /*
6735 * handle C++ namespace
6736 */
6737 int ind_cpp_namespace = 0;
6738
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006739 /*
6740 * handle continuation lines containing conditions of if(), for() and
6741 * while()
6742 */
6743 int ind_if_for_while = 0;
6744
Bram Moolenaar071d4272004-06-13 20:20:40 +00006745 pos_T cur_curpos;
6746 int amount;
6747 int scope_amount;
Bram Moolenaarb21e5842006-04-16 18:30:08 +00006748 int cur_amount = MAXCOL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006749 colnr_T col;
6750 char_u *theline;
6751 char_u *linecopy;
6752 pos_T *trypos;
6753 pos_T *tryposBrace = NULL;
6754 pos_T our_paren_pos;
6755 char_u *start;
6756 int start_brace;
Bram Moolenaare21877a2008-02-13 09:58:14 +00006757#define BRACE_IN_COL0 1 /* '{' is in column 0 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006758#define BRACE_AT_START 2 /* '{' is at start of line */
6759#define BRACE_AT_END 3 /* '{' is at end of line */
6760 linenr_T ourscope;
6761 char_u *l;
6762 char_u *look;
6763 char_u terminated;
6764 int lookfor;
6765#define LOOKFOR_INITIAL 0
6766#define LOOKFOR_IF 1
6767#define LOOKFOR_DO 2
6768#define LOOKFOR_CASE 3
6769#define LOOKFOR_ANY 4
6770#define LOOKFOR_TERM 5
6771#define LOOKFOR_UNTERM 6
6772#define LOOKFOR_SCOPEDECL 7
6773#define LOOKFOR_NOBREAK 8
6774#define LOOKFOR_CPP_BASECLASS 9
6775#define LOOKFOR_ENUM_OR_INIT 10
6776
6777 int whilelevel;
6778 linenr_T lnum;
6779 char_u *options;
Bram Moolenaar48d27922012-06-13 13:40:48 +02006780 char_u *digits;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006781 int fraction = 0; /* init for GCC */
6782 int divider;
6783 int n;
6784 int iscase;
6785 int lookfor_break;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02006786 int lookfor_cpp_namespace = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006787 int cont_amount = 0; /* amount for continuation line */
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006788 int original_line_islabel;
Bram Moolenaare79d1532011-10-04 18:03:47 +02006789 int added_to_amount = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006790
6791 for (options = curbuf->b_p_cino; *options; )
6792 {
6793 l = options++;
6794 if (*options == '-')
6795 ++options;
Bram Moolenaar48d27922012-06-13 13:40:48 +02006796 digits = options; /* remember where the digits start */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006797 n = getdigits(&options);
6798 divider = 0;
6799 if (*options == '.') /* ".5s" means a fraction */
6800 {
6801 fraction = atol((char *)++options);
6802 while (VIM_ISDIGIT(*options))
6803 {
6804 ++options;
6805 if (divider)
6806 divider *= 10;
6807 else
6808 divider = 10;
6809 }
6810 }
6811 if (*options == 's') /* "2s" means two times 'shiftwidth' */
6812 {
Bram Moolenaar48d27922012-06-13 13:40:48 +02006813 if (options == digits)
Bram Moolenaar14f24742012-08-08 18:01:05 +02006814 n = sw; /* just "s" is one 'shiftwidth' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006815 else
6816 {
Bram Moolenaar14f24742012-08-08 18:01:05 +02006817 n *= sw;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006818 if (divider)
Bram Moolenaar14f24742012-08-08 18:01:05 +02006819 n += (sw * fraction + divider / 2) / divider;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006820 }
6821 ++options;
6822 }
6823 if (l[1] == '-')
6824 n = -n;
6825 /* When adding an entry here, also update the default 'cinoptions' in
Bram Moolenaar39353fd2007-03-27 09:02:11 +00006826 * doc/indent.txt, and add explanation for it! */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006827 switch (*l)
6828 {
6829 case '>': ind_level = n; break;
6830 case 'e': ind_open_imag = n; break;
6831 case 'n': ind_no_brace = n; break;
6832 case 'f': ind_first_open = n; break;
6833 case '{': ind_open_extra = n; break;
6834 case '}': ind_close_extra = n; break;
6835 case '^': ind_open_left_imag = n; break;
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006836 case 'L': ind_jump_label = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006837 case ':': ind_case = n; break;
6838 case '=': ind_case_code = n; break;
6839 case 'b': ind_case_break = n; break;
6840 case 'p': ind_param = n; break;
6841 case 't': ind_func_type = n; break;
6842 case '/': ind_comment = n; break;
6843 case 'c': ind_in_comment = n; break;
6844 case 'C': ind_in_comment2 = n; break;
6845 case 'i': ind_cpp_baseclass = n; break;
6846 case '+': ind_continuation = n; break;
6847 case '(': ind_unclosed = n; break;
6848 case 'u': ind_unclosed2 = n; break;
6849 case 'U': ind_unclosed_noignore = n; break;
6850 case 'W': ind_unclosed_wrapped = n; break;
6851 case 'w': ind_unclosed_whiteok = n; break;
6852 case 'm': ind_matching_paren = n; break;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006853 case 'M': ind_paren_prev = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006854 case ')': ind_maxparen = n; break;
6855 case '*': ind_maxcomment = n; break;
6856 case 'g': ind_scopedecl = n; break;
6857 case 'h': ind_scopedecl_code = n; break;
6858 case 'j': ind_java = n; break;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006859 case 'J': ind_js = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006860 case 'l': ind_keep_case_label = n; break;
Bram Moolenaar39353fd2007-03-27 09:02:11 +00006861 case '#': ind_hash_comment = n; break;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02006862 case 'N': ind_cpp_namespace = n; break;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02006863 case 'k': ind_if_for_while = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006864 }
Bram Moolenaardfdf3c42010-03-23 18:22:46 +01006865 if (*options == ',')
6866 ++options;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006867 }
6868
6869 /* remember where the cursor was when we started */
6870 cur_curpos = curwin->w_cursor;
6871
Bram Moolenaar3acfc302010-07-11 17:23:02 +02006872 /* if we are at line 1 0 is fine, right? */
6873 if (cur_curpos.lnum == 1)
6874 return 0;
6875
Bram Moolenaar071d4272004-06-13 20:20:40 +00006876 /* Get a copy of the current contents of the line.
6877 * This is required, because only the most recent line obtained with
6878 * ml_get is valid! */
6879 linecopy = vim_strsave(ml_get(cur_curpos.lnum));
6880 if (linecopy == NULL)
6881 return 0;
6882
6883 /*
6884 * In insert mode and the cursor is on a ')' truncate the line at the
6885 * cursor position. We don't want to line up with the matching '(' when
6886 * inserting new stuff.
6887 * For unknown reasons the cursor might be past the end of the line, thus
6888 * check for that.
6889 */
6890 if ((State & INSERT)
Bram Moolenaar2c4278f2009-05-17 11:33:22 +00006891 && curwin->w_cursor.col < (colnr_T)STRLEN(linecopy)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006892 && linecopy[curwin->w_cursor.col] == ')')
6893 linecopy[curwin->w_cursor.col] = NUL;
6894
6895 theline = skipwhite(linecopy);
6896
6897 /* move the cursor to the start of the line */
6898
6899 curwin->w_cursor.col = 0;
6900
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006901 original_line_islabel = cin_islabel(ind_maxcomment); /* XXX */
6902
Bram Moolenaar071d4272004-06-13 20:20:40 +00006903 /*
6904 * #defines and so on always go at the left when included in 'cinkeys'.
6905 */
6906 if (*theline == '#' && (*linecopy == '#' || in_cinkeys('#', ' ', TRUE)))
6907 {
6908 amount = 0;
6909 }
6910
6911 /*
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006912 * Is it a non-case label? Then that goes at the left margin too unless:
6913 * - JS flag is set.
6914 * - 'L' item has a positive value.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006915 */
Bram Moolenaar02c707a2010-07-17 17:12:06 +02006916 else if (original_line_islabel && !ind_js && ind_jump_label < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006917 {
6918 amount = 0;
6919 }
6920
6921 /*
6922 * If we're inside a "//" comment and there is a "//" comment in a
6923 * previous line, lineup with that one.
6924 */
6925 else if (cin_islinecomment(theline)
6926 && (trypos = find_line_comment()) != NULL) /* XXX */
6927 {
6928 /* find how indented the line beginning the comment is */
6929 getvcol(curwin, trypos, &col, NULL, NULL);
6930 amount = col;
6931 }
6932
6933 /*
6934 * If we're inside a comment and not looking at the start of the
6935 * comment, try using the 'comments' option.
6936 */
6937 else if (!cin_iscomment(theline)
6938 && (trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
6939 {
6940 int lead_start_len = 2;
6941 int lead_middle_len = 1;
6942 char_u lead_start[COM_MAX_LEN]; /* start-comment string */
6943 char_u lead_middle[COM_MAX_LEN]; /* middle-comment string */
6944 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
6945 char_u *p;
6946 int start_align = 0;
6947 int start_off = 0;
6948 int done = FALSE;
6949
6950 /* find how indented the line beginning the comment is */
6951 getvcol(curwin, trypos, &col, NULL, NULL);
6952 amount = col;
Bram Moolenaar4aa97422011-04-11 14:27:38 +02006953 *lead_start = NUL;
6954 *lead_middle = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006955
6956 p = curbuf->b_p_com;
6957 while (*p != NUL)
6958 {
6959 int align = 0;
6960 int off = 0;
6961 int what = 0;
6962
6963 while (*p != NUL && *p != ':')
6964 {
6965 if (*p == COM_START || *p == COM_END || *p == COM_MIDDLE)
6966 what = *p++;
6967 else if (*p == COM_LEFT || *p == COM_RIGHT)
6968 align = *p++;
6969 else if (VIM_ISDIGIT(*p) || *p == '-')
6970 off = getdigits(&p);
6971 else
6972 ++p;
6973 }
6974
6975 if (*p == ':')
6976 ++p;
6977 (void)copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
6978 if (what == COM_START)
6979 {
6980 STRCPY(lead_start, lead_end);
6981 lead_start_len = (int)STRLEN(lead_start);
6982 start_off = off;
6983 start_align = align;
6984 }
6985 else if (what == COM_MIDDLE)
6986 {
6987 STRCPY(lead_middle, lead_end);
6988 lead_middle_len = (int)STRLEN(lead_middle);
6989 }
6990 else if (what == COM_END)
6991 {
6992 /* If our line starts with the middle comment string, line it
6993 * up with the comment opener per the 'comments' option. */
6994 if (STRNCMP(theline, lead_middle, lead_middle_len) == 0
6995 && STRNCMP(theline, lead_end, STRLEN(lead_end)) != 0)
6996 {
6997 done = TRUE;
6998 if (curwin->w_cursor.lnum > 1)
6999 {
7000 /* If the start comment string matches in the previous
Bram Moolenaare21877a2008-02-13 09:58:14 +00007001 * line, use the indent of that line plus offset. If
Bram Moolenaar071d4272004-06-13 20:20:40 +00007002 * the middle comment string matches in the previous
7003 * line, use the indent of that line. XXX */
7004 look = skipwhite(ml_get(curwin->w_cursor.lnum - 1));
7005 if (STRNCMP(look, lead_start, lead_start_len) == 0)
7006 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
7007 else if (STRNCMP(look, lead_middle,
7008 lead_middle_len) == 0)
7009 {
7010 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
7011 break;
7012 }
7013 /* If the start comment string doesn't match with the
7014 * start of the comment, skip this entry. XXX */
7015 else if (STRNCMP(ml_get(trypos->lnum) + trypos->col,
7016 lead_start, lead_start_len) != 0)
7017 continue;
7018 }
7019 if (start_off != 0)
7020 amount += start_off;
7021 else if (start_align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00007022 amount += vim_strsize(lead_start)
7023 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007024 break;
7025 }
7026
7027 /* If our line starts with the end comment string, line it up
7028 * with the middle comment */
7029 if (STRNCMP(theline, lead_middle, lead_middle_len) != 0
7030 && STRNCMP(theline, lead_end, STRLEN(lead_end)) == 0)
7031 {
7032 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
7033 /* XXX */
7034 if (off != 0)
7035 amount += off;
7036 else if (align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00007037 amount += vim_strsize(lead_start)
7038 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007039 done = TRUE;
7040 break;
7041 }
7042 }
7043 }
7044
7045 /* If our line starts with an asterisk, line up with the
7046 * asterisk in the comment opener; otherwise, line up
7047 * with the first character of the comment text.
7048 */
7049 if (done)
7050 ;
7051 else if (theline[0] == '*')
7052 amount += 1;
7053 else
7054 {
7055 /*
7056 * If we are more than one line away from the comment opener, take
7057 * the indent of the previous non-empty line. If 'cino' has "CO"
7058 * and we are just below the comment opener and there are any
7059 * white characters after it line up with the text after it;
7060 * otherwise, add the amount specified by "c" in 'cino'
7061 */
7062 amount = -1;
7063 for (lnum = cur_curpos.lnum - 1; lnum > trypos->lnum; --lnum)
7064 {
7065 if (linewhite(lnum)) /* skip blank lines */
7066 continue;
7067 amount = get_indent_lnum(lnum); /* XXX */
7068 break;
7069 }
7070 if (amount == -1) /* use the comment opener */
7071 {
7072 if (!ind_in_comment2)
7073 {
7074 start = ml_get(trypos->lnum);
7075 look = start + trypos->col + 2; /* skip / and * */
7076 if (*look != NUL) /* if something after it */
7077 trypos->col = (colnr_T)(skipwhite(look) - start);
7078 }
7079 getvcol(curwin, trypos, &col, NULL, NULL);
7080 amount = col;
7081 if (ind_in_comment2 || *look == NUL)
7082 amount += ind_in_comment;
7083 }
7084 }
7085 }
7086
7087 /*
7088 * Are we inside parentheses or braces?
7089 */ /* XXX */
7090 else if (((trypos = find_match_paren(ind_maxparen, ind_maxcomment)) != NULL
7091 && ind_java == 0)
7092 || (tryposBrace = find_start_brace(ind_maxcomment)) != NULL
7093 || trypos != NULL)
7094 {
7095 if (trypos != NULL && tryposBrace != NULL)
7096 {
7097 /* Both an unmatched '(' and '{' is found. Use the one which is
7098 * closer to the current cursor position, set the other to NULL. */
7099 if (trypos->lnum != tryposBrace->lnum
7100 ? trypos->lnum < tryposBrace->lnum
7101 : trypos->col < tryposBrace->col)
7102 trypos = NULL;
7103 else
7104 tryposBrace = NULL;
7105 }
7106
7107 if (trypos != NULL)
7108 {
7109 /*
7110 * If the matching paren is more than one line away, use the indent of
7111 * a previous non-empty line that matches the same paren.
7112 */
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007113 if (theline[0] == ')' && ind_paren_prev)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007114 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007115 /* Line up with the start of the matching paren line. */
7116 amount = get_indent_lnum(curwin->w_cursor.lnum - 1); /* XXX */
7117 }
7118 else
7119 {
7120 amount = -1;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007121 our_paren_pos = *trypos;
7122 for (lnum = cur_curpos.lnum - 1; lnum > our_paren_pos.lnum; --lnum)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007123 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007124 l = skipwhite(ml_get(lnum));
7125 if (cin_nocode(l)) /* skip comment lines */
7126 continue;
7127 if (cin_ispreproc_cont(&l, &lnum))
7128 continue; /* ignore #define, #if, etc. */
7129 curwin->w_cursor.lnum = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007130
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007131 /* Skip a comment. XXX */
7132 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
7133 {
7134 lnum = trypos->lnum + 1;
7135 continue;
7136 }
7137
7138 /* XXX */
7139 if ((trypos = find_match_paren(
7140 corr_ind_maxparen(ind_maxparen, &cur_curpos),
Bram Moolenaar071d4272004-06-13 20:20:40 +00007141 ind_maxcomment)) != NULL
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007142 && trypos->lnum == our_paren_pos.lnum
7143 && trypos->col == our_paren_pos.col)
7144 {
7145 amount = get_indent_lnum(lnum); /* XXX */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007146
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007147 if (theline[0] == ')')
7148 {
7149 if (our_paren_pos.lnum != lnum
7150 && cur_amount > amount)
7151 cur_amount = amount;
7152 amount = -1;
7153 }
7154 break;
7155 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007156 }
7157 }
7158
7159 /*
7160 * Line up with line where the matching paren is. XXX
7161 * If the line starts with a '(' or the indent for unclosed
7162 * parentheses is zero, line up with the unclosed parentheses.
7163 */
7164 if (amount == -1)
7165 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007166 int ignore_paren_col = 0;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007167 int is_if_for_while = 0;
7168
7169 if (ind_if_for_while)
7170 {
7171 /* Look for the outermost opening parenthesis on this line
7172 * and check whether it belongs to an "if", "for" or "while". */
7173
7174 pos_T cursor_save = curwin->w_cursor;
7175 pos_T outermost;
7176 char_u *line;
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007177
7178 trypos = &our_paren_pos;
7179 do {
7180 outermost = *trypos;
7181 curwin->w_cursor.lnum = outermost.lnum;
7182 curwin->w_cursor.col = outermost.col;
7183
7184 trypos = find_match_paren(ind_maxparen, ind_maxcomment);
7185 } while (trypos && trypos->lnum == outermost.lnum);
7186
7187 curwin->w_cursor = cursor_save;
7188
7189 line = ml_get(outermost.lnum);
7190
7191 is_if_for_while =
Bram Moolenaarb345d492012-04-09 20:42:26 +02007192 cin_is_if_for_while_before_offset(line, &outermost.col);
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007193 }
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007194
Bram Moolenaar071d4272004-06-13 20:20:40 +00007195 amount = skip_label(our_paren_pos.lnum, &look, ind_maxcomment);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007196 look = skipwhite(look);
7197 if (*look == '(')
7198 {
7199 linenr_T save_lnum = curwin->w_cursor.lnum;
7200 char_u *line;
7201 int look_col;
7202
7203 /* Ignore a '(' in front of the line that has a match before
7204 * our matching '('. */
7205 curwin->w_cursor.lnum = our_paren_pos.lnum;
7206 line = ml_get_curline();
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007207 look_col = (int)(look - line);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007208 curwin->w_cursor.col = look_col + 1;
7209 if ((trypos = findmatchlimit(NULL, ')', 0, ind_maxparen))
7210 != NULL
7211 && trypos->lnum == our_paren_pos.lnum
7212 && trypos->col < our_paren_pos.col)
7213 ignore_paren_col = trypos->col + 1;
7214
7215 curwin->w_cursor.lnum = save_lnum;
7216 look = ml_get(our_paren_pos.lnum) + look_col;
7217 }
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007218 if (theline[0] == ')' || (ind_unclosed == 0 && is_if_for_while == 0)
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007219 || (!ind_unclosed_noignore && *look == '('
7220 && ignore_paren_col == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007221 {
7222 /*
7223 * If we're looking at a close paren, line up right there;
7224 * otherwise, line up with the next (non-white) character.
7225 * When ind_unclosed_wrapped is set and the matching paren is
7226 * the last nonwhite character of the line, use either the
7227 * indent of the current line or the indentation of the next
7228 * outer paren and add ind_unclosed_wrapped (for very long
7229 * lines).
7230 */
7231 if (theline[0] != ')')
7232 {
7233 cur_amount = MAXCOL;
7234 l = ml_get(our_paren_pos.lnum);
7235 if (ind_unclosed_wrapped
7236 && cin_ends_in(l, (char_u *)"(", NULL))
7237 {
7238 /* look for opening unmatched paren, indent one level
7239 * for each additional level */
7240 n = 1;
7241 for (col = 0; col < our_paren_pos.col; ++col)
7242 {
7243 switch (l[col])
7244 {
7245 case '(':
7246 case '{': ++n;
7247 break;
7248
7249 case ')':
7250 case '}': if (n > 1)
7251 --n;
7252 break;
7253 }
7254 }
7255
7256 our_paren_pos.col = 0;
7257 amount += n * ind_unclosed_wrapped;
7258 }
7259 else if (ind_unclosed_whiteok)
7260 our_paren_pos.col++;
7261 else
7262 {
7263 col = our_paren_pos.col + 1;
7264 while (vim_iswhite(l[col]))
7265 col++;
7266 if (l[col] != NUL) /* In case of trailing space */
7267 our_paren_pos.col = col;
7268 else
7269 our_paren_pos.col++;
7270 }
7271 }
7272
7273 /*
7274 * Find how indented the paren is, or the character after it
7275 * if we did the above "if".
7276 */
7277 if (our_paren_pos.col > 0)
7278 {
7279 getvcol(curwin, &our_paren_pos, &col, NULL, NULL);
7280 if (cur_amount > (int)col)
7281 cur_amount = col;
7282 }
7283 }
7284
7285 if (theline[0] == ')' && ind_matching_paren)
7286 {
7287 /* Line up with the start of the matching paren line. */
7288 }
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007289 else if ((ind_unclosed == 0 && is_if_for_while == 0)
7290 || (!ind_unclosed_noignore
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007291 && *look == '(' && ignore_paren_col == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007292 {
7293 if (cur_amount != MAXCOL)
7294 amount = cur_amount;
7295 }
7296 else
7297 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007298 /* Add ind_unclosed2 for each '(' before our matching one, but
7299 * ignore (void) before the line (ignore_paren_col). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007300 col = our_paren_pos.col;
Bram Moolenaarb21e5842006-04-16 18:30:08 +00007301 while ((int)our_paren_pos.col > ignore_paren_col)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007302 {
7303 --our_paren_pos.col;
7304 switch (*ml_get_pos(&our_paren_pos))
7305 {
7306 case '(': amount += ind_unclosed2;
7307 col = our_paren_pos.col;
7308 break;
7309 case ')': amount -= ind_unclosed2;
7310 col = MAXCOL;
7311 break;
7312 }
7313 }
7314
7315 /* Use ind_unclosed once, when the first '(' is not inside
7316 * braces */
7317 if (col == MAXCOL)
7318 amount += ind_unclosed;
7319 else
7320 {
7321 curwin->w_cursor.lnum = our_paren_pos.lnum;
7322 curwin->w_cursor.col = col;
Bram Moolenaar367bec82011-04-11 14:26:19 +02007323 if (find_match_paren(ind_maxparen, ind_maxcomment) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007324 amount += ind_unclosed2;
7325 else
Bram Moolenaar3675fa02012-04-05 17:17:42 +02007326 {
7327 if (is_if_for_while)
7328 amount += ind_if_for_while;
7329 else
7330 amount += ind_unclosed;
7331 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007332 }
7333 /*
7334 * For a line starting with ')' use the minimum of the two
7335 * positions, to avoid giving it more indent than the previous
7336 * lines:
7337 * func_long_name( if (x
7338 * arg && yy
7339 * ) ^ not here ) ^ not here
7340 */
7341 if (cur_amount < amount)
7342 amount = cur_amount;
7343 }
7344 }
7345
7346 /* add extra indent for a comment */
7347 if (cin_iscomment(theline))
7348 amount += ind_comment;
7349 }
7350
7351 /*
7352 * Are we at least inside braces, then?
7353 */
7354 else
7355 {
7356 trypos = tryposBrace;
7357
7358 ourscope = trypos->lnum;
7359 start = ml_get(ourscope);
7360
7361 /*
7362 * Now figure out how indented the line is in general.
7363 * If the brace was at the start of the line, we use that;
7364 * otherwise, check out the indentation of the line as
7365 * a whole and then add the "imaginary indent" to that.
7366 */
7367 look = skipwhite(start);
7368 if (*look == '{')
7369 {
7370 getvcol(curwin, trypos, &col, NULL, NULL);
7371 amount = col;
7372 if (*start == '{')
7373 start_brace = BRACE_IN_COL0;
7374 else
7375 start_brace = BRACE_AT_START;
7376 }
7377 else
7378 {
7379 /*
7380 * that opening brace might have been on a continuation
7381 * line. if so, find the start of the line.
7382 */
7383 curwin->w_cursor.lnum = ourscope;
7384
7385 /*
7386 * position the cursor over the rightmost paren, so that
7387 * matching it will take us back to the start of the line.
7388 */
7389 lnum = ourscope;
7390 if (find_last_paren(start, '(', ')')
7391 && (trypos = find_match_paren(ind_maxparen,
7392 ind_maxcomment)) != NULL)
7393 lnum = trypos->lnum;
7394
7395 /*
7396 * It could have been something like
7397 * case 1: if (asdf &&
7398 * ldfd) {
7399 * }
7400 */
Bram Moolenaar6ec154b2011-06-12 21:51:08 +02007401 if (ind_js || (ind_keep_case_label
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007402 && cin_iscase(skipwhite(ml_get_curline()), FALSE)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007403 amount = get_indent();
7404 else
7405 amount = skip_label(lnum, &l, ind_maxcomment);
7406
7407 start_brace = BRACE_AT_END;
7408 }
7409
7410 /*
7411 * if we're looking at a closing brace, that's where
7412 * we want to be. otherwise, add the amount of room
7413 * that an indent is supposed to be.
7414 */
7415 if (theline[0] == '}')
7416 {
7417 /*
7418 * they may want closing braces to line up with something
7419 * other than the open brace. indulge them, if so.
7420 */
7421 amount += ind_close_extra;
7422 }
7423 else
7424 {
7425 /*
7426 * If we're looking at an "else", try to find an "if"
7427 * to match it with.
7428 * If we're looking at a "while", try to find a "do"
7429 * to match it with.
7430 */
7431 lookfor = LOOKFOR_INITIAL;
7432 if (cin_iselse(theline))
7433 lookfor = LOOKFOR_IF;
7434 else if (cin_iswhileofdo(theline, cur_curpos.lnum, ind_maxparen))
7435 /* XXX */
7436 lookfor = LOOKFOR_DO;
7437 if (lookfor != LOOKFOR_INITIAL)
7438 {
7439 curwin->w_cursor.lnum = cur_curpos.lnum;
7440 if (find_match(lookfor, ourscope, ind_maxparen,
7441 ind_maxcomment) == OK)
7442 {
7443 amount = get_indent(); /* XXX */
7444 goto theend;
7445 }
7446 }
7447
7448 /*
7449 * We get here if we are not on an "while-of-do" or "else" (or
7450 * failed to find a matching "if").
7451 * Search backwards for something to line up with.
7452 * First set amount for when we don't find anything.
7453 */
7454
7455 /*
7456 * if the '{' is _really_ at the left margin, use the imaginary
7457 * location of a left-margin brace. Otherwise, correct the
7458 * location for ind_open_extra.
7459 */
7460
7461 if (start_brace == BRACE_IN_COL0) /* '{' is in column 0 */
7462 {
7463 amount = ind_open_left_imag;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007464 lookfor_cpp_namespace = TRUE;
7465 }
7466 else if (start_brace == BRACE_AT_START &&
7467 lookfor_cpp_namespace) /* '{' is at start */
7468 {
7469
7470 lookfor_cpp_namespace = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007471 }
7472 else
7473 {
7474 if (start_brace == BRACE_AT_END) /* '{' is at end of line */
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007475 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007476 amount += ind_open_imag;
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007477
7478 l = skipwhite(ml_get_curline());
7479 if (cin_is_cpp_namespace(l))
7480 amount += ind_cpp_namespace;
7481 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007482 else
7483 {
7484 /* Compensate for adding ind_open_extra later. */
7485 amount -= ind_open_extra;
7486 if (amount < 0)
7487 amount = 0;
7488 }
7489 }
7490
7491 lookfor_break = FALSE;
7492
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007493 if (cin_iscase(theline, FALSE)) /* it's a switch() label */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007494 {
7495 lookfor = LOOKFOR_CASE; /* find a previous switch() label */
7496 amount += ind_case;
7497 }
7498 else if (cin_isscopedecl(theline)) /* private:, ... */
7499 {
7500 lookfor = LOOKFOR_SCOPEDECL; /* class decl is this block */
7501 amount += ind_scopedecl;
7502 }
7503 else
7504 {
7505 if (ind_case_break && cin_isbreak(theline)) /* break; ... */
7506 lookfor_break = TRUE;
7507
7508 lookfor = LOOKFOR_INITIAL;
7509 amount += ind_level; /* ind_level from start of block */
7510 }
7511 scope_amount = amount;
7512 whilelevel = 0;
7513
7514 /*
7515 * Search backwards. If we find something we recognize, line up
7516 * with that.
7517 *
7518 * if we're looking at an open brace, indent
7519 * the usual amount relative to the conditional
7520 * that opens the block.
7521 */
7522 curwin->w_cursor = cur_curpos;
7523 for (;;)
7524 {
7525 curwin->w_cursor.lnum--;
7526 curwin->w_cursor.col = 0;
7527
7528 /*
7529 * If we went all the way back to the start of our scope, line
7530 * up with it.
7531 */
7532 if (curwin->w_cursor.lnum <= ourscope)
7533 {
7534 /* we reached end of scope:
7535 * if looking for a enum or structure initialization
7536 * go further back:
7537 * if it is an initializer (enum xxx or xxx =), then
7538 * don't add ind_continuation, otherwise it is a variable
7539 * declaration:
7540 * int x,
7541 * here; <-- add ind_continuation
7542 */
7543 if (lookfor == LOOKFOR_ENUM_OR_INIT)
7544 {
7545 if (curwin->w_cursor.lnum == 0
7546 || curwin->w_cursor.lnum
7547 < ourscope - ind_maxparen)
7548 {
7549 /* nothing found (abuse ind_maxparen as limit)
7550 * assume terminated line (i.e. a variable
7551 * initialization) */
7552 if (cont_amount > 0)
7553 amount = cont_amount;
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007554 else if (!ind_js)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007555 amount += ind_continuation;
7556 break;
7557 }
7558
7559 l = ml_get_curline();
7560
7561 /*
7562 * If we're in a comment now, skip to the start of the
7563 * comment.
7564 */
7565 trypos = find_start_comment(ind_maxcomment);
7566 if (trypos != NULL)
7567 {
7568 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007569 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007570 continue;
7571 }
7572
7573 /*
7574 * Skip preprocessor directives and blank lines.
7575 */
7576 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7577 continue;
7578
7579 if (cin_nocode(l))
7580 continue;
7581
7582 terminated = cin_isterminated(l, FALSE, TRUE);
7583
7584 /*
7585 * If we are at top level and the line looks like a
7586 * function declaration, we are done
7587 * (it's a variable declaration).
7588 */
7589 if (start_brace != BRACE_IN_COL0
Bram Moolenaarc367faa2011-12-14 20:21:35 +01007590 || !cin_isfuncdecl(&l, curwin->w_cursor.lnum,
7591 0, ind_maxparen, ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007592 {
7593 /* if the line is terminated with another ','
7594 * it is a continued variable initialization.
7595 * don't add extra indent.
7596 * TODO: does not work, if a function
7597 * declaration is split over multiple lines:
7598 * cin_isfuncdecl returns FALSE then.
7599 */
7600 if (terminated == ',')
7601 break;
7602
7603 /* if it es a enum declaration or an assignment,
7604 * we are done.
7605 */
7606 if (terminated != ';' && cin_isinit())
7607 break;
7608
7609 /* nothing useful found */
7610 if (terminated == 0 || terminated == '{')
7611 continue;
7612 }
7613
7614 if (terminated != ';')
7615 {
7616 /* Skip parens and braces. Position the cursor
7617 * over the rightmost paren, so that matching it
7618 * will take us back to the start of the line.
7619 */ /* XXX */
7620 trypos = NULL;
7621 if (find_last_paren(l, '(', ')'))
7622 trypos = find_match_paren(ind_maxparen,
7623 ind_maxcomment);
7624
7625 if (trypos == NULL && find_last_paren(l, '{', '}'))
7626 trypos = find_start_brace(ind_maxcomment);
7627
7628 if (trypos != NULL)
7629 {
7630 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007631 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007632 continue;
7633 }
7634 }
7635
7636 /* it's a variable declaration, add indentation
7637 * like in
7638 * int a,
7639 * b;
7640 */
7641 if (cont_amount > 0)
7642 amount = cont_amount;
7643 else
7644 amount += ind_continuation;
7645 }
7646 else if (lookfor == LOOKFOR_UNTERM)
7647 {
7648 if (cont_amount > 0)
7649 amount = cont_amount;
7650 else
7651 amount += ind_continuation;
7652 }
Bram Moolenaare79d1532011-10-04 18:03:47 +02007653 else
Bram Moolenaared38b0a2011-05-25 15:16:18 +02007654 {
Bram Moolenaare79d1532011-10-04 18:03:47 +02007655 if (lookfor != LOOKFOR_TERM
Bram Moolenaar071d4272004-06-13 20:20:40 +00007656 && lookfor != LOOKFOR_CPP_BASECLASS)
Bram Moolenaare79d1532011-10-04 18:03:47 +02007657 {
7658 amount = scope_amount;
7659 if (theline[0] == '{')
7660 {
7661 amount += ind_open_extra;
7662 added_to_amount = ind_open_extra;
7663 }
7664 }
7665
7666 if (lookfor_cpp_namespace)
7667 {
7668 /*
7669 * Looking for C++ namespace, need to look further
7670 * back.
7671 */
7672 if (curwin->w_cursor.lnum == ourscope)
7673 continue;
7674
7675 if (curwin->w_cursor.lnum == 0
7676 || curwin->w_cursor.lnum
7677 < ourscope - FIND_NAMESPACE_LIM)
7678 break;
7679
7680 l = ml_get_curline();
7681
7682 /* If we're in a comment now, skip to the start of
7683 * the comment. */
7684 trypos = find_start_comment(ind_maxcomment);
7685 if (trypos != NULL)
7686 {
7687 curwin->w_cursor.lnum = trypos->lnum + 1;
7688 curwin->w_cursor.col = 0;
7689 continue;
7690 }
7691
7692 /* Skip preprocessor directives and blank lines. */
7693 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7694 continue;
7695
7696 /* Finally the actual check for "namespace". */
7697 if (cin_is_cpp_namespace(l))
7698 {
7699 amount += ind_cpp_namespace - added_to_amount;
7700 break;
7701 }
7702
7703 if (cin_nocode(l))
7704 continue;
7705 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007706 }
7707 break;
7708 }
7709
7710 /*
7711 * If we're in a comment now, skip to the start of the comment.
7712 */ /* XXX */
7713 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
7714 {
7715 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007716 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007717 continue;
7718 }
7719
7720 l = ml_get_curline();
7721
7722 /*
7723 * If this is a switch() label, may line up relative to that.
Bram Moolenaar18144c82006-04-12 21:52:12 +00007724 * If this is a C++ scope declaration, do the same.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007725 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007726 iscase = cin_iscase(l, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007727 if (iscase || cin_isscopedecl(l))
7728 {
7729 /* we are only looking for cpp base class
7730 * declaration/initialization any longer */
7731 if (lookfor == LOOKFOR_CPP_BASECLASS)
7732 break;
7733
7734 /* When looking for a "do" we are not interested in
7735 * labels. */
7736 if (whilelevel > 0)
7737 continue;
7738
7739 /*
7740 * case xx:
7741 * c = 99 + <- this indent plus continuation
7742 *-> here;
7743 */
7744 if (lookfor == LOOKFOR_UNTERM
7745 || lookfor == LOOKFOR_ENUM_OR_INIT)
7746 {
7747 if (cont_amount > 0)
7748 amount = cont_amount;
7749 else
7750 amount += ind_continuation;
7751 break;
7752 }
7753
7754 /*
7755 * case xx: <- line up with this case
7756 * x = 333;
7757 * case yy:
7758 */
7759 if ( (iscase && lookfor == LOOKFOR_CASE)
7760 || (iscase && lookfor_break)
7761 || (!iscase && lookfor == LOOKFOR_SCOPEDECL))
7762 {
7763 /*
7764 * Check that this case label is not for another
7765 * switch()
7766 */ /* XXX */
7767 if ((trypos = find_start_brace(ind_maxcomment)) ==
7768 NULL || trypos->lnum == ourscope)
7769 {
7770 amount = get_indent(); /* XXX */
7771 break;
7772 }
7773 continue;
7774 }
7775
7776 n = get_indent_nolabel(curwin->w_cursor.lnum); /* XXX */
7777
7778 /*
7779 * case xx: if (cond) <- line up with this if
7780 * y = y + 1;
7781 * -> s = 99;
7782 *
7783 * case xx:
7784 * if (cond) <- line up with this line
7785 * y = y + 1;
7786 * -> s = 99;
7787 */
7788 if (lookfor == LOOKFOR_TERM)
7789 {
7790 if (n)
7791 amount = n;
7792
7793 if (!lookfor_break)
7794 break;
7795 }
7796
7797 /*
7798 * case xx: x = x + 1; <- line up with this x
7799 * -> y = y + 1;
7800 *
7801 * case xx: if (cond) <- line up with this if
7802 * -> y = y + 1;
7803 */
7804 if (n)
7805 {
7806 amount = n;
7807 l = after_label(ml_get_curline());
7808 if (l != NULL && cin_is_cinword(l))
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007809 {
7810 if (theline[0] == '{')
7811 amount += ind_open_extra;
7812 else
7813 amount += ind_level + ind_no_brace;
7814 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007815 break;
7816 }
7817
7818 /*
7819 * Try to get the indent of a statement before the switch
7820 * label. If nothing is found, line up relative to the
7821 * switch label.
7822 * break; <- may line up with this line
7823 * case xx:
7824 * -> y = 1;
7825 */
7826 scope_amount = get_indent() + (iscase /* XXX */
7827 ? ind_case_code : ind_scopedecl_code);
7828 lookfor = ind_case_break ? LOOKFOR_NOBREAK : LOOKFOR_ANY;
7829 continue;
7830 }
7831
7832 /*
7833 * Looking for a switch() label or C++ scope declaration,
7834 * ignore other lines, skip {}-blocks.
7835 */
7836 if (lookfor == LOOKFOR_CASE || lookfor == LOOKFOR_SCOPEDECL)
7837 {
7838 if (find_last_paren(l, '{', '}') && (trypos =
7839 find_start_brace(ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007840 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007841 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007842 curwin->w_cursor.col = 0;
7843 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007844 continue;
7845 }
7846
7847 /*
7848 * Ignore jump labels with nothing after them.
7849 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007850 if (!ind_js && cin_islabel(ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007851 {
7852 l = after_label(ml_get_curline());
7853 if (l == NULL || cin_nocode(l))
7854 continue;
7855 }
7856
7857 /*
7858 * Ignore #defines, #if, etc.
7859 * Ignore comment and empty lines.
7860 * (need to get the line again, cin_islabel() may have
7861 * unlocked it)
7862 */
7863 l = ml_get_curline();
7864 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum)
7865 || cin_nocode(l))
7866 continue;
7867
7868 /*
7869 * Are we at the start of a cpp base class declaration or
7870 * constructor initialization?
7871 */ /* XXX */
Bram Moolenaar18144c82006-04-12 21:52:12 +00007872 n = FALSE;
7873 if (lookfor != LOOKFOR_TERM && ind_cpp_baseclass > 0)
7874 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00007875 n = cin_is_cpp_baseclass(&col);
Bram Moolenaar18144c82006-04-12 21:52:12 +00007876 l = ml_get_curline();
7877 }
7878 if (n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007879 {
7880 if (lookfor == LOOKFOR_UNTERM)
7881 {
7882 if (cont_amount > 0)
7883 amount = cont_amount;
7884 else
7885 amount += ind_continuation;
7886 }
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007887 else if (theline[0] == '{')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007888 {
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007889 /* Need to find start of the declaration. */
7890 lookfor = LOOKFOR_UNTERM;
7891 ind_continuation = 0;
7892 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007893 }
7894 else
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007895 /* XXX */
7896 amount = get_baseclass_amount(col, ind_maxparen,
7897 ind_maxcomment, ind_cpp_baseclass);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007898 break;
7899 }
7900 else if (lookfor == LOOKFOR_CPP_BASECLASS)
7901 {
7902 /* only look, whether there is a cpp base class
Bram Moolenaar18144c82006-04-12 21:52:12 +00007903 * declaration or initialization before the opening brace.
7904 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007905 if (cin_isterminated(l, TRUE, FALSE))
7906 break;
7907 else
7908 continue;
7909 }
7910
7911 /*
7912 * What happens next depends on the line being terminated.
7913 * If terminated with a ',' only consider it terminating if
Bram Moolenaar25394022007-05-10 19:06:20 +00007914 * there is another unterminated statement behind, eg:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007915 * 123,
7916 * sizeof
7917 * here
7918 * Otherwise check whether it is a enumeration or structure
7919 * initialisation (not indented) or a variable declaration
7920 * (indented).
7921 */
7922 terminated = cin_isterminated(l, FALSE, TRUE);
7923
7924 if (terminated == 0 || (lookfor != LOOKFOR_UNTERM
7925 && terminated == ','))
7926 {
7927 /*
7928 * if we're in the middle of a paren thing,
7929 * go back to the line that starts it so
7930 * we can get the right prevailing indent
7931 * if ( foo &&
7932 * bar )
7933 */
7934 /*
7935 * position the cursor over the rightmost paren, so that
7936 * matching it will take us back to the start of the line.
7937 */
7938 (void)find_last_paren(l, '(', ')');
7939 trypos = find_match_paren(
7940 corr_ind_maxparen(ind_maxparen, &cur_curpos),
7941 ind_maxcomment);
7942
7943 /*
7944 * If we are looking for ',', we also look for matching
7945 * braces.
7946 */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007947 if (trypos == NULL && terminated == ','
7948 && find_last_paren(l, '{', '}'))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007949 trypos = find_start_brace(ind_maxcomment);
7950
7951 if (trypos != NULL)
7952 {
7953 /*
7954 * Check if we are on a case label now. This is
7955 * handled above.
7956 * case xx: if ( asdf &&
7957 * asdf)
7958 */
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007959 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007960 l = ml_get_curline();
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007961 if (cin_iscase(l, FALSE) || cin_isscopedecl(l))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007962 {
7963 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007964 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007965 continue;
7966 }
7967 }
7968
7969 /*
7970 * Skip over continuation lines to find the one to get the
7971 * indent from
7972 * char *usethis = "bla\
7973 * bla",
7974 * here;
7975 */
7976 if (terminated == ',')
7977 {
7978 while (curwin->w_cursor.lnum > 1)
7979 {
7980 l = ml_get(curwin->w_cursor.lnum - 1);
7981 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
7982 break;
7983 --curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00007984 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007985 }
7986 }
7987
7988 /*
7989 * Get indent and pointer to text for current line,
7990 * ignoring any jump label. XXX
7991 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007992 if (!ind_js)
7993 cur_amount = skip_label(curwin->w_cursor.lnum,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007994 &l, ind_maxcomment);
Bram Moolenaar3acfc302010-07-11 17:23:02 +02007995 else
7996 cur_amount = get_indent();
Bram Moolenaar071d4272004-06-13 20:20:40 +00007997 /*
7998 * If this is just above the line we are indenting, and it
7999 * starts with a '{', line it up with this line.
8000 * while (not)
8001 * -> {
8002 * }
8003 */
8004 if (terminated != ',' && lookfor != LOOKFOR_TERM
8005 && theline[0] == '{')
8006 {
8007 amount = cur_amount;
8008 /*
8009 * Only add ind_open_extra when the current line
8010 * doesn't start with a '{', which must have a match
8011 * in the same line (scope is the same). Probably:
8012 * { 1, 2 },
8013 * -> { 3, 4 }
8014 */
8015 if (*skipwhite(l) != '{')
8016 amount += ind_open_extra;
8017
8018 if (ind_cpp_baseclass)
8019 {
8020 /* have to look back, whether it is a cpp base
8021 * class declaration or initialization */
8022 lookfor = LOOKFOR_CPP_BASECLASS;
8023 continue;
8024 }
8025 break;
8026 }
8027
8028 /*
8029 * Check if we are after an "if", "while", etc.
8030 * Also allow " } else".
8031 */
8032 if (cin_is_cinword(l) || cin_iselse(skipwhite(l)))
8033 {
8034 /*
8035 * Found an unterminated line after an if (), line up
8036 * with the last one.
8037 * if (cond)
8038 * 100 +
8039 * -> here;
8040 */
8041 if (lookfor == LOOKFOR_UNTERM
8042 || lookfor == LOOKFOR_ENUM_OR_INIT)
8043 {
8044 if (cont_amount > 0)
8045 amount = cont_amount;
8046 else
8047 amount += ind_continuation;
8048 break;
8049 }
8050
8051 /*
8052 * If this is just above the line we are indenting, we
8053 * are finished.
8054 * while (not)
8055 * -> here;
8056 * Otherwise this indent can be used when the line
8057 * before this is terminated.
8058 * yyy;
8059 * if (stat)
8060 * while (not)
8061 * xxx;
8062 * -> here;
8063 */
8064 amount = cur_amount;
8065 if (theline[0] == '{')
8066 amount += ind_open_extra;
8067 if (lookfor != LOOKFOR_TERM)
8068 {
8069 amount += ind_level + ind_no_brace;
8070 break;
8071 }
8072
8073 /*
8074 * Special trick: when expecting the while () after a
8075 * do, line up with the while()
8076 * do
8077 * x = 1;
8078 * -> here
8079 */
8080 l = skipwhite(ml_get_curline());
8081 if (cin_isdo(l))
8082 {
8083 if (whilelevel == 0)
8084 break;
8085 --whilelevel;
8086 }
8087
8088 /*
8089 * When searching for a terminated line, don't use the
Bram Moolenaar334adf02011-05-25 13:34:04 +02008090 * one between the "if" and the matching "else".
Bram Moolenaar071d4272004-06-13 20:20:40 +00008091 * Need to use the scope of this "else". XXX
8092 * If whilelevel != 0 continue looking for a "do {".
8093 */
Bram Moolenaar334adf02011-05-25 13:34:04 +02008094 if (cin_iselse(l) && whilelevel == 0)
8095 {
8096 /* If we're looking at "} else", let's make sure we
8097 * find the opening brace of the enclosing scope,
8098 * not the one from "if () {". */
8099 if (*l == '}')
8100 curwin->w_cursor.col =
Bram Moolenaar9b83c2f2011-05-25 17:29:44 +02008101 (colnr_T)(l - ml_get_curline()) + 1;
Bram Moolenaar334adf02011-05-25 13:34:04 +02008102
8103 if ((trypos = find_start_brace(ind_maxcomment))
8104 == NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00008105 || find_match(LOOKFOR_IF, trypos->lnum,
Bram Moolenaar334adf02011-05-25 13:34:04 +02008106 ind_maxparen, ind_maxcomment) == FAIL)
8107 break;
8108 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008109 }
8110
8111 /*
8112 * If we're below an unterminated line that is not an
8113 * "if" or something, we may line up with this line or
Bram Moolenaar25394022007-05-10 19:06:20 +00008114 * add something for a continuation line, depending on
Bram Moolenaar071d4272004-06-13 20:20:40 +00008115 * the line before this one.
8116 */
8117 else
8118 {
8119 /*
8120 * Found two unterminated lines on a row, line up with
8121 * the last one.
8122 * c = 99 +
8123 * 100 +
8124 * -> here;
8125 */
8126 if (lookfor == LOOKFOR_UNTERM)
8127 {
8128 /* When line ends in a comma add extra indent */
8129 if (terminated == ',')
8130 amount += ind_continuation;
8131 break;
8132 }
8133
8134 if (lookfor == LOOKFOR_ENUM_OR_INIT)
8135 {
8136 /* Found two lines ending in ',', lineup with the
8137 * lowest one, but check for cpp base class
8138 * declaration/initialization, if it is an
8139 * opening brace or we are looking just for
8140 * enumerations/initializations. */
8141 if (terminated == ',')
8142 {
8143 if (ind_cpp_baseclass == 0)
8144 break;
8145
8146 lookfor = LOOKFOR_CPP_BASECLASS;
8147 continue;
8148 }
8149
8150 /* Ignore unterminated lines in between, but
8151 * reduce indent. */
8152 if (amount > cur_amount)
8153 amount = cur_amount;
8154 }
8155 else
8156 {
8157 /*
8158 * Found first unterminated line on a row, may
8159 * line up with this line, remember its indent
8160 * 100 +
8161 * -> here;
8162 */
8163 amount = cur_amount;
8164
8165 /*
8166 * If previous line ends in ',', check whether we
8167 * are in an initialization or enum
8168 * struct xxx =
8169 * {
8170 * sizeof a,
8171 * 124 };
8172 * or a normal possible continuation line.
8173 * but only, of no other statement has been found
8174 * yet.
8175 */
8176 if (lookfor == LOOKFOR_INITIAL && terminated == ',')
8177 {
8178 lookfor = LOOKFOR_ENUM_OR_INIT;
8179 cont_amount = cin_first_id_amount();
8180 }
8181 else
8182 {
8183 if (lookfor == LOOKFOR_INITIAL
8184 && *l != NUL
8185 && l[STRLEN(l) - 1] == '\\')
8186 /* XXX */
8187 cont_amount = cin_get_equal_amount(
8188 curwin->w_cursor.lnum);
8189 if (lookfor != LOOKFOR_TERM)
8190 lookfor = LOOKFOR_UNTERM;
8191 }
8192 }
8193 }
8194 }
8195
8196 /*
8197 * Check if we are after a while (cond);
8198 * If so: Ignore until the matching "do".
8199 */
8200 /* XXX */
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00008201 else if (cin_iswhileofdo_end(terminated, ind_maxparen,
8202 ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008203 {
8204 /*
8205 * Found an unterminated line after a while ();, line up
8206 * with the last one.
8207 * while (cond);
8208 * 100 + <- line up with this one
8209 * -> here;
8210 */
8211 if (lookfor == LOOKFOR_UNTERM
8212 || lookfor == LOOKFOR_ENUM_OR_INIT)
8213 {
8214 if (cont_amount > 0)
8215 amount = cont_amount;
8216 else
8217 amount += ind_continuation;
8218 break;
8219 }
8220
8221 if (whilelevel == 0)
8222 {
8223 lookfor = LOOKFOR_TERM;
8224 amount = get_indent(); /* XXX */
8225 if (theline[0] == '{')
8226 amount += ind_open_extra;
8227 }
8228 ++whilelevel;
8229 }
8230
8231 /*
8232 * We are after a "normal" statement.
8233 * If we had another statement we can stop now and use the
8234 * indent of that other statement.
8235 * Otherwise the indent of the current statement may be used,
8236 * search backwards for the next "normal" statement.
8237 */
8238 else
8239 {
8240 /*
8241 * Skip single break line, if before a switch label. It
8242 * may be lined up with the case label.
8243 */
8244 if (lookfor == LOOKFOR_NOBREAK
8245 && cin_isbreak(skipwhite(ml_get_curline())))
8246 {
8247 lookfor = LOOKFOR_ANY;
8248 continue;
8249 }
8250
8251 /*
8252 * Handle "do {" line.
8253 */
8254 if (whilelevel > 0)
8255 {
8256 l = cin_skipcomment(ml_get_curline());
8257 if (cin_isdo(l))
8258 {
8259 amount = get_indent(); /* XXX */
8260 --whilelevel;
8261 continue;
8262 }
8263 }
8264
8265 /*
8266 * Found a terminated line above an unterminated line. Add
8267 * the amount for a continuation line.
8268 * x = 1;
8269 * y = foo +
8270 * -> here;
8271 * or
8272 * int x = 1;
8273 * int foo,
8274 * -> here;
8275 */
8276 if (lookfor == LOOKFOR_UNTERM
8277 || lookfor == LOOKFOR_ENUM_OR_INIT)
8278 {
8279 if (cont_amount > 0)
8280 amount = cont_amount;
8281 else
8282 amount += ind_continuation;
8283 break;
8284 }
8285
8286 /*
8287 * Found a terminated line above a terminated line or "if"
8288 * etc. line. Use the amount of the line below us.
8289 * x = 1; x = 1;
8290 * if (asdf) y = 2;
8291 * while (asdf) ->here;
8292 * here;
8293 * ->foo;
8294 */
8295 if (lookfor == LOOKFOR_TERM)
8296 {
8297 if (!lookfor_break && whilelevel == 0)
8298 break;
8299 }
8300
8301 /*
8302 * First line above the one we're indenting is terminated.
8303 * To know what needs to be done look further backward for
8304 * a terminated line.
8305 */
8306 else
8307 {
8308 /*
8309 * position the cursor over the rightmost paren, so
8310 * that matching it will take us back to the start of
8311 * the line. Helps for:
8312 * func(asdr,
8313 * asdfasdf);
8314 * here;
8315 */
8316term_again:
8317 l = ml_get_curline();
8318 if (find_last_paren(l, '(', ')')
8319 && (trypos = find_match_paren(ind_maxparen,
8320 ind_maxcomment)) != NULL)
8321 {
8322 /*
8323 * Check if we are on a case label now. This is
8324 * handled above.
8325 * case xx: if ( asdf &&
8326 * asdf)
8327 */
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008328 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008329 l = ml_get_curline();
Bram Moolenaar3acfc302010-07-11 17:23:02 +02008330 if (cin_iscase(l, FALSE) || cin_isscopedecl(l))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008331 {
8332 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008333 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008334 continue;
8335 }
8336 }
8337
8338 /* When aligning with the case statement, don't align
8339 * with a statement after it.
8340 * case 1: { <-- don't use this { position
8341 * stat;
8342 * }
8343 * case 2:
8344 * stat;
8345 * }
8346 */
Bram Moolenaar3acfc302010-07-11 17:23:02 +02008347 iscase = (ind_keep_case_label && cin_iscase(l, FALSE));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008348
8349 /*
8350 * Get indent and pointer to text for current line,
8351 * ignoring any jump label.
8352 */
8353 amount = skip_label(curwin->w_cursor.lnum,
8354 &l, ind_maxcomment);
8355
8356 if (theline[0] == '{')
8357 amount += ind_open_extra;
8358 /* See remark above: "Only add ind_open_extra.." */
Bram Moolenaar18144c82006-04-12 21:52:12 +00008359 l = skipwhite(l);
8360 if (*l == '{')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008361 amount -= ind_open_extra;
8362 lookfor = iscase ? LOOKFOR_ANY : LOOKFOR_TERM;
8363
8364 /*
Bram Moolenaar18144c82006-04-12 21:52:12 +00008365 * When a terminated line starts with "else" skip to
8366 * the matching "if":
8367 * else 3;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008368 * indent this;
Bram Moolenaar18144c82006-04-12 21:52:12 +00008369 * Need to use the scope of this "else". XXX
8370 * If whilelevel != 0 continue looking for a "do {".
8371 */
8372 if (lookfor == LOOKFOR_TERM
8373 && *l != '}'
8374 && cin_iselse(l)
8375 && whilelevel == 0)
8376 {
8377 if ((trypos = find_start_brace(ind_maxcomment))
8378 == NULL
8379 || find_match(LOOKFOR_IF, trypos->lnum,
8380 ind_maxparen, ind_maxcomment) == FAIL)
8381 break;
8382 continue;
8383 }
8384
8385 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008386 * If we're at the end of a block, skip to the start of
8387 * that block.
8388 */
Bram Moolenaar6d8f9c62011-11-30 13:03:28 +01008389 l = ml_get_curline();
Bram Moolenaar50f42ca2011-07-15 14:12:30 +02008390 if (find_last_paren(l, '{', '}')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008391 && (trypos = find_start_brace(ind_maxcomment))
8392 != NULL) /* XXX */
8393 {
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008394 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008395 /* if not "else {" check for terminated again */
8396 /* but skip block for "} else {" */
8397 l = cin_skipcomment(ml_get_curline());
8398 if (*l == '}' || !cin_iselse(l))
8399 goto term_again;
8400 ++curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008401 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008402 }
8403 }
8404 }
8405 }
8406 }
8407 }
8408
8409 /* add extra indent for a comment */
8410 if (cin_iscomment(theline))
8411 amount += ind_comment;
Bram Moolenaar02c707a2010-07-17 17:12:06 +02008412
8413 /* subtract extra left-shift for jump labels */
8414 if (ind_jump_label > 0 && original_line_islabel)
8415 amount -= ind_jump_label;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008416 }
8417
8418 /*
8419 * ok -- we're not inside any sort of structure at all!
8420 *
8421 * this means we're at the top level, and everything should
8422 * basically just match where the previous line is, except
8423 * for the lines immediately following a function declaration,
8424 * which are K&R-style parameters and need to be indented.
8425 */
8426 else
8427 {
8428 /*
8429 * if our line starts with an open brace, forget about any
8430 * prevailing indent and make sure it looks like the start
8431 * of a function
8432 */
8433
8434 if (theline[0] == '{')
8435 {
8436 amount = ind_first_open;
8437 }
8438
8439 /*
8440 * If the NEXT line is a function declaration, the current
8441 * line needs to be indented as a function type spec.
Bram Moolenaar1a89bbe2010-03-02 12:38:22 +01008442 * Don't do this if the current line looks like a comment or if the
8443 * current line is terminated, ie. ends in ';', or if the current line
8444 * contains { or }: "void f() {\n if (1)"
Bram Moolenaar071d4272004-06-13 20:20:40 +00008445 */
8446 else if (cur_curpos.lnum < curbuf->b_ml.ml_line_count
8447 && !cin_nocode(theline)
Bram Moolenaar1a89bbe2010-03-02 12:38:22 +01008448 && vim_strchr(theline, '{') == NULL
8449 && vim_strchr(theline, '}') == NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00008450 && !cin_ends_in(theline, (char_u *)":", NULL)
8451 && !cin_ends_in(theline, (char_u *)",", NULL)
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008452 && cin_isfuncdecl(NULL, cur_curpos.lnum + 1,
8453 cur_curpos.lnum + 1,
8454 ind_maxparen, ind_maxcomment)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008455 && !cin_isterminated(theline, FALSE, TRUE))
8456 {
8457 amount = ind_func_type;
8458 }
8459 else
8460 {
8461 amount = 0;
8462 curwin->w_cursor = cur_curpos;
8463
8464 /* search backwards until we find something we recognize */
8465
8466 while (curwin->w_cursor.lnum > 1)
8467 {
8468 curwin->w_cursor.lnum--;
8469 curwin->w_cursor.col = 0;
8470
8471 l = ml_get_curline();
8472
8473 /*
8474 * If we're in a comment now, skip to the start of the comment.
8475 */ /* XXX */
8476 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
8477 {
8478 curwin->w_cursor.lnum = trypos->lnum + 1;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008479 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008480 continue;
8481 }
8482
8483 /*
Bram Moolenaar18144c82006-04-12 21:52:12 +00008484 * Are we at the start of a cpp base class declaration or
8485 * constructor initialization?
Bram Moolenaar071d4272004-06-13 20:20:40 +00008486 */ /* XXX */
Bram Moolenaar18144c82006-04-12 21:52:12 +00008487 n = FALSE;
8488 if (ind_cpp_baseclass != 0 && theline[0] != '{')
8489 {
Bram Moolenaare7c56862007-08-04 10:14:52 +00008490 n = cin_is_cpp_baseclass(&col);
Bram Moolenaar18144c82006-04-12 21:52:12 +00008491 l = ml_get_curline();
8492 }
8493 if (n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008494 {
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00008495 /* XXX */
8496 amount = get_baseclass_amount(col, ind_maxparen,
8497 ind_maxcomment, ind_cpp_baseclass);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008498 break;
8499 }
8500
8501 /*
8502 * Skip preprocessor directives and blank lines.
8503 */
8504 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
8505 continue;
8506
8507 if (cin_nocode(l))
8508 continue;
8509
8510 /*
8511 * If the previous line ends in ',', use one level of
8512 * indentation:
8513 * int foo,
8514 * bar;
8515 * do this before checking for '}' in case of eg.
8516 * enum foobar
8517 * {
8518 * ...
8519 * } foo,
8520 * bar;
8521 */
8522 n = 0;
8523 if (cin_ends_in(l, (char_u *)",", NULL)
8524 || (*l != NUL && (n = l[STRLEN(l) - 1]) == '\\'))
8525 {
8526 /* take us back to opening paren */
8527 if (find_last_paren(l, '(', ')')
8528 && (trypos = find_match_paren(ind_maxparen,
8529 ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008530 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008531
8532 /* For a line ending in ',' that is a continuation line go
8533 * back to the first line with a backslash:
8534 * char *foo = "bla\
8535 * bla",
8536 * here;
8537 */
8538 while (n == 0 && curwin->w_cursor.lnum > 1)
8539 {
8540 l = ml_get(curwin->w_cursor.lnum - 1);
8541 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
8542 break;
8543 --curwin->w_cursor.lnum;
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008544 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008545 }
8546
8547 amount = get_indent(); /* XXX */
8548
8549 if (amount == 0)
8550 amount = cin_first_id_amount();
8551 if (amount == 0)
8552 amount = ind_continuation;
8553 break;
8554 }
8555
8556 /*
8557 * If the line looks like a function declaration, and we're
8558 * not in a comment, put it the left margin.
8559 */
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008560 if (cin_isfuncdecl(NULL, cur_curpos.lnum, 0,
8561 ind_maxparen, ind_maxcomment)) /* XXX */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008562 break;
8563 l = ml_get_curline();
8564
8565 /*
8566 * Finding the closing '}' of a previous function. Put
8567 * current line at the left margin. For when 'cino' has "fs".
8568 */
8569 if (*skipwhite(l) == '}')
8570 break;
8571
8572 /* (matching {)
8573 * If the previous line ends on '};' (maybe followed by
8574 * comments) align at column 0. For example:
8575 * char *string_array[] = { "foo",
8576 * / * x * / "b};ar" }; / * foobar * /
8577 */
8578 if (cin_ends_in(l, (char_u *)"};", NULL))
8579 break;
8580
8581 /*
Bram Moolenaar3388bb42011-11-30 17:20:23 +01008582 * Find a line only has a semicolon that belongs to a previous
8583 * line ending in '}', e.g. before an #endif. Don't increase
8584 * indent then.
8585 */
8586 if (*(look = skipwhite(l)) == ';' && cin_nocode(look + 1))
8587 {
8588 pos_T curpos_save = curwin->w_cursor;
8589
8590 while (curwin->w_cursor.lnum > 1)
8591 {
8592 look = ml_get(--curwin->w_cursor.lnum);
8593 if (!(cin_nocode(look) || cin_ispreproc_cont(
8594 &look, &curwin->w_cursor.lnum)))
8595 break;
8596 }
8597 if (curwin->w_cursor.lnum > 0
8598 && cin_ends_in(look, (char_u *)"}", NULL))
8599 break;
8600
8601 curwin->w_cursor = curpos_save;
8602 }
8603
8604 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008605 * If the PREVIOUS line is a function declaration, the current
8606 * line (and the ones that follow) needs to be indented as
8607 * parameters.
8608 */
Bram Moolenaarc367faa2011-12-14 20:21:35 +01008609 if (cin_isfuncdecl(&l, curwin->w_cursor.lnum, 0,
8610 ind_maxparen, ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008611 {
8612 amount = ind_param;
8613 break;
8614 }
8615
8616 /*
8617 * If the previous line ends in ';' and the line before the
8618 * previous line ends in ',' or '\', ident to column zero:
8619 * int foo,
8620 * bar;
8621 * indent_to_0 here;
8622 */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00008623 if (cin_ends_in(l, (char_u *)";", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008624 {
8625 l = ml_get(curwin->w_cursor.lnum - 1);
8626 if (cin_ends_in(l, (char_u *)",", NULL)
8627 || (*l != NUL && l[STRLEN(l) - 1] == '\\'))
8628 break;
8629 l = ml_get_curline();
8630 }
8631
8632 /*
8633 * Doesn't look like anything interesting -- so just
8634 * use the indent of this line.
8635 *
8636 * Position the cursor over the rightmost paren, so that
8637 * matching it will take us back to the start of the line.
8638 */
8639 find_last_paren(l, '(', ')');
8640
8641 if ((trypos = find_match_paren(ind_maxparen,
8642 ind_maxcomment)) != NULL)
Bram Moolenaarddfc9782008-02-25 20:55:22 +00008643 curwin->w_cursor = *trypos;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008644 amount = get_indent(); /* XXX */
8645 break;
8646 }
8647
8648 /* add extra indent for a comment */
8649 if (cin_iscomment(theline))
8650 amount += ind_comment;
8651
8652 /* add extra indent if the previous line ended in a backslash:
8653 * "asdfasdf\
8654 * here";
8655 * char *foo = "asdf\
8656 * here";
8657 */
8658 if (cur_curpos.lnum > 1)
8659 {
8660 l = ml_get(cur_curpos.lnum - 1);
8661 if (*l != NUL && l[STRLEN(l) - 1] == '\\')
8662 {
8663 cur_amount = cin_get_equal_amount(cur_curpos.lnum - 1);
8664 if (cur_amount > 0)
8665 amount = cur_amount;
8666 else if (cur_amount == 0)
8667 amount += ind_continuation;
8668 }
8669 }
8670 }
8671 }
8672
8673theend:
8674 /* put the cursor back where it belongs */
8675 curwin->w_cursor = cur_curpos;
8676
8677 vim_free(linecopy);
8678
8679 if (amount < 0)
8680 return 0;
8681 return amount;
8682}
8683
8684 static int
8685find_match(lookfor, ourscope, ind_maxparen, ind_maxcomment)
8686 int lookfor;
8687 linenr_T ourscope;
8688 int ind_maxparen;
8689 int ind_maxcomment;
8690{
8691 char_u *look;
8692 pos_T *theirscope;
8693 char_u *mightbeif;
8694 int elselevel;
8695 int whilelevel;
8696
8697 if (lookfor == LOOKFOR_IF)
8698 {
8699 elselevel = 1;
8700 whilelevel = 0;
8701 }
8702 else
8703 {
8704 elselevel = 0;
8705 whilelevel = 1;
8706 }
8707
8708 curwin->w_cursor.col = 0;
8709
8710 while (curwin->w_cursor.lnum > ourscope + 1)
8711 {
8712 curwin->w_cursor.lnum--;
8713 curwin->w_cursor.col = 0;
8714
8715 look = cin_skipcomment(ml_get_curline());
8716 if (cin_iselse(look)
8717 || cin_isif(look)
8718 || cin_isdo(look) /* XXX */
8719 || cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
8720 {
8721 /*
8722 * if we've gone outside the braces entirely,
8723 * we must be out of scope...
8724 */
8725 theirscope = find_start_brace(ind_maxcomment); /* XXX */
8726 if (theirscope == NULL)
8727 break;
8728
8729 /*
8730 * and if the brace enclosing this is further
8731 * back than the one enclosing the else, we're
8732 * out of luck too.
8733 */
8734 if (theirscope->lnum < ourscope)
8735 break;
8736
8737 /*
8738 * and if they're enclosed in a *deeper* brace,
8739 * then we can ignore it because it's in a
8740 * different scope...
8741 */
8742 if (theirscope->lnum > ourscope)
8743 continue;
8744
8745 /*
8746 * if it was an "else" (that's not an "else if")
8747 * then we need to go back to another if, so
8748 * increment elselevel
8749 */
8750 look = cin_skipcomment(ml_get_curline());
8751 if (cin_iselse(look))
8752 {
8753 mightbeif = cin_skipcomment(look + 4);
8754 if (!cin_isif(mightbeif))
8755 ++elselevel;
8756 continue;
8757 }
8758
8759 /*
8760 * if it was a "while" then we need to go back to
8761 * another "do", so increment whilelevel. XXX
8762 */
8763 if (cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
8764 {
8765 ++whilelevel;
8766 continue;
8767 }
8768
8769 /* If it's an "if" decrement elselevel */
8770 look = cin_skipcomment(ml_get_curline());
8771 if (cin_isif(look))
8772 {
8773 elselevel--;
8774 /*
8775 * When looking for an "if" ignore "while"s that
8776 * get in the way.
8777 */
8778 if (elselevel == 0 && lookfor == LOOKFOR_IF)
8779 whilelevel = 0;
8780 }
8781
8782 /* If it's a "do" decrement whilelevel */
8783 if (cin_isdo(look))
8784 whilelevel--;
8785
8786 /*
8787 * if we've used up all the elses, then
8788 * this must be the if that we want!
8789 * match the indent level of that if.
8790 */
8791 if (elselevel <= 0 && whilelevel <= 0)
8792 {
8793 return OK;
8794 }
8795 }
8796 }
8797 return FAIL;
8798}
8799
8800# if defined(FEAT_EVAL) || defined(PROTO)
8801/*
8802 * Get indent level from 'indentexpr'.
8803 */
8804 int
8805get_expr_indent()
8806{
8807 int indent;
8808 pos_T pos;
8809 int save_State;
Bram Moolenaard1f56e62006-02-22 21:25:37 +00008810 int use_sandbox = was_set_insecurely((char_u *)"indentexpr",
8811 OPT_LOCAL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008812
8813 pos = curwin->w_cursor;
8814 set_vim_var_nr(VV_LNUM, curwin->w_cursor.lnum);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00008815 if (use_sandbox)
8816 ++sandbox;
8817 ++textlock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008818 indent = eval_to_number(curbuf->b_p_inde);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00008819 if (use_sandbox)
8820 --sandbox;
8821 --textlock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008822
8823 /* Restore the cursor position so that 'indentexpr' doesn't need to.
8824 * Pretend to be in Insert mode, allow cursor past end of line for "o"
8825 * command. */
8826 save_State = State;
8827 State = INSERT;
8828 curwin->w_cursor = pos;
8829 check_cursor();
8830 State = save_State;
8831
8832 /* If there is an error, just keep the current indent. */
8833 if (indent < 0)
8834 indent = get_indent();
8835
8836 return indent;
8837}
8838# endif
8839
8840#endif /* FEAT_CINDENT */
8841
8842#if defined(FEAT_LISP) || defined(PROTO)
8843
8844static int lisp_match __ARGS((char_u *p));
8845
8846 static int
8847lisp_match(p)
8848 char_u *p;
8849{
8850 char_u buf[LSIZE];
8851 int len;
8852 char_u *word = p_lispwords;
8853
8854 while (*word != NUL)
8855 {
8856 (void)copy_option_part(&word, buf, LSIZE, ",");
8857 len = (int)STRLEN(buf);
8858 if (STRNCMP(buf, p, len) == 0 && p[len] == ' ')
8859 return TRUE;
8860 }
8861 return FALSE;
8862}
8863
8864/*
8865 * When 'p' is present in 'cpoptions, a Vi compatible method is used.
8866 * The incompatible newer method is quite a bit better at indenting
8867 * code in lisp-like languages than the traditional one; it's still
8868 * mostly heuristics however -- Dirk van Deun, dirk@rave.org
8869 *
8870 * TODO:
8871 * Findmatch() should be adapted for lisp, also to make showmatch
8872 * work correctly: now (v5.3) it seems all C/C++ oriented:
8873 * - it does not recognize the #\( and #\) notations as character literals
8874 * - it doesn't know about comments starting with a semicolon
8875 * - it incorrectly interprets '(' as a character literal
8876 * All this messes up get_lisp_indent in some rare cases.
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008877 * Update from Sergey Khorev:
8878 * I tried to fix the first two issues.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008879 */
8880 int
8881get_lisp_indent()
8882{
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008883 pos_T *pos, realpos, paren;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008884 int amount;
8885 char_u *that;
8886 colnr_T col;
8887 colnr_T firsttry;
8888 int parencount, quotecount;
8889 int vi_lisp;
8890
8891 /* Set vi_lisp to use the vi-compatible method */
8892 vi_lisp = (vim_strchr(p_cpo, CPO_LISP) != NULL);
8893
8894 realpos = curwin->w_cursor;
8895 curwin->w_cursor.col = 0;
8896
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008897 if ((pos = findmatch(NULL, '(')) == NULL)
8898 pos = findmatch(NULL, '[');
8899 else
8900 {
8901 paren = *pos;
8902 pos = findmatch(NULL, '[');
8903 if (pos == NULL || ltp(pos, &paren))
8904 pos = &paren;
8905 }
8906 if (pos != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008907 {
8908 /* Extra trick: Take the indent of the first previous non-white
8909 * line that is at the same () level. */
8910 amount = -1;
8911 parencount = 0;
8912
8913 while (--curwin->w_cursor.lnum >= pos->lnum)
8914 {
8915 if (linewhite(curwin->w_cursor.lnum))
8916 continue;
8917 for (that = ml_get_curline(); *that != NUL; ++that)
8918 {
8919 if (*that == ';')
8920 {
8921 while (*(that + 1) != NUL)
8922 ++that;
8923 continue;
8924 }
8925 if (*that == '\\')
8926 {
8927 if (*(that + 1) != NUL)
8928 ++that;
8929 continue;
8930 }
8931 if (*that == '"' && *(that + 1) != NUL)
8932 {
Bram Moolenaar15ff6c12006-09-15 18:18:09 +00008933 while (*++that && *that != '"')
8934 {
8935 /* skipping escaped characters in the string */
8936 if (*that == '\\')
8937 {
8938 if (*++that == NUL)
8939 break;
8940 if (that[1] == NUL)
8941 {
8942 ++that;
8943 break;
8944 }
8945 }
8946 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008947 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008948 if (*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008949 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008950 else if (*that == ')' || *that == ']')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008951 --parencount;
8952 }
8953 if (parencount == 0)
8954 {
8955 amount = get_indent();
8956 break;
8957 }
8958 }
8959
8960 if (amount == -1)
8961 {
8962 curwin->w_cursor.lnum = pos->lnum;
8963 curwin->w_cursor.col = pos->col;
8964 col = pos->col;
8965
8966 that = ml_get_curline();
8967
8968 if (vi_lisp && get_indent() == 0)
8969 amount = 2;
8970 else
8971 {
8972 amount = 0;
8973 while (*that && col)
8974 {
8975 amount += lbr_chartabsize_adv(&that, (colnr_T)amount);
8976 col--;
8977 }
8978
8979 /*
8980 * Some keywords require "body" indenting rules (the
8981 * non-standard-lisp ones are Scheme special forms):
8982 *
8983 * (let ((a 1)) instead (let ((a 1))
8984 * (...)) of (...))
8985 */
8986
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008987 if (!vi_lisp && (*that == '(' || *that == '[')
8988 && lisp_match(that + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008989 amount += 2;
8990 else
8991 {
8992 that++;
8993 amount++;
8994 firsttry = amount;
8995
8996 while (vim_iswhite(*that))
8997 {
8998 amount += lbr_chartabsize(that, (colnr_T)amount);
8999 ++that;
9000 }
9001
9002 if (*that && *that != ';') /* not a comment line */
9003 {
Bram Moolenaare21877a2008-02-13 09:58:14 +00009004 /* test *that != '(' to accommodate first let/do
Bram Moolenaar071d4272004-06-13 20:20:40 +00009005 * argument if it is more than one line */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00009006 if (!vi_lisp && *that != '(' && *that != '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00009007 firsttry++;
9008
9009 parencount = 0;
9010 quotecount = 0;
9011
9012 if (vi_lisp
9013 || (*that != '"'
9014 && *that != '\''
9015 && *that != '#'
9016 && (*that < '0' || *that > '9')))
9017 {
9018 while (*that
9019 && (!vim_iswhite(*that)
9020 || quotecount
9021 || parencount)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00009022 && (!((*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00009023 && !quotecount
9024 && !parencount
9025 && vi_lisp)))
9026 {
9027 if (*that == '"')
9028 quotecount = !quotecount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00009029 if ((*that == '(' || *that == '[')
9030 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009031 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00009032 if ((*that == ')' || *that == ']')
9033 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009034 --parencount;
9035 if (*that == '\\' && *(that+1) != NUL)
9036 amount += lbr_chartabsize_adv(&that,
9037 (colnr_T)amount);
9038 amount += lbr_chartabsize_adv(&that,
9039 (colnr_T)amount);
9040 }
9041 }
9042 while (vim_iswhite(*that))
9043 {
9044 amount += lbr_chartabsize(that, (colnr_T)amount);
9045 that++;
9046 }
9047 if (!*that || *that == ';')
9048 amount = firsttry;
9049 }
9050 }
9051 }
9052 }
9053 }
9054 else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00009055 amount = 0; /* no matching '(' or '[' found, use zero indent */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009056
9057 curwin->w_cursor = realpos;
9058
9059 return amount;
9060}
9061#endif /* FEAT_LISP */
9062
9063 void
9064prepare_to_exit()
9065{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00009066#if defined(SIGHUP) && defined(SIG_IGN)
9067 /* Ignore SIGHUP, because a dropped connection causes a read error, which
9068 * makes Vim exit and then handling SIGHUP causes various reentrance
9069 * problems. */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00009070 signal(SIGHUP, SIG_IGN);
9071#endif
9072
Bram Moolenaar071d4272004-06-13 20:20:40 +00009073#ifdef FEAT_GUI
9074 if (gui.in_use)
9075 {
9076 gui.dying = TRUE;
9077 out_trash(); /* trash any pending output */
9078 }
9079 else
9080#endif
9081 {
9082 windgoto((int)Rows - 1, 0);
9083
9084 /*
9085 * Switch terminal mode back now, so messages end up on the "normal"
9086 * screen (if there are two screens).
9087 */
9088 settmode(TMODE_COOK);
9089#ifdef WIN3264
9090 if (can_end_termcap_mode(FALSE) == TRUE)
9091#endif
9092 stoptermcap();
9093 out_flush();
9094 }
9095}
9096
9097/*
9098 * Preserve files and exit.
9099 * When called IObuff must contain a message.
9100 */
9101 void
9102preserve_exit()
9103{
9104 buf_T *buf;
9105
9106 prepare_to_exit();
9107
Bram Moolenaar4770d092006-01-12 23:22:24 +00009108 /* Setting this will prevent free() calls. That avoids calling free()
9109 * recursively when free() was invoked with a bad pointer. */
9110 really_exiting = TRUE;
9111
Bram Moolenaar071d4272004-06-13 20:20:40 +00009112 out_str(IObuff);
9113 screen_start(); /* don't know where cursor is now */
9114 out_flush();
9115
9116 ml_close_notmod(); /* close all not-modified buffers */
9117
9118 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
9119 {
9120 if (buf->b_ml.ml_mfp != NULL && buf->b_ml.ml_mfp->mf_fname != NULL)
9121 {
9122 OUT_STR(_("Vim: preserving files...\n"));
9123 screen_start(); /* don't know where cursor is now */
9124 out_flush();
9125 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
9126 break;
9127 }
9128 }
9129
9130 ml_close_all(FALSE); /* close all memfiles, without deleting */
9131
9132 OUT_STR(_("Vim: Finished.\n"));
9133
9134 getout(1);
9135}
9136
9137/*
9138 * return TRUE if "fname" exists.
9139 */
9140 int
9141vim_fexists(fname)
9142 char_u *fname;
9143{
9144 struct stat st;
9145
9146 if (mch_stat((char *)fname, &st))
9147 return FALSE;
9148 return TRUE;
9149}
9150
9151/*
9152 * Check for CTRL-C pressed, but only once in a while.
9153 * Should be used instead of ui_breakcheck() for functions that check for
9154 * each line in the file. Calling ui_breakcheck() each time takes too much
9155 * time, because it can be a system call.
9156 */
9157
9158#ifndef BREAKCHECK_SKIP
9159# ifdef FEAT_GUI /* assume the GUI only runs on fast computers */
9160# define BREAKCHECK_SKIP 200
9161# else
9162# define BREAKCHECK_SKIP 32
9163# endif
9164#endif
9165
9166static int breakcheck_count = 0;
9167
9168 void
9169line_breakcheck()
9170{
9171 if (++breakcheck_count >= BREAKCHECK_SKIP)
9172 {
9173 breakcheck_count = 0;
9174 ui_breakcheck();
9175 }
9176}
9177
9178/*
9179 * Like line_breakcheck() but check 10 times less often.
9180 */
9181 void
9182fast_breakcheck()
9183{
9184 if (++breakcheck_count >= BREAKCHECK_SKIP * 10)
9185 {
9186 breakcheck_count = 0;
9187 ui_breakcheck();
9188 }
9189}
9190
9191/*
Bram Moolenaard7834d32009-12-02 16:14:36 +00009192 * Invoke expand_wildcards() for one pattern.
9193 * Expand items like "%:h" before the expansion.
9194 * Returns OK or FAIL.
9195 */
9196 int
9197expand_wildcards_eval(pat, num_file, file, flags)
9198 char_u **pat; /* pointer to input pattern */
9199 int *num_file; /* resulting number of files */
9200 char_u ***file; /* array of resulting files */
9201 int flags; /* EW_DIR, etc. */
9202{
9203 int ret = FAIL;
9204 char_u *eval_pat = NULL;
9205 char_u *exp_pat = *pat;
9206 char_u *ignored_msg;
9207 int usedlen;
9208
9209 if (*exp_pat == '%' || *exp_pat == '#' || *exp_pat == '<')
9210 {
9211 ++emsg_off;
9212 eval_pat = eval_vars(exp_pat, exp_pat, &usedlen,
9213 NULL, &ignored_msg, NULL);
9214 --emsg_off;
9215 if (eval_pat != NULL)
9216 exp_pat = concat_str(eval_pat, exp_pat + usedlen);
9217 }
9218
9219 if (exp_pat != NULL)
9220 ret = expand_wildcards(1, &exp_pat, num_file, file, flags);
9221
9222 if (eval_pat != NULL)
9223 {
9224 vim_free(exp_pat);
9225 vim_free(eval_pat);
9226 }
9227
9228 return ret;
9229}
9230
9231/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00009232 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching
9233 * 'wildignore'.
Bram Moolenaar9e193ac2010-07-19 23:11:27 +02009234 * Returns OK or FAIL. When FAIL then "num_file" won't be set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009235 */
9236 int
9237expand_wildcards(num_pat, pat, num_file, file, flags)
9238 int num_pat; /* number of input patterns */
9239 char_u **pat; /* array of input patterns */
9240 int *num_file; /* resulting number of files */
9241 char_u ***file; /* array of resulting files */
9242 int flags; /* EW_DIR, etc. */
9243{
9244 int retval;
9245 int i, j;
9246 char_u *p;
9247 int non_suf_match; /* number without matching suffix */
9248
9249 retval = gen_expand_wildcards(num_pat, pat, num_file, file, flags);
9250
9251 /* When keeping all matches, return here */
Bram Moolenaar9e193ac2010-07-19 23:11:27 +02009252 if ((flags & EW_KEEPALL) || retval == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009253 return retval;
9254
9255#ifdef FEAT_WILDIGN
9256 /*
9257 * Remove names that match 'wildignore'.
9258 */
9259 if (*p_wig)
9260 {
9261 char_u *ffname;
9262
9263 /* check all files in (*file)[] */
9264 for (i = 0; i < *num_file; ++i)
9265 {
9266 ffname = FullName_save((*file)[i], FALSE);
9267 if (ffname == NULL) /* out of memory */
9268 break;
9269# ifdef VMS
9270 vms_remove_version(ffname);
9271# endif
9272 if (match_file_list(p_wig, (*file)[i], ffname))
9273 {
9274 /* remove this matching file from the list */
9275 vim_free((*file)[i]);
9276 for (j = i; j + 1 < *num_file; ++j)
9277 (*file)[j] = (*file)[j + 1];
9278 --*num_file;
9279 --i;
9280 }
9281 vim_free(ffname);
9282 }
9283 }
9284#endif
9285
9286 /*
9287 * Move the names where 'suffixes' match to the end.
9288 */
9289 if (*num_file > 1)
9290 {
9291 non_suf_match = 0;
9292 for (i = 0; i < *num_file; ++i)
9293 {
9294 if (!match_suffix((*file)[i]))
9295 {
9296 /*
9297 * Move the name without matching suffix to the front
9298 * of the list.
9299 */
9300 p = (*file)[i];
9301 for (j = i; j > non_suf_match; --j)
9302 (*file)[j] = (*file)[j - 1];
9303 (*file)[non_suf_match++] = p;
9304 }
9305 }
9306 }
9307
9308 return retval;
9309}
9310
9311/*
9312 * Return TRUE if "fname" matches with an entry in 'suffixes'.
9313 */
9314 int
9315match_suffix(fname)
9316 char_u *fname;
9317{
9318 int fnamelen, setsuflen;
9319 char_u *setsuf;
9320#define MAXSUFLEN 30 /* maximum length of a file suffix */
9321 char_u suf_buf[MAXSUFLEN];
9322
9323 fnamelen = (int)STRLEN(fname);
9324 setsuflen = 0;
9325 for (setsuf = p_su; *setsuf; )
9326 {
9327 setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
Bram Moolenaar055a2ba2009-07-14 19:40:21 +00009328 if (setsuflen == 0)
9329 {
9330 char_u *tail = gettail(fname);
9331
9332 /* empty entry: match name without a '.' */
9333 if (vim_strchr(tail, '.') == NULL)
9334 {
9335 setsuflen = 1;
9336 break;
9337 }
9338 }
9339 else
9340 {
9341 if (fnamelen >= setsuflen
9342 && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
9343 (size_t)setsuflen) == 0)
9344 break;
9345 setsuflen = 0;
9346 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009347 }
9348 return (setsuflen != 0);
9349}
9350
9351#if !defined(NO_EXPANDPATH) || defined(PROTO)
9352
9353# ifdef VIM_BACKTICK
9354static int vim_backtick __ARGS((char_u *p));
9355static int expand_backtick __ARGS((garray_T *gap, char_u *pat, int flags));
9356# endif
9357
9358# if defined(MSDOS) || defined(FEAT_GUI_W16) || defined(WIN3264)
9359/*
9360 * File name expansion code for MS-DOS, Win16 and Win32. It's here because
9361 * it's shared between these systems.
9362 */
9363# if defined(DJGPP) || defined(PROTO)
9364# define _cdecl /* DJGPP doesn't have this */
9365# else
9366# ifdef __BORLANDC__
9367# define _cdecl _RTLENTRYF
9368# endif
9369# endif
9370
9371/*
9372 * comparison function for qsort in dos_expandpath()
9373 */
9374 static int _cdecl
9375pstrcmp(const void *a, const void *b)
9376{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00009377 return (pathcmp(*(char **)a, *(char **)b, -1));
Bram Moolenaar071d4272004-06-13 20:20:40 +00009378}
9379
9380# ifndef WIN3264
9381 static void
9382namelowcpy(
9383 char_u *d,
9384 char_u *s)
9385{
9386# ifdef DJGPP
9387 if (USE_LONG_FNAME) /* don't lower case on Windows 95/NT systems */
9388 while (*s)
9389 *d++ = *s++;
9390 else
9391# endif
9392 while (*s)
9393 *d++ = TOLOWER_LOC(*s++);
9394 *d = NUL;
9395}
9396# endif
9397
9398/*
Bram Moolenaar231334e2005-07-25 20:46:57 +00009399 * Recursively expand one path component into all matching files and/or
9400 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009401 * Return the number of matches found.
9402 * "path" has backslashes before chars that are not to be expanded, starting
9403 * at "path[wildoff]".
Bram Moolenaar231334e2005-07-25 20:46:57 +00009404 * Return the number of matches found.
9405 * NOTE: much of this is identical to unix_expandpath(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00009406 */
9407 static int
9408dos_expandpath(
9409 garray_T *gap,
9410 char_u *path,
9411 int wildoff,
Bram Moolenaar231334e2005-07-25 20:46:57 +00009412 int flags, /* EW_* flags */
Bram Moolenaar25394022007-05-10 19:06:20 +00009413 int didstar) /* expanded "**" once already */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009414{
Bram Moolenaar231334e2005-07-25 20:46:57 +00009415 char_u *buf;
9416 char_u *path_end;
9417 char_u *p, *s, *e;
9418 int start_len = gap->ga_len;
9419 char_u *pat;
9420 regmatch_T regmatch;
9421 int starts_with_dot;
9422 int matches;
9423 int len;
9424 int starstar = FALSE;
9425 static int stardepth = 0; /* depth for "**" expansion */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009426#ifdef WIN3264
9427 WIN32_FIND_DATA fb;
9428 HANDLE hFind = (HANDLE)0;
9429# ifdef FEAT_MBYTE
9430 WIN32_FIND_DATAW wfb;
9431 WCHAR *wn = NULL; /* UCS-2 name, NULL when not used. */
9432# endif
9433#else
9434 struct ffblk fb;
9435#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009436 char_u *matchname;
Bram Moolenaar231334e2005-07-25 20:46:57 +00009437 int ok;
9438
9439 /* Expanding "**" may take a long time, check for CTRL-C. */
9440 if (stardepth > 0)
9441 {
9442 ui_breakcheck();
9443 if (got_int)
9444 return 0;
9445 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009446
9447 /* make room for file name */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009448 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009449 if (buf == NULL)
9450 return 0;
9451
9452 /*
9453 * Find the first part in the path name that contains a wildcard or a ~1.
9454 * Copy it into buf, including the preceding characters.
9455 */
9456 p = buf;
9457 s = buf;
9458 e = NULL;
9459 path_end = path;
9460 while (*path_end != NUL)
9461 {
9462 /* May ignore a wildcard that has a backslash before it; it will
9463 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
9464 if (path_end >= path + wildoff && rem_backslash(path_end))
9465 *p++ = *path_end++;
9466 else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
9467 {
9468 if (e != NULL)
9469 break;
9470 s = p + 1;
9471 }
9472 else if (path_end >= path + wildoff
9473 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
9474 e = p;
9475#ifdef FEAT_MBYTE
9476 if (has_mbyte)
9477 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00009478 len = (*mb_ptr2len)(path_end);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009479 STRNCPY(p, path_end, len);
9480 p += len;
9481 path_end += len;
9482 }
9483 else
9484#endif
9485 *p++ = *path_end++;
9486 }
9487 e = p;
9488 *e = NUL;
9489
9490 /* now we have one wildcard component between s and e */
9491 /* Remove backslashes between "wildoff" and the start of the wildcard
9492 * component. */
9493 for (p = buf + wildoff; p < s; ++p)
9494 if (rem_backslash(p))
9495 {
Bram Moolenaar8c8de832008-06-24 22:58:06 +00009496 STRMOVE(p, p + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009497 --e;
9498 --s;
9499 }
9500
Bram Moolenaar231334e2005-07-25 20:46:57 +00009501 /* Check for "**" between "s" and "e". */
9502 for (p = s; p < e; ++p)
9503 if (p[0] == '*' && p[1] == '*')
9504 starstar = TRUE;
9505
Bram Moolenaar071d4272004-06-13 20:20:40 +00009506 starts_with_dot = (*s == '.');
9507 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
9508 if (pat == NULL)
9509 {
9510 vim_free(buf);
9511 return 0;
9512 }
9513
9514 /* compile the regexp into a program */
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009515 if (flags & (EW_NOERROR | EW_NOTWILD))
Bram Moolenaarb5609832011-07-20 15:04:58 +02009516 ++emsg_silent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009517 regmatch.rm_ic = TRUE; /* Always ignore case */
9518 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009519 if (flags & (EW_NOERROR | EW_NOTWILD))
Bram Moolenaarb5609832011-07-20 15:04:58 +02009520 --emsg_silent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009521 vim_free(pat);
9522
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009523 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009524 {
9525 vim_free(buf);
9526 return 0;
9527 }
9528
9529 /* remember the pattern or file name being looked for */
9530 matchname = vim_strsave(s);
9531
Bram Moolenaar231334e2005-07-25 20:46:57 +00009532 /* If "**" is by itself, this is the first time we encounter it and more
9533 * is following then find matches without any directory. */
9534 if (!didstar && stardepth < 100 && starstar && e - s == 2
9535 && *path_end == '/')
9536 {
9537 STRCPY(s, path_end + 1);
9538 ++stardepth;
9539 (void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
9540 --stardepth;
9541 }
9542
Bram Moolenaar071d4272004-06-13 20:20:40 +00009543 /* Scan all files in the directory with "dir/ *.*" */
9544 STRCPY(s, "*.*");
9545#ifdef WIN3264
9546# ifdef FEAT_MBYTE
9547 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
9548 {
9549 /* The active codepage differs from 'encoding'. Attempt using the
9550 * wide function. If it fails because it is not implemented fall back
9551 * to the non-wide version (for Windows 98) */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009552 wn = enc_to_utf16(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009553 if (wn != NULL)
9554 {
9555 hFind = FindFirstFileW(wn, &wfb);
9556 if (hFind == INVALID_HANDLE_VALUE
9557 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
9558 {
9559 vim_free(wn);
9560 wn = NULL;
9561 }
9562 }
9563 }
9564
9565 if (wn == NULL)
9566# endif
9567 hFind = FindFirstFile(buf, &fb);
9568 ok = (hFind != INVALID_HANDLE_VALUE);
9569#else
9570 /* If we are expanding wildcards we try both files and directories */
9571 ok = (findfirst((char *)buf, &fb,
9572 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
9573#endif
9574
9575 while (ok)
9576 {
9577#ifdef WIN3264
9578# ifdef FEAT_MBYTE
9579 if (wn != NULL)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009580 p = utf16_to_enc(wfb.cFileName, NULL); /* p is allocated here */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009581 else
9582# endif
9583 p = (char_u *)fb.cFileName;
9584#else
9585 p = (char_u *)fb.ff_name;
9586#endif
9587 /* Ignore entries starting with a dot, unless when asked for. Accept
9588 * all entries found with "matchname". */
9589 if ((p[0] != '.' || starts_with_dot)
9590 && (matchname == NULL
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009591 || (regmatch.regprog != NULL
9592 && vim_regexec(&regmatch, p, (colnr_T)0))
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009593 || ((flags & EW_NOTWILD)
9594 && fnamencmp(path + (s - buf), p, e - s) == 0)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009595 {
9596#ifdef WIN3264
9597 STRCPY(s, p);
9598#else
9599 namelowcpy(s, p);
9600#endif
9601 len = (int)STRLEN(buf);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009602
9603 if (starstar && stardepth < 100)
9604 {
9605 /* For "**" in the pattern first go deeper in the tree to
9606 * find matches. */
9607 STRCPY(buf + len, "/**");
9608 STRCPY(buf + len + 3, path_end);
9609 ++stardepth;
9610 (void)dos_expandpath(gap, buf, len + 1, flags, TRUE);
9611 --stardepth;
9612 }
9613
Bram Moolenaar071d4272004-06-13 20:20:40 +00009614 STRCPY(buf + len, path_end);
9615 if (mch_has_exp_wildcard(path_end))
9616 {
9617 /* need to expand another component of the path */
9618 /* remove backslashes for the remaining components only */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009619 (void)dos_expandpath(gap, buf, len + 1, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009620 }
9621 else
9622 {
9623 /* no more wildcards, check if there is a match */
9624 /* remove backslashes for the remaining components only */
9625 if (*path_end != 0)
9626 backslash_halve(buf + len + 1);
9627 if (mch_getperm(buf) >= 0) /* add existing file */
9628 addfile(gap, buf, flags);
9629 }
9630 }
9631
9632#ifdef WIN3264
9633# ifdef FEAT_MBYTE
9634 if (wn != NULL)
9635 {
9636 vim_free(p);
9637 ok = FindNextFileW(hFind, &wfb);
9638 }
9639 else
9640# endif
9641 ok = FindNextFile(hFind, &fb);
9642#else
9643 ok = (findnext(&fb) == 0);
9644#endif
9645
9646 /* If no more matches and no match was used, try expanding the name
9647 * itself. Finds the long name of a short filename. */
9648 if (!ok && matchname != NULL && gap->ga_len == start_len)
9649 {
9650 STRCPY(s, matchname);
9651#ifdef WIN3264
9652 FindClose(hFind);
9653# ifdef FEAT_MBYTE
9654 if (wn != NULL)
9655 {
9656 vim_free(wn);
Bram Moolenaar36f692d2008-11-20 16:10:17 +00009657 wn = enc_to_utf16(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009658 if (wn != NULL)
9659 hFind = FindFirstFileW(wn, &wfb);
9660 }
9661 if (wn == NULL)
9662# endif
9663 hFind = FindFirstFile(buf, &fb);
9664 ok = (hFind != INVALID_HANDLE_VALUE);
9665#else
9666 ok = (findfirst((char *)buf, &fb,
9667 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
9668#endif
9669 vim_free(matchname);
9670 matchname = NULL;
9671 }
9672 }
9673
9674#ifdef WIN3264
9675 FindClose(hFind);
9676# ifdef FEAT_MBYTE
9677 vim_free(wn);
9678# endif
9679#endif
9680 vim_free(buf);
9681 vim_free(regmatch.regprog);
9682 vim_free(matchname);
9683
9684 matches = gap->ga_len - start_len;
9685 if (matches > 0)
9686 qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
9687 sizeof(char_u *), pstrcmp);
9688 return matches;
9689}
9690
9691 int
9692mch_expandpath(
9693 garray_T *gap,
9694 char_u *path,
9695 int flags) /* EW_* flags */
9696{
Bram Moolenaar231334e2005-07-25 20:46:57 +00009697 return dos_expandpath(gap, path, 0, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009698}
9699# endif /* MSDOS || FEAT_GUI_W16 || WIN3264 */
9700
Bram Moolenaar231334e2005-07-25 20:46:57 +00009701#if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
9702 || defined(PROTO)
9703/*
9704 * Unix style wildcard expansion code.
9705 * It's here because it's used both for Unix and Mac.
9706 */
9707static int pstrcmp __ARGS((const void *, const void *));
9708
9709 static int
9710pstrcmp(a, b)
9711 const void *a, *b;
9712{
9713 return (pathcmp(*(char **)a, *(char **)b, -1));
9714}
9715
9716/*
9717 * Recursively expand one path component into all matching files and/or
9718 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
9719 * "path" has backslashes before chars that are not to be expanded, starting
9720 * at "path + wildoff".
9721 * Return the number of matches found.
9722 * NOTE: much of this is identical to dos_expandpath(), keep in sync!
9723 */
9724 int
9725unix_expandpath(gap, path, wildoff, flags, didstar)
9726 garray_T *gap;
9727 char_u *path;
9728 int wildoff;
9729 int flags; /* EW_* flags */
9730 int didstar; /* expanded "**" once already */
9731{
9732 char_u *buf;
9733 char_u *path_end;
9734 char_u *p, *s, *e;
9735 int start_len = gap->ga_len;
9736 char_u *pat;
9737 regmatch_T regmatch;
9738 int starts_with_dot;
9739 int matches;
9740 int len;
9741 int starstar = FALSE;
9742 static int stardepth = 0; /* depth for "**" expansion */
9743
9744 DIR *dirp;
9745 struct dirent *dp;
9746
9747 /* Expanding "**" may take a long time, check for CTRL-C. */
9748 if (stardepth > 0)
9749 {
9750 ui_breakcheck();
9751 if (got_int)
9752 return 0;
9753 }
9754
9755 /* make room for file name */
9756 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
9757 if (buf == NULL)
9758 return 0;
9759
9760 /*
9761 * Find the first part in the path name that contains a wildcard.
Bram Moolenaar2d0b92f2012-04-30 21:09:43 +02009762 * When EW_ICASE is set every letter is considered to be a wildcard.
Bram Moolenaar231334e2005-07-25 20:46:57 +00009763 * Copy it into "buf", including the preceding characters.
9764 */
9765 p = buf;
9766 s = buf;
9767 e = NULL;
9768 path_end = path;
9769 while (*path_end != NUL)
9770 {
9771 /* May ignore a wildcard that has a backslash before it; it will
9772 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
9773 if (path_end >= path + wildoff && rem_backslash(path_end))
9774 *p++ = *path_end++;
9775 else if (*path_end == '/')
9776 {
9777 if (e != NULL)
9778 break;
9779 s = p + 1;
9780 }
9781 else if (path_end >= path + wildoff
Bram Moolenaar2d0b92f2012-04-30 21:09:43 +02009782 && (vim_strchr((char_u *)"*?[{~$", *path_end) != NULL
9783#ifndef CASE_INSENSITIVE_FILENAME
9784 || ((flags & EW_ICASE)
9785 && isalpha(PTR2CHAR(path_end)))
9786#endif
9787 ))
Bram Moolenaar231334e2005-07-25 20:46:57 +00009788 e = p;
9789#ifdef FEAT_MBYTE
9790 if (has_mbyte)
9791 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00009792 len = (*mb_ptr2len)(path_end);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009793 STRNCPY(p, path_end, len);
9794 p += len;
9795 path_end += len;
9796 }
9797 else
9798#endif
9799 *p++ = *path_end++;
9800 }
9801 e = p;
9802 *e = NUL;
9803
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009804 /* Now we have one wildcard component between "s" and "e". */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009805 /* Remove backslashes between "wildoff" and the start of the wildcard
9806 * component. */
9807 for (p = buf + wildoff; p < s; ++p)
9808 if (rem_backslash(p))
9809 {
Bram Moolenaar8c8de832008-06-24 22:58:06 +00009810 STRMOVE(p, p + 1);
Bram Moolenaar231334e2005-07-25 20:46:57 +00009811 --e;
9812 --s;
9813 }
9814
9815 /* Check for "**" between "s" and "e". */
9816 for (p = s; p < e; ++p)
9817 if (p[0] == '*' && p[1] == '*')
9818 starstar = TRUE;
9819
9820 /* convert the file pattern to a regexp pattern */
9821 starts_with_dot = (*s == '.');
9822 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
9823 if (pat == NULL)
9824 {
9825 vim_free(buf);
9826 return 0;
9827 }
9828
9829 /* compile the regexp into a program */
Bram Moolenaarcc016f52005-12-10 20:23:46 +00009830#ifdef CASE_INSENSITIVE_FILENAME
Bram Moolenaar231334e2005-07-25 20:46:57 +00009831 regmatch.rm_ic = TRUE; /* Behave like Terminal.app */
9832#else
Bram Moolenaar94950a92010-12-02 16:01:29 +01009833 if (flags & EW_ICASE)
9834 regmatch.rm_ic = TRUE; /* 'wildignorecase' set */
9835 else
9836 regmatch.rm_ic = FALSE; /* Don't ignore case */
Bram Moolenaar231334e2005-07-25 20:46:57 +00009837#endif
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009838 if (flags & (EW_NOERROR | EW_NOTWILD))
9839 ++emsg_silent;
Bram Moolenaar231334e2005-07-25 20:46:57 +00009840 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009841 if (flags & (EW_NOERROR | EW_NOTWILD))
9842 --emsg_silent;
Bram Moolenaar231334e2005-07-25 20:46:57 +00009843 vim_free(pat);
9844
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009845 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
Bram Moolenaar231334e2005-07-25 20:46:57 +00009846 {
9847 vim_free(buf);
9848 return 0;
9849 }
9850
9851 /* If "**" is by itself, this is the first time we encounter it and more
9852 * is following then find matches without any directory. */
9853 if (!didstar && stardepth < 100 && starstar && e - s == 2
9854 && *path_end == '/')
9855 {
9856 STRCPY(s, path_end + 1);
9857 ++stardepth;
9858 (void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
9859 --stardepth;
9860 }
9861
9862 /* open the directory for scanning */
9863 *s = NUL;
9864 dirp = opendir(*buf == NUL ? "." : (char *)buf);
9865
9866 /* Find all matching entries */
9867 if (dirp != NULL)
9868 {
9869 for (;;)
9870 {
9871 dp = readdir(dirp);
9872 if (dp == NULL)
9873 break;
9874 if ((dp->d_name[0] != '.' || starts_with_dot)
Bram Moolenaar1f5965b2012-01-10 18:37:58 +01009875 && ((regmatch.regprog != NULL && vim_regexec(&regmatch,
9876 (char_u *)dp->d_name, (colnr_T)0))
Bram Moolenaar0b573a52011-07-27 17:31:47 +02009877 || ((flags & EW_NOTWILD)
9878 && fnamencmp(path + (s - buf), dp->d_name, e - s) == 0)))
Bram Moolenaar231334e2005-07-25 20:46:57 +00009879 {
9880 STRCPY(s, dp->d_name);
9881 len = STRLEN(buf);
9882
9883 if (starstar && stardepth < 100)
9884 {
9885 /* For "**" in the pattern first go deeper in the tree to
9886 * find matches. */
9887 STRCPY(buf + len, "/**");
9888 STRCPY(buf + len + 3, path_end);
9889 ++stardepth;
9890 (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
9891 --stardepth;
9892 }
9893
9894 STRCPY(buf + len, path_end);
9895 if (mch_has_exp_wildcard(path_end)) /* handle more wildcards */
9896 {
9897 /* need to expand another component of the path */
9898 /* remove backslashes for the remaining components only */
9899 (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
9900 }
9901 else
9902 {
9903 /* no more wildcards, check if there is a match */
9904 /* remove backslashes for the remaining components only */
9905 if (*path_end != NUL)
9906 backslash_halve(buf + len + 1);
9907 if (mch_getperm(buf) >= 0) /* add existing file */
9908 {
Bram Moolenaar95e9b492006-03-15 23:04:43 +00009909#ifdef MACOS_CONVERT
Bram Moolenaar231334e2005-07-25 20:46:57 +00009910 size_t precomp_len = STRLEN(buf)+1;
9911 char_u *precomp_buf =
9912 mac_precompose_path(buf, precomp_len, &precomp_len);
Bram Moolenaar95e9b492006-03-15 23:04:43 +00009913
Bram Moolenaar231334e2005-07-25 20:46:57 +00009914 if (precomp_buf)
9915 {
9916 mch_memmove(buf, precomp_buf, precomp_len);
9917 vim_free(precomp_buf);
9918 }
9919#endif
9920 addfile(gap, buf, flags);
9921 }
9922 }
9923 }
9924 }
9925
9926 closedir(dirp);
9927 }
9928
9929 vim_free(buf);
9930 vim_free(regmatch.regprog);
9931
9932 matches = gap->ga_len - start_len;
9933 if (matches > 0)
9934 qsort(((char_u **)gap->ga_data) + start_len, matches,
9935 sizeof(char_u *), pstrcmp);
9936 return matches;
9937}
9938#endif
9939
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009940#if defined(FEAT_SEARCHPATH)
9941static int find_previous_pathsep __ARGS((char_u *path, char_u **psep));
9942static int is_unique __ARGS((char_u *maybe_unique, garray_T *gap, int i));
Bram Moolenaar162bd912010-07-28 22:29:10 +02009943static void expand_path_option __ARGS((char_u *curdir, garray_T *gap));
9944static char_u *get_path_cutoff __ARGS((char_u *fname, garray_T *gap));
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009945static void uniquefy_paths __ARGS((garray_T *gap, char_u *pattern));
9946static int expand_in_path __ARGS((garray_T *gap, char_u *pattern, int flags));
9947
9948/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009949 * Moves "*psep" back to the previous path separator in "path".
9950 * Returns FAIL is "*psep" ends up at the beginning of "path".
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009951 */
9952 static int
9953find_previous_pathsep(path, psep)
9954 char_u *path;
9955 char_u **psep;
9956{
9957 /* skip the current separator */
9958 if (*psep > path && vim_ispathsep(**psep))
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009959 --*psep;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009960
9961 /* find the previous separator */
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009962 while (*psep > path)
9963 {
9964 if (vim_ispathsep(**psep))
9965 return OK;
9966 mb_ptr_back(path, *psep);
9967 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009968
9969 return FAIL;
9970}
9971
9972/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009973 * Returns TRUE if "maybe_unique" is unique wrt other_paths in "gap".
9974 * "maybe_unique" is the end portion of "((char_u **)gap->ga_data)[i]".
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009975 */
9976 static int
9977is_unique(maybe_unique, gap, i)
9978 char_u *maybe_unique;
9979 garray_T *gap;
9980 int i;
9981{
9982 int j;
9983 int candidate_len;
9984 int other_path_len;
Bram Moolenaar162bd912010-07-28 22:29:10 +02009985 char_u **other_paths = (char_u **)gap->ga_data;
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009986 char_u *rival;
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009987
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009988 for (j = 0; j < gap->ga_len; j++)
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009989 {
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009990 if (j == i)
Bram Moolenaar162bd912010-07-28 22:29:10 +02009991 continue; /* don't compare it with itself */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009992
Bram Moolenaar624c7aa2010-07-16 20:38:52 +02009993 candidate_len = (int)STRLEN(maybe_unique);
9994 other_path_len = (int)STRLEN(other_paths[j]);
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009995 if (other_path_len < candidate_len)
Bram Moolenaardc685ab2010-08-13 21:16:49 +02009996 continue; /* it's different when it's shorter */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02009997
Bram Moolenaar0be992e2010-08-12 21:50:51 +02009998 rival = other_paths[j] + other_path_len - candidate_len;
Bram Moolenaarda9836c2010-08-16 21:53:27 +02009999 if (fnamecmp(maybe_unique, rival) == 0
10000 && (rival == other_paths[j] || vim_ispathsep(*(rival - 1))))
Bram Moolenaar162bd912010-07-28 22:29:10 +020010001 return FALSE; /* match */
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010002 }
10003
Bram Moolenaar162bd912010-07-28 22:29:10 +020010004 return TRUE; /* no match found */
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010005}
10006
10007/*
Bram Moolenaar1a509df2010-08-01 17:59:57 +020010008 * Split the 'path' option into an array of strings in garray_T. Relative
Bram Moolenaar162bd912010-07-28 22:29:10 +020010009 * paths are expanded to their equivalent fullpath. This includes the "."
10010 * (relative to current buffer directory) and empty path (relative to current
10011 * directory) notations.
10012 *
10013 * TODO: handle upward search (;) and path limiter (**N) notations by
10014 * expanding each into their equivalent path(s).
10015 */
10016 static void
10017expand_path_option(curdir, gap)
10018 char_u *curdir;
10019 garray_T *gap;
10020{
10021 char_u *path_option = *curbuf->b_p_path == NUL
10022 ? p_path : curbuf->b_p_path;
10023 char_u *buf;
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010024 char_u *p;
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010025 int len;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010026
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010027 if ((buf = alloc((int)MAXPATHL)) == NULL)
Bram Moolenaar162bd912010-07-28 22:29:10 +020010028 return;
10029
10030 while (*path_option != NUL)
10031 {
10032 copy_option_part(&path_option, buf, MAXPATHL, " ,");
10033
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010034 if (buf[0] == '.' && (buf[1] == NUL || vim_ispathsep(buf[1])))
Bram Moolenaar162bd912010-07-28 22:29:10 +020010035 {
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010036 /* Relative to current buffer:
10037 * "/path/file" + "." -> "/path/"
10038 * "/path/file" + "./subdir" -> "/path/subdir" */
Bram Moolenaar162bd912010-07-28 22:29:10 +020010039 if (curbuf->b_ffname == NULL)
10040 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010041 p = gettail(curbuf->b_ffname);
10042 len = (int)(p - curbuf->b_ffname);
10043 if (len + (int)STRLEN(buf) >= MAXPATHL)
10044 continue;
10045 if (buf[1] == NUL)
10046 buf[len] = NUL;
10047 else
10048 STRMOVE(buf + len, buf + 2);
10049 mch_memmove(buf, curbuf->b_ffname, len);
10050 simplify_filename(buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010051 }
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010052 else if (buf[0] == NUL)
10053 /* relative to current directory */
Bram Moolenaar162bd912010-07-28 22:29:10 +020010054 STRCPY(buf, curdir);
Bram Moolenaar84f888a2010-08-05 21:40:16 +020010055 else if (path_with_url(buf))
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010056 /* URL can't be used here */
Bram Moolenaar84f888a2010-08-05 21:40:16 +020010057 continue;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010058 else if (!mch_isFullName(buf))
10059 {
10060 /* Expand relative path to their full path equivalent */
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010061 len = (int)STRLEN(curdir);
10062 if (len + (int)STRLEN(buf) + 3 > MAXPATHL)
Bram Moolenaar162bd912010-07-28 22:29:10 +020010063 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010064 STRMOVE(buf + len + 1, buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010065 STRCPY(buf, curdir);
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010066 buf[len] = PATHSEP;
Bram Moolenaar57adda12010-08-03 22:11:29 +020010067 simplify_filename(buf);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010068 }
10069
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010070 if (ga_grow(gap, 1) == FAIL)
10071 break;
10072 p = vim_strsave(buf);
10073 if (p == NULL)
10074 break;
10075 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010076 }
10077
10078 vim_free(buf);
10079}
10080
10081/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010082 * Returns a pointer to the file or directory name in "fname" that matches the
10083 * longest path in "ga"p, or NULL if there is no match. For example:
Bram Moolenaar162bd912010-07-28 22:29:10 +020010084 *
10085 * path: /foo/bar/baz
10086 * fname: /foo/bar/baz/quux.txt
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010087 * returns: ^this
Bram Moolenaar162bd912010-07-28 22:29:10 +020010088 */
10089 static char_u *
10090get_path_cutoff(fname, gap)
10091 char_u *fname;
10092 garray_T *gap;
10093{
10094 int i;
10095 int maxlen = 0;
10096 char_u **path_part = (char_u **)gap->ga_data;
10097 char_u *cutoff = NULL;
10098
10099 for (i = 0; i < gap->ga_len; i++)
10100 {
10101 int j = 0;
10102
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010103 while ((fname[j] == path_part[i][j]
Bram Moolenaar2d7c47d2010-08-10 19:50:26 +020010104# if defined(MSWIN) || defined(MSDOS)
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010105 || (vim_ispathsep(fname[j]) && vim_ispathsep(path_part[i][j]))
10106#endif
10107 ) && fname[j] != NUL && path_part[i][j] != NUL)
Bram Moolenaar162bd912010-07-28 22:29:10 +020010108 j++;
10109 if (j > maxlen)
10110 {
10111 maxlen = j;
10112 cutoff = &fname[j];
10113 }
10114 }
10115
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010116 /* skip to the file or directory name */
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010117 if (cutoff != NULL)
Bram Moolenaar31710262010-08-13 13:36:15 +020010118 while (vim_ispathsep(*cutoff))
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010119 mb_ptr_adv(cutoff);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010120
10121 return cutoff;
10122}
10123
10124/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010125 * Sorts, removes duplicates and modifies all the fullpath names in "gap" so
10126 * that they are unique with respect to each other while conserving the part
10127 * that matches the pattern. Beware, this is at least O(n^2) wrt "gap->ga_len".
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010128 */
10129 static void
10130uniquefy_paths(gap, pattern)
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +020010131 garray_T *gap;
10132 char_u *pattern;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010133{
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +020010134 int i;
10135 int len;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010136 char_u **fnames = (char_u **)gap->ga_data;
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010137 int sort_again = FALSE;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010138 char_u *pat;
10139 char_u *file_pattern;
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010140 char_u *curdir;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010141 regmatch_T regmatch;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010142 garray_T path_ga;
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010143 char_u **in_curdir = NULL;
10144 char_u *short_name;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010145
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +020010146 remove_duplicates(gap);
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010147 ga_init2(&path_ga, (int)sizeof(char_u *), 1);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010148
10149 /*
10150 * We need to prepend a '*' at the beginning of file_pattern so that the
10151 * regex matches anywhere in the path. FIXME: is this valid for all
Bram Moolenaarb31e4382010-07-24 16:01:56 +020010152 * possible patterns?
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010153 */
Bram Moolenaar624c7aa2010-07-16 20:38:52 +020010154 len = (int)STRLEN(pattern);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010155 file_pattern = alloc(len + 2);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010156 if (file_pattern == NULL)
10157 return;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010158 file_pattern[0] = '*';
Bram Moolenaar162bd912010-07-28 22:29:10 +020010159 file_pattern[1] = NUL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010160 STRCAT(file_pattern, pattern);
10161 pat = file_pat_to_reg_pat(file_pattern, NULL, NULL, TRUE);
10162 vim_free(file_pattern);
Bram Moolenaarb31e4382010-07-24 16:01:56 +020010163 if (pat == NULL)
10164 return;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010165
Bram Moolenaarb31e4382010-07-24 16:01:56 +020010166 regmatch.rm_ic = TRUE; /* always ignore case */
10167 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
10168 vim_free(pat);
10169 if (regmatch.regprog == NULL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010170 return;
10171
Bram Moolenaar162bd912010-07-28 22:29:10 +020010172 if ((curdir = alloc((int)(MAXPATHL))) == NULL)
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010173 goto theend;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010174 mch_dirname(curdir, MAXPATHL);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010175 expand_path_option(curdir, &path_ga);
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010176
10177 in_curdir = (char_u **)alloc_clear(gap->ga_len * sizeof(char_u *));
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010178 if (in_curdir == NULL)
10179 goto theend;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010180
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010181 for (i = 0; i < gap->ga_len && !got_int; i++)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010182 {
Bram Moolenaar162bd912010-07-28 22:29:10 +020010183 char_u *path = fnames[i];
10184 int is_in_curdir;
Bram Moolenaar31710262010-08-13 13:36:15 +020010185 char_u *dir_end = gettail_dir(path);
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010186 char_u *pathsep_p;
10187 char_u *path_cutoff;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010188
Bram Moolenaar624c7aa2010-07-16 20:38:52 +020010189 len = (int)STRLEN(path);
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010190 is_in_curdir = fnamencmp(curdir, path, dir_end - path) == 0
Bram Moolenaar162bd912010-07-28 22:29:10 +020010191 && curdir[dir_end - path] == NUL;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010192 if (is_in_curdir)
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010193 in_curdir[i] = vim_strsave(path);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010194
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010195 /* Shorten the filename while maintaining its uniqueness */
10196 path_cutoff = get_path_cutoff(path, &path_ga);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010197
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010198 /* we start at the end of the path */
10199 pathsep_p = path + len - 1;
10200
10201 while (find_previous_pathsep(path, &pathsep_p))
10202 if (vim_regexec(&regmatch, pathsep_p + 1, (colnr_T)0)
10203 && is_unique(pathsep_p + 1, gap, i)
10204 && path_cutoff != NULL && pathsep_p + 1 >= path_cutoff)
10205 {
10206 sort_again = TRUE;
10207 mch_memmove(path, pathsep_p + 1, STRLEN(pathsep_p));
10208 break;
10209 }
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010210
10211 if (mch_isFullName(path))
10212 {
10213 /*
10214 * Last resort: shorten relative to curdir if possible.
10215 * 'possible' means:
10216 * 1. It is under the current directory.
10217 * 2. The result is actually shorter than the original.
10218 *
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010219 * Before curdir After
10220 * /foo/bar/file.txt /foo/bar ./file.txt
10221 * c:\foo\bar\file.txt c:\foo\bar .\file.txt
10222 * /file.txt / /file.txt
10223 * c:\file.txt c:\ .\file.txt
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010224 */
10225 short_name = shorten_fname(path, curdir);
Bram Moolenaar31710262010-08-13 13:36:15 +020010226 if (short_name != NULL && short_name > path + 1
10227#if defined(MSWIN) || defined(MSDOS)
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010228 /* On windows,
Bram Moolenaar31710262010-08-13 13:36:15 +020010229 * shorten_fname("c:\a\a.txt", "c:\a\b")
Bram Moolenaar31710262010-08-13 13:36:15 +020010230 * returns "\a\a.txt", which is not really the short
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010231 * name, hence: */
Bram Moolenaar31710262010-08-13 13:36:15 +020010232 && !vim_ispathsep(*short_name)
10233#endif
10234 )
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010235 {
10236 STRCPY(path, ".");
10237 add_pathsep(path);
Bram Moolenaarcda000e2010-08-14 13:34:39 +020010238 STRMOVE(path + STRLEN(path), short_name);
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010239 }
10240 }
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010241 ui_breakcheck();
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010242 }
10243
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010244 /* Shorten filenames in /in/current/directory/{filename} */
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010245 for (i = 0; i < gap->ga_len && !got_int; i++)
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010246 {
10247 char_u *rel_path;
10248 char_u *path = in_curdir[i];
10249
10250 if (path == NULL)
10251 continue;
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010252
10253 /* If the {filename} is not unique, change it to ./{filename}.
10254 * Else reduce it to {filename} */
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010255 short_name = shorten_fname(path, curdir);
10256 if (short_name == NULL)
10257 short_name = path;
10258 if (is_unique(short_name, gap, i))
10259 {
10260 STRCPY(fnames[i], short_name);
10261 continue;
10262 }
10263
10264 rel_path = alloc((int)(STRLEN(short_name) + STRLEN(PATHSEPSTR) + 2));
10265 if (rel_path == NULL)
10266 goto theend;
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010267 STRCPY(rel_path, ".");
10268 add_pathsep(rel_path);
10269 STRCAT(rel_path, short_name);
10270
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010271 vim_free(fnames[i]);
10272 fnames[i] = rel_path;
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010273 sort_again = TRUE;
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010274 ui_breakcheck();
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010275 }
10276
Bram Moolenaar162bd912010-07-28 22:29:10 +020010277theend:
10278 vim_free(curdir);
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010279 if (in_curdir != NULL)
10280 {
10281 for (i = 0; i < gap->ga_len; i++)
10282 vim_free(in_curdir[i]);
10283 vim_free(in_curdir);
10284 }
Bram Moolenaar162bd912010-07-28 22:29:10 +020010285 ga_clear_strings(&path_ga);
Bram Moolenaarb31e4382010-07-24 16:01:56 +020010286 vim_free(regmatch.regprog);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010287
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010288 if (sort_again)
Bram Moolenaarcb9d45c2010-07-20 18:10:15 +020010289 remove_duplicates(gap);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010290}
10291
10292/*
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010293 * Calls globpath() with 'path' values for the given pattern and stores the
10294 * result in "gap".
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010295 * Returns the total number of matches.
10296 */
10297 static int
10298expand_in_path(gap, pattern, flags)
10299 garray_T *gap;
10300 char_u *pattern;
10301 int flags; /* EW_* flags */
10302{
Bram Moolenaar162bd912010-07-28 22:29:10 +020010303 char_u *curdir;
10304 garray_T path_ga;
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010305 char_u *files = NULL;
10306 char_u *s; /* start */
10307 char_u *e; /* end */
10308 char_u *paths = NULL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010309
Bram Moolenaar7f0f6212010-08-03 22:21:00 +020010310 if ((curdir = alloc((unsigned)MAXPATHL)) == NULL)
Bram Moolenaar162bd912010-07-28 22:29:10 +020010311 return 0;
10312 mch_dirname(curdir, MAXPATHL);
10313
Bram Moolenaar0be992e2010-08-12 21:50:51 +020010314 ga_init2(&path_ga, (int)sizeof(char_u *), 1);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010315 expand_path_option(curdir, &path_ga);
10316 vim_free(curdir);
Bram Moolenaar006d2b02010-08-04 12:39:44 +020010317 if (path_ga.ga_len == 0)
10318 return 0;
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010319
10320 paths = ga_concat_strings(&path_ga);
10321 ga_clear_strings(&path_ga);
10322 if (paths == NULL)
Bram Moolenaar7f0f6212010-08-03 22:21:00 +020010323 return 0;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010324
Bram Moolenaar94950a92010-12-02 16:01:29 +010010325 files = globpath(paths, pattern, (flags & EW_ICASE) ? WILD_ICASE : 0);
Bram Moolenaar162bd912010-07-28 22:29:10 +020010326 vim_free(paths);
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010327 if (files == NULL)
10328 return 0;
10329
10330 /* Copy each path in files into gap */
10331 s = e = files;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010332 while (*s != NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010333 {
Bram Moolenaar162bd912010-07-28 22:29:10 +020010334 while (*e != '\n' && *e != NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010335 e++;
Bram Moolenaar162bd912010-07-28 22:29:10 +020010336 if (*e == NUL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010337 {
10338 addfile(gap, s, flags);
10339 break;
10340 }
10341 else
10342 {
10343 /* *e is '\n' */
Bram Moolenaar162bd912010-07-28 22:29:10 +020010344 *e = NUL;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010345 addfile(gap, s, flags);
10346 e++;
10347 s = e;
10348 }
10349 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010350 vim_free(files);
10351
Bram Moolenaarbdc975c2010-08-02 21:33:37 +020010352 return gap->ga_len;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010353}
10354#endif
10355
Bram Moolenaar1587a1e2010-07-29 20:59:59 +020010356#if defined(FEAT_SEARCHPATH) || defined(FEAT_CMDL_COMPL) || defined(PROTO)
10357/*
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010358 * Sort "gap" and remove duplicate entries. "gap" is expected to contain a
10359 * list of file names in allocated memory.
Bram Moolenaar1587a1e2010-07-29 20:59:59 +020010360 */
10361 void
10362remove_duplicates(gap)
10363 garray_T *gap;
10364{
10365 int i;
10366 int j;
10367 char_u **fnames = (char_u **)gap->ga_data;
10368
Bram Moolenaardc685ab2010-08-13 21:16:49 +020010369 sort_strings(fnames, gap->ga_len);
Bram Moolenaar1587a1e2010-07-29 20:59:59 +020010370 for (i = gap->ga_len - 1; i > 0; --i)
10371 if (fnamecmp(fnames[i - 1], fnames[i]) == 0)
10372 {
10373 vim_free(fnames[i]);
10374 for (j = i + 1; j < gap->ga_len; ++j)
10375 fnames[j - 1] = fnames[j];
10376 --gap->ga_len;
10377 }
10378}
10379#endif
10380
Bram Moolenaar071d4272004-06-13 20:20:40 +000010381/*
10382 * Generic wildcard expansion code.
10383 *
10384 * Characters in "pat" that should not be expanded must be preceded with a
10385 * backslash. E.g., "/path\ with\ spaces/my\*star*"
10386 *
10387 * Return FAIL when no single file was found. In this case "num_file" is not
10388 * set, and "file" may contain an error message.
10389 * Return OK when some files found. "num_file" is set to the number of
10390 * matches, "file" to the array of matches. Call FreeWild() later.
10391 */
10392 int
10393gen_expand_wildcards(num_pat, pat, num_file, file, flags)
10394 int num_pat; /* number of input patterns */
10395 char_u **pat; /* array of input patterns */
10396 int *num_file; /* resulting number of files */
10397 char_u ***file; /* array of resulting files */
10398 int flags; /* EW_* flags */
10399{
10400 int i;
10401 garray_T ga;
10402 char_u *p;
10403 static int recursive = FALSE;
10404 int add_pat;
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010405#if defined(FEAT_SEARCHPATH)
10406 int did_expand_in_path = FALSE;
10407#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000010408
10409 /*
10410 * expand_env() is called to expand things like "~user". If this fails,
10411 * it calls ExpandOne(), which brings us back here. In this case, always
10412 * call the machine specific expansion function, if possible. Otherwise,
10413 * return FAIL.
10414 */
10415 if (recursive)
10416#ifdef SPECIAL_WILDCHAR
10417 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
10418#else
10419 return FAIL;
10420#endif
10421
10422#ifdef SPECIAL_WILDCHAR
10423 /*
10424 * If there are any special wildcard characters which we cannot handle
10425 * here, call machine specific function for all the expansion. This
10426 * avoids starting the shell for each argument separately.
10427 * For `=expr` do use the internal function.
10428 */
10429 for (i = 0; i < num_pat; i++)
10430 {
10431 if (vim_strpbrk(pat[i], (char_u *)SPECIAL_WILDCHAR) != NULL
10432# ifdef VIM_BACKTICK
10433 && !(vim_backtick(pat[i]) && pat[i][1] == '=')
10434# endif
10435 )
10436 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
10437 }
10438#endif
10439
10440 recursive = TRUE;
10441
10442 /*
10443 * The matching file names are stored in a growarray. Init it empty.
10444 */
10445 ga_init2(&ga, (int)sizeof(char_u *), 30);
10446
10447 for (i = 0; i < num_pat; ++i)
10448 {
10449 add_pat = -1;
10450 p = pat[i];
10451
10452#ifdef VIM_BACKTICK
10453 if (vim_backtick(p))
10454 add_pat = expand_backtick(&ga, p, flags);
10455 else
10456#endif
10457 {
10458 /*
10459 * First expand environment variables, "~/" and "~user/".
10460 */
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010461 if (vim_strchr(p, '$') != NULL || *p == '~')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010462 {
Bram Moolenaar9f0545d2007-09-26 20:36:32 +000010463 p = expand_env_save_opt(p, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010464 if (p == NULL)
10465 p = pat[i];
10466#ifdef UNIX
10467 /*
10468 * On Unix, if expand_env() can't expand an environment
10469 * variable, use the shell to do that. Discard previously
10470 * found file names and start all over again.
10471 */
Bram Moolenaar9bc040c2010-08-11 22:05:57 +020010472 else if (vim_strchr(p, '$') != NULL || *p == '~')
Bram Moolenaar071d4272004-06-13 20:20:40 +000010473 {
10474 vim_free(p);
Bram Moolenaar782027e2009-06-24 14:25:49 +000010475 ga_clear_strings(&ga);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010476 i = mch_expand_wildcards(num_pat, pat, num_file, file,
10477 flags);
10478 recursive = FALSE;
10479 return i;
10480 }
10481#endif
10482 }
10483
10484 /*
10485 * If there are wildcards: Expand file names and add each match to
10486 * the list. If there is no match, and EW_NOTFOUND is given, add
10487 * the pattern.
10488 * If there are no wildcards: Add the file name if it exists or
10489 * when EW_NOTFOUND is given.
10490 */
10491 if (mch_has_exp_wildcard(p))
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010492 {
10493#if defined(FEAT_SEARCHPATH)
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010494 if ((flags & EW_PATH)
10495 && !mch_isFullName(p)
10496 && !(p[0] == '.'
10497 && (vim_ispathsep(p[1])
10498 || (p[1] == '.' && vim_ispathsep(p[2]))))
10499 )
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010500 {
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010501 /* :find completion where 'path' is used.
10502 * Recursiveness is OK here. */
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010503 recursive = FALSE;
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010504 add_pat = expand_in_path(&ga, p, flags);
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010505 recursive = TRUE;
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010506 did_expand_in_path = TRUE;
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +020010507 }
Bram Moolenaarcc448b32010-07-14 16:52:17 +020010508 else
10509#endif
10510 add_pat = mch_expandpath(&ga, p, flags);
10511 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010512 }
10513
10514 if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
10515 {
10516 char_u *t = backslash_halve_save(p);
10517
10518#if defined(MACOS_CLASSIC)
10519 slash_to_colon(t);
10520#endif
10521 /* When EW_NOTFOUND is used, always add files and dirs. Makes
10522 * "vim c:/" work. */
10523 if (flags & EW_NOTFOUND)
10524 addfile(&ga, t, flags | EW_DIR | EW_FILE);
10525 else if (mch_getperm(t) >= 0)
10526 addfile(&ga, t, flags);
10527 vim_free(t);
10528 }
10529
Bram Moolenaarb28ebbc2010-07-14 16:59:57 +020010530#if defined(FEAT_SEARCHPATH)
Bram Moolenaard732f9a2010-08-15 13:29:11 +020010531 if (did_expand_in_path && ga.ga_len > 0 && (flags & EW_PATH))
Bram Moolenaarb28ebbc2010-07-14 16:59:57 +020010532 uniquefy_paths(&ga, p);
10533#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000010534 if (p != pat[i])
10535 vim_free(p);
10536 }
10537
10538 *num_file = ga.ga_len;
10539 *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data : (char_u **)"";
10540
10541 recursive = FALSE;
10542
10543 return (ga.ga_data != NULL) ? OK : FAIL;
10544}
10545
10546# ifdef VIM_BACKTICK
10547
10548/*
10549 * Return TRUE if we can expand this backtick thing here.
10550 */
10551 static int
10552vim_backtick(p)
10553 char_u *p;
10554{
10555 return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
10556}
10557
10558/*
10559 * Expand an item in `backticks` by executing it as a command.
10560 * Currently only works when pat[] starts and ends with a `.
10561 * Returns number of file names found.
10562 */
10563 static int
10564expand_backtick(gap, pat, flags)
10565 garray_T *gap;
10566 char_u *pat;
10567 int flags; /* EW_* flags */
10568{
10569 char_u *p;
10570 char_u *cmd;
10571 char_u *buffer;
10572 int cnt = 0;
10573 int i;
10574
10575 /* Create the command: lop off the backticks. */
10576 cmd = vim_strnsave(pat + 1, (int)STRLEN(pat) - 2);
10577 if (cmd == NULL)
10578 return 0;
10579
10580#ifdef FEAT_EVAL
10581 if (*cmd == '=') /* `={expr}`: Expand expression */
Bram Moolenaar362e1a32006-03-06 23:29:24 +000010582 buffer = eval_to_string(cmd + 1, &p, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010583 else
10584#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010585 buffer = get_cmd_output(cmd, NULL,
10586 (flags & EW_SILENT) ? SHELL_SILENT : 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010587 vim_free(cmd);
10588 if (buffer == NULL)
10589 return 0;
10590
10591 cmd = buffer;
10592 while (*cmd != NUL)
10593 {
10594 cmd = skipwhite(cmd); /* skip over white space */
10595 p = cmd;
10596 while (*p != NUL && *p != '\r' && *p != '\n') /* skip over entry */
10597 ++p;
10598 /* add an entry if it is not empty */
10599 if (p > cmd)
10600 {
10601 i = *p;
10602 *p = NUL;
10603 addfile(gap, cmd, flags);
10604 *p = i;
10605 ++cnt;
10606 }
10607 cmd = p;
10608 while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
10609 ++cmd;
10610 }
10611
10612 vim_free(buffer);
10613 return cnt;
10614}
10615# endif /* VIM_BACKTICK */
10616
10617/*
10618 * Add a file to a file list. Accepted flags:
10619 * EW_DIR add directories
10620 * EW_FILE add files
Bram Moolenaar1f35bf92006-03-07 22:38:47 +000010621 * EW_EXEC add executable files
Bram Moolenaar071d4272004-06-13 20:20:40 +000010622 * EW_NOTFOUND add even when it doesn't exist
10623 * EW_ADDSLASH add slash after directory name
10624 */
10625 void
10626addfile(gap, f, flags)
10627 garray_T *gap;
10628 char_u *f; /* filename */
10629 int flags;
10630{
10631 char_u *p;
10632 int isdir;
10633
10634 /* if the file/dir doesn't exist, may not add it */
10635 if (!(flags & EW_NOTFOUND) && mch_getperm(f) < 0)
10636 return;
10637
10638#ifdef FNAME_ILLEGAL
10639 /* if the file/dir contains illegal characters, don't add it */
10640 if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
10641 return;
10642#endif
10643
10644 isdir = mch_isdir(f);
10645 if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
10646 return;
10647
Bram Moolenaar1f35bf92006-03-07 22:38:47 +000010648 /* If the file isn't executable, may not add it. Do accept directories. */
10649 if (!isdir && (flags & EW_EXEC) && !mch_can_exe(f))
10650 return;
10651
Bram Moolenaar071d4272004-06-13 20:20:40 +000010652 /* Make room for another item in the file list. */
10653 if (ga_grow(gap, 1) == FAIL)
10654 return;
10655
10656 p = alloc((unsigned)(STRLEN(f) + 1 + isdir));
10657 if (p == NULL)
10658 return;
10659
10660 STRCPY(p, f);
10661#ifdef BACKSLASH_IN_FILENAME
10662 slash_adjust(p);
10663#endif
10664 /*
10665 * Append a slash or backslash after directory names if none is present.
10666 */
10667#ifndef DONT_ADD_PATHSEP_TO_DIR
10668 if (isdir && (flags & EW_ADDSLASH))
10669 add_pathsep(p);
10670#endif
10671 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010672}
10673#endif /* !NO_EXPANDPATH */
10674
10675#if defined(VIM_BACKTICK) || defined(FEAT_EVAL) || defined(PROTO)
10676
10677#ifndef SEEK_SET
10678# define SEEK_SET 0
10679#endif
10680#ifndef SEEK_END
10681# define SEEK_END 2
10682#endif
10683
10684/*
10685 * Get the stdout of an external command.
10686 * Returns an allocated string, or NULL for error.
10687 */
10688 char_u *
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010689get_cmd_output(cmd, infile, flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010690 char_u *cmd;
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010691 char_u *infile; /* optional input file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010692 int flags; /* can be SHELL_SILENT */
10693{
10694 char_u *tempname;
10695 char_u *command;
10696 char_u *buffer = NULL;
10697 int len;
10698 int i = 0;
10699 FILE *fd;
10700
10701 if (check_restricted() || check_secure())
10702 return NULL;
10703
10704 /* get a name for the temp file */
10705 if ((tempname = vim_tempname('o')) == NULL)
10706 {
10707 EMSG(_(e_notmp));
10708 return NULL;
10709 }
10710
10711 /* Add the redirection stuff */
Bram Moolenaarc0197e22004-09-13 20:26:32 +000010712 command = make_filter_cmd(cmd, infile, tempname);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010713 if (command == NULL)
10714 goto done;
10715
10716 /*
10717 * Call the shell to execute the command (errors are ignored).
10718 * Don't check timestamps here.
10719 */
10720 ++no_check_timestamps;
10721 call_shell(command, SHELL_DOOUT | SHELL_EXPAND | flags);
10722 --no_check_timestamps;
10723
10724 vim_free(command);
10725
10726 /*
10727 * read the names from the file into memory
10728 */
10729# ifdef VMS
Bram Moolenaar25394022007-05-10 19:06:20 +000010730 /* created temporary file is not always readable as binary */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010731 fd = mch_fopen((char *)tempname, "r");
10732# else
10733 fd = mch_fopen((char *)tempname, READBIN);
10734# endif
10735
10736 if (fd == NULL)
10737 {
10738 EMSG2(_(e_notopen), tempname);
10739 goto done;
10740 }
10741
10742 fseek(fd, 0L, SEEK_END);
10743 len = ftell(fd); /* get size of temp file */
10744 fseek(fd, 0L, SEEK_SET);
10745
10746 buffer = alloc(len + 1);
10747 if (buffer != NULL)
10748 i = (int)fread((char *)buffer, (size_t)1, (size_t)len, fd);
10749 fclose(fd);
10750 mch_remove(tempname);
10751 if (buffer == NULL)
10752 goto done;
10753#ifdef VMS
10754 len = i; /* VMS doesn't give us what we asked for... */
10755#endif
10756 if (i != len)
10757 {
10758 EMSG2(_(e_notread), tempname);
10759 vim_free(buffer);
10760 buffer = NULL;
10761 }
10762 else
Bram Moolenaar162bd912010-07-28 22:29:10 +020010763 buffer[len] = NUL; /* make sure the buffer is terminated */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010764
10765done:
10766 vim_free(tempname);
10767 return buffer;
10768}
10769#endif
10770
10771/*
10772 * Free the list of files returned by expand_wildcards() or other expansion
10773 * functions.
10774 */
10775 void
10776FreeWild(count, files)
10777 int count;
10778 char_u **files;
10779{
Bram Moolenaarfc1421e2006-04-20 22:17:20 +000010780 if (count <= 0 || files == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010781 return;
10782#if defined(__EMX__) && defined(__ALWAYS_HAS_TRAILING_NULL_POINTER) /* XXX */
10783 /*
10784 * Is this still OK for when other functions than expand_wildcards() have
10785 * been used???
10786 */
10787 _fnexplodefree((char **)files);
10788#else
10789 while (count--)
10790 vim_free(files[count]);
10791 vim_free(files);
10792#endif
10793}
10794
10795/*
Bram Moolenaara9dc3752010-07-11 20:46:53 +020010796 * Return TRUE when need to go to Insert mode because of 'insertmode'.
Bram Moolenaar071d4272004-06-13 20:20:40 +000010797 * Don't do this when still processing a command or a mapping.
10798 * Don't do this when inside a ":normal" command.
10799 */
10800 int
10801goto_im()
10802{
10803 return (p_im && stuff_empty() && typebuf_typed());
10804}