blob: c6207ff042a11ab86c8c5d5e875934de0433fc77 [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 * misc2.c: Various functions.
12 */
13#include "vim.h"
14
Bram Moolenaarf461c8e2005-06-25 23:04:51 +000015static char_u *username = NULL; /* cached result of mch_get_user_name() */
16
17static char_u *ff_expand_buffer = NULL; /* used for expanding filenames */
18
Bram Moolenaar071d4272004-06-13 20:20:40 +000019#if defined(FEAT_VIRTUALEDIT) || defined(PROTO)
20static int coladvance2 __ARGS((pos_T *pos, int addspaces, int finetune, colnr_T wcol));
21
22/*
23 * Return TRUE if in the current mode we need to use virtual.
24 */
25 int
26virtual_active()
27{
28 /* While an operator is being executed we return "virtual_op", because
29 * VIsual_active has already been reset, thus we can't check for "block"
30 * being used. */
31 if (virtual_op != MAYBE)
32 return virtual_op;
33 return (ve_flags == VE_ALL
34# ifdef FEAT_VISUAL
35 || ((ve_flags & VE_BLOCK) && VIsual_active && VIsual_mode == Ctrl_V)
36# endif
37 || ((ve_flags & VE_INSERT) && (State & INSERT)));
38}
39
40/*
41 * Get the screen position of the cursor.
42 */
43 int
44getviscol()
45{
46 colnr_T x;
47
48 getvvcol(curwin, &curwin->w_cursor, &x, NULL, NULL);
49 return (int)x;
50}
51
52/*
53 * Get the screen position of character col with a coladd in the cursor line.
54 */
55 int
56getviscol2(col, coladd)
57 colnr_T col;
58 colnr_T coladd;
59{
60 colnr_T x;
61 pos_T pos;
62
63 pos.lnum = curwin->w_cursor.lnum;
64 pos.col = col;
65 pos.coladd = coladd;
66 getvvcol(curwin, &pos, &x, NULL, NULL);
67 return (int)x;
68}
69
70/*
Bram Moolenaar7aa9f6a2007-05-10 18:00:30 +000071 * Go to column "wcol", and add/insert white space as necessary to get the
Bram Moolenaar071d4272004-06-13 20:20:40 +000072 * cursor in that column.
73 * The caller must have saved the cursor line for undo!
74 */
75 int
76coladvance_force(wcol)
77 colnr_T wcol;
78{
79 int rc = coladvance2(&curwin->w_cursor, TRUE, FALSE, wcol);
80
81 if (wcol == MAXCOL)
82 curwin->w_valid &= ~VALID_VIRTCOL;
83 else
84 {
85 /* Virtcol is valid */
86 curwin->w_valid |= VALID_VIRTCOL;
87 curwin->w_virtcol = wcol;
88 }
89 return rc;
90}
91#endif
92
93/*
94 * Try to advance the Cursor to the specified screen column.
95 * If virtual editing: fine tune the cursor position.
96 * Note that all virtual positions off the end of a line should share
97 * a curwin->w_cursor.col value (n.b. this is equal to STRLEN(line)),
98 * beginning at coladd 0.
99 *
100 * return OK if desired column is reached, FAIL if not
101 */
102 int
103coladvance(wcol)
104 colnr_T wcol;
105{
106 int rc = getvpos(&curwin->w_cursor, wcol);
107
108 if (wcol == MAXCOL || rc == FAIL)
109 curwin->w_valid &= ~VALID_VIRTCOL;
Bram Moolenaardfccaf02004-12-31 20:56:11 +0000110 else if (*ml_get_cursor() != TAB)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000111 {
Bram Moolenaardfccaf02004-12-31 20:56:11 +0000112 /* Virtcol is valid when not on a TAB */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000113 curwin->w_valid |= VALID_VIRTCOL;
114 curwin->w_virtcol = wcol;
115 }
116 return rc;
117}
118
119/*
120 * Return in "pos" the position of the cursor advanced to screen column "wcol".
121 * return OK if desired column is reached, FAIL if not
122 */
123 int
124getvpos(pos, wcol)
125 pos_T *pos;
126 colnr_T wcol;
127{
128#ifdef FEAT_VIRTUALEDIT
129 return coladvance2(pos, FALSE, virtual_active(), wcol);
130}
131
132 static int
133coladvance2(pos, addspaces, finetune, wcol)
134 pos_T *pos;
135 int addspaces; /* change the text to achieve our goal? */
Bram Moolenaar7aa9f6a2007-05-10 18:00:30 +0000136 int finetune; /* change char offset for the exact column */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000137 colnr_T wcol; /* column to move to */
138{
139#endif
140 int idx;
141 char_u *ptr;
142 char_u *line;
143 colnr_T col = 0;
144 int csize = 0;
145 int one_more;
146#ifdef FEAT_LINEBREAK
147 int head = 0;
148#endif
149
Bram Moolenaarefd2bf12006-03-16 21:41:35 +0000150 one_more = (State & INSERT)
151 || restart_edit != NUL
Bram Moolenaar071d4272004-06-13 20:20:40 +0000152#ifdef FEAT_VISUAL
Bram Moolenaarefd2bf12006-03-16 21:41:35 +0000153 || (VIsual_active && *p_sel != 'o')
Bram Moolenaar071d4272004-06-13 20:20:40 +0000154#endif
Bram Moolenaarefd2bf12006-03-16 21:41:35 +0000155#ifdef FEAT_VIRTUALEDIT
Bram Moolenaar97b2ad32006-03-18 21:40:56 +0000156 || ((ve_flags & VE_ONEMORE) && wcol < MAXCOL)
Bram Moolenaarefd2bf12006-03-16 21:41:35 +0000157#endif
158 ;
Bram Moolenaara1381de2009-11-03 15:44:21 +0000159 line = ml_get_buf(curbuf, pos->lnum, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000160
161 if (wcol >= MAXCOL)
162 {
163 idx = (int)STRLEN(line) - 1 + one_more;
164 col = wcol;
165
166#ifdef FEAT_VIRTUALEDIT
167 if ((addspaces || finetune) && !VIsual_active)
168 {
169 curwin->w_curswant = linetabsize(line) + one_more;
170 if (curwin->w_curswant > 0)
171 --curwin->w_curswant;
172 }
173#endif
174 }
175 else
176 {
177#ifdef FEAT_VIRTUALEDIT
178 int width = W_WIDTH(curwin) - win_col_off(curwin);
179
Bram Moolenaarebefac62005-12-28 22:39:57 +0000180 if (finetune
Bram Moolenaar071d4272004-06-13 20:20:40 +0000181 && curwin->w_p_wrap
182# ifdef FEAT_VERTSPLIT
183 && curwin->w_width != 0
184# endif
185 && wcol >= (colnr_T)width)
186 {
187 csize = linetabsize(line);
188 if (csize > 0)
189 csize--;
190
Bram Moolenaarebefac62005-12-28 22:39:57 +0000191 if (wcol / width > (colnr_T)csize / width
192 && ((State & INSERT) == 0 || (int)wcol > csize + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000193 {
194 /* In case of line wrapping don't move the cursor beyond the
Bram Moolenaarebefac62005-12-28 22:39:57 +0000195 * right screen edge. In Insert mode allow going just beyond
196 * the last character (like what happens when typing and
197 * reaching the right window edge). */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000198 wcol = (csize / width + 1) * width - 1;
199 }
200 }
201#endif
202
Bram Moolenaar071d4272004-06-13 20:20:40 +0000203 ptr = line;
204 while (col <= wcol && *ptr != NUL)
205 {
206 /* Count a tab for what it's worth (if list mode not on) */
207#ifdef FEAT_LINEBREAK
208 csize = win_lbr_chartabsize(curwin, ptr, col, &head);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000209 mb_ptr_adv(ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000210#else
211 csize = lbr_chartabsize_adv(&ptr, col);
212#endif
213 col += csize;
214 }
215 idx = (int)(ptr - line);
216 /*
217 * Handle all the special cases. The virtual_active() check
218 * is needed to ensure that a virtual position off the end of
219 * a line has the correct indexing. The one_more comparison
220 * replaces an explicit add of one_more later on.
221 */
222 if (col > wcol || (!virtual_active() && one_more == 0))
223 {
224 idx -= 1;
225# ifdef FEAT_LINEBREAK
226 /* Don't count the chars from 'showbreak'. */
227 csize -= head;
228# endif
229 col -= csize;
230 }
231
232#ifdef FEAT_VIRTUALEDIT
233 if (virtual_active()
234 && addspaces
235 && ((col != wcol && col != wcol + 1) || csize > 1))
236 {
237 /* 'virtualedit' is set: The difference between wcol and col is
238 * filled with spaces. */
239
240 if (line[idx] == NUL)
241 {
242 /* Append spaces */
243 int correct = wcol - col;
244 char_u *newline = alloc(idx + correct + 1);
245 int t;
246
247 if (newline == NULL)
248 return FAIL;
249
250 for (t = 0; t < idx; ++t)
251 newline[t] = line[t];
252
253 for (t = 0; t < correct; ++t)
254 newline[t + idx] = ' ';
255
256 newline[idx + correct] = NUL;
257
258 ml_replace(pos->lnum, newline, FALSE);
259 changed_bytes(pos->lnum, (colnr_T)idx);
260 idx += correct;
261 col = wcol;
262 }
263 else
264 {
265 /* Break a tab */
266 int linelen = (int)STRLEN(line);
267 int correct = wcol - col - csize + 1; /* negative!! */
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000268 char_u *newline;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000269 int t, s = 0;
270 int v;
271
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000272 if (-correct > csize)
273 return FAIL;
274
275 newline = alloc(linelen + csize);
276 if (newline == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000277 return FAIL;
278
279 for (t = 0; t < linelen; t++)
280 {
281 if (t != idx)
282 newline[s++] = line[t];
283 else
284 for (v = 0; v < csize; v++)
285 newline[s++] = ' ';
286 }
287
288 newline[linelen + csize - 1] = NUL;
289
290 ml_replace(pos->lnum, newline, FALSE);
291 changed_bytes(pos->lnum, idx);
292 idx += (csize - 1 + correct);
293 col += correct;
294 }
295 }
296#endif
297 }
298
299 if (idx < 0)
300 pos->col = 0;
301 else
302 pos->col = idx;
303
304#ifdef FEAT_VIRTUALEDIT
305 pos->coladd = 0;
306
307 if (finetune)
308 {
309 if (wcol == MAXCOL)
310 {
311 /* The width of the last character is used to set coladd. */
312 if (!one_more)
313 {
314 colnr_T scol, ecol;
315
316 getvcol(curwin, pos, &scol, NULL, &ecol);
317 pos->coladd = ecol - scol;
318 }
319 }
320 else
321 {
322 int b = (int)wcol - (int)col;
323
324 /* The difference between wcol and col is used to set coladd. */
325 if (b > 0 && b < (MAXCOL - 2 * W_WIDTH(curwin)))
326 pos->coladd = b;
327
328 col += b;
329 }
330 }
331#endif
332
333#ifdef FEAT_MBYTE
Bram Moolenaara1381de2009-11-03 15:44:21 +0000334 /* prevent from moving onto a trail byte */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000335 if (has_mbyte)
Bram Moolenaara1381de2009-11-03 15:44:21 +0000336 mb_adjustpos(pos);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000337#endif
338
339 if (col < wcol)
340 return FAIL;
341 return OK;
342}
343
344/*
Bram Moolenaar446cb832008-06-24 21:56:24 +0000345 * Increment the cursor position. See inc() for return values.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000346 */
347 int
348inc_cursor()
349{
350 return inc(&curwin->w_cursor);
351}
352
Bram Moolenaar446cb832008-06-24 21:56:24 +0000353/*
354 * Increment the line pointer "lp" crossing line boundaries as necessary.
355 * Return 1 when going to the next line.
356 * Return 2 when moving forward onto a NUL at the end of the line).
357 * Return -1 when at the end of file.
358 * Return 0 otherwise.
359 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000360 int
361inc(lp)
362 pos_T *lp;
363{
364 char_u *p = ml_get_pos(lp);
365
366 if (*p != NUL) /* still within line, move to next char (may be NUL) */
367 {
368#ifdef FEAT_MBYTE
369 if (has_mbyte)
370 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +0000371 int l = (*mb_ptr2len)(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000372
373 lp->col += l;
374 return ((p[l] != NUL) ? 0 : 2);
375 }
376#endif
377 lp->col++;
378#ifdef FEAT_VIRTUALEDIT
379 lp->coladd = 0;
380#endif
381 return ((p[1] != NUL) ? 0 : 2);
382 }
383 if (lp->lnum != curbuf->b_ml.ml_line_count) /* there is a next line */
384 {
385 lp->col = 0;
386 lp->lnum++;
387#ifdef FEAT_VIRTUALEDIT
388 lp->coladd = 0;
389#endif
390 return 1;
391 }
392 return -1;
393}
394
395/*
396 * incl(lp): same as inc(), but skip the NUL at the end of non-empty lines
397 */
398 int
399incl(lp)
400 pos_T *lp;
401{
402 int r;
403
404 if ((r = inc(lp)) >= 1 && lp->col)
405 r = inc(lp);
406 return r;
407}
408
409/*
410 * dec(p)
411 *
412 * Decrement the line pointer 'p' crossing line boundaries as necessary.
413 * Return 1 when crossing a line, -1 when at start of file, 0 otherwise.
414 */
415 int
416dec_cursor()
417{
418 return dec(&curwin->w_cursor);
419}
420
421 int
422dec(lp)
423 pos_T *lp;
424{
425 char_u *p;
426
427#ifdef FEAT_VIRTUALEDIT
428 lp->coladd = 0;
429#endif
430 if (lp->col > 0) /* still within line */
431 {
432 lp->col--;
433#ifdef FEAT_MBYTE
434 if (has_mbyte)
435 {
436 p = ml_get(lp->lnum);
437 lp->col -= (*mb_head_off)(p, p + lp->col);
438 }
439#endif
440 return 0;
441 }
442 if (lp->lnum > 1) /* there is a prior line */
443 {
444 lp->lnum--;
445 p = ml_get(lp->lnum);
446 lp->col = (colnr_T)STRLEN(p);
447#ifdef FEAT_MBYTE
448 if (has_mbyte)
449 lp->col -= (*mb_head_off)(p, p + lp->col);
450#endif
451 return 1;
452 }
453 return -1; /* at start of file */
454}
455
456/*
457 * decl(lp): same as dec(), but skip the NUL at the end of non-empty lines
458 */
459 int
460decl(lp)
461 pos_T *lp;
462{
463 int r;
464
465 if ((r = dec(lp)) == 1 && lp->col)
466 r = dec(lp);
467 return r;
468}
469
470/*
Bram Moolenaar64486672010-05-16 15:46:46 +0200471 * Get the line number relative to the current cursor position, i.e. the
472 * difference between line number and cursor position. Only look for lines that
473 * can be visible, folded lines don't count.
474 */
475 linenr_T
476get_cursor_rel_lnum(wp, lnum)
477 win_T *wp;
478 linenr_T lnum; /* line number to get the result for */
479{
480 linenr_T cursor = wp->w_cursor.lnum;
481 linenr_T retval = 0;
482
483#ifdef FEAT_FOLDING
484 if (hasAnyFolding(wp))
485 {
486 if (lnum > cursor)
487 {
488 while (lnum > cursor)
489 {
490 (void)hasFolding(lnum, &lnum, NULL);
491 /* if lnum and cursor are in the same fold,
492 * now lnum <= cursor */
493 if (lnum > cursor)
494 retval++;
495 lnum--;
496 }
497 }
498 else if (lnum < cursor)
499 {
500 while (lnum < cursor)
501 {
502 (void)hasFolding(lnum, NULL, &lnum);
503 /* if lnum and cursor are in the same fold,
504 * now lnum >= cursor */
505 if (lnum < cursor)
506 retval--;
507 lnum++;
508 }
509 }
510 /* else if (lnum == cursor)
511 * retval = 0;
512 */
513 }
514 else
515#endif
516 retval = lnum - cursor;
517
518 return retval;
519}
520
521/*
Bram Moolenaar071d4272004-06-13 20:20:40 +0000522 * Make sure curwin->w_cursor.lnum is valid.
523 */
524 void
525check_cursor_lnum()
526{
527 if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
528 {
529#ifdef FEAT_FOLDING
530 /* If there is a closed fold at the end of the file, put the cursor in
531 * its first line. Otherwise in the last line. */
532 if (!hasFolding(curbuf->b_ml.ml_line_count,
533 &curwin->w_cursor.lnum, NULL))
534#endif
535 curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
536 }
537 if (curwin->w_cursor.lnum <= 0)
538 curwin->w_cursor.lnum = 1;
539}
540
541/*
542 * Make sure curwin->w_cursor.col is valid.
543 */
544 void
545check_cursor_col()
546{
547 colnr_T len;
548#ifdef FEAT_VIRTUALEDIT
Bram Moolenaar552c8a52009-03-11 16:29:20 +0000549 colnr_T oldcol = curwin->w_cursor.col;
550 colnr_T oldcoladd = curwin->w_cursor.col + curwin->w_cursor.coladd;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000551#endif
552
553 len = (colnr_T)STRLEN(ml_get_curline());
554 if (len == 0)
555 curwin->w_cursor.col = 0;
556 else if (curwin->w_cursor.col >= len)
557 {
Bram Moolenaar33f54432008-01-04 20:25:44 +0000558 /* Allow cursor past end-of-line when:
559 * - in Insert mode or restarting Insert mode
560 * - in Visual mode and 'selection' isn't "old"
561 * - 'virtualedit' is set */
Bram Moolenaarebefac62005-12-28 22:39:57 +0000562 if ((State & INSERT) || restart_edit
Bram Moolenaar071d4272004-06-13 20:20:40 +0000563#ifdef FEAT_VISUAL
564 || (VIsual_active && *p_sel != 'o')
565#endif
Bram Moolenaar33f54432008-01-04 20:25:44 +0000566#ifdef FEAT_VIRTUALEDIT
567 || (ve_flags & VE_ONEMORE)
568#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000569 || virtual_active())
570 curwin->w_cursor.col = len;
571 else
Bram Moolenaar87c19962007-04-26 08:54:21 +0000572 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000573 curwin->w_cursor.col = len - 1;
Bram Moolenaar87c19962007-04-26 08:54:21 +0000574#ifdef FEAT_MBYTE
575 /* prevent cursor from moving on the trail byte */
576 if (has_mbyte)
577 mb_adjust_cursor();
578#endif
579 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000580 }
Bram Moolenaar742d1ec2009-12-31 12:18:30 +0000581 else if (curwin->w_cursor.col < 0)
582 curwin->w_cursor.col = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000583
584#ifdef FEAT_VIRTUALEDIT
585 /* If virtual editing is on, we can leave the cursor on the old position,
586 * only we must set it to virtual. But don't do it when at the end of the
587 * line. */
588 if (oldcol == MAXCOL)
589 curwin->w_cursor.coladd = 0;
590 else if (ve_flags == VE_ALL)
Bram Moolenaar552c8a52009-03-11 16:29:20 +0000591 {
592 if (oldcoladd > curwin->w_cursor.col)
593 curwin->w_cursor.coladd = oldcoladd - curwin->w_cursor.col;
594 else
595 /* avoid weird number when there is a miscalculation or overflow */
596 curwin->w_cursor.coladd = 0;
597 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000598#endif
599}
600
601/*
602 * make sure curwin->w_cursor in on a valid character
603 */
604 void
605check_cursor()
606{
607 check_cursor_lnum();
608 check_cursor_col();
609}
610
611#if defined(FEAT_TEXTOBJ) || defined(PROTO)
612/*
613 * Make sure curwin->w_cursor is not on the NUL at the end of the line.
614 * Allow it when in Visual mode and 'selection' is not "old".
615 */
616 void
617adjust_cursor_col()
618{
619 if (curwin->w_cursor.col > 0
620# ifdef FEAT_VISUAL
621 && (!VIsual_active || *p_sel == 'o')
622# endif
623 && gchar_cursor() == NUL)
624 --curwin->w_cursor.col;
625}
626#endif
627
628/*
629 * When curwin->w_leftcol has changed, adjust the cursor position.
630 * Return TRUE if the cursor was moved.
631 */
632 int
633leftcol_changed()
634{
635 long lastcol;
636 colnr_T s, e;
637 int retval = FALSE;
638
639 changed_cline_bef_curs();
640 lastcol = curwin->w_leftcol + W_WIDTH(curwin) - curwin_col_off() - 1;
641 validate_virtcol();
642
643 /*
644 * If the cursor is right or left of the screen, move it to last or first
645 * character.
646 */
647 if (curwin->w_virtcol > (colnr_T)(lastcol - p_siso))
648 {
649 retval = TRUE;
650 coladvance((colnr_T)(lastcol - p_siso));
651 }
652 else if (curwin->w_virtcol < curwin->w_leftcol + p_siso)
653 {
654 retval = TRUE;
655 (void)coladvance((colnr_T)(curwin->w_leftcol + p_siso));
656 }
657
658 /*
659 * If the start of the character under the cursor is not on the screen,
660 * advance the cursor one more char. If this fails (last char of the
661 * line) adjust the scrolling.
662 */
663 getvvcol(curwin, &curwin->w_cursor, &s, NULL, &e);
664 if (e > (colnr_T)lastcol)
665 {
666 retval = TRUE;
667 coladvance(s - 1);
668 }
669 else if (s < curwin->w_leftcol)
670 {
671 retval = TRUE;
672 if (coladvance(e + 1) == FAIL) /* there isn't another character */
673 {
674 curwin->w_leftcol = s; /* adjust w_leftcol instead */
675 changed_cline_bef_curs();
676 }
677 }
678
679 if (retval)
680 curwin->w_set_curswant = TRUE;
681 redraw_later(NOT_VALID);
682 return retval;
683}
684
685/**********************************************************************
686 * Various routines dealing with allocation and deallocation of memory.
687 */
688
689#if defined(MEM_PROFILE) || defined(PROTO)
690
691# define MEM_SIZES 8200
692static long_u mem_allocs[MEM_SIZES];
693static long_u mem_frees[MEM_SIZES];
694static long_u mem_allocated;
695static long_u mem_freed;
696static long_u mem_peak;
697static long_u num_alloc;
698static long_u num_freed;
699
700static void mem_pre_alloc_s __ARGS((size_t *sizep));
701static void mem_pre_alloc_l __ARGS((long_u *sizep));
702static void mem_post_alloc __ARGS((void **pp, size_t size));
703static void mem_pre_free __ARGS((void **pp));
704
705 static void
706mem_pre_alloc_s(sizep)
707 size_t *sizep;
708{
709 *sizep += sizeof(size_t);
710}
711
712 static void
713mem_pre_alloc_l(sizep)
714 long_u *sizep;
715{
716 *sizep += sizeof(size_t);
717}
718
719 static void
720mem_post_alloc(pp, size)
721 void **pp;
722 size_t size;
723{
724 if (*pp == NULL)
725 return;
726 size -= sizeof(size_t);
727 *(long_u *)*pp = size;
728 if (size <= MEM_SIZES-1)
729 mem_allocs[size-1]++;
730 else
731 mem_allocs[MEM_SIZES-1]++;
732 mem_allocated += size;
733 if (mem_allocated - mem_freed > mem_peak)
734 mem_peak = mem_allocated - mem_freed;
735 num_alloc++;
736 *pp = (void *)((char *)*pp + sizeof(size_t));
737}
738
739 static void
740mem_pre_free(pp)
741 void **pp;
742{
743 long_u size;
744
745 *pp = (void *)((char *)*pp - sizeof(size_t));
746 size = *(size_t *)*pp;
747 if (size <= MEM_SIZES-1)
748 mem_frees[size-1]++;
749 else
750 mem_frees[MEM_SIZES-1]++;
751 mem_freed += size;
752 num_freed++;
753}
754
755/*
756 * called on exit via atexit()
757 */
758 void
759vim_mem_profile_dump()
760{
761 int i, j;
762
763 printf("\r\n");
764 j = 0;
765 for (i = 0; i < MEM_SIZES - 1; i++)
766 {
767 if (mem_allocs[i] || mem_frees[i])
768 {
769 if (mem_frees[i] > mem_allocs[i])
770 printf("\r\n%s", _("ERROR: "));
771 printf("[%4d / %4lu-%-4lu] ", i + 1, mem_allocs[i], mem_frees[i]);
772 j++;
773 if (j > 3)
774 {
775 j = 0;
776 printf("\r\n");
777 }
778 }
779 }
780
781 i = MEM_SIZES - 1;
782 if (mem_allocs[i])
783 {
784 printf("\r\n");
785 if (mem_frees[i] > mem_allocs[i])
Bram Moolenaar2f1e0502010-08-13 11:18:02 +0200786 puts(_("ERROR: "));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000787 printf("[>%d / %4lu-%-4lu]", i, mem_allocs[i], mem_frees[i]);
788 }
789
790 printf(_("\n[bytes] total alloc-freed %lu-%lu, in use %lu, peak use %lu\n"),
791 mem_allocated, mem_freed, mem_allocated - mem_freed, mem_peak);
792 printf(_("[calls] total re/malloc()'s %lu, total free()'s %lu\n\n"),
793 num_alloc, num_freed);
794}
795
796#endif /* MEM_PROFILE */
797
798/*
799 * Some memory is reserved for error messages and for being able to
800 * call mf_release_all(), which needs some memory for mf_trans_add().
801 */
802#if defined(MSDOS) && !defined(DJGPP)
803# define SMALL_MEM
804# define KEEP_ROOM 8192L
805#else
806# define KEEP_ROOM (2 * 8192L)
807#endif
808
809/*
Bram Moolenaar2a329742008-04-01 12:53:43 +0000810 * Note: if unsigned is 16 bits we can only allocate up to 64K with alloc().
Bram Moolenaar071d4272004-06-13 20:20:40 +0000811 * Use lalloc for larger blocks.
812 */
813 char_u *
814alloc(size)
815 unsigned size;
816{
817 return (lalloc((long_u)size, TRUE));
818}
819
820/*
821 * Allocate memory and set all bytes to zero.
822 */
823 char_u *
824alloc_clear(size)
825 unsigned size;
826{
827 char_u *p;
828
Bram Moolenaar2f1e0502010-08-13 11:18:02 +0200829 p = lalloc((long_u)size, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000830 if (p != NULL)
831 (void)vim_memset(p, 0, (size_t)size);
832 return p;
833}
834
835/*
836 * alloc() with check for maximum line length
837 */
838 char_u *
839alloc_check(size)
840 unsigned size;
841{
842#if !defined(UNIX) && !defined(__EMX__)
843 if (sizeof(int) == 2 && size > 0x7fff)
844 {
845 /* Don't hide this message */
846 emsg_silent = 0;
847 EMSG(_("E340: Line is becoming too long"));
848 return NULL;
849 }
850#endif
851 return (lalloc((long_u)size, TRUE));
852}
853
854/*
855 * Allocate memory like lalloc() and set all bytes to zero.
856 */
857 char_u *
858lalloc_clear(size, message)
859 long_u size;
860 int message;
861{
862 char_u *p;
863
864 p = (lalloc(size, message));
865 if (p != NULL)
866 (void)vim_memset(p, 0, (size_t)size);
867 return p;
868}
869
870/*
871 * Low level memory allocation function.
872 * This is used often, KEEP IT FAST!
873 */
874 char_u *
875lalloc(size, message)
876 long_u size;
877 int message;
878{
879 char_u *p; /* pointer to new storage space */
880 static int releasing = FALSE; /* don't do mf_release_all() recursive */
881 int try_again;
882#if defined(HAVE_AVAIL_MEM) && !defined(SMALL_MEM)
883 static long_u allocated = 0; /* allocated since last avail check */
884#endif
885
886 /* Safety check for allocating zero bytes */
887 if (size == 0)
888 {
889 /* Don't hide this message */
890 emsg_silent = 0;
891 EMSGN(_("E341: Internal error: lalloc(%ld, )"), size);
892 return NULL;
893 }
894
895#ifdef MEM_PROFILE
896 mem_pre_alloc_l(&size);
897#endif
898
899#if defined(MSDOS) && !defined(DJGPP)
900 if (size >= 0xfff0) /* in MSDOS we can't deal with >64K blocks */
901 p = NULL;
902 else
903#endif
904
905 /*
906 * Loop when out of memory: Try to release some memfile blocks and
907 * if some blocks are released call malloc again.
908 */
909 for (;;)
910 {
911 /*
912 * Handle three kind of systems:
913 * 1. No check for available memory: Just return.
914 * 2. Slow check for available memory: call mch_avail_mem() after
915 * allocating KEEP_ROOM amount of memory.
916 * 3. Strict check for available memory: call mch_avail_mem()
917 */
918 if ((p = (char_u *)malloc((size_t)size)) != NULL)
919 {
920#ifndef HAVE_AVAIL_MEM
921 /* 1. No check for available memory: Just return. */
922 goto theend;
923#else
924# ifndef SMALL_MEM
925 /* 2. Slow check for available memory: call mch_avail_mem() after
926 * allocating (KEEP_ROOM / 2) amount of memory. */
927 allocated += size;
928 if (allocated < KEEP_ROOM / 2)
929 goto theend;
930 allocated = 0;
931# endif
932 /* 3. check for available memory: call mch_avail_mem() */
933 if (mch_avail_mem(TRUE) < KEEP_ROOM && !releasing)
934 {
Bram Moolenaar5a221812008-11-12 12:08:45 +0000935 free((char *)p); /* System is low... no go! */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000936 p = NULL;
937 }
938 else
939 goto theend;
940#endif
941 }
942 /*
943 * Remember that mf_release_all() is being called to avoid an endless
944 * loop, because mf_release_all() may call alloc() recursively.
945 */
946 if (releasing)
947 break;
948 releasing = TRUE;
Bram Moolenaar661b1822005-07-28 22:36:45 +0000949
950 clear_sb_text(); /* free any scrollback text */
951 try_again = mf_release_all(); /* release as many blocks as possible */
Bram Moolenaar39a58ca2005-06-27 22:42:44 +0000952#ifdef FEAT_EVAL
Bram Moolenaar661b1822005-07-28 22:36:45 +0000953 try_again |= garbage_collect(); /* cleanup recursive lists/dicts */
Bram Moolenaar39a58ca2005-06-27 22:42:44 +0000954#endif
Bram Moolenaar661b1822005-07-28 22:36:45 +0000955
Bram Moolenaar071d4272004-06-13 20:20:40 +0000956 releasing = FALSE;
957 if (!try_again)
958 break;
959 }
960
961 if (message && p == NULL)
962 do_outofmem_msg(size);
963
964theend:
965#ifdef MEM_PROFILE
966 mem_post_alloc((void **)&p, (size_t)size);
967#endif
968 return p;
969}
970
971#if defined(MEM_PROFILE) || defined(PROTO)
972/*
973 * realloc() with memory profiling.
974 */
975 void *
976mem_realloc(ptr, size)
977 void *ptr;
978 size_t size;
979{
980 void *p;
981
982 mem_pre_free(&ptr);
983 mem_pre_alloc_s(&size);
984
985 p = realloc(ptr, size);
986
987 mem_post_alloc(&p, size);
988
989 return p;
990}
991#endif
992
993/*
994* Avoid repeating the error message many times (they take 1 second each).
995* Did_outofmem_msg is reset when a character is read.
996*/
997 void
998do_outofmem_msg(size)
999 long_u size;
1000{
1001 if (!did_outofmem_msg)
1002 {
1003 /* Don't hide this message */
1004 emsg_silent = 0;
1005 EMSGN(_("E342: Out of memory! (allocating %lu bytes)"), size);
1006 did_outofmem_msg = TRUE;
1007 }
1008}
1009
Bram Moolenaar1ec484f2005-06-24 23:07:47 +00001010#if defined(EXITFREE) || defined(PROTO)
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00001011
1012# if defined(FEAT_SEARCHPATH)
1013static void free_findfile __ARGS((void));
1014# endif
1015
Bram Moolenaar1ec484f2005-06-24 23:07:47 +00001016/*
1017 * Free everything that we allocated.
1018 * Can be used to detect memory leaks, e.g., with ccmalloc.
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00001019 * NOTE: This is tricky! Things are freed that functions depend on. Don't be
1020 * surprised if Vim crashes...
1021 * Some things can't be freed, esp. things local to a library function.
Bram Moolenaar1ec484f2005-06-24 23:07:47 +00001022 */
1023 void
1024free_all_mem()
1025{
1026 buf_T *buf, *nextbuf;
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00001027 static int entered = FALSE;
1028
1029 /* When we cause a crash here it is caught and Vim tries to exit cleanly.
1030 * Don't try freeing everything again. */
1031 if (entered)
1032 return;
1033 entered = TRUE;
Bram Moolenaar1ec484f2005-06-24 23:07:47 +00001034
Bram Moolenaare0ca7b22007-11-24 20:28:24 +00001035# ifdef FEAT_AUTOCMD
Bram Moolenaar78ab3312007-09-29 12:16:41 +00001036 block_autocmds(); /* don't want to trigger autocommands here */
Bram Moolenaare0ca7b22007-11-24 20:28:24 +00001037# endif
Bram Moolenaar1ec484f2005-06-24 23:07:47 +00001038
Bram Moolenaare0ca7b22007-11-24 20:28:24 +00001039# ifdef FEAT_WINDOWS
Bram Moolenaar5bedfc62010-07-20 22:30:01 +02001040 /* Close all tabs and windows. Reset 'equalalways' to avoid redraws. */
1041 p_ea = FALSE;
Bram Moolenaar7d47b6e2006-03-15 22:59:18 +00001042 if (first_tabpage->tp_next != NULL)
1043 do_cmdline_cmd((char_u *)"tabonly!");
1044 if (firstwin != lastwin)
1045 do_cmdline_cmd((char_u *)"only!");
Bram Moolenaare0ca7b22007-11-24 20:28:24 +00001046# endif
Bram Moolenaar997fb4b2006-02-17 21:53:23 +00001047
Bram Moolenaarc4956c82006-03-12 21:58:43 +00001048# if defined(FEAT_SPELL)
Bram Moolenaar1ec484f2005-06-24 23:07:47 +00001049 /* Free all spell info. */
1050 spell_free_all();
1051# endif
1052
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00001053# if defined(FEAT_USR_CMDS)
Bram Moolenaar1ec484f2005-06-24 23:07:47 +00001054 /* Clear user commands (before deleting buffers). */
1055 ex_comclear(NULL);
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00001056# endif
Bram Moolenaar1ec484f2005-06-24 23:07:47 +00001057
1058# ifdef FEAT_MENU
1059 /* Clear menus. */
1060 do_cmdline_cmd((char_u *)"aunmenu *");
Bram Moolenaar21160b92009-11-11 15:56:10 +00001061# ifdef FEAT_MULTI_LANG
1062 do_cmdline_cmd((char_u *)"menutranslate clear");
1063# endif
Bram Moolenaar1ec484f2005-06-24 23:07:47 +00001064# endif
1065
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00001066 /* Clear mappings, abbreviations, breakpoints. */
Bram Moolenaar21160b92009-11-11 15:56:10 +00001067 do_cmdline_cmd((char_u *)"lmapclear");
1068 do_cmdline_cmd((char_u *)"xmapclear");
Bram Moolenaar1ec484f2005-06-24 23:07:47 +00001069 do_cmdline_cmd((char_u *)"mapclear");
1070 do_cmdline_cmd((char_u *)"mapclear!");
1071 do_cmdline_cmd((char_u *)"abclear");
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00001072# if defined(FEAT_EVAL)
1073 do_cmdline_cmd((char_u *)"breakdel *");
1074# endif
Bram Moolenaar1e498f52005-06-26 22:29:44 +00001075# if defined(FEAT_PROFILE)
1076 do_cmdline_cmd((char_u *)"profdel *");
1077# endif
Bram Moolenaarde0dfed2009-02-24 03:30:14 +00001078# if defined(FEAT_KEYMAP)
1079 do_cmdline_cmd((char_u *)"set keymap=");
1080#endif
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00001081
1082# ifdef FEAT_TITLE
1083 free_titles();
1084# endif
1085# if defined(FEAT_SEARCHPATH)
1086 free_findfile();
1087# endif
Bram Moolenaar1ec484f2005-06-24 23:07:47 +00001088
1089 /* Obviously named calls. */
Bram Moolenaar1ec484f2005-06-24 23:07:47 +00001090# if defined(FEAT_AUTOCMD)
1091 free_all_autocmds();
1092# endif
1093 clear_termcodes();
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00001094 free_all_options();
1095 free_all_marks();
1096 alist_clear(&global_alist);
1097 free_homedir();
1098 free_search_patterns();
1099 free_old_sub();
1100 free_last_insert();
1101 free_prev_shellcmd();
1102 free_regexp_stuff();
1103 free_tag_stuff();
1104 free_cd_dir();
Bram Moolenaarde0dfed2009-02-24 03:30:14 +00001105# ifdef FEAT_SIGNS
1106 free_signs();
1107# endif
Bram Moolenaare0ca7b22007-11-24 20:28:24 +00001108# ifdef FEAT_EVAL
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00001109 set_expr_line(NULL);
Bram Moolenaare0ca7b22007-11-24 20:28:24 +00001110# endif
1111# ifdef FEAT_DIFF
Bram Moolenaar997fb4b2006-02-17 21:53:23 +00001112 diff_clear(curtab);
Bram Moolenaare0ca7b22007-11-24 20:28:24 +00001113# endif
Bram Moolenaara40ceaf2006-01-13 22:35:40 +00001114 clear_sb_text(); /* free any scrollback text */
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00001115
1116 /* Free some global vars. */
1117 vim_free(username);
Bram Moolenaaraf92ee82007-10-07 13:45:08 +00001118# ifdef FEAT_CLIPBOARD
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00001119 vim_free(clip_exclude_prog);
Bram Moolenaaraf92ee82007-10-07 13:45:08 +00001120# endif
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00001121 vim_free(last_cmdline);
Bram Moolenaare0ca7b22007-11-24 20:28:24 +00001122# ifdef FEAT_CMDHIST
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00001123 vim_free(new_last_cmdline);
Bram Moolenaare0ca7b22007-11-24 20:28:24 +00001124# endif
Bram Moolenaar238a5642006-02-21 22:12:05 +00001125 set_keep_msg(NULL, 0);
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00001126 vim_free(ff_expand_buffer);
Bram Moolenaar1ec484f2005-06-24 23:07:47 +00001127
1128 /* Clear cmdline history. */
1129 p_hi = 0;
Bram Moolenaare0ca7b22007-11-24 20:28:24 +00001130# ifdef FEAT_CMDHIST
Bram Moolenaar1ec484f2005-06-24 23:07:47 +00001131 init_history();
Bram Moolenaare0ca7b22007-11-24 20:28:24 +00001132# endif
Bram Moolenaar1ec484f2005-06-24 23:07:47 +00001133
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00001134#ifdef FEAT_QUICKFIX
Bram Moolenaare0ca7b22007-11-24 20:28:24 +00001135 {
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00001136 win_T *win;
1137 tabpage_T *tab;
Bram Moolenaare0ca7b22007-11-24 20:28:24 +00001138
1139 qf_free_all(NULL);
1140 /* Free all location lists */
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00001141 FOR_ALL_TAB_WINDOWS(tab, win)
Bram Moolenaare0ca7b22007-11-24 20:28:24 +00001142 qf_free_all(win);
1143 }
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00001144#endif
1145
1146 /* Close all script inputs. */
1147 close_all_scripts();
1148
1149#if defined(FEAT_WINDOWS)
1150 /* Destroy all windows. Must come before freeing buffers. */
1151 win_free_all();
1152#endif
1153
Bram Moolenaar2a329742008-04-01 12:53:43 +00001154 /* Free all buffers. Reset 'autochdir' to avoid accessing things that
1155 * were freed already. */
1156#ifdef FEAT_AUTOCHDIR
1157 p_acd = FALSE;
1158#endif
Bram Moolenaar1ec484f2005-06-24 23:07:47 +00001159 for (buf = firstbuf; buf != NULL; )
1160 {
1161 nextbuf = buf->b_next;
1162 close_buffer(NULL, buf, DOBUF_WIPE);
1163 if (buf_valid(buf))
1164 buf = nextbuf; /* didn't work, try next one */
1165 else
1166 buf = firstbuf;
1167 }
1168
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00001169#ifdef FEAT_ARABIC
1170 free_cmdline_buf();
Bram Moolenaar1ec484f2005-06-24 23:07:47 +00001171#endif
1172
1173 /* Clear registers. */
1174 clear_registers();
1175 ResetRedobuff();
1176 ResetRedobuff();
1177
Bram Moolenaar85c79d32007-02-20 01:59:20 +00001178#if defined(FEAT_CLIENTSERVER) && defined(FEAT_X11)
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00001179 vim_free(serverDelayedStartName);
1180#endif
1181
Bram Moolenaar1ec484f2005-06-24 23:07:47 +00001182 /* highlight info */
1183 free_highlight();
1184
Bram Moolenaar1e498f52005-06-26 22:29:44 +00001185 reset_last_sourcing();
1186
Bram Moolenaar7d47b6e2006-03-15 22:59:18 +00001187#ifdef FEAT_WINDOWS
Bram Moolenaar06a89a52006-04-29 22:01:03 +00001188 free_tabpage(first_tabpage);
1189 first_tabpage = NULL;
Bram Moolenaar7d47b6e2006-03-15 22:59:18 +00001190#endif
1191
Bram Moolenaar1ec484f2005-06-24 23:07:47 +00001192# ifdef UNIX
1193 /* Machine-specific free. */
1194 mch_free_mem();
1195# endif
1196
1197 /* message history */
1198 for (;;)
1199 if (delete_first_msg() == FAIL)
1200 break;
1201
1202# ifdef FEAT_EVAL
1203 eval_clear();
1204# endif
1205
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00001206 free_termoptions();
1207
Bram Moolenaar1ec484f2005-06-24 23:07:47 +00001208 /* screenlines (can't display anything now!) */
1209 free_screenlines();
1210
1211#if defined(USE_XSMP)
1212 xsmp_close();
1213#endif
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00001214#ifdef FEAT_GUI_GTK
1215 gui_mch_free_all();
1216#endif
1217 clear_hl_tables();
Bram Moolenaar1ec484f2005-06-24 23:07:47 +00001218
1219 vim_free(IObuff);
1220 vim_free(NameBuff);
1221}
1222#endif
1223
Bram Moolenaar071d4272004-06-13 20:20:40 +00001224/*
Bram Moolenaare980d8a2010-12-08 13:11:21 +01001225 * Copy "string" into newly allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001226 */
1227 char_u *
1228vim_strsave(string)
1229 char_u *string;
1230{
1231 char_u *p;
1232 unsigned len;
1233
1234 len = (unsigned)STRLEN(string) + 1;
1235 p = alloc(len);
1236 if (p != NULL)
1237 mch_memmove(p, string, (size_t)len);
1238 return p;
1239}
1240
Bram Moolenaare980d8a2010-12-08 13:11:21 +01001241/*
1242 * Copy up to "len" bytes of "string" into newly allocated memory and
1243 * terminate with a NUL.
1244 * The allocated memory always has size "len + 1", also when "string" is
1245 * shorter.
1246 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001247 char_u *
1248vim_strnsave(string, len)
1249 char_u *string;
1250 int len;
1251{
1252 char_u *p;
1253
1254 p = alloc((unsigned)(len + 1));
1255 if (p != NULL)
1256 {
1257 STRNCPY(p, string, len);
1258 p[len] = NUL;
1259 }
1260 return p;
1261}
1262
Bram Moolenaar071d4272004-06-13 20:20:40 +00001263/*
1264 * Same as vim_strsave(), but any characters found in esc_chars are preceded
1265 * by a backslash.
1266 */
1267 char_u *
1268vim_strsave_escaped(string, esc_chars)
1269 char_u *string;
1270 char_u *esc_chars;
1271{
Bram Moolenaar2df6dcc2004-07-12 15:53:54 +00001272 return vim_strsave_escaped_ext(string, esc_chars, '\\', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001273}
1274
1275/*
1276 * Same as vim_strsave_escaped(), but when "bsl" is TRUE also escape
1277 * characters where rem_backslash() would remove the backslash.
Bram Moolenaar2df6dcc2004-07-12 15:53:54 +00001278 * Escape the characters with "cc".
Bram Moolenaar071d4272004-06-13 20:20:40 +00001279 */
1280 char_u *
Bram Moolenaar2df6dcc2004-07-12 15:53:54 +00001281vim_strsave_escaped_ext(string, esc_chars, cc, bsl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001282 char_u *string;
1283 char_u *esc_chars;
Bram Moolenaar2df6dcc2004-07-12 15:53:54 +00001284 int cc;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001285 int bsl;
1286{
1287 char_u *p;
1288 char_u *p2;
1289 char_u *escaped_string;
1290 unsigned length;
1291#ifdef FEAT_MBYTE
1292 int l;
1293#endif
1294
1295 /*
1296 * First count the number of backslashes required.
1297 * Then allocate the memory and insert them.
1298 */
1299 length = 1; /* count the trailing NUL */
1300 for (p = string; *p; p++)
1301 {
1302#ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00001303 if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001304 {
1305 length += l; /* count a multibyte char */
1306 p += l - 1;
1307 continue;
1308 }
1309#endif
1310 if (vim_strchr(esc_chars, *p) != NULL || (bsl && rem_backslash(p)))
1311 ++length; /* count a backslash */
1312 ++length; /* count an ordinary char */
1313 }
1314 escaped_string = alloc(length);
1315 if (escaped_string != NULL)
1316 {
1317 p2 = escaped_string;
1318 for (p = string; *p; p++)
1319 {
1320#ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00001321 if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001322 {
1323 mch_memmove(p2, p, (size_t)l);
1324 p2 += l;
1325 p += l - 1; /* skip multibyte char */
1326 continue;
1327 }
1328#endif
1329 if (vim_strchr(esc_chars, *p) != NULL || (bsl && rem_backslash(p)))
Bram Moolenaar2df6dcc2004-07-12 15:53:54 +00001330 *p2++ = cc;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001331 *p2++ = *p;
1332 }
1333 *p2 = NUL;
1334 }
1335 return escaped_string;
1336}
1337
Bram Moolenaar7693ec62008-07-24 18:29:37 +00001338/*
1339 * Return TRUE when 'shell' has "csh" in the tail.
1340 */
1341 int
1342csh_like_shell()
1343{
1344 return (strstr((char *)gettail(p_sh), "csh") != NULL);
1345}
Bram Moolenaar7693ec62008-07-24 18:29:37 +00001346
Bram Moolenaar60a495f2006-10-03 12:44:42 +00001347/*
1348 * Escape "string" for use as a shell argument with system().
Bram Moolenaar21160b92009-11-11 15:56:10 +00001349 * This uses single quotes, except when we know we need to use double quotes
Bram Moolenaar60a495f2006-10-03 12:44:42 +00001350 * (MS-DOS and MS-Windows without 'shellslash' set).
Bram Moolenaarffd66c42008-07-16 20:43:37 +00001351 * Escape a newline, depending on the 'shell' option.
1352 * When "do_special" is TRUE also replace "!", "%", "#" and things starting
1353 * with "<" like "<cfile>".
Bram Moolenaar60a495f2006-10-03 12:44:42 +00001354 * Returns the result in allocated memory, NULL if we have run out.
1355 */
1356 char_u *
Bram Moolenaar05bb9532008-07-04 09:44:11 +00001357vim_strsave_shellescape(string, do_special)
Bram Moolenaar60a495f2006-10-03 12:44:42 +00001358 char_u *string;
Bram Moolenaar05bb9532008-07-04 09:44:11 +00001359 int do_special;
Bram Moolenaar60a495f2006-10-03 12:44:42 +00001360{
1361 unsigned length;
1362 char_u *p;
1363 char_u *d;
1364 char_u *escaped_string;
Bram Moolenaar05bb9532008-07-04 09:44:11 +00001365 int l;
Bram Moolenaarffd66c42008-07-16 20:43:37 +00001366 int csh_like;
1367
1368 /* Only csh and similar shells expand '!' within single quotes. For sh and
1369 * the like we must not put a backslash before it, it will be taken
1370 * literally. If do_special is set the '!' will be escaped twice.
1371 * Csh also needs to have "\n" escaped twice when do_special is set. */
Bram Moolenaar7693ec62008-07-24 18:29:37 +00001372 csh_like = csh_like_shell();
Bram Moolenaar60a495f2006-10-03 12:44:42 +00001373
1374 /* First count the number of extra bytes required. */
Bram Moolenaar77f66d62007-02-20 02:16:18 +00001375 length = (unsigned)STRLEN(string) + 3; /* two quotes and a trailing NUL */
Bram Moolenaar60a495f2006-10-03 12:44:42 +00001376 for (p = string; *p != NUL; mb_ptr_adv(p))
1377 {
1378# if defined(WIN32) || defined(WIN16) || defined(DOS)
1379 if (!p_ssl)
1380 {
1381 if (*p == '"')
1382 ++length; /* " -> "" */
1383 }
1384 else
1385# endif
1386 if (*p == '\'')
1387 length += 3; /* ' => '\'' */
Bram Moolenaarffd66c42008-07-16 20:43:37 +00001388 if (*p == '\n' || (*p == '!' && (csh_like || do_special)))
1389 {
1390 ++length; /* insert backslash */
1391 if (csh_like && do_special)
1392 ++length; /* insert backslash */
1393 }
Bram Moolenaar05bb9532008-07-04 09:44:11 +00001394 if (do_special && find_cmdline_var(p, &l) >= 0)
1395 {
1396 ++length; /* insert backslash */
1397 p += l - 1;
1398 }
Bram Moolenaar60a495f2006-10-03 12:44:42 +00001399 }
1400
1401 /* Allocate memory for the result and fill it. */
1402 escaped_string = alloc(length);
1403 if (escaped_string != NULL)
1404 {
1405 d = escaped_string;
1406
1407 /* add opening quote */
1408# if defined(WIN32) || defined(WIN16) || defined(DOS)
1409 if (!p_ssl)
1410 *d++ = '"';
1411 else
1412# endif
1413 *d++ = '\'';
1414
1415 for (p = string; *p != NUL; )
1416 {
1417# if defined(WIN32) || defined(WIN16) || defined(DOS)
1418 if (!p_ssl)
1419 {
1420 if (*p == '"')
1421 {
1422 *d++ = '"';
1423 *d++ = '"';
1424 ++p;
1425 continue;
1426 }
1427 }
1428 else
1429# endif
1430 if (*p == '\'')
1431 {
Bram Moolenaar05bb9532008-07-04 09:44:11 +00001432 *d++ = '\'';
1433 *d++ = '\\';
1434 *d++ = '\'';
1435 *d++ = '\'';
Bram Moolenaar60a495f2006-10-03 12:44:42 +00001436 ++p;
1437 continue;
1438 }
Bram Moolenaarffd66c42008-07-16 20:43:37 +00001439 if (*p == '\n' || (*p == '!' && (csh_like || do_special)))
1440 {
1441 *d++ = '\\';
1442 if (csh_like && do_special)
1443 *d++ = '\\';
1444 *d++ = *p++;
1445 continue;
1446 }
Bram Moolenaar05bb9532008-07-04 09:44:11 +00001447 if (do_special && find_cmdline_var(p, &l) >= 0)
1448 {
1449 *d++ = '\\'; /* insert backslash */
1450 while (--l >= 0) /* copy the var */
1451 *d++ = *p++;
Bram Moolenaar099d01d2009-11-25 16:14:45 +00001452 continue;
Bram Moolenaar05bb9532008-07-04 09:44:11 +00001453 }
Bram Moolenaar60a495f2006-10-03 12:44:42 +00001454
1455 MB_COPY_CHAR(p, d);
1456 }
1457
1458 /* add terminating quote and finish with a NUL */
1459# if defined(WIN32) || defined(WIN16) || defined(DOS)
1460 if (!p_ssl)
1461 *d++ = '"';
1462 else
1463# endif
1464 *d++ = '\'';
1465 *d = NUL;
1466 }
1467
1468 return escaped_string;
1469}
Bram Moolenaar60a495f2006-10-03 12:44:42 +00001470
Bram Moolenaar071d4272004-06-13 20:20:40 +00001471/*
1472 * Like vim_strsave(), but make all characters uppercase.
1473 * This uses ASCII lower-to-upper case translation, language independent.
1474 */
1475 char_u *
1476vim_strsave_up(string)
1477 char_u *string;
1478{
1479 char_u *p1;
1480
1481 p1 = vim_strsave(string);
1482 vim_strup(p1);
1483 return p1;
1484}
1485
1486/*
1487 * Like vim_strnsave(), but make all characters uppercase.
1488 * This uses ASCII lower-to-upper case translation, language independent.
1489 */
1490 char_u *
1491vim_strnsave_up(string, len)
1492 char_u *string;
1493 int len;
1494{
1495 char_u *p1;
1496
1497 p1 = vim_strnsave(string, len);
1498 vim_strup(p1);
1499 return p1;
1500}
1501
1502/*
1503 * ASCII lower-to-upper case translation, language independent.
1504 */
1505 void
1506vim_strup(p)
1507 char_u *p;
1508{
1509 char_u *p2;
1510 int c;
1511
1512 if (p != NULL)
1513 {
1514 p2 = p;
1515 while ((c = *p2) != NUL)
1516#ifdef EBCDIC
1517 *p2++ = isalpha(c) ? toupper(c) : c;
1518#else
1519 *p2++ = (c < 'a' || c > 'z') ? c : (c - 0x20);
1520#endif
1521 }
1522}
1523
Bram Moolenaarc4956c82006-03-12 21:58:43 +00001524#if defined(FEAT_EVAL) || defined(FEAT_SPELL) || defined(PROTO)
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001525/*
1526 * Make string "s" all upper-case and return it in allocated memory.
1527 * Handles multi-byte characters as well as possible.
1528 * Returns NULL when out of memory.
1529 */
1530 char_u *
1531strup_save(orig)
1532 char_u *orig;
1533{
1534 char_u *p;
1535 char_u *res;
1536
1537 res = p = vim_strsave(orig);
1538
1539 if (res != NULL)
1540 while (*p != NUL)
1541 {
1542# ifdef FEAT_MBYTE
1543 int l;
1544
1545 if (enc_utf8)
1546 {
1547 int c, uc;
1548 int nl;
1549 char_u *s;
1550
1551 c = utf_ptr2char(p);
1552 uc = utf_toupper(c);
1553
1554 /* Reallocate string when byte count changes. This is rare,
1555 * thus it's OK to do another malloc()/free(). */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00001556 l = utf_ptr2len(p);
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001557 nl = utf_char2len(uc);
1558 if (nl != l)
1559 {
1560 s = alloc((unsigned)STRLEN(res) + 1 + nl - l);
1561 if (s == NULL)
1562 break;
1563 mch_memmove(s, res, p - res);
1564 STRCPY(s + (p - res) + nl, p + l);
1565 p = s + (p - res);
1566 vim_free(res);
1567 res = s;
1568 }
1569
1570 utf_char2bytes(uc, p);
1571 p += nl;
1572 }
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00001573 else if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001574 p += l; /* skip multi-byte character */
1575 else
1576# endif
1577 {
1578 *p = TOUPPER_LOC(*p); /* note that toupper() can be a macro */
1579 p++;
1580 }
1581 }
1582
1583 return res;
1584}
1585#endif
1586
Bram Moolenaar071d4272004-06-13 20:20:40 +00001587/*
1588 * copy a space a number of times
1589 */
1590 void
1591copy_spaces(ptr, count)
1592 char_u *ptr;
1593 size_t count;
1594{
1595 size_t i = count;
1596 char_u *p = ptr;
1597
1598 while (i--)
1599 *p++ = ' ';
1600}
1601
1602#if defined(FEAT_VISUALEXTRA) || defined(PROTO)
1603/*
1604 * Copy a character a number of times.
Bram Moolenaar21160b92009-11-11 15:56:10 +00001605 * Does not work for multi-byte characters!
Bram Moolenaar071d4272004-06-13 20:20:40 +00001606 */
1607 void
1608copy_chars(ptr, count, c)
1609 char_u *ptr;
1610 size_t count;
1611 int c;
1612{
1613 size_t i = count;
1614 char_u *p = ptr;
1615
1616 while (i--)
1617 *p++ = c;
1618}
1619#endif
1620
1621/*
1622 * delete spaces at the end of a string
1623 */
1624 void
1625del_trailing_spaces(ptr)
1626 char_u *ptr;
1627{
1628 char_u *q;
1629
1630 q = ptr + STRLEN(ptr);
1631 while (--q > ptr && vim_iswhite(q[0]) && q[-1] != '\\' && q[-1] != Ctrl_V)
1632 *q = NUL;
1633}
1634
1635/*
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001636 * Like strncpy(), but always terminate the result with one NUL.
Bram Moolenaard042c562005-06-30 22:04:15 +00001637 * "to" must be "len + 1" long!
Bram Moolenaar071d4272004-06-13 20:20:40 +00001638 */
1639 void
1640vim_strncpy(to, from, len)
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001641 char_u *to;
1642 char_u *from;
Bram Moolenaarbbebc852005-07-18 21:47:53 +00001643 size_t len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001644{
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001645 STRNCPY(to, from, len);
1646 to[len] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001647}
1648
1649/*
Bram Moolenaaref9d6aa2011-04-11 16:56:35 +02001650 * Like strcat(), but make sure the result fits in "tosize" bytes and is
1651 * always NUL terminated.
1652 */
1653 void
1654vim_strcat(to, from, tosize)
1655 char_u *to;
1656 char_u *from;
1657 size_t tosize;
1658{
1659 size_t tolen = STRLEN(to);
1660 size_t fromlen = STRLEN(from);
1661
1662 if (tolen + fromlen + 1 > tosize)
1663 {
1664 mch_memmove(to + tolen, from, tosize - tolen - 1);
1665 to[tosize - 1] = NUL;
1666 }
1667 else
1668 STRCPY(to + tolen, from);
1669}
1670
1671/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001672 * Isolate one part of a string option where parts are separated with
1673 * "sep_chars".
Bram Moolenaar83bab712005-08-01 21:58:57 +00001674 * The part is copied into "buf[maxlen]".
Bram Moolenaar071d4272004-06-13 20:20:40 +00001675 * "*option" is advanced to the next part.
1676 * The length is returned.
1677 */
1678 int
1679copy_option_part(option, buf, maxlen, sep_chars)
1680 char_u **option;
1681 char_u *buf;
1682 int maxlen;
1683 char *sep_chars;
1684{
1685 int len = 0;
1686 char_u *p = *option;
1687
1688 /* skip '.' at start of option part, for 'suffixes' */
1689 if (*p == '.')
1690 buf[len++] = *p++;
1691 while (*p != NUL && vim_strchr((char_u *)sep_chars, *p) == NULL)
1692 {
1693 /*
1694 * Skip backslash before a separator character and space.
1695 */
1696 if (p[0] == '\\' && vim_strchr((char_u *)sep_chars, p[1]) != NULL)
1697 ++p;
1698 if (len < maxlen - 1)
1699 buf[len++] = *p;
1700 ++p;
1701 }
1702 buf[len] = NUL;
1703
1704 if (*p != NUL && *p != ',') /* skip non-standard separator */
1705 ++p;
1706 p = skip_to_option_part(p); /* p points to next file name */
1707
1708 *option = p;
1709 return len;
1710}
1711
1712/*
Bram Moolenaar4770d092006-01-12 23:22:24 +00001713 * Replacement for free() that ignores NULL pointers.
1714 * Also skip free() when exiting for sure, this helps when we caught a deadly
1715 * signal that was caused by a crash in free().
Bram Moolenaar071d4272004-06-13 20:20:40 +00001716 */
1717 void
1718vim_free(x)
1719 void *x;
1720{
Bram Moolenaar4770d092006-01-12 23:22:24 +00001721 if (x != NULL && !really_exiting)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001722 {
1723#ifdef MEM_PROFILE
1724 mem_pre_free(&x);
1725#endif
1726 free(x);
1727 }
1728}
1729
1730#ifndef HAVE_MEMSET
1731 void *
1732vim_memset(ptr, c, size)
1733 void *ptr;
1734 int c;
1735 size_t size;
1736{
1737 char *p = ptr;
1738
1739 while (size-- > 0)
1740 *p++ = c;
1741 return ptr;
1742}
1743#endif
1744
1745#ifdef VIM_MEMCMP
1746/*
1747 * Return zero when "b1" and "b2" are the same for "len" bytes.
1748 * Return non-zero otherwise.
1749 */
1750 int
1751vim_memcmp(b1, b2, len)
1752 void *b1;
1753 void *b2;
1754 size_t len;
1755{
1756 char_u *p1 = (char_u *)b1, *p2 = (char_u *)b2;
1757
1758 for ( ; len > 0; --len)
1759 {
1760 if (*p1 != *p2)
1761 return 1;
1762 ++p1;
1763 ++p2;
1764 }
1765 return 0;
1766}
1767#endif
1768
1769#ifdef VIM_MEMMOVE
1770/*
1771 * Version of memmove() that handles overlapping source and destination.
1772 * For systems that don't have a function that is guaranteed to do that (SYSV).
1773 */
1774 void
1775mch_memmove(dst_arg, src_arg, len)
1776 void *src_arg, *dst_arg;
1777 size_t len;
1778{
1779 /*
1780 * A void doesn't have a size, we use char pointers.
1781 */
1782 char *dst = dst_arg, *src = src_arg;
1783
1784 /* overlap, copy backwards */
1785 if (dst > src && dst < src + len)
1786 {
1787 src += len;
1788 dst += len;
1789 while (len-- > 0)
1790 *--dst = *--src;
1791 }
1792 else /* copy forwards */
1793 while (len-- > 0)
1794 *dst++ = *src++;
1795}
1796#endif
1797
1798#if (!defined(HAVE_STRCASECMP) && !defined(HAVE_STRICMP)) || defined(PROTO)
1799/*
1800 * Compare two strings, ignoring case, using current locale.
1801 * Doesn't work for multi-byte characters.
1802 * return 0 for match, < 0 for smaller, > 0 for bigger
1803 */
1804 int
1805vim_stricmp(s1, s2)
1806 char *s1;
1807 char *s2;
1808{
1809 int i;
1810
1811 for (;;)
1812 {
1813 i = (int)TOLOWER_LOC(*s1) - (int)TOLOWER_LOC(*s2);
1814 if (i != 0)
1815 return i; /* this character different */
1816 if (*s1 == NUL)
1817 break; /* strings match until NUL */
1818 ++s1;
1819 ++s2;
1820 }
1821 return 0; /* strings match */
1822}
1823#endif
1824
1825#if (!defined(HAVE_STRNCASECMP) && !defined(HAVE_STRNICMP)) || defined(PROTO)
1826/*
1827 * Compare two strings, for length "len", ignoring case, using current locale.
1828 * Doesn't work for multi-byte characters.
1829 * return 0 for match, < 0 for smaller, > 0 for bigger
1830 */
1831 int
1832vim_strnicmp(s1, s2, len)
1833 char *s1;
1834 char *s2;
1835 size_t len;
1836{
1837 int i;
1838
1839 while (len > 0)
1840 {
1841 i = (int)TOLOWER_LOC(*s1) - (int)TOLOWER_LOC(*s2);
1842 if (i != 0)
1843 return i; /* this character different */
1844 if (*s1 == NUL)
1845 break; /* strings match until NUL */
1846 ++s1;
1847 ++s2;
1848 --len;
1849 }
1850 return 0; /* strings match */
1851}
1852#endif
1853
Bram Moolenaar071d4272004-06-13 20:20:40 +00001854/*
1855 * Version of strchr() and strrchr() that handle unsigned char strings
Bram Moolenaar05159a02005-02-26 23:04:13 +00001856 * with characters from 128 to 255 correctly. It also doesn't return a
1857 * pointer to the NUL at the end of the string.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001858 */
1859 char_u *
1860vim_strchr(string, c)
1861 char_u *string;
1862 int c;
1863{
1864 char_u *p;
1865 int b;
1866
1867 p = string;
1868#ifdef FEAT_MBYTE
1869 if (enc_utf8 && c >= 0x80)
1870 {
1871 while (*p != NUL)
1872 {
1873 if (utf_ptr2char(p) == c)
1874 return p;
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00001875 p += (*mb_ptr2len)(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001876 }
1877 return NULL;
1878 }
1879 if (enc_dbcs != 0 && c > 255)
1880 {
1881 int n2 = c & 0xff;
1882
1883 c = ((unsigned)c >> 8) & 0xff;
1884 while ((b = *p) != NUL)
1885 {
1886 if (b == c && p[1] == n2)
1887 return p;
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00001888 p += (*mb_ptr2len)(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001889 }
1890 return NULL;
1891 }
1892 if (has_mbyte)
1893 {
1894 while ((b = *p) != NUL)
1895 {
1896 if (b == c)
1897 return p;
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00001898 p += (*mb_ptr2len)(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001899 }
1900 return NULL;
1901 }
1902#endif
1903 while ((b = *p) != NUL)
1904 {
1905 if (b == c)
1906 return p;
1907 ++p;
1908 }
1909 return NULL;
1910}
1911
1912/*
Bram Moolenaar05159a02005-02-26 23:04:13 +00001913 * Version of strchr() that only works for bytes and handles unsigned char
1914 * strings with characters above 128 correctly. It also doesn't return a
1915 * pointer to the NUL at the end of the string.
1916 */
1917 char_u *
1918vim_strbyte(string, c)
1919 char_u *string;
1920 int c;
1921{
1922 char_u *p = string;
1923
1924 while (*p != NUL)
1925 {
1926 if (*p == c)
1927 return p;
1928 ++p;
1929 }
1930 return NULL;
1931}
1932
1933/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001934 * Search for last occurrence of "c" in "string".
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00001935 * Return NULL if not found.
Bram Moolenaar05159a02005-02-26 23:04:13 +00001936 * Does not handle multi-byte char for "c"!
Bram Moolenaar071d4272004-06-13 20:20:40 +00001937 */
1938 char_u *
1939vim_strrchr(string, c)
1940 char_u *string;
1941 int c;
1942{
1943 char_u *retval = NULL;
Bram Moolenaar05159a02005-02-26 23:04:13 +00001944 char_u *p = string;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001945
Bram Moolenaar05159a02005-02-26 23:04:13 +00001946 while (*p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001947 {
Bram Moolenaar05159a02005-02-26 23:04:13 +00001948 if (*p == c)
1949 retval = p;
1950 mb_ptr_adv(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001951 }
1952 return retval;
1953}
1954
1955/*
1956 * Vim's version of strpbrk(), in case it's missing.
1957 * Don't generate a prototype for this, causes problems when it's not used.
1958 */
1959#ifndef PROTO
1960# ifndef HAVE_STRPBRK
1961# ifdef vim_strpbrk
1962# undef vim_strpbrk
1963# endif
1964 char_u *
1965vim_strpbrk(s, charset)
1966 char_u *s;
1967 char_u *charset;
1968{
1969 while (*s)
1970 {
1971 if (vim_strchr(charset, *s) != NULL)
1972 return s;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001973 mb_ptr_adv(s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001974 }
1975 return NULL;
1976}
1977# endif
1978#endif
1979
1980/*
1981 * Vim has its own isspace() function, because on some machines isspace()
1982 * can't handle characters above 128.
1983 */
1984 int
1985vim_isspace(x)
1986 int x;
1987{
1988 return ((x >= 9 && x <= 13) || x == ' ');
1989}
1990
1991/************************************************************************
Bram Moolenaar383f9bc2005-01-19 22:18:32 +00001992 * Functions for handling growing arrays.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001993 */
1994
1995/*
1996 * Clear an allocated growing array.
1997 */
1998 void
1999ga_clear(gap)
2000 garray_T *gap;
2001{
2002 vim_free(gap->ga_data);
2003 ga_init(gap);
2004}
2005
2006/*
2007 * Clear a growing array that contains a list of strings.
2008 */
2009 void
2010ga_clear_strings(gap)
2011 garray_T *gap;
2012{
2013 int i;
2014
2015 for (i = 0; i < gap->ga_len; ++i)
2016 vim_free(((char_u **)(gap->ga_data))[i]);
2017 ga_clear(gap);
2018}
2019
2020/*
2021 * Initialize a growing array. Don't forget to set ga_itemsize and
2022 * ga_growsize! Or use ga_init2().
2023 */
2024 void
2025ga_init(gap)
2026 garray_T *gap;
2027{
2028 gap->ga_data = NULL;
Bram Moolenaar86b68352004-12-27 21:59:20 +00002029 gap->ga_maxlen = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002030 gap->ga_len = 0;
2031}
2032
2033 void
2034ga_init2(gap, itemsize, growsize)
2035 garray_T *gap;
2036 int itemsize;
2037 int growsize;
2038{
2039 ga_init(gap);
2040 gap->ga_itemsize = itemsize;
2041 gap->ga_growsize = growsize;
2042}
2043
2044/*
2045 * Make room in growing array "gap" for at least "n" items.
2046 * Return FAIL for failure, OK otherwise.
2047 */
2048 int
2049ga_grow(gap, n)
2050 garray_T *gap;
2051 int n;
2052{
2053 size_t len;
2054 char_u *pp;
2055
Bram Moolenaar86b68352004-12-27 21:59:20 +00002056 if (gap->ga_maxlen - gap->ga_len < n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002057 {
2058 if (n < gap->ga_growsize)
2059 n = gap->ga_growsize;
2060 len = gap->ga_itemsize * (gap->ga_len + n);
2061 pp = alloc_clear((unsigned)len);
2062 if (pp == NULL)
2063 return FAIL;
Bram Moolenaar86b68352004-12-27 21:59:20 +00002064 gap->ga_maxlen = gap->ga_len + n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002065 if (gap->ga_data != NULL)
2066 {
2067 mch_memmove(pp, gap->ga_data,
2068 (size_t)(gap->ga_itemsize * gap->ga_len));
2069 vim_free(gap->ga_data);
2070 }
2071 gap->ga_data = pp;
2072 }
2073 return OK;
2074}
2075
2076/*
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +02002077 * For a growing array that contains a list of strings: concatenate all the
2078 * strings with a separating comma.
2079 * Returns NULL when out of memory.
2080 */
2081 char_u *
2082ga_concat_strings(gap)
2083 garray_T *gap;
2084{
2085 int i;
2086 int len = 0;
2087 char_u *s;
2088
2089 for (i = 0; i < gap->ga_len; ++i)
2090 len += (int)STRLEN(((char_u **)(gap->ga_data))[i]) + 1;
2091
2092 s = alloc(len + 1);
2093 if (s != NULL)
2094 {
2095 *s = NUL;
2096 for (i = 0; i < gap->ga_len; ++i)
2097 {
2098 if (*s != NUL)
2099 STRCAT(s, ",");
2100 STRCAT(s, ((char_u **)(gap->ga_data))[i]);
2101 }
2102 }
2103 return s;
2104}
2105
2106/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00002107 * Concatenate a string to a growarray which contains characters.
2108 * Note: Does NOT copy the NUL at the end!
2109 */
2110 void
2111ga_concat(gap, s)
2112 garray_T *gap;
2113 char_u *s;
2114{
2115 int len = (int)STRLEN(s);
2116
2117 if (ga_grow(gap, len) == OK)
2118 {
2119 mch_memmove((char *)gap->ga_data + gap->ga_len, s, (size_t)len);
2120 gap->ga_len += len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002121 }
2122}
2123
2124/*
2125 * Append one byte to a growarray which contains bytes.
2126 */
2127 void
2128ga_append(gap, c)
2129 garray_T *gap;
2130 int c;
2131{
2132 if (ga_grow(gap, 1) == OK)
2133 {
2134 *((char *)gap->ga_data + gap->ga_len) = c;
2135 ++gap->ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002136 }
2137}
2138
2139/************************************************************************
2140 * functions that use lookup tables for various things, generally to do with
2141 * special key codes.
2142 */
2143
2144/*
2145 * Some useful tables.
2146 */
2147
2148static struct modmasktable
2149{
2150 short mod_mask; /* Bit-mask for particular key modifier */
2151 short mod_flag; /* Bit(s) for particular key modifier */
2152 char_u name; /* Single letter name of modifier */
2153} mod_mask_table[] =
2154{
2155 {MOD_MASK_ALT, MOD_MASK_ALT, (char_u)'M'},
Bram Moolenaar19a09a12005-03-04 23:39:37 +00002156 {MOD_MASK_META, MOD_MASK_META, (char_u)'T'},
Bram Moolenaar071d4272004-06-13 20:20:40 +00002157 {MOD_MASK_CTRL, MOD_MASK_CTRL, (char_u)'C'},
2158 {MOD_MASK_SHIFT, MOD_MASK_SHIFT, (char_u)'S'},
2159 {MOD_MASK_MULTI_CLICK, MOD_MASK_2CLICK, (char_u)'2'},
2160 {MOD_MASK_MULTI_CLICK, MOD_MASK_3CLICK, (char_u)'3'},
2161 {MOD_MASK_MULTI_CLICK, MOD_MASK_4CLICK, (char_u)'4'},
2162#ifdef MACOS
2163 {MOD_MASK_CMD, MOD_MASK_CMD, (char_u)'D'},
2164#endif
2165 /* 'A' must be the last one */
2166 {MOD_MASK_ALT, MOD_MASK_ALT, (char_u)'A'},
2167 {0, 0, NUL}
2168};
2169
2170/*
2171 * Shifted key terminal codes and their unshifted equivalent.
Bram Moolenaar7aa9f6a2007-05-10 18:00:30 +00002172 * Don't add mouse codes here, they are handled separately!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002173 */
2174#define MOD_KEYS_ENTRY_SIZE 5
2175
2176static char_u modifier_keys_table[] =
2177{
2178/* mod mask with modifier without modifier */
2179 MOD_MASK_SHIFT, '&', '9', '@', '1', /* begin */
2180 MOD_MASK_SHIFT, '&', '0', '@', '2', /* cancel */
2181 MOD_MASK_SHIFT, '*', '1', '@', '4', /* command */
2182 MOD_MASK_SHIFT, '*', '2', '@', '5', /* copy */
2183 MOD_MASK_SHIFT, '*', '3', '@', '6', /* create */
2184 MOD_MASK_SHIFT, '*', '4', 'k', 'D', /* delete char */
2185 MOD_MASK_SHIFT, '*', '5', 'k', 'L', /* delete line */
2186 MOD_MASK_SHIFT, '*', '7', '@', '7', /* end */
2187 MOD_MASK_CTRL, KS_EXTRA, (int)KE_C_END, '@', '7', /* end */
2188 MOD_MASK_SHIFT, '*', '9', '@', '9', /* exit */
2189 MOD_MASK_SHIFT, '*', '0', '@', '0', /* find */
2190 MOD_MASK_SHIFT, '#', '1', '%', '1', /* help */
2191 MOD_MASK_SHIFT, '#', '2', 'k', 'h', /* home */
2192 MOD_MASK_CTRL, KS_EXTRA, (int)KE_C_HOME, 'k', 'h', /* home */
2193 MOD_MASK_SHIFT, '#', '3', 'k', 'I', /* insert */
2194 MOD_MASK_SHIFT, '#', '4', 'k', 'l', /* left arrow */
2195 MOD_MASK_CTRL, KS_EXTRA, (int)KE_C_LEFT, 'k', 'l', /* left arrow */
2196 MOD_MASK_SHIFT, '%', 'a', '%', '3', /* message */
2197 MOD_MASK_SHIFT, '%', 'b', '%', '4', /* move */
2198 MOD_MASK_SHIFT, '%', 'c', '%', '5', /* next */
2199 MOD_MASK_SHIFT, '%', 'd', '%', '7', /* options */
2200 MOD_MASK_SHIFT, '%', 'e', '%', '8', /* previous */
2201 MOD_MASK_SHIFT, '%', 'f', '%', '9', /* print */
2202 MOD_MASK_SHIFT, '%', 'g', '%', '0', /* redo */
2203 MOD_MASK_SHIFT, '%', 'h', '&', '3', /* replace */
2204 MOD_MASK_SHIFT, '%', 'i', 'k', 'r', /* right arr. */
2205 MOD_MASK_CTRL, KS_EXTRA, (int)KE_C_RIGHT, 'k', 'r', /* right arr. */
2206 MOD_MASK_SHIFT, '%', 'j', '&', '5', /* resume */
2207 MOD_MASK_SHIFT, '!', '1', '&', '6', /* save */
2208 MOD_MASK_SHIFT, '!', '2', '&', '7', /* suspend */
2209 MOD_MASK_SHIFT, '!', '3', '&', '8', /* undo */
2210 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_UP, 'k', 'u', /* up arrow */
2211 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_DOWN, 'k', 'd', /* down arrow */
2212
2213 /* vt100 F1 */
2214 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF1, KS_EXTRA, (int)KE_XF1,
2215 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF2, KS_EXTRA, (int)KE_XF2,
2216 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF3, KS_EXTRA, (int)KE_XF3,
2217 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF4, KS_EXTRA, (int)KE_XF4,
2218
2219 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F1, 'k', '1', /* F1 */
2220 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F2, 'k', '2',
2221 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F3, 'k', '3',
2222 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F4, 'k', '4',
2223 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F5, 'k', '5',
2224 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F6, 'k', '6',
2225 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F7, 'k', '7',
2226 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F8, 'k', '8',
2227 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F9, 'k', '9',
2228 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F10, 'k', ';', /* F10 */
2229
2230 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F11, 'F', '1',
2231 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F12, 'F', '2',
2232 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F13, 'F', '3',
2233 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F14, 'F', '4',
2234 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F15, 'F', '5',
2235 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F16, 'F', '6',
2236 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F17, 'F', '7',
2237 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F18, 'F', '8',
2238 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F19, 'F', '9',
2239 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F20, 'F', 'A',
2240
2241 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F21, 'F', 'B',
2242 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F22, 'F', 'C',
2243 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F23, 'F', 'D',
2244 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F24, 'F', 'E',
2245 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F25, 'F', 'F',
2246 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F26, 'F', 'G',
2247 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F27, 'F', 'H',
2248 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F28, 'F', 'I',
2249 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F29, 'F', 'J',
2250 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F30, 'F', 'K',
2251
2252 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F31, 'F', 'L',
2253 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F32, 'F', 'M',
2254 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F33, 'F', 'N',
2255 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F34, 'F', 'O',
2256 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F35, 'F', 'P',
2257 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F36, 'F', 'Q',
2258 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F37, 'F', 'R',
2259
2260 /* TAB pseudo code*/
2261 MOD_MASK_SHIFT, 'k', 'B', KS_EXTRA, (int)KE_TAB,
2262
2263 NUL
2264};
2265
2266static struct key_name_entry
2267{
2268 int key; /* Special key code or ascii value */
2269 char_u *name; /* Name of key */
2270} key_names_table[] =
2271{
2272 {' ', (char_u *)"Space"},
2273 {TAB, (char_u *)"Tab"},
2274 {K_TAB, (char_u *)"Tab"},
2275 {NL, (char_u *)"NL"},
2276 {NL, (char_u *)"NewLine"}, /* Alternative name */
2277 {NL, (char_u *)"LineFeed"}, /* Alternative name */
2278 {NL, (char_u *)"LF"}, /* Alternative name */
2279 {CAR, (char_u *)"CR"},
2280 {CAR, (char_u *)"Return"}, /* Alternative name */
2281 {CAR, (char_u *)"Enter"}, /* Alternative name */
2282 {K_BS, (char_u *)"BS"},
2283 {K_BS, (char_u *)"BackSpace"}, /* Alternative name */
2284 {ESC, (char_u *)"Esc"},
2285 {CSI, (char_u *)"CSI"},
2286 {K_CSI, (char_u *)"xCSI"},
2287 {'|', (char_u *)"Bar"},
2288 {'\\', (char_u *)"Bslash"},
2289 {K_DEL, (char_u *)"Del"},
2290 {K_DEL, (char_u *)"Delete"}, /* Alternative name */
2291 {K_KDEL, (char_u *)"kDel"},
2292 {K_UP, (char_u *)"Up"},
2293 {K_DOWN, (char_u *)"Down"},
2294 {K_LEFT, (char_u *)"Left"},
2295 {K_RIGHT, (char_u *)"Right"},
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002296 {K_XUP, (char_u *)"xUp"},
2297 {K_XDOWN, (char_u *)"xDown"},
2298 {K_XLEFT, (char_u *)"xLeft"},
2299 {K_XRIGHT, (char_u *)"xRight"},
Bram Moolenaar071d4272004-06-13 20:20:40 +00002300
2301 {K_F1, (char_u *)"F1"},
2302 {K_F2, (char_u *)"F2"},
2303 {K_F3, (char_u *)"F3"},
2304 {K_F4, (char_u *)"F4"},
2305 {K_F5, (char_u *)"F5"},
2306 {K_F6, (char_u *)"F6"},
2307 {K_F7, (char_u *)"F7"},
2308 {K_F8, (char_u *)"F8"},
2309 {K_F9, (char_u *)"F9"},
2310 {K_F10, (char_u *)"F10"},
2311
2312 {K_F11, (char_u *)"F11"},
2313 {K_F12, (char_u *)"F12"},
2314 {K_F13, (char_u *)"F13"},
2315 {K_F14, (char_u *)"F14"},
2316 {K_F15, (char_u *)"F15"},
2317 {K_F16, (char_u *)"F16"},
2318 {K_F17, (char_u *)"F17"},
2319 {K_F18, (char_u *)"F18"},
2320 {K_F19, (char_u *)"F19"},
2321 {K_F20, (char_u *)"F20"},
2322
2323 {K_F21, (char_u *)"F21"},
2324 {K_F22, (char_u *)"F22"},
2325 {K_F23, (char_u *)"F23"},
2326 {K_F24, (char_u *)"F24"},
2327 {K_F25, (char_u *)"F25"},
2328 {K_F26, (char_u *)"F26"},
2329 {K_F27, (char_u *)"F27"},
2330 {K_F28, (char_u *)"F28"},
2331 {K_F29, (char_u *)"F29"},
2332 {K_F30, (char_u *)"F30"},
2333
2334 {K_F31, (char_u *)"F31"},
2335 {K_F32, (char_u *)"F32"},
2336 {K_F33, (char_u *)"F33"},
2337 {K_F34, (char_u *)"F34"},
2338 {K_F35, (char_u *)"F35"},
2339 {K_F36, (char_u *)"F36"},
2340 {K_F37, (char_u *)"F37"},
2341
2342 {K_XF1, (char_u *)"xF1"},
2343 {K_XF2, (char_u *)"xF2"},
2344 {K_XF3, (char_u *)"xF3"},
2345 {K_XF4, (char_u *)"xF4"},
2346
2347 {K_HELP, (char_u *)"Help"},
2348 {K_UNDO, (char_u *)"Undo"},
2349 {K_INS, (char_u *)"Insert"},
2350 {K_INS, (char_u *)"Ins"}, /* Alternative name */
2351 {K_KINS, (char_u *)"kInsert"},
2352 {K_HOME, (char_u *)"Home"},
2353 {K_KHOME, (char_u *)"kHome"},
2354 {K_XHOME, (char_u *)"xHome"},
Bram Moolenaar68b76a62005-03-25 21:53:48 +00002355 {K_ZHOME, (char_u *)"zHome"},
Bram Moolenaar071d4272004-06-13 20:20:40 +00002356 {K_END, (char_u *)"End"},
2357 {K_KEND, (char_u *)"kEnd"},
2358 {K_XEND, (char_u *)"xEnd"},
Bram Moolenaar68b76a62005-03-25 21:53:48 +00002359 {K_ZEND, (char_u *)"zEnd"},
Bram Moolenaar071d4272004-06-13 20:20:40 +00002360 {K_PAGEUP, (char_u *)"PageUp"},
2361 {K_PAGEDOWN, (char_u *)"PageDown"},
2362 {K_KPAGEUP, (char_u *)"kPageUp"},
2363 {K_KPAGEDOWN, (char_u *)"kPageDown"},
2364
2365 {K_KPLUS, (char_u *)"kPlus"},
2366 {K_KMINUS, (char_u *)"kMinus"},
2367 {K_KDIVIDE, (char_u *)"kDivide"},
2368 {K_KMULTIPLY, (char_u *)"kMultiply"},
2369 {K_KENTER, (char_u *)"kEnter"},
2370 {K_KPOINT, (char_u *)"kPoint"},
2371
2372 {K_K0, (char_u *)"k0"},
2373 {K_K1, (char_u *)"k1"},
2374 {K_K2, (char_u *)"k2"},
2375 {K_K3, (char_u *)"k3"},
2376 {K_K4, (char_u *)"k4"},
2377 {K_K5, (char_u *)"k5"},
2378 {K_K6, (char_u *)"k6"},
2379 {K_K7, (char_u *)"k7"},
2380 {K_K8, (char_u *)"k8"},
2381 {K_K9, (char_u *)"k9"},
2382
2383 {'<', (char_u *)"lt"},
2384
2385 {K_MOUSE, (char_u *)"Mouse"},
2386 {K_NETTERM_MOUSE, (char_u *)"NetMouse"},
2387 {K_DEC_MOUSE, (char_u *)"DecMouse"},
2388 {K_JSBTERM_MOUSE, (char_u *)"JsbMouse"},
2389 {K_PTERM_MOUSE, (char_u *)"PtermMouse"},
2390 {K_LEFTMOUSE, (char_u *)"LeftMouse"},
2391 {K_LEFTMOUSE_NM, (char_u *)"LeftMouseNM"},
2392 {K_LEFTDRAG, (char_u *)"LeftDrag"},
2393 {K_LEFTRELEASE, (char_u *)"LeftRelease"},
2394 {K_LEFTRELEASE_NM, (char_u *)"LeftReleaseNM"},
2395 {K_MIDDLEMOUSE, (char_u *)"MiddleMouse"},
2396 {K_MIDDLEDRAG, (char_u *)"MiddleDrag"},
2397 {K_MIDDLERELEASE, (char_u *)"MiddleRelease"},
2398 {K_RIGHTMOUSE, (char_u *)"RightMouse"},
2399 {K_RIGHTDRAG, (char_u *)"RightDrag"},
2400 {K_RIGHTRELEASE, (char_u *)"RightRelease"},
Bram Moolenaar8d9b40e2010-07-25 15:49:07 +02002401 {K_MOUSEDOWN, (char_u *)"ScrollWheelUp"},
2402 {K_MOUSEUP, (char_u *)"ScrollWheelDown"},
2403 {K_MOUSELEFT, (char_u *)"ScrollWheelRight"},
2404 {K_MOUSERIGHT, (char_u *)"ScrollWheelLeft"},
2405 {K_MOUSEDOWN, (char_u *)"MouseDown"}, /* OBSOLETE: Use */
2406 {K_MOUSEUP, (char_u *)"MouseUp"}, /* ScrollWheelXXX instead */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002407 {K_X1MOUSE, (char_u *)"X1Mouse"},
2408 {K_X1DRAG, (char_u *)"X1Drag"},
2409 {K_X1RELEASE, (char_u *)"X1Release"},
2410 {K_X2MOUSE, (char_u *)"X2Mouse"},
2411 {K_X2DRAG, (char_u *)"X2Drag"},
2412 {K_X2RELEASE, (char_u *)"X2Release"},
2413 {K_DROP, (char_u *)"Drop"},
2414 {K_ZERO, (char_u *)"Nul"},
2415#ifdef FEAT_EVAL
2416 {K_SNR, (char_u *)"SNR"},
2417#endif
2418 {K_PLUG, (char_u *)"Plug"},
2419 {0, NULL}
2420};
2421
2422#define KEY_NAMES_TABLE_LEN (sizeof(key_names_table) / sizeof(struct key_name_entry))
2423
2424#ifdef FEAT_MOUSE
2425static struct mousetable
2426{
2427 int pseudo_code; /* Code for pseudo mouse event */
2428 int button; /* Which mouse button is it? */
2429 int is_click; /* Is it a mouse button click event? */
2430 int is_drag; /* Is it a mouse drag event? */
2431} mouse_table[] =
2432{
2433 {(int)KE_LEFTMOUSE, MOUSE_LEFT, TRUE, FALSE},
2434#ifdef FEAT_GUI
2435 {(int)KE_LEFTMOUSE_NM, MOUSE_LEFT, TRUE, FALSE},
2436#endif
2437 {(int)KE_LEFTDRAG, MOUSE_LEFT, FALSE, TRUE},
2438 {(int)KE_LEFTRELEASE, MOUSE_LEFT, FALSE, FALSE},
2439#ifdef FEAT_GUI
2440 {(int)KE_LEFTRELEASE_NM, MOUSE_LEFT, FALSE, FALSE},
2441#endif
2442 {(int)KE_MIDDLEMOUSE, MOUSE_MIDDLE, TRUE, FALSE},
2443 {(int)KE_MIDDLEDRAG, MOUSE_MIDDLE, FALSE, TRUE},
2444 {(int)KE_MIDDLERELEASE, MOUSE_MIDDLE, FALSE, FALSE},
2445 {(int)KE_RIGHTMOUSE, MOUSE_RIGHT, TRUE, FALSE},
2446 {(int)KE_RIGHTDRAG, MOUSE_RIGHT, FALSE, TRUE},
2447 {(int)KE_RIGHTRELEASE, MOUSE_RIGHT, FALSE, FALSE},
2448 {(int)KE_X1MOUSE, MOUSE_X1, TRUE, FALSE},
2449 {(int)KE_X1DRAG, MOUSE_X1, FALSE, TRUE},
2450 {(int)KE_X1RELEASE, MOUSE_X1, FALSE, FALSE},
2451 {(int)KE_X2MOUSE, MOUSE_X2, TRUE, FALSE},
2452 {(int)KE_X2DRAG, MOUSE_X2, FALSE, TRUE},
2453 {(int)KE_X2RELEASE, MOUSE_X2, FALSE, FALSE},
2454 /* DRAG without CLICK */
2455 {(int)KE_IGNORE, MOUSE_RELEASE, FALSE, TRUE},
2456 /* RELEASE without CLICK */
2457 {(int)KE_IGNORE, MOUSE_RELEASE, FALSE, FALSE},
2458 {0, 0, 0, 0},
2459};
2460#endif /* FEAT_MOUSE */
2461
2462/*
2463 * Return the modifier mask bit (MOD_MASK_*) which corresponds to the given
2464 * modifier name ('S' for Shift, 'C' for Ctrl etc).
2465 */
2466 int
2467name_to_mod_mask(c)
2468 int c;
2469{
2470 int i;
2471
2472 c = TOUPPER_ASC(c);
2473 for (i = 0; mod_mask_table[i].mod_mask != 0; i++)
2474 if (c == mod_mask_table[i].name)
2475 return mod_mask_table[i].mod_flag;
2476 return 0;
2477}
2478
Bram Moolenaar071d4272004-06-13 20:20:40 +00002479/*
2480 * Check if if there is a special key code for "key" that includes the
2481 * modifiers specified.
2482 */
2483 int
2484simplify_key(key, modifiers)
2485 int key;
2486 int *modifiers;
2487{
2488 int i;
2489 int key0;
2490 int key1;
2491
2492 if (*modifiers & (MOD_MASK_SHIFT | MOD_MASK_CTRL | MOD_MASK_ALT))
2493 {
2494 /* TAB is a special case */
2495 if (key == TAB && (*modifiers & MOD_MASK_SHIFT))
2496 {
2497 *modifiers &= ~MOD_MASK_SHIFT;
2498 return K_S_TAB;
2499 }
2500 key0 = KEY2TERMCAP0(key);
2501 key1 = KEY2TERMCAP1(key);
2502 for (i = 0; modifier_keys_table[i] != NUL; i += MOD_KEYS_ENTRY_SIZE)
2503 if (key0 == modifier_keys_table[i + 3]
2504 && key1 == modifier_keys_table[i + 4]
2505 && (*modifiers & modifier_keys_table[i]))
2506 {
2507 *modifiers &= ~modifier_keys_table[i];
2508 return TERMCAP2KEY(modifier_keys_table[i + 1],
2509 modifier_keys_table[i + 2]);
2510 }
2511 }
2512 return key;
2513}
2514
2515/*
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002516 * Change <xHome> to <Home>, <xUp> to <Up>, etc.
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002517 */
2518 int
2519handle_x_keys(key)
2520 int key;
2521{
2522 switch (key)
2523 {
2524 case K_XUP: return K_UP;
2525 case K_XDOWN: return K_DOWN;
2526 case K_XLEFT: return K_LEFT;
2527 case K_XRIGHT: return K_RIGHT;
2528 case K_XHOME: return K_HOME;
Bram Moolenaar68b76a62005-03-25 21:53:48 +00002529 case K_ZHOME: return K_HOME;
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002530 case K_XEND: return K_END;
Bram Moolenaar68b76a62005-03-25 21:53:48 +00002531 case K_ZEND: return K_END;
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002532 case K_XF1: return K_F1;
2533 case K_XF2: return K_F2;
2534 case K_XF3: return K_F3;
2535 case K_XF4: return K_F4;
2536 case K_S_XF1: return K_S_F1;
2537 case K_S_XF2: return K_S_F2;
2538 case K_S_XF3: return K_S_F3;
2539 case K_S_XF4: return K_S_F4;
2540 }
2541 return key;
2542}
2543
2544/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00002545 * Return a string which contains the name of the given key when the given
2546 * modifiers are down.
2547 */
2548 char_u *
2549get_special_key_name(c, modifiers)
2550 int c;
2551 int modifiers;
2552{
2553 static char_u string[MAX_KEY_NAME_LEN + 1];
2554
2555 int i, idx;
2556 int table_idx;
2557 char_u *s;
2558
2559 string[0] = '<';
2560 idx = 1;
2561
2562 /* Key that stands for a normal character. */
2563 if (IS_SPECIAL(c) && KEY2TERMCAP0(c) == KS_KEY)
2564 c = KEY2TERMCAP1(c);
2565
2566 /*
2567 * Translate shifted special keys into unshifted keys and set modifier.
2568 * Same for CTRL and ALT modifiers.
2569 */
2570 if (IS_SPECIAL(c))
2571 {
2572 for (i = 0; modifier_keys_table[i] != 0; i += MOD_KEYS_ENTRY_SIZE)
2573 if ( KEY2TERMCAP0(c) == (int)modifier_keys_table[i + 1]
2574 && (int)KEY2TERMCAP1(c) == (int)modifier_keys_table[i + 2])
2575 {
2576 modifiers |= modifier_keys_table[i];
2577 c = TERMCAP2KEY(modifier_keys_table[i + 3],
2578 modifier_keys_table[i + 4]);
2579 break;
2580 }
2581 }
2582
2583 /* try to find the key in the special key table */
2584 table_idx = find_special_key_in_table(c);
2585
2586 /*
2587 * When not a known special key, and not a printable character, try to
2588 * extract modifiers.
2589 */
2590 if (c > 0
2591#ifdef FEAT_MBYTE
2592 && (*mb_char2len)(c) == 1
2593#endif
2594 )
2595 {
2596 if (table_idx < 0
2597 && (!vim_isprintc(c) || (c & 0x7f) == ' ')
2598 && (c & 0x80))
2599 {
2600 c &= 0x7f;
2601 modifiers |= MOD_MASK_ALT;
2602 /* try again, to find the un-alted key in the special key table */
2603 table_idx = find_special_key_in_table(c);
2604 }
2605 if (table_idx < 0 && !vim_isprintc(c) && c < ' ')
2606 {
2607#ifdef EBCDIC
2608 c = CtrlChar(c);
2609#else
2610 c += '@';
2611#endif
2612 modifiers |= MOD_MASK_CTRL;
2613 }
2614 }
2615
2616 /* translate the modifier into a string */
2617 for (i = 0; mod_mask_table[i].name != 'A'; i++)
2618 if ((modifiers & mod_mask_table[i].mod_mask)
2619 == mod_mask_table[i].mod_flag)
2620 {
2621 string[idx++] = mod_mask_table[i].name;
2622 string[idx++] = (char_u)'-';
2623 }
2624
2625 if (table_idx < 0) /* unknown special key, may output t_xx */
2626 {
2627 if (IS_SPECIAL(c))
2628 {
2629 string[idx++] = 't';
2630 string[idx++] = '_';
2631 string[idx++] = KEY2TERMCAP0(c);
2632 string[idx++] = KEY2TERMCAP1(c);
2633 }
2634 /* Not a special key, only modifiers, output directly */
2635 else
2636 {
2637#ifdef FEAT_MBYTE
2638 if (has_mbyte && (*mb_char2len)(c) > 1)
2639 idx += (*mb_char2bytes)(c, string + idx);
2640 else
2641#endif
2642 if (vim_isprintc(c))
2643 string[idx++] = c;
2644 else
2645 {
2646 s = transchar(c);
2647 while (*s)
2648 string[idx++] = *s++;
2649 }
2650 }
2651 }
2652 else /* use name of special key */
2653 {
2654 STRCPY(string + idx, key_names_table[table_idx].name);
2655 idx = (int)STRLEN(string);
2656 }
2657 string[idx++] = '>';
2658 string[idx] = NUL;
2659 return string;
2660}
2661
2662/*
2663 * Try translating a <> name at (*srcp)[] to dst[].
2664 * Return the number of characters added to dst[], zero for no match.
2665 * If there is a match, srcp is advanced to after the <> name.
2666 * dst[] must be big enough to hold the result (up to six characters)!
2667 */
2668 int
2669trans_special(srcp, dst, keycode)
2670 char_u **srcp;
2671 char_u *dst;
2672 int keycode; /* prefer key code, e.g. K_DEL instead of DEL */
2673{
2674 int modifiers = 0;
2675 int key;
2676 int dlen = 0;
2677
Bram Moolenaar2a8ced02008-12-24 11:54:31 +00002678 key = find_special_key(srcp, &modifiers, keycode, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002679 if (key == 0)
2680 return 0;
2681
2682 /* Put the appropriate modifier in a string */
2683 if (modifiers != 0)
2684 {
2685 dst[dlen++] = K_SPECIAL;
2686 dst[dlen++] = KS_MODIFIER;
2687 dst[dlen++] = modifiers;
2688 }
2689
2690 if (IS_SPECIAL(key))
2691 {
2692 dst[dlen++] = K_SPECIAL;
2693 dst[dlen++] = KEY2TERMCAP0(key);
2694 dst[dlen++] = KEY2TERMCAP1(key);
2695 }
2696#ifdef FEAT_MBYTE
2697 else if (has_mbyte && !keycode)
2698 dlen += (*mb_char2bytes)(key, dst + dlen);
2699#endif
2700 else if (keycode)
2701 dlen = (int)(add_char2buf(key, dst + dlen) - dst);
2702 else
2703 dst[dlen++] = key;
2704
2705 return dlen;
2706}
2707
2708/*
2709 * Try translating a <> name at (*srcp)[], return the key and modifiers.
2710 * srcp is advanced to after the <> name.
2711 * returns 0 if there is no match.
2712 */
2713 int
Bram Moolenaar2a8ced02008-12-24 11:54:31 +00002714find_special_key(srcp, modp, keycode, keep_x_key)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002715 char_u **srcp;
2716 int *modp;
Bram Moolenaar2a8ced02008-12-24 11:54:31 +00002717 int keycode; /* prefer key code, e.g. K_DEL instead of DEL */
2718 int keep_x_key; /* don't translate xHome to Home key */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002719{
2720 char_u *last_dash;
2721 char_u *end_of_name;
2722 char_u *src;
2723 char_u *bp;
2724 int modifiers;
2725 int bit;
2726 int key;
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002727 unsigned long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002728
2729 src = *srcp;
2730 if (src[0] != '<')
2731 return 0;
2732
2733 /* Find end of modifier list */
2734 last_dash = src;
2735 for (bp = src + 1; *bp == '-' || vim_isIDc(*bp); bp++)
2736 {
2737 if (*bp == '-')
2738 {
2739 last_dash = bp;
2740 if (bp[1] != NUL && bp[2] == '>')
2741 ++bp; /* anything accepted, like <C-?> */
2742 }
2743 if (bp[0] == 't' && bp[1] == '_' && bp[2] && bp[3])
2744 bp += 3; /* skip t_xx, xx may be '-' or '>' */
2745 }
2746
2747 if (*bp == '>') /* found matching '>' */
2748 {
2749 end_of_name = bp + 1;
2750
2751 if (STRNICMP(src + 1, "char-", 5) == 0 && VIM_ISDIGIT(src[6]))
2752 {
2753 /* <Char-123> or <Char-033> or <Char-0x33> */
2754 vim_str2nr(src + 6, NULL, NULL, TRUE, TRUE, NULL, &n);
2755 *modp = 0;
2756 *srcp = end_of_name;
2757 return (int)n;
2758 }
2759
2760 /* Which modifiers are given? */
2761 modifiers = 0x0;
2762 for (bp = src + 1; bp < last_dash; bp++)
2763 {
2764 if (*bp != '-')
2765 {
2766 bit = name_to_mod_mask(*bp);
2767 if (bit == 0x0)
2768 break; /* Illegal modifier name */
2769 modifiers |= bit;
2770 }
2771 }
2772
2773 /*
2774 * Legal modifier name.
2775 */
2776 if (bp >= last_dash)
2777 {
2778 /*
2779 * Modifier with single letter, or special key name.
2780 */
2781 if (modifiers != 0 && last_dash[2] == '>')
2782 key = last_dash[1];
2783 else
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002784 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002785 key = get_special_key_code(last_dash + 1);
Bram Moolenaar2a8ced02008-12-24 11:54:31 +00002786 if (!keep_x_key)
2787 key = handle_x_keys(key);
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002788 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002789
2790 /*
2791 * get_special_key_code() may return NUL for invalid
2792 * special key name.
2793 */
2794 if (key != NUL)
2795 {
2796 /*
2797 * Only use a modifier when there is no special key code that
2798 * includes the modifier.
2799 */
2800 key = simplify_key(key, &modifiers);
2801
2802 if (!keycode)
2803 {
2804 /* don't want keycode, use single byte code */
2805 if (key == K_BS)
2806 key = BS;
2807 else if (key == K_DEL || key == K_KDEL)
2808 key = DEL;
2809 }
2810
2811 /*
2812 * Normal Key with modifier: Try to make a single byte code.
2813 */
2814 if (!IS_SPECIAL(key))
2815 key = extract_modifiers(key, &modifiers);
2816
2817 *modp = modifiers;
2818 *srcp = end_of_name;
2819 return key;
2820 }
2821 }
2822 }
2823 return 0;
2824}
2825
2826/*
2827 * Try to include modifiers in the key.
2828 * Changes "Shift-a" to 'A', "Alt-A" to 0xc0, etc.
2829 */
2830 int
2831extract_modifiers(key, modp)
2832 int key;
2833 int *modp;
2834{
2835 int modifiers = *modp;
2836
2837#ifdef MACOS
2838 /* Command-key really special, No fancynest */
2839 if (!(modifiers & MOD_MASK_CMD))
2840#endif
2841 if ((modifiers & MOD_MASK_SHIFT) && ASCII_ISALPHA(key))
2842 {
2843 key = TOUPPER_ASC(key);
2844 modifiers &= ~MOD_MASK_SHIFT;
2845 }
2846 if ((modifiers & MOD_MASK_CTRL)
2847#ifdef EBCDIC
2848 /* * TODO: EBCDIC Better use:
2849 * && (Ctrl_chr(key) || key == '?')
2850 * ??? */
2851 && strchr("?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_", key)
2852 != NULL
2853#else
2854 && ((key >= '?' && key <= '_') || ASCII_ISALPHA(key))
2855#endif
2856 )
2857 {
2858 key = Ctrl_chr(key);
2859 modifiers &= ~MOD_MASK_CTRL;
2860 /* <C-@> is <Nul> */
2861 if (key == 0)
2862 key = K_ZERO;
2863 }
2864#ifdef MACOS
2865 /* Command-key really special, No fancynest */
2866 if (!(modifiers & MOD_MASK_CMD))
2867#endif
2868 if ((modifiers & MOD_MASK_ALT) && key < 0x80
2869#ifdef FEAT_MBYTE
2870 && !enc_dbcs /* avoid creating a lead byte */
2871#endif
2872 )
2873 {
2874 key |= 0x80;
2875 modifiers &= ~MOD_MASK_ALT; /* remove the META modifier */
2876 }
2877
2878 *modp = modifiers;
2879 return key;
2880}
2881
2882/*
2883 * Try to find key "c" in the special key table.
2884 * Return the index when found, -1 when not found.
2885 */
2886 int
2887find_special_key_in_table(c)
2888 int c;
2889{
2890 int i;
2891
2892 for (i = 0; key_names_table[i].name != NULL; i++)
2893 if (c == key_names_table[i].key)
2894 break;
2895 if (key_names_table[i].name == NULL)
2896 i = -1;
2897 return i;
2898}
2899
2900/*
2901 * Find the special key with the given name (the given string does not have to
2902 * end with NUL, the name is assumed to end before the first non-idchar).
2903 * If the name starts with "t_" the next two characters are interpreted as a
2904 * termcap name.
2905 * Return the key code, or 0 if not found.
2906 */
2907 int
2908get_special_key_code(name)
2909 char_u *name;
2910{
2911 char_u *table_name;
2912 char_u string[3];
2913 int i, j;
2914
2915 /*
2916 * If it's <t_xx> we get the code for xx from the termcap
2917 */
2918 if (name[0] == 't' && name[1] == '_' && name[2] != NUL && name[3] != NUL)
2919 {
2920 string[0] = name[2];
2921 string[1] = name[3];
2922 string[2] = NUL;
2923 if (add_termcap_entry(string, FALSE) == OK)
2924 return TERMCAP2KEY(name[2], name[3]);
2925 }
2926 else
2927 for (i = 0; key_names_table[i].name != NULL; i++)
2928 {
2929 table_name = key_names_table[i].name;
2930 for (j = 0; vim_isIDc(name[j]) && table_name[j] != NUL; j++)
2931 if (TOLOWER_ASC(table_name[j]) != TOLOWER_ASC(name[j]))
2932 break;
2933 if (!vim_isIDc(name[j]) && table_name[j] == NUL)
2934 return key_names_table[i].key;
2935 }
2936 return 0;
2937}
2938
Bram Moolenaar05bb9532008-07-04 09:44:11 +00002939#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002940 char_u *
2941get_key_name(i)
2942 int i;
2943{
Bram Moolenaare1fbddc2009-05-16 19:07:03 +00002944 if (i >= (int)KEY_NAMES_TABLE_LEN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002945 return NULL;
2946 return key_names_table[i].name;
2947}
2948#endif
2949
Bram Moolenaar05bb9532008-07-04 09:44:11 +00002950#if defined(FEAT_MOUSE) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002951/*
2952 * Look up the given mouse code to return the relevant information in the other
2953 * arguments. Return which button is down or was released.
2954 */
2955 int
2956get_mouse_button(code, is_click, is_drag)
2957 int code;
2958 int *is_click;
2959 int *is_drag;
2960{
2961 int i;
2962
2963 for (i = 0; mouse_table[i].pseudo_code; i++)
2964 if (code == mouse_table[i].pseudo_code)
2965 {
2966 *is_click = mouse_table[i].is_click;
2967 *is_drag = mouse_table[i].is_drag;
2968 return mouse_table[i].button;
2969 }
2970 return 0; /* Shouldn't get here */
2971}
2972
2973/*
2974 * Return the appropriate pseudo mouse event token (KE_LEFTMOUSE etc) based on
2975 * the given information about which mouse button is down, and whether the
2976 * mouse was clicked, dragged or released.
2977 */
2978 int
2979get_pseudo_mouse_code(button, is_click, is_drag)
2980 int button; /* eg MOUSE_LEFT */
2981 int is_click;
2982 int is_drag;
2983{
2984 int i;
2985
2986 for (i = 0; mouse_table[i].pseudo_code; i++)
2987 if (button == mouse_table[i].button
2988 && is_click == mouse_table[i].is_click
2989 && is_drag == mouse_table[i].is_drag)
2990 {
2991#ifdef FEAT_GUI
Bram Moolenaarc91506a2005-04-24 22:04:21 +00002992 /* Trick: a non mappable left click and release has mouse_col -1
2993 * or added MOUSE_COLOFF. Used for 'mousefocus' in
2994 * gui_mouse_moved() */
2995 if (mouse_col < 0 || mouse_col > MOUSE_COLOFF)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002996 {
Bram Moolenaarc91506a2005-04-24 22:04:21 +00002997 if (mouse_col < 0)
2998 mouse_col = 0;
2999 else
3000 mouse_col -= MOUSE_COLOFF;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003001 if (mouse_table[i].pseudo_code == (int)KE_LEFTMOUSE)
3002 return (int)KE_LEFTMOUSE_NM;
3003 if (mouse_table[i].pseudo_code == (int)KE_LEFTRELEASE)
3004 return (int)KE_LEFTRELEASE_NM;
3005 }
3006#endif
3007 return mouse_table[i].pseudo_code;
3008 }
Bram Moolenaar7aa9f6a2007-05-10 18:00:30 +00003009 return (int)KE_IGNORE; /* not recognized, ignore it */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003010}
3011#endif /* FEAT_MOUSE */
3012
3013/*
3014 * Return the current end-of-line type: EOL_DOS, EOL_UNIX or EOL_MAC.
3015 */
3016 int
3017get_fileformat(buf)
3018 buf_T *buf;
3019{
3020 int c = *buf->b_p_ff;
3021
3022 if (buf->b_p_bin || c == 'u')
3023 return EOL_UNIX;
3024 if (c == 'm')
3025 return EOL_MAC;
3026 return EOL_DOS;
3027}
3028
3029/*
3030 * Like get_fileformat(), but override 'fileformat' with "p" for "++opt=val"
3031 * argument.
3032 */
3033 int
3034get_fileformat_force(buf, eap)
3035 buf_T *buf;
3036 exarg_T *eap; /* can be NULL! */
3037{
3038 int c;
3039
3040 if (eap != NULL && eap->force_ff != 0)
3041 c = eap->cmd[eap->force_ff];
3042 else
3043 {
3044 if ((eap != NULL && eap->force_bin != 0)
3045 ? (eap->force_bin == FORCE_BIN) : buf->b_p_bin)
3046 return EOL_UNIX;
3047 c = *buf->b_p_ff;
3048 }
3049 if (c == 'u')
3050 return EOL_UNIX;
3051 if (c == 'm')
3052 return EOL_MAC;
3053 return EOL_DOS;
3054}
3055
3056/*
3057 * Set the current end-of-line type to EOL_DOS, EOL_UNIX or EOL_MAC.
3058 * Sets both 'textmode' and 'fileformat'.
3059 * Note: Does _not_ set global value of 'textmode'!
3060 */
3061 void
3062set_fileformat(t, opt_flags)
3063 int t;
3064 int opt_flags; /* OPT_LOCAL and/or OPT_GLOBAL */
3065{
3066 char *p = NULL;
3067
3068 switch (t)
3069 {
3070 case EOL_DOS:
3071 p = FF_DOS;
3072 curbuf->b_p_tx = TRUE;
3073 break;
3074 case EOL_UNIX:
3075 p = FF_UNIX;
3076 curbuf->b_p_tx = FALSE;
3077 break;
3078 case EOL_MAC:
3079 p = FF_MAC;
3080 curbuf->b_p_tx = FALSE;
3081 break;
3082 }
3083 if (p != NULL)
3084 set_string_option_direct((char_u *)"ff", -1, (char_u *)p,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00003085 OPT_FREE | opt_flags, 0);
3086
Bram Moolenaar071d4272004-06-13 20:20:40 +00003087#ifdef FEAT_WINDOWS
Bram Moolenaarf740b292006-02-16 22:11:02 +00003088 /* This may cause the buffer to become (un)modified. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003089 check_status(curbuf);
Bram Moolenaar997fb4b2006-02-17 21:53:23 +00003090 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003091#endif
3092#ifdef FEAT_TITLE
3093 need_maketitle = TRUE; /* set window title later */
3094#endif
3095}
3096
3097/*
3098 * Return the default fileformat from 'fileformats'.
3099 */
3100 int
3101default_fileformat()
3102{
3103 switch (*p_ffs)
3104 {
3105 case 'm': return EOL_MAC;
3106 case 'd': return EOL_DOS;
3107 }
3108 return EOL_UNIX;
3109}
3110
3111/*
3112 * Call shell. Calls mch_call_shell, with 'shellxquote' added.
3113 */
3114 int
3115call_shell(cmd, opt)
3116 char_u *cmd;
3117 int opt;
3118{
3119 char_u *ncmd;
3120 int retval;
Bram Moolenaar05159a02005-02-26 23:04:13 +00003121#ifdef FEAT_PROFILE
3122 proftime_T wait_time;
3123#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003124
3125 if (p_verbose > 3)
3126 {
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00003127 verbose_enter();
Bram Moolenaar051b7822005-05-19 21:00:46 +00003128 smsg((char_u *)_("Calling shell to execute: \"%s\""),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003129 cmd == NULL ? p_sh : cmd);
3130 out_char('\n');
3131 cursor_on();
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00003132 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003133 }
3134
Bram Moolenaar05159a02005-02-26 23:04:13 +00003135#ifdef FEAT_PROFILE
Bram Moolenaar01265852006-03-20 21:50:15 +00003136 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00003137 prof_child_enter(&wait_time);
3138#endif
3139
Bram Moolenaar071d4272004-06-13 20:20:40 +00003140 if (*p_sh == NUL)
3141 {
3142 EMSG(_(e_shellempty));
3143 retval = -1;
3144 }
3145 else
3146 {
3147#ifdef FEAT_GUI_MSWIN
3148 /* Don't hide the pointer while executing a shell command. */
3149 gui_mch_mousehide(FALSE);
3150#endif
3151#ifdef FEAT_GUI
3152 ++hold_gui_events;
3153#endif
3154 /* The external command may update a tags file, clear cached tags. */
3155 tag_freematch();
3156
3157 if (cmd == NULL || *p_sxq == NUL)
3158 retval = mch_call_shell(cmd, opt);
3159 else
3160 {
3161 ncmd = alloc((unsigned)(STRLEN(cmd) + STRLEN(p_sxq) * 2 + 1));
3162 if (ncmd != NULL)
3163 {
3164 STRCPY(ncmd, p_sxq);
3165 STRCAT(ncmd, cmd);
3166 STRCAT(ncmd, p_sxq);
3167 retval = mch_call_shell(ncmd, opt);
3168 vim_free(ncmd);
3169 }
3170 else
3171 retval = -1;
3172 }
3173#ifdef FEAT_GUI
3174 --hold_gui_events;
3175#endif
3176 /*
3177 * Check the window size, in case it changed while executing the
3178 * external command.
3179 */
3180 shell_resized_check();
3181 }
3182
3183#ifdef FEAT_EVAL
3184 set_vim_var_nr(VV_SHELL_ERROR, (long)retval);
Bram Moolenaar05159a02005-02-26 23:04:13 +00003185# ifdef FEAT_PROFILE
Bram Moolenaar01265852006-03-20 21:50:15 +00003186 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00003187 prof_child_exit(&wait_time);
3188# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003189#endif
3190
3191 return retval;
3192}
3193
3194/*
Bram Moolenaar01265852006-03-20 21:50:15 +00003195 * VISUAL, SELECTMODE and OP_PENDING State are never set, they are equal to
3196 * NORMAL State with a condition. This function returns the real State.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003197 */
3198 int
3199get_real_state()
3200{
3201 if (State & NORMAL)
3202 {
3203#ifdef FEAT_VISUAL
3204 if (VIsual_active)
Bram Moolenaar01265852006-03-20 21:50:15 +00003205 {
3206 if (VIsual_select)
3207 return SELECTMODE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003208 return VISUAL;
Bram Moolenaar01265852006-03-20 21:50:15 +00003209 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003210 else
3211#endif
3212 if (finish_op)
Bram Moolenaar01265852006-03-20 21:50:15 +00003213 return OP_PENDING;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003214 }
3215 return State;
3216}
3217
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003218#if defined(FEAT_MBYTE) || defined(PROTO)
3219/*
3220 * Return TRUE if "p" points to just after a path separator.
3221 * Take care of multi-byte characters.
3222 * "b" must point to the start of the file name
3223 */
3224 int
3225after_pathsep(b, p)
3226 char_u *b;
3227 char_u *p;
3228{
3229 return vim_ispathsep(p[-1])
3230 && (!has_mbyte || (*mb_head_off)(b, p - 1) == 0);
3231}
3232#endif
3233
3234/*
3235 * Return TRUE if file names "f1" and "f2" are in the same directory.
3236 * "f1" may be a short name, "f2" must be a full path.
3237 */
3238 int
3239same_directory(f1, f2)
3240 char_u *f1;
3241 char_u *f2;
3242{
3243 char_u ffname[MAXPATHL];
3244 char_u *t1;
3245 char_u *t2;
3246
3247 /* safety check */
3248 if (f1 == NULL || f2 == NULL)
3249 return FALSE;
3250
3251 (void)vim_FullName(f1, ffname, MAXPATHL, FALSE);
3252 t1 = gettail_sep(ffname);
3253 t2 = gettail_sep(f2);
3254 return (t1 - ffname == t2 - f2
3255 && pathcmp((char *)ffname, (char *)f2, (int)(t1 - ffname)) == 0);
3256}
3257
Bram Moolenaar071d4272004-06-13 20:20:40 +00003258#if defined(FEAT_SESSION) || defined(MSWIN) || defined(FEAT_GUI_MAC) \
Bram Moolenaar9372a112005-12-06 19:59:18 +00003259 || ((defined(FEAT_GUI_GTK)) \
Bram Moolenaar843ee412004-06-30 16:16:41 +00003260 && ( defined(FEAT_WINDOWS) || defined(FEAT_DND)) ) \
Bram Moolenaar071d4272004-06-13 20:20:40 +00003261 || defined(FEAT_SUN_WORKSHOP) || defined(FEAT_NETBEANS_INTG) \
3262 || defined(PROTO)
3263/*
3264 * Change to a file's directory.
3265 * Caller must call shorten_fnames()!
3266 * Return OK or FAIL.
3267 */
3268 int
3269vim_chdirfile(fname)
3270 char_u *fname;
3271{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003272 char_u dir[MAXPATHL];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003273
Bram Moolenaarbbebc852005-07-18 21:47:53 +00003274 vim_strncpy(dir, fname, MAXPATHL - 1);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003275 *gettail_sep(dir) = NUL;
3276 return mch_chdir((char *)dir) == 0 ? OK : FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003277}
3278#endif
3279
3280#if defined(STAT_IGNORES_SLASH) || defined(PROTO)
3281/*
3282 * Check if "name" ends in a slash and is not a directory.
3283 * Used for systems where stat() ignores a trailing slash on a file name.
3284 * The Vim code assumes a trailing slash is only ignored for a directory.
3285 */
3286 int
3287illegal_slash(name)
3288 char *name;
3289{
3290 if (name[0] == NUL)
3291 return FALSE; /* no file name is not illegal */
3292 if (name[strlen(name) - 1] != '/')
3293 return FALSE; /* no trailing slash */
3294 if (mch_isdir((char_u *)name))
3295 return FALSE; /* trailing slash for a directory */
3296 return TRUE;
3297}
3298#endif
3299
3300#if defined(CURSOR_SHAPE) || defined(PROTO)
3301
3302/*
3303 * Handling of cursor and mouse pointer shapes in various modes.
3304 */
3305
3306cursorentry_T shape_table[SHAPE_IDX_COUNT] =
3307{
3308 /* The values will be filled in from the 'guicursor' and 'mouseshape'
3309 * defaults when Vim starts.
3310 * Adjust the SHAPE_IDX_ defines when making changes! */
3311 {0, 0, 0, 700L, 400L, 250L, 0, 0, "n", SHAPE_CURSOR+SHAPE_MOUSE},
3312 {0, 0, 0, 700L, 400L, 250L, 0, 0, "v", SHAPE_CURSOR+SHAPE_MOUSE},
3313 {0, 0, 0, 700L, 400L, 250L, 0, 0, "i", SHAPE_CURSOR+SHAPE_MOUSE},
3314 {0, 0, 0, 700L, 400L, 250L, 0, 0, "r", SHAPE_CURSOR+SHAPE_MOUSE},
3315 {0, 0, 0, 700L, 400L, 250L, 0, 0, "c", SHAPE_CURSOR+SHAPE_MOUSE},
3316 {0, 0, 0, 700L, 400L, 250L, 0, 0, "ci", SHAPE_CURSOR+SHAPE_MOUSE},
3317 {0, 0, 0, 700L, 400L, 250L, 0, 0, "cr", SHAPE_CURSOR+SHAPE_MOUSE},
3318 {0, 0, 0, 700L, 400L, 250L, 0, 0, "o", SHAPE_CURSOR+SHAPE_MOUSE},
3319 {0, 0, 0, 700L, 400L, 250L, 0, 0, "ve", SHAPE_CURSOR+SHAPE_MOUSE},
3320 {0, 0, 0, 0L, 0L, 0L, 0, 0, "e", SHAPE_MOUSE},
3321 {0, 0, 0, 0L, 0L, 0L, 0, 0, "s", SHAPE_MOUSE},
3322 {0, 0, 0, 0L, 0L, 0L, 0, 0, "sd", SHAPE_MOUSE},
3323 {0, 0, 0, 0L, 0L, 0L, 0, 0, "vs", SHAPE_MOUSE},
3324 {0, 0, 0, 0L, 0L, 0L, 0, 0, "vd", SHAPE_MOUSE},
3325 {0, 0, 0, 0L, 0L, 0L, 0, 0, "m", SHAPE_MOUSE},
3326 {0, 0, 0, 0L, 0L, 0L, 0, 0, "ml", SHAPE_MOUSE},
3327 {0, 0, 0, 100L, 100L, 100L, 0, 0, "sm", SHAPE_CURSOR},
3328};
3329
3330#ifdef FEAT_MOUSESHAPE
3331/*
3332 * Table with names for mouse shapes. Keep in sync with all the tables for
3333 * mch_set_mouse_shape()!.
3334 */
3335static char * mshape_names[] =
3336{
3337 "arrow", /* default, must be the first one */
3338 "blank", /* hidden */
3339 "beam",
3340 "updown",
3341 "udsizing",
3342 "leftright",
3343 "lrsizing",
3344 "busy",
3345 "no",
3346 "crosshair",
3347 "hand1",
3348 "hand2",
3349 "pencil",
3350 "question",
3351 "rightup-arrow",
3352 "up-arrow",
3353 NULL
3354};
3355#endif
3356
3357/*
3358 * Parse the 'guicursor' option ("what" is SHAPE_CURSOR) or 'mouseshape'
3359 * ("what" is SHAPE_MOUSE).
3360 * Returns error message for an illegal option, NULL otherwise.
3361 */
3362 char_u *
3363parse_shape_opt(what)
3364 int what;
3365{
3366 char_u *modep;
3367 char_u *colonp;
3368 char_u *commap;
3369 char_u *slashp;
3370 char_u *p, *endp;
3371 int idx = 0; /* init for GCC */
3372 int all_idx;
3373 int len;
3374 int i;
3375 long n;
3376 int found_ve = FALSE; /* found "ve" flag */
3377 int round;
3378
3379 /*
3380 * First round: check for errors; second round: do it for real.
3381 */
3382 for (round = 1; round <= 2; ++round)
3383 {
3384 /*
3385 * Repeat for all comma separated parts.
3386 */
3387#ifdef FEAT_MOUSESHAPE
3388 if (what == SHAPE_MOUSE)
3389 modep = p_mouseshape;
3390 else
3391#endif
3392 modep = p_guicursor;
3393 while (*modep != NUL)
3394 {
3395 colonp = vim_strchr(modep, ':');
3396 if (colonp == NULL)
3397 return (char_u *)N_("E545: Missing colon");
3398 if (colonp == modep)
3399 return (char_u *)N_("E546: Illegal mode");
3400 commap = vim_strchr(modep, ',');
3401
3402 /*
3403 * Repeat for all mode's before the colon.
3404 * For the 'a' mode, we loop to handle all the modes.
3405 */
3406 all_idx = -1;
3407 while (modep < colonp || all_idx >= 0)
3408 {
3409 if (all_idx < 0)
3410 {
3411 /* Find the mode. */
3412 if (modep[1] == '-' || modep[1] == ':')
3413 len = 1;
3414 else
3415 len = 2;
3416 if (len == 1 && TOLOWER_ASC(modep[0]) == 'a')
3417 all_idx = SHAPE_IDX_COUNT - 1;
3418 else
3419 {
3420 for (idx = 0; idx < SHAPE_IDX_COUNT; ++idx)
3421 if (STRNICMP(modep, shape_table[idx].name, len)
3422 == 0)
3423 break;
3424 if (idx == SHAPE_IDX_COUNT
3425 || (shape_table[idx].used_for & what) == 0)
3426 return (char_u *)N_("E546: Illegal mode");
3427 if (len == 2 && modep[0] == 'v' && modep[1] == 'e')
3428 found_ve = TRUE;
3429 }
3430 modep += len + 1;
3431 }
3432
3433 if (all_idx >= 0)
3434 idx = all_idx--;
3435 else if (round == 2)
3436 {
3437#ifdef FEAT_MOUSESHAPE
3438 if (what == SHAPE_MOUSE)
3439 {
3440 /* Set the default, for the missing parts */
3441 shape_table[idx].mshape = 0;
3442 }
3443 else
3444#endif
3445 {
3446 /* Set the defaults, for the missing parts */
3447 shape_table[idx].shape = SHAPE_BLOCK;
3448 shape_table[idx].blinkwait = 700L;
3449 shape_table[idx].blinkon = 400L;
3450 shape_table[idx].blinkoff = 250L;
3451 }
3452 }
3453
3454 /* Parse the part after the colon */
3455 for (p = colonp + 1; *p && *p != ','; )
3456 {
3457#ifdef FEAT_MOUSESHAPE
3458 if (what == SHAPE_MOUSE)
3459 {
3460 for (i = 0; ; ++i)
3461 {
3462 if (mshape_names[i] == NULL)
3463 {
3464 if (!VIM_ISDIGIT(*p))
3465 return (char_u *)N_("E547: Illegal mouseshape");
3466 if (round == 2)
3467 shape_table[idx].mshape =
3468 getdigits(&p) + MSHAPE_NUMBERED;
3469 else
3470 (void)getdigits(&p);
3471 break;
3472 }
3473 len = (int)STRLEN(mshape_names[i]);
3474 if (STRNICMP(p, mshape_names[i], len) == 0)
3475 {
3476 if (round == 2)
3477 shape_table[idx].mshape = i;
3478 p += len;
3479 break;
3480 }
3481 }
3482 }
3483 else /* if (what == SHAPE_MOUSE) */
3484#endif
3485 {
3486 /*
3487 * First handle the ones with a number argument.
3488 */
3489 i = *p;
3490 len = 0;
3491 if (STRNICMP(p, "ver", 3) == 0)
3492 len = 3;
3493 else if (STRNICMP(p, "hor", 3) == 0)
3494 len = 3;
3495 else if (STRNICMP(p, "blinkwait", 9) == 0)
3496 len = 9;
3497 else if (STRNICMP(p, "blinkon", 7) == 0)
3498 len = 7;
3499 else if (STRNICMP(p, "blinkoff", 8) == 0)
3500 len = 8;
3501 if (len != 0)
3502 {
3503 p += len;
3504 if (!VIM_ISDIGIT(*p))
3505 return (char_u *)N_("E548: digit expected");
3506 n = getdigits(&p);
3507 if (len == 3) /* "ver" or "hor" */
3508 {
3509 if (n == 0)
3510 return (char_u *)N_("E549: Illegal percentage");
3511 if (round == 2)
3512 {
3513 if (TOLOWER_ASC(i) == 'v')
3514 shape_table[idx].shape = SHAPE_VER;
3515 else
3516 shape_table[idx].shape = SHAPE_HOR;
3517 shape_table[idx].percentage = n;
3518 }
3519 }
3520 else if (round == 2)
3521 {
3522 if (len == 9)
3523 shape_table[idx].blinkwait = n;
3524 else if (len == 7)
3525 shape_table[idx].blinkon = n;
3526 else
3527 shape_table[idx].blinkoff = n;
3528 }
3529 }
3530 else if (STRNICMP(p, "block", 5) == 0)
3531 {
3532 if (round == 2)
3533 shape_table[idx].shape = SHAPE_BLOCK;
3534 p += 5;
3535 }
3536 else /* must be a highlight group name then */
3537 {
3538 endp = vim_strchr(p, '-');
3539 if (commap == NULL) /* last part */
3540 {
3541 if (endp == NULL)
3542 endp = p + STRLEN(p); /* find end of part */
3543 }
3544 else if (endp > commap || endp == NULL)
3545 endp = commap;
3546 slashp = vim_strchr(p, '/');
3547 if (slashp != NULL && slashp < endp)
3548 {
3549 /* "group/langmap_group" */
3550 i = syn_check_group(p, (int)(slashp - p));
3551 p = slashp + 1;
3552 }
3553 if (round == 2)
3554 {
3555 shape_table[idx].id = syn_check_group(p,
3556 (int)(endp - p));
3557 shape_table[idx].id_lm = shape_table[idx].id;
3558 if (slashp != NULL && slashp < endp)
3559 shape_table[idx].id = i;
3560 }
3561 p = endp;
3562 }
3563 } /* if (what != SHAPE_MOUSE) */
3564
3565 if (*p == '-')
3566 ++p;
3567 }
3568 }
3569 modep = p;
3570 if (*modep == ',')
3571 ++modep;
3572 }
3573 }
3574
3575 /* If the 's' flag is not given, use the 'v' cursor for 's' */
3576 if (!found_ve)
3577 {
3578#ifdef FEAT_MOUSESHAPE
3579 if (what == SHAPE_MOUSE)
3580 {
3581 shape_table[SHAPE_IDX_VE].mshape = shape_table[SHAPE_IDX_V].mshape;
3582 }
3583 else
3584#endif
3585 {
3586 shape_table[SHAPE_IDX_VE].shape = shape_table[SHAPE_IDX_V].shape;
3587 shape_table[SHAPE_IDX_VE].percentage =
3588 shape_table[SHAPE_IDX_V].percentage;
3589 shape_table[SHAPE_IDX_VE].blinkwait =
3590 shape_table[SHAPE_IDX_V].blinkwait;
3591 shape_table[SHAPE_IDX_VE].blinkon =
3592 shape_table[SHAPE_IDX_V].blinkon;
3593 shape_table[SHAPE_IDX_VE].blinkoff =
3594 shape_table[SHAPE_IDX_V].blinkoff;
3595 shape_table[SHAPE_IDX_VE].id = shape_table[SHAPE_IDX_V].id;
3596 shape_table[SHAPE_IDX_VE].id_lm = shape_table[SHAPE_IDX_V].id_lm;
3597 }
3598 }
3599
3600 return NULL;
3601}
3602
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00003603# if defined(MCH_CURSOR_SHAPE) || defined(FEAT_GUI) \
3604 || defined(FEAT_MOUSESHAPE) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003605/*
3606 * Return the index into shape_table[] for the current mode.
3607 * When "mouse" is TRUE, consider indexes valid for the mouse pointer.
3608 */
3609 int
3610get_shape_idx(mouse)
3611 int mouse;
3612{
3613#ifdef FEAT_MOUSESHAPE
3614 if (mouse && (State == HITRETURN || State == ASKMORE))
3615 {
3616# ifdef FEAT_GUI
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00003617 int x, y;
3618 gui_mch_getmouse(&x, &y);
3619 if (Y_2_ROW(y) == Rows - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003620 return SHAPE_IDX_MOREL;
3621# endif
3622 return SHAPE_IDX_MORE;
3623 }
3624 if (mouse && drag_status_line)
3625 return SHAPE_IDX_SDRAG;
3626# ifdef FEAT_VERTSPLIT
3627 if (mouse && drag_sep_line)
3628 return SHAPE_IDX_VDRAG;
3629# endif
3630#endif
3631 if (!mouse && State == SHOWMATCH)
3632 return SHAPE_IDX_SM;
3633#ifdef FEAT_VREPLACE
3634 if (State & VREPLACE_FLAG)
3635 return SHAPE_IDX_R;
3636#endif
3637 if (State & REPLACE_FLAG)
3638 return SHAPE_IDX_R;
3639 if (State & INSERT)
3640 return SHAPE_IDX_I;
3641 if (State & CMDLINE)
3642 {
3643 if (cmdline_at_end())
3644 return SHAPE_IDX_C;
3645 if (cmdline_overstrike())
3646 return SHAPE_IDX_CR;
3647 return SHAPE_IDX_CI;
3648 }
3649 if (finish_op)
3650 return SHAPE_IDX_O;
3651#ifdef FEAT_VISUAL
3652 if (VIsual_active)
3653 {
3654 if (*p_sel == 'e')
3655 return SHAPE_IDX_VE;
3656 else
3657 return SHAPE_IDX_V;
3658 }
3659#endif
3660 return SHAPE_IDX_N;
3661}
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00003662#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003663
3664# if defined(FEAT_MOUSESHAPE) || defined(PROTO)
3665static int old_mouse_shape = 0;
3666
3667/*
3668 * Set the mouse shape:
3669 * If "shape" is -1, use shape depending on the current mode,
3670 * depending on the current state.
3671 * If "shape" is -2, only update the shape when it's CLINE or STATUS (used
3672 * when the mouse moves off the status or command line).
3673 */
3674 void
3675update_mouseshape(shape_idx)
3676 int shape_idx;
3677{
3678 int new_mouse_shape;
3679
3680 /* Only works in GUI mode. */
Bram Moolenaar6bb68362005-03-22 23:03:44 +00003681 if (!gui.in_use || gui.starting)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003682 return;
3683
3684 /* Postpone the updating when more is to come. Speeds up executing of
3685 * mappings. */
3686 if (shape_idx == -1 && char_avail())
3687 {
3688 postponed_mouseshape = TRUE;
3689 return;
3690 }
3691
Bram Moolenaar14716812006-05-04 21:54:08 +00003692 /* When ignoring the mouse don't change shape on the statusline. */
3693 if (*p_mouse == NUL
3694 && (shape_idx == SHAPE_IDX_CLINE
3695 || shape_idx == SHAPE_IDX_STATUS
3696 || shape_idx == SHAPE_IDX_VSEP))
3697 shape_idx = -2;
3698
Bram Moolenaar071d4272004-06-13 20:20:40 +00003699 if (shape_idx == -2
3700 && old_mouse_shape != shape_table[SHAPE_IDX_CLINE].mshape
3701 && old_mouse_shape != shape_table[SHAPE_IDX_STATUS].mshape
3702 && old_mouse_shape != shape_table[SHAPE_IDX_VSEP].mshape)
3703 return;
3704 if (shape_idx < 0)
3705 new_mouse_shape = shape_table[get_shape_idx(TRUE)].mshape;
3706 else
3707 new_mouse_shape = shape_table[shape_idx].mshape;
3708 if (new_mouse_shape != old_mouse_shape)
3709 {
3710 mch_set_mouse_shape(new_mouse_shape);
3711 old_mouse_shape = new_mouse_shape;
3712 }
3713 postponed_mouseshape = FALSE;
3714}
3715# endif
3716
3717#endif /* CURSOR_SHAPE */
3718
3719
3720#ifdef FEAT_CRYPT
3721/*
Bram Moolenaar7aa9f6a2007-05-10 18:00:30 +00003722 * Optional encryption support.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003723 * Mohsin Ahmed, mosh@sasi.com, 98-09-24
3724 * Based on zip/crypt sources.
3725 *
3726 * NOTE FOR USA: Since 2000 exporting this code from the USA is allowed to
3727 * most countries. There are a few exceptions, but that still should not be a
3728 * problem since this code was originally created in Europe and India.
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003729 *
3730 * Blowfish addition originally made by Mohsin Ahmed,
3731 * http://www.cs.albany.edu/~mosh 2010-03-14
3732 * Based on blowfish by Bruce Schneier (http://www.schneier.com/blowfish.html)
3733 * and sha256 by Christophe Devine.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003734 */
3735
3736/* from zip.h */
3737
3738typedef unsigned short ush; /* unsigned 16-bit value */
3739typedef unsigned long ulg; /* unsigned 32-bit value */
3740
3741static void make_crc_tab __ARGS((void));
3742
Bram Moolenaard6f676d2005-06-01 21:51:55 +00003743static ulg crc_32_tab[256];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003744
3745/*
3746 * Fill the CRC table.
3747 */
3748 static void
3749make_crc_tab()
3750{
3751 ulg s,t,v;
3752 static int done = FALSE;
3753
3754 if (done)
3755 return;
3756 for (t = 0; t < 256; t++)
3757 {
3758 v = t;
3759 for (s = 0; s < 8; s++)
3760 v = (v >> 1) ^ ((v & 1) * (ulg)0xedb88320L);
3761 crc_32_tab[t] = v;
3762 }
3763 done = TRUE;
3764}
3765
3766#define CRC32(c, b) (crc_32_tab[((int)(c) ^ (b)) & 0xff] ^ ((c) >> 8))
3767
Bram Moolenaar071d4272004-06-13 20:20:40 +00003768static ulg keys[3]; /* keys defining the pseudo-random sequence */
3769
3770/*
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02003771 * Return the next byte in the pseudo-random sequence.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003772 */
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02003773#define DECRYPT_BYTE_ZIP(t) { \
3774 ush temp; \
3775 \
3776 temp = (ush)keys[2] | 2; \
3777 t = (int)(((unsigned)(temp * (temp ^ 1)) >> 8) & 0xff); \
Bram Moolenaar071d4272004-06-13 20:20:40 +00003778}
3779
3780/*
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02003781 * Update the encryption keys with the next byte of plain text.
3782 */
3783#define UPDATE_KEYS_ZIP(c) { \
3784 keys[0] = CRC32(keys[0], (c)); \
3785 keys[1] += keys[0] & 0xff; \
3786 keys[1] = keys[1] * 134775813L + 1; \
3787 keys[2] = CRC32(keys[2], (int)(keys[1] >> 24)); \
3788}
3789
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003790static int crypt_busy = 0;
3791static ulg saved_keys[3];
3792static int saved_crypt_method;
3793
3794/*
Bram Moolenaar49771f42010-07-20 17:32:38 +02003795 * Return int value for crypt method string:
3796 * 0 for "zip", the old method. Also for any non-valid value.
3797 * 1 for "blowfish".
3798 */
3799 int
3800crypt_method_from_string(s)
3801 char_u *s;
3802{
3803 return *s == 'b' ? 1 : 0;
3804}
3805
3806/*
3807 * Get the crypt method for buffer "buf" as a number.
3808 */
3809 int
3810get_crypt_method(buf)
3811 buf_T *buf;
3812{
3813 return crypt_method_from_string(*buf->b_p_cm == NUL ? p_cm : buf->b_p_cm);
3814}
3815
3816/*
3817 * Set the crypt method for buffer "buf" to "method" using the int value as
3818 * returned by crypt_method_from_string().
3819 */
3820 void
3821set_crypt_method(buf, method)
3822 buf_T *buf;
3823 int method;
3824{
3825 free_string_option(buf->b_p_cm);
3826 buf->b_p_cm = vim_strsave((char_u *)(method == 0 ? "zip" : "blowfish"));
3827}
3828
3829/*
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003830 * Prepare for initializing encryption. If already doing encryption then save
3831 * the state.
Bram Moolenaar2f1e0502010-08-13 11:18:02 +02003832 * Must always be called symmetrically with crypt_pop_state().
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003833 */
3834 void
3835crypt_push_state()
3836{
3837 if (crypt_busy == 1)
3838 {
3839 /* save the state */
3840 if (use_crypt_method == 0)
3841 {
3842 saved_keys[0] = keys[0];
3843 saved_keys[1] = keys[1];
3844 saved_keys[2] = keys[2];
3845 }
3846 else
3847 bf_crypt_save();
3848 saved_crypt_method = use_crypt_method;
3849 }
3850 else if (crypt_busy > 1)
3851 EMSG2(_(e_intern2), "crypt_push_state()");
3852 ++crypt_busy;
3853}
3854
3855/*
3856 * End encryption. If doing encryption before crypt_push_state() then restore
3857 * the saved state.
Bram Moolenaar2f1e0502010-08-13 11:18:02 +02003858 * Must always be called symmetrically with crypt_push_state().
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003859 */
3860 void
3861crypt_pop_state()
3862{
3863 --crypt_busy;
3864 if (crypt_busy == 1)
3865 {
3866 use_crypt_method = saved_crypt_method;
3867 if (use_crypt_method == 0)
3868 {
3869 keys[0] = saved_keys[0];
3870 keys[1] = saved_keys[1];
3871 keys[2] = saved_keys[2];
3872 }
3873 else
3874 bf_crypt_restore();
3875 }
3876}
3877
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02003878/*
3879 * Encrypt "from[len]" into "to[len]".
3880 * "from" and "to" can be equal to encrypt in place.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003881 */
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003882 void
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02003883crypt_encode(from, len, to)
3884 char_u *from;
3885 size_t len;
3886 char_u *to;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003887{
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02003888 size_t i;
3889 int ztemp, t;
3890
3891 if (use_crypt_method == 0)
3892 for (i = 0; i < len; ++i)
3893 {
3894 ztemp = from[i];
3895 DECRYPT_BYTE_ZIP(t);
3896 UPDATE_KEYS_ZIP(ztemp);
3897 to[i] = t ^ ztemp;
3898 }
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003899 else
Bram Moolenaarbbd6afe2010-06-02 20:32:23 +02003900 bf_crypt_encode(from, len, to);
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02003901}
3902
3903/*
3904 * Decrypt "ptr[len]" in place.
3905 */
3906 void
3907crypt_decode(ptr, len)
3908 char_u *ptr;
3909 long len;
3910{
3911 char_u *p;
3912
3913 if (use_crypt_method == 0)
3914 for (p = ptr; p < ptr + len; ++p)
3915 {
3916 ush temp;
3917
3918 temp = (ush)keys[2] | 2;
3919 temp = (int)(((unsigned)(temp * (temp ^ 1)) >> 8) & 0xff);
3920 UPDATE_KEYS_ZIP(*p ^= temp);
3921 }
3922 else
Bram Moolenaarbbd6afe2010-06-02 20:32:23 +02003923 bf_crypt_decode(ptr, len);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003924}
3925
3926/*
3927 * Initialize the encryption keys and the random header according to
3928 * the given password.
3929 * If "passwd" is NULL or empty, don't do anything.
3930 */
3931 void
3932crypt_init_keys(passwd)
3933 char_u *passwd; /* password string with which to modify keys */
3934{
3935 if (passwd != NULL && *passwd != NUL)
3936 {
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02003937 if (use_crypt_method == 0)
Bram Moolenaarbbd6afe2010-06-02 20:32:23 +02003938 {
3939 char_u *p;
3940
3941 make_crc_tab();
3942 keys[0] = 305419896L;
3943 keys[1] = 591751049L;
3944 keys[2] = 878082192L;
3945 for (p = passwd; *p!= NUL; ++p)
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02003946 {
Bram Moolenaarbbd6afe2010-06-02 20:32:23 +02003947 UPDATE_KEYS_ZIP((int)*p);
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02003948 }
Bram Moolenaarbbd6afe2010-06-02 20:32:23 +02003949 }
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02003950 else
Bram Moolenaarbbd6afe2010-06-02 20:32:23 +02003951 bf_crypt_init_keys(passwd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003952 }
3953}
3954
3955/*
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003956 * Free an allocated crypt key. Clear the text to make sure it doesn't stay
3957 * in memory anywhere.
3958 */
3959 void
3960free_crypt_key(key)
3961 char_u *key;
3962{
3963 char_u *p;
3964
3965 if (key != NULL)
3966 {
3967 for (p = key; *p != NUL; ++p)
Bram Moolenaarbe18d102010-05-22 21:37:53 +02003968 *p = 0;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003969 vim_free(key);
3970 }
3971}
3972
3973/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003974 * Ask the user for a crypt key.
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003975 * When "store" is TRUE, the new key is stored in the 'key' option, and the
Bram Moolenaar071d4272004-06-13 20:20:40 +00003976 * 'key' option value is returned: Don't free it.
3977 * When "store" is FALSE, the typed key is returned in allocated memory.
3978 * Returns NULL on failure.
3979 */
3980 char_u *
3981get_crypt_key(store, twice)
3982 int store;
3983 int twice; /* Ask for the key twice. */
3984{
3985 char_u *p1, *p2 = NULL;
3986 int round;
3987
3988 for (round = 0; ; ++round)
3989 {
3990 cmdline_star = TRUE;
3991 cmdline_row = msg_row;
3992 p1 = getcmdline_prompt(NUL, round == 0
3993 ? (char_u *)_("Enter encryption key: ")
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00003994 : (char_u *)_("Enter same key again: "), 0, EXPAND_NOTHING,
3995 NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003996 cmdline_star = FALSE;
3997
3998 if (p1 == NULL)
3999 break;
4000
4001 if (round == twice)
4002 {
4003 if (p2 != NULL && STRCMP(p1, p2) != 0)
4004 {
4005 MSG(_("Keys don't match!"));
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004006 free_crypt_key(p1);
4007 free_crypt_key(p2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004008 p2 = NULL;
4009 round = -1; /* do it again */
4010 continue;
4011 }
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004012
Bram Moolenaar071d4272004-06-13 20:20:40 +00004013 if (store)
4014 {
4015 set_option_value((char_u *)"key", 0L, p1, OPT_LOCAL);
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004016 free_crypt_key(p1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004017 p1 = curbuf->b_p_key;
4018 }
4019 break;
4020 }
4021 p2 = p1;
4022 }
4023
4024 /* since the user typed this, no need to wait for return */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004025 if (msg_didout)
4026 msg_putchar('\n');
Bram Moolenaare4ce65d2010-08-04 20:12:32 +02004027 need_wait_return = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004028 msg_didout = FALSE;
4029
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004030 free_crypt_key(p2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004031 return p1;
4032}
4033
4034#endif /* FEAT_CRYPT */
4035
4036/* TODO: make some #ifdef for this */
4037/*--------[ file searching ]-------------------------------------------------*/
4038/*
4039 * File searching functions for 'path', 'tags' and 'cdpath' options.
4040 * External visible functions:
4041 * vim_findfile_init() creates/initialises the search context
4042 * vim_findfile_free_visited() free list of visited files/dirs of search
4043 * context
4044 * vim_findfile() find a file in the search context
4045 * vim_findfile_cleanup() cleanup/free search context created by
4046 * vim_findfile_init()
4047 *
4048 * All static functions and variables start with 'ff_'
4049 *
4050 * In general it works like this:
4051 * First you create yourself a search context by calling vim_findfile_init().
4052 * It is possible to give a search context from a previous call to
4053 * vim_findfile_init(), so it can be reused. After this you call vim_findfile()
4054 * until you are satisfied with the result or it returns NULL. On every call it
4055 * returns the next file which matches the conditions given to
4056 * vim_findfile_init(). If it doesn't find a next file it returns NULL.
4057 *
4058 * It is possible to call vim_findfile_init() again to reinitialise your search
4059 * with some new parameters. Don't forget to pass your old search context to
4060 * it, so it can reuse it and especially reuse the list of already visited
4061 * directories. If you want to delete the list of already visited directories
4062 * simply call vim_findfile_free_visited().
4063 *
4064 * When you are done call vim_findfile_cleanup() to free the search context.
4065 *
4066 * The function vim_findfile_init() has a long comment, which describes the
4067 * needed parameters.
4068 *
4069 *
4070 *
4071 * ATTENTION:
4072 * ==========
Bram Moolenaar77f66d62007-02-20 02:16:18 +00004073 * Also we use an allocated search context here, this functions are NOT
Bram Moolenaar071d4272004-06-13 20:20:40 +00004074 * thread-safe!!!!!
4075 *
4076 * To minimize parameter passing (or because I'm to lazy), only the
4077 * external visible functions get a search context as a parameter. This is
4078 * then assigned to a static global, which is used throughout the local
4079 * functions.
4080 */
4081
4082/*
4083 * type for the directory search stack
4084 */
4085typedef struct ff_stack
4086{
4087 struct ff_stack *ffs_prev;
4088
4089 /* the fix part (no wildcards) and the part containing the wildcards
4090 * of the search path
4091 */
4092 char_u *ffs_fix_path;
4093#ifdef FEAT_PATH_EXTRA
4094 char_u *ffs_wc_path;
4095#endif
4096
4097 /* files/dirs found in the above directory, matched by the first wildcard
4098 * of wc_part
4099 */
4100 char_u **ffs_filearray;
4101 int ffs_filearray_size;
4102 char_u ffs_filearray_cur; /* needed for partly handled dirs */
4103
4104 /* to store status of partly handled directories
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004105 * 0: we work on this directory for the first time
Bram Moolenaar071d4272004-06-13 20:20:40 +00004106 * 1: this directory was partly searched in an earlier step
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004107 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004108 int ffs_stage;
4109
4110 /* How deep are we in the directory tree?
4111 * Counts backward from value of level parameter to vim_findfile_init
4112 */
4113 int ffs_level;
4114
4115 /* Did we already expand '**' to an empty string? */
4116 int ffs_star_star_empty;
4117} ff_stack_T;
4118
4119/*
4120 * type for already visited directories or files.
4121 */
4122typedef struct ff_visited
4123{
4124 struct ff_visited *ffv_next;
4125
4126#ifdef FEAT_PATH_EXTRA
4127 /* Visited directories are different if the wildcard string are
4128 * different. So we have to save it.
4129 */
4130 char_u *ffv_wc_path;
4131#endif
4132 /* for unix use inode etc for comparison (needed because of links), else
4133 * use filename.
4134 */
4135#ifdef UNIX
Bram Moolenaare1fbddc2009-05-16 19:07:03 +00004136 int ffv_dev_valid; /* ffv_dev and ffv_ino were set */
4137 dev_t ffv_dev; /* device number */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004138 ino_t ffv_ino; /* inode number */
4139#endif
4140 /* The memory for this struct is allocated according to the length of
4141 * ffv_fname.
4142 */
4143 char_u ffv_fname[1]; /* actually longer */
4144} ff_visited_T;
4145
4146/*
4147 * We might have to manage several visited lists during a search.
Bram Moolenaar7aa9f6a2007-05-10 18:00:30 +00004148 * This is especially needed for the tags option. If tags is set to:
Bram Moolenaar071d4272004-06-13 20:20:40 +00004149 * "./++/tags,./++/TAGS,++/tags" (replace + with *)
4150 * So we have to do 3 searches:
4151 * 1) search from the current files directory downward for the file "tags"
4152 * 2) search from the current files directory downward for the file "TAGS"
4153 * 3) search from Vims current directory downwards for the file "tags"
4154 * As you can see, the first and the third search are for the same file, so for
4155 * the third search we can use the visited list of the first search. For the
4156 * second search we must start from a empty visited list.
4157 * The struct ff_visited_list_hdr is used to manage a linked list of already
4158 * visited lists.
4159 */
4160typedef struct ff_visited_list_hdr
4161{
4162 struct ff_visited_list_hdr *ffvl_next;
4163
4164 /* the filename the attached visited list is for */
4165 char_u *ffvl_filename;
4166
4167 ff_visited_T *ffvl_visited_list;
4168
4169} ff_visited_list_hdr_T;
4170
4171
4172/*
4173 * '**' can be expanded to several directory levels.
Bram Moolenaar7aa9f6a2007-05-10 18:00:30 +00004174 * Set the default maximum depth.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004175 */
4176#define FF_MAX_STAR_STAR_EXPAND ((char_u)30)
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004177
Bram Moolenaar071d4272004-06-13 20:20:40 +00004178/*
4179 * The search context:
4180 * ffsc_stack_ptr: the stack for the dirs to search
4181 * ffsc_visited_list: the currently active visited list
4182 * ffsc_dir_visited_list: the currently active visited list for search dirs
4183 * ffsc_visited_lists_list: the list of all visited lists
4184 * ffsc_dir_visited_lists_list: the list of all visited lists for search dirs
4185 * ffsc_file_to_search: the file to search for
4186 * ffsc_start_dir: the starting directory, if search path was relative
4187 * ffsc_fix_path: the fix part of the given path (without wildcards)
4188 * Needed for upward search.
4189 * ffsc_wc_path: the part of the given path containing wildcards
4190 * ffsc_level: how many levels of dirs to search downwards
4191 * ffsc_stopdirs_v: array of stop directories for upward search
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004192 * ffsc_find_what: FINDFILE_BOTH, FINDFILE_DIR or FINDFILE_FILE
Bram Moolenaar463ee342010-08-08 18:17:52 +02004193 * ffsc_tagfile: searching for tags file, don't use 'suffixesadd'
Bram Moolenaar071d4272004-06-13 20:20:40 +00004194 */
4195typedef struct ff_search_ctx_T
4196{
4197 ff_stack_T *ffsc_stack_ptr;
4198 ff_visited_list_hdr_T *ffsc_visited_list;
4199 ff_visited_list_hdr_T *ffsc_dir_visited_list;
4200 ff_visited_list_hdr_T *ffsc_visited_lists_list;
4201 ff_visited_list_hdr_T *ffsc_dir_visited_lists_list;
4202 char_u *ffsc_file_to_search;
4203 char_u *ffsc_start_dir;
4204 char_u *ffsc_fix_path;
4205#ifdef FEAT_PATH_EXTRA
4206 char_u *ffsc_wc_path;
4207 int ffsc_level;
4208 char_u **ffsc_stopdirs_v;
4209#endif
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004210 int ffsc_find_what;
Bram Moolenaar463ee342010-08-08 18:17:52 +02004211 int ffsc_tagfile;
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00004212} ff_search_ctx_T;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004213
Bram Moolenaar071d4272004-06-13 20:20:40 +00004214/* locally needed functions */
4215#ifdef FEAT_PATH_EXTRA
4216static int ff_check_visited __ARGS((ff_visited_T **, char_u *, char_u *));
4217#else
4218static int ff_check_visited __ARGS((ff_visited_T **, char_u *));
4219#endif
4220static void vim_findfile_free_visited_list __ARGS((ff_visited_list_hdr_T **list_headp));
4221static void ff_free_visited_list __ARGS((ff_visited_T *vl));
4222static ff_visited_list_hdr_T* ff_get_visited_list __ARGS((char_u *, ff_visited_list_hdr_T **list_headp));
4223#ifdef FEAT_PATH_EXTRA
4224static int ff_wc_equal __ARGS((char_u *s1, char_u *s2));
4225#endif
4226
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004227static void ff_push __ARGS((ff_search_ctx_T *search_ctx, ff_stack_T *stack_ptr));
4228static ff_stack_T *ff_pop __ARGS((ff_search_ctx_T *search_ctx));
4229static void ff_clear __ARGS((ff_search_ctx_T *search_ctx));
4230static void ff_free_stack_element __ARGS((ff_stack_T *stack_ptr));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004231#ifdef FEAT_PATH_EXTRA
4232static ff_stack_T *ff_create_stack_element __ARGS((char_u *, char_u *, int, int));
4233#else
4234static ff_stack_T *ff_create_stack_element __ARGS((char_u *, int, int));
4235#endif
4236#ifdef FEAT_PATH_EXTRA
4237static int ff_path_in_stoplist __ARGS((char_u *, int, char_u **));
4238#endif
4239
Bram Moolenaar071d4272004-06-13 20:20:40 +00004240#if 0
4241/*
4242 * if someone likes findfirst/findnext, here are the functions
4243 * NOT TESTED!!
4244 */
4245
4246static void *ff_fn_search_context = NULL;
4247
4248 char_u *
4249vim_findfirst(path, filename, level)
4250 char_u *path;
4251 char_u *filename;
4252 int level;
4253{
4254 ff_fn_search_context =
4255 vim_findfile_init(path, filename, NULL, level, TRUE, FALSE,
4256 ff_fn_search_context, rel_fname);
4257 if (NULL == ff_fn_search_context)
4258 return NULL;
4259 else
4260 return vim_findnext()
4261}
4262
4263 char_u *
4264vim_findnext()
4265{
4266 char_u *ret = vim_findfile(ff_fn_search_context);
4267
4268 if (NULL == ret)
4269 {
4270 vim_findfile_cleanup(ff_fn_search_context);
4271 ff_fn_search_context = NULL;
4272 }
4273 return ret;
4274}
4275#endif
4276
4277/*
Bram Moolenaare2b590e2010-08-08 18:29:48 +02004278 * Initialization routine for vim_findfile().
Bram Moolenaar071d4272004-06-13 20:20:40 +00004279 *
Bram Moolenaarbe18d102010-05-22 21:37:53 +02004280 * Returns the newly allocated search context or NULL if an error occurred.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004281 *
4282 * Don't forget to clean up by calling vim_findfile_cleanup() if you are done
4283 * with the search context.
4284 *
4285 * Find the file 'filename' in the directory 'path'.
4286 * The parameter 'path' may contain wildcards. If so only search 'level'
4287 * directories deep. The parameter 'level' is the absolute maximum and is
4288 * not related to restricts given to the '**' wildcard. If 'level' is 100
4289 * and you use '**200' vim_findfile() will stop after 100 levels.
4290 *
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004291 * 'filename' cannot contain wildcards! It is used as-is, no backslashes to
4292 * escape special characters.
4293 *
Bram Moolenaar071d4272004-06-13 20:20:40 +00004294 * If 'stopdirs' is not NULL and nothing is found downward, the search is
4295 * restarted on the next higher directory level. This is repeated until the
4296 * start-directory of a search is contained in 'stopdirs'. 'stopdirs' has the
4297 * format ";*<dirname>*\(;<dirname>\)*;\=$".
4298 *
4299 * If the 'path' is relative, the starting dir for the search is either VIM's
4300 * current dir or if the path starts with "./" the current files dir.
Bram Moolenaarbe18d102010-05-22 21:37:53 +02004301 * If the 'path' is absolute, the starting dir is that part of the path before
Bram Moolenaar071d4272004-06-13 20:20:40 +00004302 * the first wildcard.
4303 *
4304 * Upward search is only done on the starting dir.
4305 *
4306 * If 'free_visited' is TRUE the list of already visited files/directories is
4307 * cleared. Set this to FALSE if you just want to search from another
4308 * directory, but want to be sure that no directory from a previous search is
4309 * searched again. This is useful if you search for a file at different places.
4310 * The list of visited files/dirs can also be cleared with the function
4311 * vim_findfile_free_visited().
4312 *
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004313 * Set the parameter 'find_what' to FINDFILE_DIR if you want to search for
4314 * directories only, FINDFILE_FILE for files only, FINDFILE_BOTH for both.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004315 *
4316 * A search context returned by a previous call to vim_findfile_init() can be
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004317 * passed in the parameter "search_ctx_arg". This context is reused and
4318 * reinitialized with the new parameters. The list of already visited
Bram Moolenaar071d4272004-06-13 20:20:40 +00004319 * directories from this context is only deleted if the parameter
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004320 * "free_visited" is true. Be aware that the passed "search_ctx_arg" is freed
4321 * if the reinitialization fails.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004322 *
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004323 * If you don't have a search context from a previous call "search_ctx_arg"
4324 * must be NULL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004325 *
4326 * This function silently ignores a few errors, vim_findfile() will have
4327 * limited functionality then.
4328 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004329 void *
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004330vim_findfile_init(path, filename, stopdirs, level, free_visited, find_what,
4331 search_ctx_arg, tagfile, rel_fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004332 char_u *path;
4333 char_u *filename;
Bram Moolenaare1fbddc2009-05-16 19:07:03 +00004334 char_u *stopdirs UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004335 int level;
4336 int free_visited;
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004337 int find_what;
4338 void *search_ctx_arg;
Bram Moolenaar463ee342010-08-08 18:17:52 +02004339 int tagfile; /* expanding names of tags files */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004340 char_u *rel_fname; /* file name to use for "." */
4341{
4342#ifdef FEAT_PATH_EXTRA
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004343 char_u *wc_part;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004344#endif
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004345 ff_stack_T *sptr;
4346 ff_search_ctx_T *search_ctx;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004347
4348 /* If a search context is given by the caller, reuse it, else allocate a
4349 * new one.
4350 */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004351 if (search_ctx_arg != NULL)
4352 search_ctx = search_ctx_arg;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004353 else
4354 {
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004355 search_ctx = (ff_search_ctx_T*)alloc((unsigned)sizeof(ff_search_ctx_T));
4356 if (search_ctx == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004357 goto error_return;
Bram Moolenaar7db5fc82010-05-24 11:59:29 +02004358 vim_memset(search_ctx, 0, sizeof(ff_search_ctx_T));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004359 }
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004360 search_ctx->ffsc_find_what = find_what;
Bram Moolenaar463ee342010-08-08 18:17:52 +02004361 search_ctx->ffsc_tagfile = tagfile;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004362
4363 /* clear the search context, but NOT the visited lists */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004364 ff_clear(search_ctx);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004365
4366 /* clear visited list if wanted */
4367 if (free_visited == TRUE)
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004368 vim_findfile_free_visited(search_ctx);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004369 else
4370 {
4371 /* Reuse old visited lists. Get the visited list for the given
4372 * filename. If no list for the current filename exists, creates a new
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004373 * one. */
4374 search_ctx->ffsc_visited_list = ff_get_visited_list(filename,
4375 &search_ctx->ffsc_visited_lists_list);
4376 if (search_ctx->ffsc_visited_list == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004377 goto error_return;
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004378 search_ctx->ffsc_dir_visited_list = ff_get_visited_list(filename,
4379 &search_ctx->ffsc_dir_visited_lists_list);
4380 if (search_ctx->ffsc_dir_visited_list == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004381 goto error_return;
4382 }
4383
4384 if (ff_expand_buffer == NULL)
4385 {
4386 ff_expand_buffer = (char_u*)alloc(MAXPATHL);
4387 if (ff_expand_buffer == NULL)
4388 goto error_return;
4389 }
4390
4391 /* Store information on starting dir now if path is relative.
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00004392 * If path is absolute, we do that later. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004393 if (path[0] == '.'
4394 && (vim_ispathsep(path[1]) || path[1] == NUL)
4395 && (!tagfile || vim_strchr(p_cpo, CPO_DOTTAG) == NULL)
4396 && rel_fname != NULL)
4397 {
4398 int len = (int)(gettail(rel_fname) - rel_fname);
4399
4400 if (!vim_isAbsName(rel_fname) && len + 1 < MAXPATHL)
4401 {
4402 /* Make the start dir an absolute path name. */
Bram Moolenaarbbebc852005-07-18 21:47:53 +00004403 vim_strncpy(ff_expand_buffer, rel_fname, len);
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004404 search_ctx->ffsc_start_dir = FullName_save(ff_expand_buffer, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004405 }
4406 else
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004407 search_ctx->ffsc_start_dir = vim_strnsave(rel_fname, len);
4408 if (search_ctx->ffsc_start_dir == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004409 goto error_return;
4410 if (*++path != NUL)
4411 ++path;
4412 }
4413 else if (*path == NUL || !vim_isAbsName(path))
4414 {
4415#ifdef BACKSLASH_IN_FILENAME
4416 /* "c:dir" needs "c:" to be expanded, otherwise use current dir */
4417 if (*path != NUL && path[1] == ':')
4418 {
4419 char_u drive[3];
4420
4421 drive[0] = path[0];
4422 drive[1] = ':';
4423 drive[2] = NUL;
4424 if (vim_FullName(drive, ff_expand_buffer, MAXPATHL, TRUE) == FAIL)
4425 goto error_return;
4426 path += 2;
4427 }
4428 else
4429#endif
4430 if (mch_dirname(ff_expand_buffer, MAXPATHL) == FAIL)
4431 goto error_return;
4432
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004433 search_ctx->ffsc_start_dir = vim_strsave(ff_expand_buffer);
4434 if (search_ctx->ffsc_start_dir == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004435 goto error_return;
4436
4437#ifdef BACKSLASH_IN_FILENAME
4438 /* A path that starts with "/dir" is relative to the drive, not to the
4439 * directory (but not for "//machine/dir"). Only use the drive name. */
4440 if ((*path == '/' || *path == '\\')
4441 && path[1] != path[0]
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004442 && search_ctx->ffsc_start_dir[1] == ':')
4443 search_ctx->ffsc_start_dir[2] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004444#endif
4445 }
4446
4447#ifdef FEAT_PATH_EXTRA
4448 /*
4449 * If stopdirs are given, split them into an array of pointers.
4450 * If this fails (mem allocation), there is no upward search at all or a
4451 * stop directory is not recognized -> continue silently.
4452 * If stopdirs just contains a ";" or is empty,
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004453 * search_ctx->ffsc_stopdirs_v will only contain a NULL pointer. This
Bram Moolenaar071d4272004-06-13 20:20:40 +00004454 * is handled as unlimited upward search. See function
4455 * ff_path_in_stoplist() for details.
4456 */
4457 if (stopdirs != NULL)
4458 {
4459 char_u *walker = stopdirs;
4460 int dircount;
4461
4462 while (*walker == ';')
4463 walker++;
4464
4465 dircount = 1;
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004466 search_ctx->ffsc_stopdirs_v =
4467 (char_u **)alloc((unsigned)sizeof(char_u *));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004468
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004469 if (search_ctx->ffsc_stopdirs_v != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004470 {
4471 do
4472 {
4473 char_u *helper;
4474 void *ptr;
4475
4476 helper = walker;
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004477 ptr = vim_realloc(search_ctx->ffsc_stopdirs_v,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004478 (dircount + 1) * sizeof(char_u *));
4479 if (ptr)
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004480 search_ctx->ffsc_stopdirs_v = ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004481 else
4482 /* ignore, keep what we have and continue */
4483 break;
4484 walker = vim_strchr(walker, ';');
4485 if (walker)
4486 {
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004487 search_ctx->ffsc_stopdirs_v[dircount-1] =
4488 vim_strnsave(helper, (int)(walker - helper));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004489 walker++;
4490 }
4491 else
4492 /* this might be "", which means ascent till top
4493 * of directory tree.
4494 */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004495 search_ctx->ffsc_stopdirs_v[dircount-1] =
4496 vim_strsave(helper);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004497
4498 dircount++;
4499
4500 } while (walker != NULL);
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004501 search_ctx->ffsc_stopdirs_v[dircount-1] = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004502 }
4503 }
4504#endif
4505
4506#ifdef FEAT_PATH_EXTRA
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004507 search_ctx->ffsc_level = level;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004508
4509 /* split into:
4510 * -fix path
4511 * -wildcard_stuff (might be NULL)
4512 */
4513 wc_part = vim_strchr(path, '*');
4514 if (wc_part != NULL)
4515 {
4516 int llevel;
4517 int len;
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00004518 char *errpt;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004519
4520 /* save the fix part of the path */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004521 search_ctx->ffsc_fix_path = vim_strnsave(path, (int)(wc_part - path));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004522
4523 /*
4524 * copy wc_path and add restricts to the '**' wildcard.
Bram Moolenaar7aa9f6a2007-05-10 18:00:30 +00004525 * The octet after a '**' is used as a (binary) counter.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004526 * So '**3' is transposed to '**^C' ('^C' is ASCII value 3)
4527 * or '**76' is transposed to '**N'( 'N' is ASCII value 76).
4528 * For EBCDIC you get different character values.
4529 * If no restrict is given after '**' the default is used.
Bram Moolenaar21160b92009-11-11 15:56:10 +00004530 * Due to this technique the path looks awful if you print it as a
Bram Moolenaar071d4272004-06-13 20:20:40 +00004531 * string.
4532 */
4533 len = 0;
4534 while (*wc_part != NUL)
4535 {
4536 if (STRNCMP(wc_part, "**", 2) == 0)
4537 {
4538 ff_expand_buffer[len++] = *wc_part++;
4539 ff_expand_buffer[len++] = *wc_part++;
4540
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00004541 llevel = strtol((char *)wc_part, &errpt, 10);
4542 if ((char_u *)errpt != wc_part && llevel > 0 && llevel < 255)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004543 ff_expand_buffer[len++] = llevel;
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00004544 else if ((char_u *)errpt != wc_part && llevel == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004545 /* restrict is 0 -> remove already added '**' */
4546 len -= 2;
4547 else
4548 ff_expand_buffer[len++] = FF_MAX_STAR_STAR_EXPAND;
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00004549 wc_part = (char_u *)errpt;
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00004550 if (*wc_part != NUL && !vim_ispathsep(*wc_part))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004551 {
4552 EMSG2(_("E343: Invalid path: '**[number]' must be at the end of the path or be followed by '%s'."), PATHSEPSTR);
4553 goto error_return;
4554 }
4555 }
4556 else
4557 ff_expand_buffer[len++] = *wc_part++;
4558 }
4559 ff_expand_buffer[len] = NUL;
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004560 search_ctx->ffsc_wc_path = vim_strsave(ff_expand_buffer);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004561
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004562 if (search_ctx->ffsc_wc_path == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004563 goto error_return;
4564 }
4565 else
4566#endif
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004567 search_ctx->ffsc_fix_path = vim_strsave(path);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004568
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004569 if (search_ctx->ffsc_start_dir == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004570 {
4571 /* store the fix part as startdir.
4572 * This is needed if the parameter path is fully qualified.
4573 */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004574 search_ctx->ffsc_start_dir = vim_strsave(search_ctx->ffsc_fix_path);
Bram Moolenaara9d52e32010-07-31 16:44:19 +02004575 if (search_ctx->ffsc_start_dir == NULL)
4576 goto error_return;
4577 search_ctx->ffsc_fix_path[0] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004578 }
4579
4580 /* create an absolute path */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004581 STRCPY(ff_expand_buffer, search_ctx->ffsc_start_dir);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004582 add_pathsep(ff_expand_buffer);
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004583 STRCAT(ff_expand_buffer, search_ctx->ffsc_fix_path);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004584 add_pathsep(ff_expand_buffer);
4585
4586 sptr = ff_create_stack_element(ff_expand_buffer,
4587#ifdef FEAT_PATH_EXTRA
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004588 search_ctx->ffsc_wc_path,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004589#endif
4590 level, 0);
4591
4592 if (sptr == NULL)
4593 goto error_return;
4594
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004595 ff_push(search_ctx, sptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004596
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004597 search_ctx->ffsc_file_to_search = vim_strsave(filename);
4598 if (search_ctx->ffsc_file_to_search == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004599 goto error_return;
4600
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004601 return search_ctx;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004602
4603error_return:
4604 /*
4605 * We clear the search context now!
4606 * Even when the caller gave us a (perhaps valid) context we free it here,
4607 * as we might have already destroyed it.
4608 */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004609 vim_findfile_cleanup(search_ctx);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004610 return NULL;
4611}
4612
4613#if defined(FEAT_PATH_EXTRA) || defined(PROTO)
4614/*
4615 * Get the stopdir string. Check that ';' is not escaped.
4616 */
4617 char_u *
4618vim_findfile_stopdir(buf)
4619 char_u *buf;
4620{
4621 char_u *r_ptr = buf;
4622
4623 while (*r_ptr != NUL && *r_ptr != ';')
4624 {
4625 if (r_ptr[0] == '\\' && r_ptr[1] == ';')
4626 {
4627 /* overwrite the escape char,
4628 * use STRLEN(r_ptr) to move the trailing '\0'
4629 */
Bram Moolenaar446cb832008-06-24 21:56:24 +00004630 STRMOVE(r_ptr, r_ptr + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004631 r_ptr++;
4632 }
4633 r_ptr++;
4634 }
4635 if (*r_ptr == ';')
4636 {
4637 *r_ptr = 0;
4638 r_ptr++;
4639 }
4640 else if (*r_ptr == NUL)
4641 r_ptr = NULL;
4642 return r_ptr;
4643}
4644#endif
4645
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004646/*
4647 * Clean up the given search context. Can handle a NULL pointer.
4648 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004649 void
4650vim_findfile_cleanup(ctx)
4651 void *ctx;
4652{
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00004653 if (ctx == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004654 return;
4655
Bram Moolenaar071d4272004-06-13 20:20:40 +00004656 vim_findfile_free_visited(ctx);
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004657 ff_clear(ctx);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004658 vim_free(ctx);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004659}
4660
4661/*
4662 * Find a file in a search context.
4663 * The search context was created with vim_findfile_init() above.
4664 * Return a pointer to an allocated file name or NULL if nothing found.
4665 * To get all matching files call this function until you get NULL.
4666 *
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00004667 * If the passed search_context is NULL, NULL is returned.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004668 *
4669 * The search algorithm is depth first. To change this replace the
4670 * stack with a list (don't forget to leave partly searched directories on the
4671 * top of the list).
4672 */
4673 char_u *
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004674vim_findfile(search_ctx_arg)
4675 void *search_ctx_arg;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004676{
4677 char_u *file_path;
4678#ifdef FEAT_PATH_EXTRA
4679 char_u *rest_of_wildcards;
4680 char_u *path_end = NULL;
4681#endif
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004682 ff_stack_T *stackp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004683#if defined(FEAT_SEARCHPATH) || defined(FEAT_PATH_EXTRA)
4684 int len;
4685#endif
4686 int i;
4687 char_u *p;
4688#ifdef FEAT_SEARCHPATH
4689 char_u *suf;
4690#endif
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004691 ff_search_ctx_T *search_ctx;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004692
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004693 if (search_ctx_arg == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004694 return NULL;
4695
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004696 search_ctx = (ff_search_ctx_T *)search_ctx_arg;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004697
4698 /*
4699 * filepath is used as buffer for various actions and as the storage to
4700 * return a found filename.
4701 */
4702 if ((file_path = alloc((int)MAXPATHL)) == NULL)
4703 return NULL;
4704
4705#ifdef FEAT_PATH_EXTRA
4706 /* store the end of the start dir -- needed for upward search */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004707 if (search_ctx->ffsc_start_dir != NULL)
4708 path_end = &search_ctx->ffsc_start_dir[
4709 STRLEN(search_ctx->ffsc_start_dir)];
Bram Moolenaar071d4272004-06-13 20:20:40 +00004710#endif
4711
4712#ifdef FEAT_PATH_EXTRA
4713 /* upward search loop */
4714 for (;;)
4715 {
4716#endif
4717 /* downward search loop */
4718 for (;;)
4719 {
4720 /* check if user user wants to stop the search*/
4721 ui_breakcheck();
4722 if (got_int)
4723 break;
4724
4725 /* get directory to work on from stack */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004726 stackp = ff_pop(search_ctx);
4727 if (stackp == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004728 break;
4729
4730 /*
4731 * TODO: decide if we leave this test in
4732 *
4733 * GOOD: don't search a directory(-tree) twice.
4734 * BAD: - check linked list for every new directory entered.
4735 * - check for double files also done below
4736 *
4737 * Here we check if we already searched this directory.
4738 * We already searched a directory if:
4739 * 1) The directory is the same.
4740 * 2) We would use the same wildcard string.
4741 *
4742 * Good if you have links on same directory via several ways
4743 * or you have selfreferences in directories (e.g. SuSE Linux 6.3:
4744 * /etc/rc.d/init.d is linked to /etc/rc.d -> endless loop)
4745 *
4746 * This check is only needed for directories we work on for the
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004747 * first time (hence stackp->ff_filearray == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004748 */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004749 if (stackp->ffs_filearray == NULL
4750 && ff_check_visited(&search_ctx->ffsc_dir_visited_list
Bram Moolenaar071d4272004-06-13 20:20:40 +00004751 ->ffvl_visited_list,
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004752 stackp->ffs_fix_path
Bram Moolenaar071d4272004-06-13 20:20:40 +00004753#ifdef FEAT_PATH_EXTRA
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004754 , stackp->ffs_wc_path
Bram Moolenaar071d4272004-06-13 20:20:40 +00004755#endif
4756 ) == FAIL)
4757 {
4758#ifdef FF_VERBOSE
4759 if (p_verbose >= 5)
4760 {
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004761 verbose_enter_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004762 smsg((char_u *)"Already Searched: %s (%s)",
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004763 stackp->ffs_fix_path, stackp->ffs_wc_path);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004764 /* don't overwrite this either */
4765 msg_puts((char_u *)"\n");
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004766 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004767 }
4768#endif
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004769 ff_free_stack_element(stackp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004770 continue;
4771 }
4772#ifdef FF_VERBOSE
4773 else if (p_verbose >= 5)
4774 {
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004775 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00004776 smsg((char_u *)"Searching: %s (%s)",
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004777 stackp->ffs_fix_path, stackp->ffs_wc_path);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004778 /* don't overwrite this either */
4779 msg_puts((char_u *)"\n");
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004780 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004781 }
4782#endif
4783
4784 /* check depth */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004785 if (stackp->ffs_level <= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004786 {
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004787 ff_free_stack_element(stackp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004788 continue;
4789 }
4790
4791 file_path[0] = NUL;
4792
4793 /*
4794 * If no filearray till now expand wildcards
4795 * The function expand_wildcards() can handle an array of paths
4796 * and all possible expands are returned in one array. We use this
4797 * to handle the expansion of '**' into an empty string.
4798 */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004799 if (stackp->ffs_filearray == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004800 {
4801 char_u *dirptrs[2];
4802
4803 /* we use filepath to build the path expand_wildcards() should
4804 * expand.
4805 */
4806 dirptrs[0] = file_path;
4807 dirptrs[1] = NULL;
4808
4809 /* if we have a start dir copy it in */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004810 if (!vim_isAbsName(stackp->ffs_fix_path)
4811 && search_ctx->ffsc_start_dir)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004812 {
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004813 STRCPY(file_path, search_ctx->ffsc_start_dir);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004814 add_pathsep(file_path);
4815 }
4816
4817 /* append the fix part of the search path */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004818 STRCAT(file_path, stackp->ffs_fix_path);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004819 add_pathsep(file_path);
4820
4821#ifdef FEAT_PATH_EXTRA
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004822 rest_of_wildcards = stackp->ffs_wc_path;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004823 if (*rest_of_wildcards != NUL)
4824 {
4825 len = (int)STRLEN(file_path);
4826 if (STRNCMP(rest_of_wildcards, "**", 2) == 0)
4827 {
4828 /* pointer to the restrict byte
4829 * The restrict byte is not a character!
4830 */
4831 p = rest_of_wildcards + 2;
4832
4833 if (*p > 0)
4834 {
4835 (*p)--;
4836 file_path[len++] = '*';
4837 }
4838
4839 if (*p == 0)
4840 {
4841 /* remove '**<numb> from wildcards */
Bram Moolenaar446cb832008-06-24 21:56:24 +00004842 STRMOVE(rest_of_wildcards, rest_of_wildcards + 3);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004843 }
4844 else
4845 rest_of_wildcards += 3;
4846
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004847 if (stackp->ffs_star_star_empty == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004848 {
4849 /* if not done before, expand '**' to empty */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004850 stackp->ffs_star_star_empty = 1;
4851 dirptrs[1] = stackp->ffs_fix_path;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004852 }
4853 }
4854
4855 /*
4856 * Here we copy until the next path separator or the end of
4857 * the path. If we stop at a path separator, there is
Bram Moolenaar7aa9f6a2007-05-10 18:00:30 +00004858 * still something else left. This is handled below by
Bram Moolenaar071d4272004-06-13 20:20:40 +00004859 * pushing every directory returned from expand_wildcards()
4860 * on the stack again for further search.
4861 */
4862 while (*rest_of_wildcards
4863 && !vim_ispathsep(*rest_of_wildcards))
4864 file_path[len++] = *rest_of_wildcards++;
4865
4866 file_path[len] = NUL;
4867 if (vim_ispathsep(*rest_of_wildcards))
4868 rest_of_wildcards++;
4869 }
4870#endif
4871
4872 /*
4873 * Expand wildcards like "*" and "$VAR".
4874 * If the path is a URL don't try this.
4875 */
4876 if (path_with_url(dirptrs[0]))
4877 {
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004878 stackp->ffs_filearray = (char_u **)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004879 alloc((unsigned)sizeof(char *));
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004880 if (stackp->ffs_filearray != NULL
4881 && (stackp->ffs_filearray[0]
Bram Moolenaar071d4272004-06-13 20:20:40 +00004882 = vim_strsave(dirptrs[0])) != NULL)
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004883 stackp->ffs_filearray_size = 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004884 else
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004885 stackp->ffs_filearray_size = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004886 }
4887 else
4888 expand_wildcards((dirptrs[1] == NULL) ? 1 : 2, dirptrs,
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004889 &stackp->ffs_filearray_size,
4890 &stackp->ffs_filearray,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004891 EW_DIR|EW_ADDSLASH|EW_SILENT);
4892
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004893 stackp->ffs_filearray_cur = 0;
4894 stackp->ffs_stage = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004895 }
4896#ifdef FEAT_PATH_EXTRA
4897 else
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004898 rest_of_wildcards = &stackp->ffs_wc_path[
4899 STRLEN(stackp->ffs_wc_path)];
Bram Moolenaar071d4272004-06-13 20:20:40 +00004900#endif
4901
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004902 if (stackp->ffs_stage == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004903 {
4904 /* this is the first time we work on this directory */
4905#ifdef FEAT_PATH_EXTRA
4906 if (*rest_of_wildcards == NUL)
4907#endif
4908 {
4909 /*
4910 * we don't have further wildcards to expand, so we have to
4911 * check for the final file now
4912 */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004913 for (i = stackp->ffs_filearray_cur;
4914 i < stackp->ffs_filearray_size; ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004915 {
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004916 if (!path_with_url(stackp->ffs_filearray[i])
4917 && !mch_isdir(stackp->ffs_filearray[i]))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004918 continue; /* not a directory */
4919
Bram Moolenaar21160b92009-11-11 15:56:10 +00004920 /* prepare the filename to be checked for existence
Bram Moolenaar071d4272004-06-13 20:20:40 +00004921 * below */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004922 STRCPY(file_path, stackp->ffs_filearray[i]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004923 add_pathsep(file_path);
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004924 STRCAT(file_path, search_ctx->ffsc_file_to_search);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004925
4926 /*
4927 * Try without extra suffix and then with suffixes
4928 * from 'suffixesadd'.
4929 */
4930#ifdef FEAT_SEARCHPATH
4931 len = (int)STRLEN(file_path);
Bram Moolenaar463ee342010-08-08 18:17:52 +02004932 if (search_ctx->ffsc_tagfile)
4933 suf = (char_u *)"";
4934 else
4935 suf = curbuf->b_p_sua;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004936 for (;;)
4937#endif
4938 {
4939 /* if file exists and we didn't already find it */
4940 if ((path_with_url(file_path)
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004941 || (mch_getperm(file_path) >= 0
4942 && (search_ctx->ffsc_find_what
4943 == FINDFILE_BOTH
4944 || ((search_ctx->ffsc_find_what
4945 == FINDFILE_DIR)
4946 == mch_isdir(file_path)))))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004947#ifndef FF_VERBOSE
4948 && (ff_check_visited(
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004949 &search_ctx->ffsc_visited_list->ffvl_visited_list,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004950 file_path
4951#ifdef FEAT_PATH_EXTRA
4952 , (char_u *)""
4953#endif
4954 ) == OK)
4955#endif
4956 )
4957 {
4958#ifdef FF_VERBOSE
4959 if (ff_check_visited(
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004960 &search_ctx->ffsc_visited_list->ffvl_visited_list,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004961 file_path
4962#ifdef FEAT_PATH_EXTRA
4963 , (char_u *)""
4964#endif
4965 ) == FAIL)
4966 {
4967 if (p_verbose >= 5)
4968 {
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004969 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00004970 smsg((char_u *)"Already: %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004971 file_path);
4972 /* don't overwrite this either */
4973 msg_puts((char_u *)"\n");
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004974 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004975 }
4976 continue;
4977 }
4978#endif
4979
4980 /* push dir to examine rest of subdirs later */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004981 stackp->ffs_filearray_cur = i + 1;
4982 ff_push(search_ctx, stackp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004983
Bram Moolenaar6bab9fa2009-01-22 20:32:12 +00004984 if (!path_with_url(file_path))
4985 simplify_filename(file_path);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004986 if (mch_dirname(ff_expand_buffer, MAXPATHL)
4987 == OK)
4988 {
4989 p = shorten_fname(file_path,
4990 ff_expand_buffer);
4991 if (p != NULL)
Bram Moolenaar446cb832008-06-24 21:56:24 +00004992 STRMOVE(file_path, p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004993 }
4994#ifdef FF_VERBOSE
4995 if (p_verbose >= 5)
4996 {
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004997 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00004998 smsg((char_u *)"HIT: %s", file_path);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004999 /* don't overwrite this either */
5000 msg_puts((char_u *)"\n");
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00005001 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005002 }
5003#endif
5004 return file_path;
5005 }
5006
5007#ifdef FEAT_SEARCHPATH
5008 /* Not found or found already, try next suffix. */
5009 if (*suf == NUL)
5010 break;
5011 copy_option_part(&suf, file_path + len,
5012 MAXPATHL - len, ",");
5013#endif
5014 }
5015 }
5016 }
5017#ifdef FEAT_PATH_EXTRA
5018 else
5019 {
5020 /*
5021 * still wildcards left, push the directories for further
5022 * search
5023 */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005024 for (i = stackp->ffs_filearray_cur;
5025 i < stackp->ffs_filearray_size; ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005026 {
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005027 if (!mch_isdir(stackp->ffs_filearray[i]))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005028 continue; /* not a directory */
5029
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005030 ff_push(search_ctx,
5031 ff_create_stack_element(
5032 stackp->ffs_filearray[i],
5033 rest_of_wildcards,
5034 stackp->ffs_level - 1, 0));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005035 }
5036 }
5037#endif
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005038 stackp->ffs_filearray_cur = 0;
5039 stackp->ffs_stage = 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005040 }
5041
5042#ifdef FEAT_PATH_EXTRA
5043 /*
5044 * if wildcards contains '**' we have to descent till we reach the
5045 * leaves of the directory tree.
5046 */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005047 if (STRNCMP(stackp->ffs_wc_path, "**", 2) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005048 {
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005049 for (i = stackp->ffs_filearray_cur;
5050 i < stackp->ffs_filearray_size; ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005051 {
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005052 if (fnamecmp(stackp->ffs_filearray[i],
5053 stackp->ffs_fix_path) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005054 continue; /* don't repush same directory */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005055 if (!mch_isdir(stackp->ffs_filearray[i]))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005056 continue; /* not a directory */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005057 ff_push(search_ctx,
5058 ff_create_stack_element(stackp->ffs_filearray[i],
5059 stackp->ffs_wc_path, stackp->ffs_level - 1, 1));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005060 }
5061 }
5062#endif
5063
5064 /* we are done with the current directory */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005065 ff_free_stack_element(stackp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005066
5067 }
5068
5069#ifdef FEAT_PATH_EXTRA
5070 /* If we reached this, we didn't find anything downwards.
5071 * Let's check if we should do an upward search.
5072 */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005073 if (search_ctx->ffsc_start_dir
5074 && search_ctx->ffsc_stopdirs_v != NULL && !got_int)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005075 {
5076 ff_stack_T *sptr;
5077
5078 /* is the last starting directory in the stop list? */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005079 if (ff_path_in_stoplist(search_ctx->ffsc_start_dir,
5080 (int)(path_end - search_ctx->ffsc_start_dir),
5081 search_ctx->ffsc_stopdirs_v) == TRUE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005082 break;
5083
5084 /* cut of last dir */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005085 while (path_end > search_ctx->ffsc_start_dir
5086 && vim_ispathsep(*path_end))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005087 path_end--;
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005088 while (path_end > search_ctx->ffsc_start_dir
5089 && !vim_ispathsep(path_end[-1]))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005090 path_end--;
5091 *path_end = 0;
5092 path_end--;
5093
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005094 if (*search_ctx->ffsc_start_dir == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005095 break;
5096
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005097 STRCPY(file_path, search_ctx->ffsc_start_dir);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005098 add_pathsep(file_path);
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005099 STRCAT(file_path, search_ctx->ffsc_fix_path);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005100
5101 /* create a new stack entry */
5102 sptr = ff_create_stack_element(file_path,
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005103 search_ctx->ffsc_wc_path, search_ctx->ffsc_level, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005104 if (sptr == NULL)
5105 break;
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005106 ff_push(search_ctx, sptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005107 }
5108 else
5109 break;
5110 }
5111#endif
5112
5113 vim_free(file_path);
5114 return NULL;
5115}
5116
5117/*
5118 * Free the list of lists of visited files and directories
5119 * Can handle it if the passed search_context is NULL;
5120 */
5121 void
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005122vim_findfile_free_visited(search_ctx_arg)
5123 void *search_ctx_arg;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005124{
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005125 ff_search_ctx_T *search_ctx;
5126
5127 if (search_ctx_arg == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005128 return;
5129
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005130 search_ctx = (ff_search_ctx_T *)search_ctx_arg;
5131 vim_findfile_free_visited_list(&search_ctx->ffsc_visited_lists_list);
5132 vim_findfile_free_visited_list(&search_ctx->ffsc_dir_visited_lists_list);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005133}
5134
5135 static void
5136vim_findfile_free_visited_list(list_headp)
5137 ff_visited_list_hdr_T **list_headp;
5138{
5139 ff_visited_list_hdr_T *vp;
5140
5141 while (*list_headp != NULL)
5142 {
5143 vp = (*list_headp)->ffvl_next;
5144 ff_free_visited_list((*list_headp)->ffvl_visited_list);
5145
5146 vim_free((*list_headp)->ffvl_filename);
5147 vim_free(*list_headp);
5148 *list_headp = vp;
5149 }
5150 *list_headp = NULL;
5151}
5152
5153 static void
5154ff_free_visited_list(vl)
5155 ff_visited_T *vl;
5156{
5157 ff_visited_T *vp;
5158
5159 while (vl != NULL)
5160 {
5161 vp = vl->ffv_next;
5162#ifdef FEAT_PATH_EXTRA
5163 vim_free(vl->ffv_wc_path);
5164#endif
5165 vim_free(vl);
5166 vl = vp;
5167 }
5168 vl = NULL;
5169}
5170
5171/*
5172 * Returns the already visited list for the given filename. If none is found it
5173 * allocates a new one.
5174 */
5175 static ff_visited_list_hdr_T*
5176ff_get_visited_list(filename, list_headp)
5177 char_u *filename;
5178 ff_visited_list_hdr_T **list_headp;
5179{
5180 ff_visited_list_hdr_T *retptr = NULL;
5181
5182 /* check if a visited list for the given filename exists */
5183 if (*list_headp != NULL)
5184 {
5185 retptr = *list_headp;
5186 while (retptr != NULL)
5187 {
5188 if (fnamecmp(filename, retptr->ffvl_filename) == 0)
5189 {
5190#ifdef FF_VERBOSE
5191 if (p_verbose >= 5)
5192 {
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00005193 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00005194 smsg((char_u *)"ff_get_visited_list: FOUND list for %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005195 filename);
5196 /* don't overwrite this either */
5197 msg_puts((char_u *)"\n");
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00005198 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005199 }
5200#endif
5201 return retptr;
5202 }
5203 retptr = retptr->ffvl_next;
5204 }
5205 }
5206
5207#ifdef FF_VERBOSE
5208 if (p_verbose >= 5)
5209 {
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00005210 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00005211 smsg((char_u *)"ff_get_visited_list: new list for %s", filename);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005212 /* don't overwrite this either */
5213 msg_puts((char_u *)"\n");
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00005214 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005215 }
5216#endif
5217
5218 /*
5219 * if we reach this we didn't find a list and we have to allocate new list
5220 */
5221 retptr = (ff_visited_list_hdr_T*)alloc((unsigned)sizeof(*retptr));
5222 if (retptr == NULL)
5223 return NULL;
5224
5225 retptr->ffvl_visited_list = NULL;
5226 retptr->ffvl_filename = vim_strsave(filename);
5227 if (retptr->ffvl_filename == NULL)
5228 {
5229 vim_free(retptr);
5230 return NULL;
5231 }
5232 retptr->ffvl_next = *list_headp;
5233 *list_headp = retptr;
5234
5235 return retptr;
5236}
5237
5238#ifdef FEAT_PATH_EXTRA
5239/*
5240 * check if two wildcard paths are equal. Returns TRUE or FALSE.
5241 * They are equal if:
5242 * - both paths are NULL
5243 * - they have the same length
5244 * - char by char comparison is OK
5245 * - the only differences are in the counters behind a '**', so
5246 * '**\20' is equal to '**\24'
5247 */
5248 static int
5249ff_wc_equal(s1, s2)
5250 char_u *s1;
5251 char_u *s2;
5252{
5253 int i;
5254
5255 if (s1 == s2)
5256 return TRUE;
5257
5258 if (s1 == NULL || s2 == NULL)
5259 return FALSE;
5260
5261 if (STRLEN(s1) != STRLEN(s2))
5262 return FAIL;
5263
5264 for (i = 0; s1[i] != NUL && s2[i] != NUL; i++)
5265 {
5266 if (s1[i] != s2[i]
5267#ifdef CASE_INSENSITIVE_FILENAME
5268 && TOUPPER_LOC(s1[i]) != TOUPPER_LOC(s2[i])
5269#endif
5270 )
5271 {
5272 if (i >= 2)
5273 if (s1[i-1] == '*' && s1[i-2] == '*')
5274 continue;
5275 else
5276 return FAIL;
5277 else
5278 return FAIL;
5279 }
5280 }
5281 return TRUE;
5282}
5283#endif
5284
5285/*
5286 * maintains the list of already visited files and dirs
5287 * returns FAIL if the given file/dir is already in the list
5288 * returns OK if it is newly added
5289 *
5290 * TODO: What to do on memory allocation problems?
5291 * -> return TRUE - Better the file is found several times instead of
5292 * never.
5293 */
5294 static int
5295ff_check_visited(visited_list, fname
5296#ifdef FEAT_PATH_EXTRA
5297 , wc_path
5298#endif
5299 )
5300 ff_visited_T **visited_list;
5301 char_u *fname;
5302#ifdef FEAT_PATH_EXTRA
5303 char_u *wc_path;
5304#endif
5305{
5306 ff_visited_T *vp;
5307#ifdef UNIX
5308 struct stat st;
5309 int url = FALSE;
5310#endif
5311
5312 /* For an URL we only compare the name, otherwise we compare the
5313 * device/inode (unix) or the full path name (not Unix). */
5314 if (path_with_url(fname))
5315 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00005316 vim_strncpy(ff_expand_buffer, fname, MAXPATHL - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005317#ifdef UNIX
5318 url = TRUE;
5319#endif
5320 }
5321 else
5322 {
5323 ff_expand_buffer[0] = NUL;
5324#ifdef UNIX
5325 if (mch_stat((char *)fname, &st) < 0)
5326#else
5327 if (vim_FullName(fname, ff_expand_buffer, MAXPATHL, TRUE) == FAIL)
5328#endif
5329 return FAIL;
5330 }
5331
5332 /* check against list of already visited files */
5333 for (vp = *visited_list; vp != NULL; vp = vp->ffv_next)
5334 {
5335 if (
5336#ifdef UNIX
Bram Moolenaare1fbddc2009-05-16 19:07:03 +00005337 !url ? (vp->ffv_dev_valid && vp->ffv_dev == st.st_dev
5338 && vp->ffv_ino == st.st_ino)
5339 :
Bram Moolenaar071d4272004-06-13 20:20:40 +00005340#endif
5341 fnamecmp(vp->ffv_fname, ff_expand_buffer) == 0
5342 )
5343 {
5344#ifdef FEAT_PATH_EXTRA
5345 /* are the wildcard parts equal */
5346 if (ff_wc_equal(vp->ffv_wc_path, wc_path) == TRUE)
5347#endif
5348 /* already visited */
5349 return FAIL;
5350 }
5351 }
5352
5353 /*
5354 * New file/dir. Add it to the list of visited files/dirs.
5355 */
5356 vp = (ff_visited_T *)alloc((unsigned)(sizeof(ff_visited_T)
5357 + STRLEN(ff_expand_buffer)));
5358
5359 if (vp != NULL)
5360 {
5361#ifdef UNIX
5362 if (!url)
5363 {
Bram Moolenaare1fbddc2009-05-16 19:07:03 +00005364 vp->ffv_dev_valid = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005365 vp->ffv_ino = st.st_ino;
5366 vp->ffv_dev = st.st_dev;
5367 vp->ffv_fname[0] = NUL;
5368 }
5369 else
5370 {
Bram Moolenaare1fbddc2009-05-16 19:07:03 +00005371 vp->ffv_dev_valid = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005372#endif
5373 STRCPY(vp->ffv_fname, ff_expand_buffer);
5374#ifdef UNIX
5375 }
5376#endif
5377#ifdef FEAT_PATH_EXTRA
5378 if (wc_path != NULL)
5379 vp->ffv_wc_path = vim_strsave(wc_path);
5380 else
5381 vp->ffv_wc_path = NULL;
5382#endif
5383
5384 vp->ffv_next = *visited_list;
5385 *visited_list = vp;
5386 }
5387
5388 return OK;
5389}
5390
5391/*
5392 * create stack element from given path pieces
5393 */
5394 static ff_stack_T *
5395ff_create_stack_element(fix_part,
5396#ifdef FEAT_PATH_EXTRA
5397 wc_part,
5398#endif
5399 level, star_star_empty)
5400 char_u *fix_part;
5401#ifdef FEAT_PATH_EXTRA
5402 char_u *wc_part;
5403#endif
5404 int level;
5405 int star_star_empty;
5406{
5407 ff_stack_T *new;
5408
5409 new = (ff_stack_T *)alloc((unsigned)sizeof(ff_stack_T));
5410 if (new == NULL)
5411 return NULL;
5412
5413 new->ffs_prev = NULL;
5414 new->ffs_filearray = NULL;
5415 new->ffs_filearray_size = 0;
5416 new->ffs_filearray_cur = 0;
5417 new->ffs_stage = 0;
5418 new->ffs_level = level;
5419 new->ffs_star_star_empty = star_star_empty;;
5420
5421 /* the following saves NULL pointer checks in vim_findfile */
5422 if (fix_part == NULL)
5423 fix_part = (char_u *)"";
5424 new->ffs_fix_path = vim_strsave(fix_part);
5425
5426#ifdef FEAT_PATH_EXTRA
5427 if (wc_part == NULL)
5428 wc_part = (char_u *)"";
5429 new->ffs_wc_path = vim_strsave(wc_part);
5430#endif
5431
5432 if (new->ffs_fix_path == NULL
5433#ifdef FEAT_PATH_EXTRA
5434 || new->ffs_wc_path == NULL
5435#endif
5436 )
5437 {
5438 ff_free_stack_element(new);
5439 new = NULL;
5440 }
5441
5442 return new;
5443}
5444
5445/*
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005446 * Push a dir on the directory stack.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005447 */
5448 static void
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005449ff_push(search_ctx, stack_ptr)
5450 ff_search_ctx_T *search_ctx;
5451 ff_stack_T *stack_ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005452{
5453 /* check for NULL pointer, not to return an error to the user, but
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005454 * to prevent a crash */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005455 if (stack_ptr != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005456 {
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005457 stack_ptr->ffs_prev = search_ctx->ffsc_stack_ptr;
5458 search_ctx->ffsc_stack_ptr = stack_ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005459 }
5460}
5461
5462/*
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005463 * Pop a dir from the directory stack.
5464 * Returns NULL if stack is empty.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005465 */
5466 static ff_stack_T *
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005467ff_pop(search_ctx)
5468 ff_search_ctx_T *search_ctx;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005469{
5470 ff_stack_T *sptr;
5471
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005472 sptr = search_ctx->ffsc_stack_ptr;
5473 if (search_ctx->ffsc_stack_ptr != NULL)
5474 search_ctx->ffsc_stack_ptr = search_ctx->ffsc_stack_ptr->ffs_prev;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005475
5476 return sptr;
5477}
5478
5479/*
5480 * free the given stack element
5481 */
5482 static void
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005483ff_free_stack_element(stack_ptr)
5484 ff_stack_T *stack_ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005485{
5486 /* vim_free handles possible NULL pointers */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005487 vim_free(stack_ptr->ffs_fix_path);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005488#ifdef FEAT_PATH_EXTRA
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005489 vim_free(stack_ptr->ffs_wc_path);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005490#endif
5491
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005492 if (stack_ptr->ffs_filearray != NULL)
5493 FreeWild(stack_ptr->ffs_filearray_size, stack_ptr->ffs_filearray);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005494
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005495 vim_free(stack_ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005496}
5497
5498/*
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005499 * Clear the search context, but NOT the visited list.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005500 */
5501 static void
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005502ff_clear(search_ctx)
5503 ff_search_ctx_T *search_ctx;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005504{
5505 ff_stack_T *sptr;
5506
5507 /* clear up stack */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005508 while ((sptr = ff_pop(search_ctx)) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005509 ff_free_stack_element(sptr);
5510
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005511 vim_free(search_ctx->ffsc_file_to_search);
5512 vim_free(search_ctx->ffsc_start_dir);
5513 vim_free(search_ctx->ffsc_fix_path);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005514#ifdef FEAT_PATH_EXTRA
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005515 vim_free(search_ctx->ffsc_wc_path);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005516#endif
5517
5518#ifdef FEAT_PATH_EXTRA
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005519 if (search_ctx->ffsc_stopdirs_v != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005520 {
5521 int i = 0;
5522
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005523 while (search_ctx->ffsc_stopdirs_v[i] != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005524 {
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005525 vim_free(search_ctx->ffsc_stopdirs_v[i]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005526 i++;
5527 }
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005528 vim_free(search_ctx->ffsc_stopdirs_v);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005529 }
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005530 search_ctx->ffsc_stopdirs_v = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005531#endif
5532
5533 /* reset everything */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005534 search_ctx->ffsc_file_to_search = NULL;
5535 search_ctx->ffsc_start_dir = NULL;
5536 search_ctx->ffsc_fix_path = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005537#ifdef FEAT_PATH_EXTRA
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005538 search_ctx->ffsc_wc_path = NULL;
5539 search_ctx->ffsc_level = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005540#endif
5541}
5542
5543#ifdef FEAT_PATH_EXTRA
5544/*
5545 * check if the given path is in the stopdirs
5546 * returns TRUE if yes else FALSE
5547 */
5548 static int
5549ff_path_in_stoplist(path, path_len, stopdirs_v)
5550 char_u *path;
5551 int path_len;
5552 char_u **stopdirs_v;
5553{
5554 int i = 0;
5555
5556 /* eat up trailing path separators, except the first */
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00005557 while (path_len > 1 && vim_ispathsep(path[path_len - 1]))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005558 path_len--;
5559
5560 /* if no path consider it as match */
5561 if (path_len == 0)
5562 return TRUE;
5563
5564 for (i = 0; stopdirs_v[i] != NULL; i++)
5565 {
5566 if ((int)STRLEN(stopdirs_v[i]) > path_len)
5567 {
5568 /* match for parent directory. So '/home' also matches
5569 * '/home/rks'. Check for PATHSEP in stopdirs_v[i], else
5570 * '/home/r' would also match '/home/rks'
5571 */
5572 if (fnamencmp(stopdirs_v[i], path, path_len) == 0
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00005573 && vim_ispathsep(stopdirs_v[i][path_len]))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005574 return TRUE;
5575 }
5576 else
5577 {
5578 if (fnamecmp(stopdirs_v[i], path) == 0)
5579 return TRUE;
5580 }
5581 }
5582 return FALSE;
5583}
5584#endif
5585
5586#if defined(FEAT_SEARCHPATH) || defined(PROTO)
5587/*
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005588 * Find the file name "ptr[len]" in the path. Also finds directory names.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005589 *
5590 * On the first call set the parameter 'first' to TRUE to initialize
5591 * the search. For repeating calls to FALSE.
5592 *
5593 * Repeating calls will return other files called 'ptr[len]' from the path.
5594 *
5595 * Only on the first call 'ptr' and 'len' are used. For repeating calls they
5596 * don't need valid values.
5597 *
5598 * If nothing found on the first call the option FNAME_MESS will issue the
5599 * message:
5600 * 'Can't find file "<file>" in path'
5601 * On repeating calls:
5602 * 'No more file "<file>" found in path'
5603 *
5604 * options:
5605 * FNAME_MESS give error message when not found
5606 *
5607 * Uses NameBuff[]!
5608 *
5609 * Returns an allocated string for the file name. NULL for error.
5610 *
5611 */
5612 char_u *
5613find_file_in_path(ptr, len, options, first, rel_fname)
5614 char_u *ptr; /* file name */
5615 int len; /* length of file name */
5616 int options;
5617 int first; /* use count'th matching file name */
5618 char_u *rel_fname; /* file name searching relative to */
5619{
5620 return find_file_in_path_option(ptr, len, options, first,
5621 *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path,
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005622 FINDFILE_BOTH, rel_fname, curbuf->b_p_sua);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005623}
5624
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005625static char_u *ff_file_to_find = NULL;
5626static void *fdip_search_ctx = NULL;
5627
5628#if defined(EXITFREE)
5629 static void
5630free_findfile()
5631{
5632 vim_free(ff_file_to_find);
5633 vim_findfile_cleanup(fdip_search_ctx);
5634}
5635#endif
5636
Bram Moolenaar071d4272004-06-13 20:20:40 +00005637/*
5638 * Find the directory name "ptr[len]" in the path.
5639 *
5640 * options:
5641 * FNAME_MESS give error message when not found
5642 *
5643 * Uses NameBuff[]!
5644 *
5645 * Returns an allocated string for the file name. NULL for error.
5646 */
5647 char_u *
5648find_directory_in_path(ptr, len, options, rel_fname)
5649 char_u *ptr; /* file name */
5650 int len; /* length of file name */
5651 int options;
5652 char_u *rel_fname; /* file name searching relative to */
5653{
5654 return find_file_in_path_option(ptr, len, options, TRUE, p_cdpath,
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005655 FINDFILE_DIR, rel_fname, (char_u *)"");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005656}
5657
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00005658 char_u *
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005659find_file_in_path_option(ptr, len, options, first, path_option, find_what, rel_fname, suffixes)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005660 char_u *ptr; /* file name */
5661 int len; /* length of file name */
5662 int options;
5663 int first; /* use count'th matching file name */
5664 char_u *path_option; /* p_path or p_cdpath */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005665 int find_what; /* FINDFILE_FILE, _DIR or _BOTH */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005666 char_u *rel_fname; /* file name we are looking relative to. */
Bram Moolenaar433f7c82006-03-21 21:29:36 +00005667 char_u *suffixes; /* list of suffixes, 'suffixesadd' option */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005668{
Bram Moolenaar071d4272004-06-13 20:20:40 +00005669 static char_u *dir;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005670 static int did_findfile_init = FALSE;
5671 char_u save_char;
5672 char_u *file_name = NULL;
5673 char_u *buf = NULL;
5674 int rel_to_curdir;
5675#ifdef AMIGA
5676 struct Process *proc = (struct Process *)FindTask(0L);
5677 APTR save_winptr = proc->pr_WindowPtr;
5678
5679 /* Avoid a requester here for a volume that doesn't exist. */
5680 proc->pr_WindowPtr = (APTR)-1L;
5681#endif
5682
5683 if (first == TRUE)
5684 {
5685 /* copy file name into NameBuff, expanding environment variables */
5686 save_char = ptr[len];
5687 ptr[len] = NUL;
5688 expand_env(ptr, NameBuff, MAXPATHL);
5689 ptr[len] = save_char;
5690
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005691 vim_free(ff_file_to_find);
5692 ff_file_to_find = vim_strsave(NameBuff);
5693 if (ff_file_to_find == NULL) /* out of memory */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005694 {
5695 file_name = NULL;
5696 goto theend;
5697 }
5698 }
5699
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005700 rel_to_curdir = (ff_file_to_find[0] == '.'
5701 && (ff_file_to_find[1] == NUL
5702 || vim_ispathsep(ff_file_to_find[1])
5703 || (ff_file_to_find[1] == '.'
5704 && (ff_file_to_find[2] == NUL
5705 || vim_ispathsep(ff_file_to_find[2])))));
5706 if (vim_isAbsName(ff_file_to_find)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005707 /* "..", "../path", "." and "./path": don't use the path_option */
5708 || rel_to_curdir
5709#if defined(MSWIN) || defined(MSDOS) || defined(OS2)
5710 /* handle "\tmp" as absolute path */
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005711 || vim_ispathsep(ff_file_to_find[0])
Bram Moolenaar21160b92009-11-11 15:56:10 +00005712 /* handle "c:name" as absolute path */
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005713 || (ff_file_to_find[0] != NUL && ff_file_to_find[1] == ':')
Bram Moolenaar071d4272004-06-13 20:20:40 +00005714#endif
5715#ifdef AMIGA
5716 /* handle ":tmp" as absolute path */
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005717 || ff_file_to_find[0] == ':'
Bram Moolenaar071d4272004-06-13 20:20:40 +00005718#endif
5719 )
5720 {
5721 /*
5722 * Absolute path, no need to use "path_option".
5723 * If this is not a first call, return NULL. We already returned a
5724 * filename on the first call.
5725 */
5726 if (first == TRUE)
5727 {
5728 int l;
5729 int run;
5730
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005731 if (path_with_url(ff_file_to_find))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005732 {
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005733 file_name = vim_strsave(ff_file_to_find);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005734 goto theend;
5735 }
5736
5737 /* When FNAME_REL flag given first use the directory of the file.
5738 * Otherwise or when this fails use the current directory. */
5739 for (run = 1; run <= 2; ++run)
5740 {
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005741 l = (int)STRLEN(ff_file_to_find);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005742 if (run == 1
5743 && rel_to_curdir
5744 && (options & FNAME_REL)
5745 && rel_fname != NULL
5746 && STRLEN(rel_fname) + l < MAXPATHL)
5747 {
5748 STRCPY(NameBuff, rel_fname);
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005749 STRCPY(gettail(NameBuff), ff_file_to_find);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005750 l = (int)STRLEN(NameBuff);
5751 }
5752 else
5753 {
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005754 STRCPY(NameBuff, ff_file_to_find);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005755 run = 2;
5756 }
5757
5758 /* When the file doesn't exist, try adding parts of
5759 * 'suffixesadd'. */
Bram Moolenaar433f7c82006-03-21 21:29:36 +00005760 buf = suffixes;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005761 for (;;)
5762 {
5763 if (
5764#ifdef DJGPP
5765 /* "C:" by itself will fail for mch_getperm(),
5766 * assume it's always valid. */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005767 (find_what != FINDFILE_FILE && NameBuff[0] != NUL
Bram Moolenaar071d4272004-06-13 20:20:40 +00005768 && NameBuff[1] == ':'
5769 && NameBuff[2] == NUL) ||
5770#endif
5771 (mch_getperm(NameBuff) >= 0
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005772 && (find_what == FINDFILE_BOTH
5773 || ((find_what == FINDFILE_DIR)
5774 == mch_isdir(NameBuff)))))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005775 {
5776 file_name = vim_strsave(NameBuff);
5777 goto theend;
5778 }
5779 if (*buf == NUL)
5780 break;
5781 copy_option_part(&buf, NameBuff + l, MAXPATHL - l, ",");
5782 }
5783 }
5784 }
5785 }
5786 else
5787 {
5788 /*
5789 * Loop over all paths in the 'path' or 'cdpath' option.
5790 * When "first" is set, first setup to the start of the option.
5791 * Otherwise continue to find the next match.
5792 */
5793 if (first == TRUE)
5794 {
5795 /* vim_findfile_free_visited can handle a possible NULL pointer */
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005796 vim_findfile_free_visited(fdip_search_ctx);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005797 dir = path_option;
5798 did_findfile_init = FALSE;
5799 }
5800
5801 for (;;)
5802 {
5803 if (did_findfile_init)
5804 {
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005805 file_name = vim_findfile(fdip_search_ctx);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005806 if (file_name != NULL)
5807 break;
5808
5809 did_findfile_init = FALSE;
5810 }
5811 else
5812 {
5813 char_u *r_ptr;
5814
5815 if (dir == NULL || *dir == NUL)
5816 {
5817 /* We searched all paths of the option, now we can
5818 * free the search context. */
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005819 vim_findfile_cleanup(fdip_search_ctx);
5820 fdip_search_ctx = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005821 break;
5822 }
5823
5824 if ((buf = alloc((int)(MAXPATHL))) == NULL)
5825 break;
5826
5827 /* copy next path */
5828 buf[0] = 0;
5829 copy_option_part(&dir, buf, MAXPATHL, " ,");
5830
5831#ifdef FEAT_PATH_EXTRA
5832 /* get the stopdir string */
5833 r_ptr = vim_findfile_stopdir(buf);
5834#else
5835 r_ptr = NULL;
5836#endif
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005837 fdip_search_ctx = vim_findfile_init(buf, ff_file_to_find,
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005838 r_ptr, 100, FALSE, find_what,
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005839 fdip_search_ctx, FALSE, rel_fname);
5840 if (fdip_search_ctx != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005841 did_findfile_init = TRUE;
5842 vim_free(buf);
5843 }
5844 }
5845 }
5846 if (file_name == NULL && (options & FNAME_MESS))
5847 {
5848 if (first == TRUE)
5849 {
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005850 if (find_what == FINDFILE_DIR)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005851 EMSG2(_("E344: Can't find directory \"%s\" in cdpath"),
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005852 ff_file_to_find);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005853 else
5854 EMSG2(_("E345: Can't find file \"%s\" in path"),
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005855 ff_file_to_find);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005856 }
5857 else
5858 {
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005859 if (find_what == FINDFILE_DIR)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005860 EMSG2(_("E346: No more directory \"%s\" found in cdpath"),
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005861 ff_file_to_find);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005862 else
5863 EMSG2(_("E347: No more file \"%s\" found in path"),
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005864 ff_file_to_find);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005865 }
5866 }
5867
5868theend:
5869#ifdef AMIGA
5870 proc->pr_WindowPtr = save_winptr;
5871#endif
5872 return file_name;
5873}
5874
5875#endif /* FEAT_SEARCHPATH */
5876
5877/*
5878 * Change directory to "new_dir". If FEAT_SEARCHPATH is defined, search
5879 * 'cdpath' for relative directory names, otherwise just mch_chdir().
5880 */
5881 int
5882vim_chdir(new_dir)
5883 char_u *new_dir;
5884{
5885#ifndef FEAT_SEARCHPATH
5886 return mch_chdir((char *)new_dir);
5887#else
5888 char_u *dir_name;
5889 int r;
5890
5891 dir_name = find_directory_in_path(new_dir, (int)STRLEN(new_dir),
5892 FNAME_MESS, curbuf->b_ffname);
5893 if (dir_name == NULL)
5894 return -1;
5895 r = mch_chdir((char *)dir_name);
5896 vim_free(dir_name);
5897 return r;
5898#endif
5899}
5900
5901/*
Bram Moolenaarbbebc852005-07-18 21:47:53 +00005902 * Get user name from machine-specific function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005903 * Returns the user name in "buf[len]".
Bram Moolenaarbbebc852005-07-18 21:47:53 +00005904 * Some systems are quite slow in obtaining the user name (Windows NT), thus
5905 * cache the result.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005906 * Returns OK or FAIL.
5907 */
5908 int
5909get_user_name(buf, len)
5910 char_u *buf;
5911 int len;
5912{
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005913 if (username == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005914 {
5915 if (mch_get_user_name(buf, len) == FAIL)
5916 return FAIL;
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005917 username = vim_strsave(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005918 }
5919 else
Bram Moolenaarbbebc852005-07-18 21:47:53 +00005920 vim_strncpy(buf, username, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005921 return OK;
5922}
5923
5924#ifndef HAVE_QSORT
5925/*
5926 * Our own qsort(), for systems that don't have it.
5927 * It's simple and slow. From the K&R C book.
5928 */
5929 void
5930qsort(base, elm_count, elm_size, cmp)
5931 void *base;
5932 size_t elm_count;
5933 size_t elm_size;
5934 int (*cmp) __ARGS((const void *, const void *));
5935{
5936 char_u *buf;
5937 char_u *p1;
5938 char_u *p2;
5939 int i, j;
5940 int gap;
5941
5942 buf = alloc((unsigned)elm_size);
5943 if (buf == NULL)
5944 return;
5945
5946 for (gap = elm_count / 2; gap > 0; gap /= 2)
5947 for (i = gap; i < elm_count; ++i)
5948 for (j = i - gap; j >= 0; j -= gap)
5949 {
5950 /* Compare the elements. */
5951 p1 = (char_u *)base + j * elm_size;
5952 p2 = (char_u *)base + (j + gap) * elm_size;
5953 if ((*cmp)((void *)p1, (void *)p2) <= 0)
5954 break;
Bram Moolenaar21160b92009-11-11 15:56:10 +00005955 /* Exchange the elements. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005956 mch_memmove(buf, p1, elm_size);
5957 mch_memmove(p1, p2, elm_size);
5958 mch_memmove(p2, buf, elm_size);
5959 }
5960
5961 vim_free(buf);
5962}
5963#endif
5964
Bram Moolenaar071d4272004-06-13 20:20:40 +00005965/*
5966 * Sort an array of strings.
5967 */
5968static int
5969#ifdef __BORLANDC__
5970_RTLENTRYF
5971#endif
5972sort_compare __ARGS((const void *s1, const void *s2));
5973
5974 static int
5975#ifdef __BORLANDC__
5976_RTLENTRYF
5977#endif
5978sort_compare(s1, s2)
5979 const void *s1;
5980 const void *s2;
5981{
5982 return STRCMP(*(char **)s1, *(char **)s2);
5983}
5984
5985 void
5986sort_strings(files, count)
5987 char_u **files;
5988 int count;
5989{
5990 qsort((void *)files, (size_t)count, sizeof(char_u *), sort_compare);
5991}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005992
5993#if !defined(NO_EXPANDPATH) || defined(PROTO)
5994/*
5995 * Compare path "p[]" to "q[]".
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005996 * If "maxlen" >= 0 compare "p[maxlen]" to "q[maxlen]"
Bram Moolenaar071d4272004-06-13 20:20:40 +00005997 * Return value like strcmp(p, q), but consider path separators.
5998 */
5999 int
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006000pathcmp(p, q, maxlen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006001 const char *p, *q;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006002 int maxlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006003{
6004 int i;
Bram Moolenaar86b68352004-12-27 21:59:20 +00006005 const char *s = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006006
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006007 for (i = 0; maxlen < 0 || i < maxlen; ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006008 {
6009 /* End of "p": check if "q" also ends or just has a slash. */
6010 if (p[i] == NUL)
6011 {
6012 if (q[i] == NUL) /* full match */
6013 return 0;
6014 s = q;
6015 break;
6016 }
6017
6018 /* End of "q": check if "p" just has a slash. */
6019 if (q[i] == NUL)
6020 {
6021 s = p;
6022 break;
6023 }
6024
6025 if (
6026#ifdef CASE_INSENSITIVE_FILENAME
6027 TOUPPER_LOC(p[i]) != TOUPPER_LOC(q[i])
6028#else
6029 p[i] != q[i]
6030#endif
6031#ifdef BACKSLASH_IN_FILENAME
6032 /* consider '/' and '\\' to be equal */
6033 && !((p[i] == '/' && q[i] == '\\')
6034 || (p[i] == '\\' && q[i] == '/'))
6035#endif
6036 )
6037 {
6038 if (vim_ispathsep(p[i]))
6039 return -1;
6040 if (vim_ispathsep(q[i]))
6041 return 1;
6042 return ((char_u *)p)[i] - ((char_u *)q)[i]; /* no match */
6043 }
6044 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00006045 if (s == NULL) /* "i" ran into "maxlen" */
6046 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006047
6048 /* ignore a trailing slash, but not "//" or ":/" */
Bram Moolenaar86b68352004-12-27 21:59:20 +00006049 if (s[i + 1] == NUL
6050 && i > 0
6051 && !after_pathsep((char_u *)s, (char_u *)s + i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006052#ifdef BACKSLASH_IN_FILENAME
Bram Moolenaar86b68352004-12-27 21:59:20 +00006053 && (s[i] == '/' || s[i] == '\\')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006054#else
Bram Moolenaar86b68352004-12-27 21:59:20 +00006055 && s[i] == '/'
Bram Moolenaar071d4272004-06-13 20:20:40 +00006056#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00006057 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00006058 return 0; /* match with trailing slash */
6059 if (s == q)
6060 return -1; /* no match */
6061 return 1;
6062}
6063#endif
6064
Bram Moolenaar071d4272004-06-13 20:20:40 +00006065/*
6066 * The putenv() implementation below comes from the "screen" program.
6067 * Included with permission from Juergen Weigert.
6068 * See pty.c for the copyright notice.
6069 */
6070
6071/*
6072 * putenv -- put value into environment
6073 *
6074 * Usage: i = putenv (string)
6075 * int i;
6076 * char *string;
6077 *
6078 * where string is of the form <name>=<value>.
6079 * Putenv returns 0 normally, -1 on error (not enough core for malloc).
6080 *
6081 * Putenv may need to add a new name into the environment, or to
6082 * associate a value longer than the current value with a particular
6083 * name. So, to make life simpler, putenv() copies your entire
6084 * environment into the heap (i.e. malloc()) from the stack
6085 * (i.e. where it resides when your process is initiated) the first
6086 * time you call it.
6087 *
6088 * (history removed, not very interesting. See the "screen" sources.)
6089 */
6090
6091#if !defined(HAVE_SETENV) && !defined(HAVE_PUTENV)
6092
6093#define EXTRASIZE 5 /* increment to add to env. size */
6094
6095static int envsize = -1; /* current size of environment */
6096#ifndef MACOS_CLASSIC
6097extern
6098#endif
6099 char **environ; /* the global which is your env. */
6100
6101static int findenv __ARGS((char *name)); /* look for a name in the env. */
6102static int newenv __ARGS((void)); /* copy env. from stack to heap */
6103static int moreenv __ARGS((void)); /* incr. size of env. */
6104
6105 int
6106putenv(string)
6107 const char *string;
6108{
6109 int i;
6110 char *p;
6111
6112 if (envsize < 0)
6113 { /* first time putenv called */
6114 if (newenv() < 0) /* copy env. to heap */
6115 return -1;
6116 }
6117
6118 i = findenv((char *)string); /* look for name in environment */
6119
6120 if (i < 0)
6121 { /* name must be added */
6122 for (i = 0; environ[i]; i++);
6123 if (i >= (envsize - 1))
6124 { /* need new slot */
6125 if (moreenv() < 0)
6126 return -1;
6127 }
6128 p = (char *)alloc((unsigned)(strlen(string) + 1));
6129 if (p == NULL) /* not enough core */
6130 return -1;
6131 environ[i + 1] = 0; /* new end of env. */
6132 }
6133 else
6134 { /* name already in env. */
6135 p = vim_realloc(environ[i], strlen(string) + 1);
6136 if (p == NULL)
6137 return -1;
6138 }
6139 sprintf(p, "%s", string); /* copy into env. */
6140 environ[i] = p;
6141
6142 return 0;
6143}
6144
6145 static int
6146findenv(name)
6147 char *name;
6148{
6149 char *namechar, *envchar;
6150 int i, found;
6151
6152 found = 0;
6153 for (i = 0; environ[i] && !found; i++)
6154 {
6155 envchar = environ[i];
6156 namechar = name;
6157 while (*namechar && *namechar != '=' && (*namechar == *envchar))
6158 {
6159 namechar++;
6160 envchar++;
6161 }
6162 found = ((*namechar == '\0' || *namechar == '=') && *envchar == '=');
6163 }
6164 return found ? i - 1 : -1;
6165}
6166
6167 static int
6168newenv()
6169{
6170 char **env, *elem;
6171 int i, esize;
6172
6173#ifdef MACOS
6174 /* for Mac a new, empty environment is created */
6175 i = 0;
6176#else
6177 for (i = 0; environ[i]; i++)
6178 ;
6179#endif
6180 esize = i + EXTRASIZE + 1;
6181 env = (char **)alloc((unsigned)(esize * sizeof (elem)));
6182 if (env == NULL)
6183 return -1;
6184
6185#ifndef MACOS
6186 for (i = 0; environ[i]; i++)
6187 {
6188 elem = (char *)alloc((unsigned)(strlen(environ[i]) + 1));
6189 if (elem == NULL)
6190 return -1;
6191 env[i] = elem;
6192 strcpy(elem, environ[i]);
6193 }
6194#endif
6195
6196 env[i] = 0;
6197 environ = env;
6198 envsize = esize;
6199 return 0;
6200}
6201
6202 static int
6203moreenv()
6204{
6205 int esize;
6206 char **env;
6207
6208 esize = envsize + EXTRASIZE;
6209 env = (char **)vim_realloc((char *)environ, esize * sizeof (*env));
6210 if (env == 0)
6211 return -1;
6212 environ = env;
6213 envsize = esize;
6214 return 0;
6215}
6216
6217# ifdef USE_VIMPTY_GETENV
6218 char_u *
6219vimpty_getenv(string)
6220 const char_u *string;
6221{
6222 int i;
6223 char_u *p;
6224
6225 if (envsize < 0)
6226 return NULL;
6227
6228 i = findenv((char *)string);
6229
6230 if (i < 0)
6231 return NULL;
6232
6233 p = vim_strchr((char_u *)environ[i], '=');
6234 return (p + 1);
6235}
6236# endif
6237
6238#endif /* !defined(HAVE_SETENV) && !defined(HAVE_PUTENV) */
Bram Moolenaarc4a06d32005-06-07 21:04:49 +00006239
Bram Moolenaarc4956c82006-03-12 21:58:43 +00006240#if defined(FEAT_EVAL) || defined(FEAT_SPELL) || defined(PROTO)
Bram Moolenaarc4a06d32005-06-07 21:04:49 +00006241/*
6242 * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
6243 * rights to write into.
6244 */
6245 int
6246filewritable(fname)
6247 char_u *fname;
6248{
6249 int retval = 0;
6250#if defined(UNIX) || defined(VMS)
6251 int perm = 0;
6252#endif
6253
6254#if defined(UNIX) || defined(VMS)
6255 perm = mch_getperm(fname);
6256#endif
6257#ifndef MACOS_CLASSIC /* TODO: get either mch_writable or mch_access */
6258 if (
6259# ifdef WIN3264
6260 mch_writable(fname) &&
6261# else
6262# if defined(UNIX) || defined(VMS)
6263 (perm & 0222) &&
6264# endif
6265# endif
6266 mch_access((char *)fname, W_OK) == 0
6267 )
6268#endif
6269 {
6270 ++retval;
6271 if (mch_isdir(fname))
6272 ++retval;
6273 }
6274 return retval;
6275}
6276#endif
Bram Moolenaar6bab4d12005-06-16 21:53:56 +00006277
6278/*
6279 * Print an error message with one or two "%s" and one or two string arguments.
6280 * This is not in message.c to avoid a warning for prototypes.
6281 */
6282 int
6283emsg3(s, a1, a2)
6284 char_u *s, *a1, *a2;
6285{
Bram Moolenaareb3593b2006-04-22 22:33:57 +00006286 if (emsg_not_now())
Bram Moolenaar6bab4d12005-06-16 21:53:56 +00006287 return TRUE; /* no error messages at the moment */
Bram Moolenaar6f192452007-11-08 19:49:02 +00006288#ifdef HAVE_STDARG_H
6289 vim_snprintf((char *)IObuff, IOSIZE, (char *)s, a1, a2);
6290#else
Bram Moolenaareb3593b2006-04-22 22:33:57 +00006291 vim_snprintf((char *)IObuff, IOSIZE, (char *)s, (long_u)a1, (long_u)a2);
Bram Moolenaar6f192452007-11-08 19:49:02 +00006292#endif
Bram Moolenaar6bab4d12005-06-16 21:53:56 +00006293 return emsg(IObuff);
6294}
6295
6296/*
6297 * Print an error message with one "%ld" and one long int argument.
6298 * This is not in message.c to avoid a warning for prototypes.
6299 */
6300 int
6301emsgn(s, n)
6302 char_u *s;
6303 long n;
6304{
Bram Moolenaareb3593b2006-04-22 22:33:57 +00006305 if (emsg_not_now())
Bram Moolenaar6bab4d12005-06-16 21:53:56 +00006306 return TRUE; /* no error messages at the moment */
6307 vim_snprintf((char *)IObuff, IOSIZE, (char *)s, n);
6308 return emsg(IObuff);
6309}
Bram Moolenaarcdf04202010-05-29 15:11:47 +02006310
6311#if defined(FEAT_SPELL) || defined(FEAT_PERSISTENT_UNDO) || defined(PROTO)
6312/*
6313 * Read 2 bytes from "fd" and turn them into an int, MSB first.
6314 */
6315 int
6316get2c(fd)
6317 FILE *fd;
6318{
Bram Moolenaar9db58062010-05-29 20:33:07 +02006319 int n;
Bram Moolenaarcdf04202010-05-29 15:11:47 +02006320
6321 n = getc(fd);
6322 n = (n << 8) + getc(fd);
6323 return n;
6324}
6325
6326/*
6327 * Read 3 bytes from "fd" and turn them into an int, MSB first.
6328 */
6329 int
6330get3c(fd)
6331 FILE *fd;
6332{
Bram Moolenaar9db58062010-05-29 20:33:07 +02006333 int n;
Bram Moolenaarcdf04202010-05-29 15:11:47 +02006334
6335 n = getc(fd);
6336 n = (n << 8) + getc(fd);
6337 n = (n << 8) + getc(fd);
6338 return n;
6339}
6340
6341/*
6342 * Read 4 bytes from "fd" and turn them into an int, MSB first.
6343 */
6344 int
6345get4c(fd)
6346 FILE *fd;
6347{
Bram Moolenaar9db58062010-05-29 20:33:07 +02006348 int n;
Bram Moolenaarcdf04202010-05-29 15:11:47 +02006349
6350 n = getc(fd);
6351 n = (n << 8) + getc(fd);
6352 n = (n << 8) + getc(fd);
6353 n = (n << 8) + getc(fd);
6354 return n;
6355}
6356
6357/*
6358 * Read 8 bytes from "fd" and turn them into a time_t, MSB first.
6359 */
6360 time_t
6361get8ctime(fd)
6362 FILE *fd;
6363{
6364 time_t n = 0;
6365 int i;
6366
6367 for (i = 0; i < 8; ++i)
6368 n = (n << 8) + getc(fd);
6369 return n;
6370}
6371
6372/*
6373 * Read a string of length "cnt" from "fd" into allocated memory.
6374 * Returns NULL when out of memory or unable to read that many bytes.
6375 */
6376 char_u *
6377read_string(fd, cnt)
6378 FILE *fd;
6379 int cnt;
6380{
6381 char_u *str;
6382 int i;
6383 int c;
6384
6385 /* allocate memory */
6386 str = alloc((unsigned)cnt + 1);
6387 if (str != NULL)
6388 {
6389 /* Read the string. Quit when running into the EOF. */
6390 for (i = 0; i < cnt; ++i)
6391 {
6392 c = getc(fd);
6393 if (c == EOF)
6394 {
6395 vim_free(str);
6396 return NULL;
6397 }
6398 str[i] = c;
6399 }
6400 str[i] = NUL;
6401 }
6402 return str;
6403}
6404
6405/*
6406 * Write a number to file "fd", MSB first, in "len" bytes.
6407 */
6408 int
6409put_bytes(fd, nr, len)
6410 FILE *fd;
6411 long_u nr;
6412 int len;
6413{
6414 int i;
6415
6416 for (i = len - 1; i >= 0; --i)
6417 if (putc((int)(nr >> (i * 8)), fd) == EOF)
6418 return FAIL;
6419 return OK;
6420}
6421
6422#ifdef _MSC_VER
6423# if (_MSC_VER <= 1200)
6424/* This line is required for VC6 without the service pack. Also see the
6425 * matching #pragma below. */
6426 # pragma optimize("", off)
6427# endif
6428#endif
6429
6430/*
6431 * Write time_t to file "fd" in 8 bytes.
6432 */
6433 void
6434put_time(fd, the_time)
6435 FILE *fd;
6436 time_t the_time;
6437{
6438 int c;
6439 int i;
6440 time_t wtime = the_time;
6441
6442 /* time_t can be up to 8 bytes in size, more than long_u, thus we
6443 * can't use put_bytes() here.
6444 * Another problem is that ">>" may do an arithmetic shift that keeps the
Bram Moolenaar644fdff2010-05-30 13:26:21 +02006445 * sign. This happens for large values of wtime. A cast to long_u may
6446 * truncate if time_t is 8 bytes. So only use a cast when it is 4 bytes,
6447 * it's safe to assume that long_u is 4 bytes or more and when using 8
6448 * bytes the top bit won't be set. */
Bram Moolenaarcdf04202010-05-29 15:11:47 +02006449 for (i = 7; i >= 0; --i)
6450 {
6451 if (i + 1 > (int)sizeof(time_t))
6452 /* ">>" doesn't work well when shifting more bits than avail */
6453 putc(0, fd);
6454 else
6455 {
Bram Moolenaar644fdff2010-05-30 13:26:21 +02006456#if defined(SIZEOF_TIME_T) && SIZEOF_TIME_T > 4
Bram Moolenaarbbd6afe2010-06-02 20:32:23 +02006457 c = (int)(wtime >> (i * 8));
Bram Moolenaar644fdff2010-05-30 13:26:21 +02006458#else
Bram Moolenaarbbd6afe2010-06-02 20:32:23 +02006459 c = (int)((long_u)wtime >> (i * 8));
Bram Moolenaar644fdff2010-05-30 13:26:21 +02006460#endif
Bram Moolenaarcdf04202010-05-29 15:11:47 +02006461 putc(c, fd);
6462 }
6463 }
6464}
6465
6466#ifdef _MSC_VER
6467# if (_MSC_VER <= 1200)
6468 # pragma optimize("", on)
6469# endif
6470#endif
6471
6472#endif