blob: c6f4f112d2cf0c183f0d454383f4f340ee96475c [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/*
1650 * Isolate one part of a string option where parts are separated with
1651 * "sep_chars".
Bram Moolenaar83bab712005-08-01 21:58:57 +00001652 * The part is copied into "buf[maxlen]".
Bram Moolenaar071d4272004-06-13 20:20:40 +00001653 * "*option" is advanced to the next part.
1654 * The length is returned.
1655 */
1656 int
1657copy_option_part(option, buf, maxlen, sep_chars)
1658 char_u **option;
1659 char_u *buf;
1660 int maxlen;
1661 char *sep_chars;
1662{
1663 int len = 0;
1664 char_u *p = *option;
1665
1666 /* skip '.' at start of option part, for 'suffixes' */
1667 if (*p == '.')
1668 buf[len++] = *p++;
1669 while (*p != NUL && vim_strchr((char_u *)sep_chars, *p) == NULL)
1670 {
1671 /*
1672 * Skip backslash before a separator character and space.
1673 */
1674 if (p[0] == '\\' && vim_strchr((char_u *)sep_chars, p[1]) != NULL)
1675 ++p;
1676 if (len < maxlen - 1)
1677 buf[len++] = *p;
1678 ++p;
1679 }
1680 buf[len] = NUL;
1681
1682 if (*p != NUL && *p != ',') /* skip non-standard separator */
1683 ++p;
1684 p = skip_to_option_part(p); /* p points to next file name */
1685
1686 *option = p;
1687 return len;
1688}
1689
1690/*
Bram Moolenaar4770d092006-01-12 23:22:24 +00001691 * Replacement for free() that ignores NULL pointers.
1692 * Also skip free() when exiting for sure, this helps when we caught a deadly
1693 * signal that was caused by a crash in free().
Bram Moolenaar071d4272004-06-13 20:20:40 +00001694 */
1695 void
1696vim_free(x)
1697 void *x;
1698{
Bram Moolenaar4770d092006-01-12 23:22:24 +00001699 if (x != NULL && !really_exiting)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001700 {
1701#ifdef MEM_PROFILE
1702 mem_pre_free(&x);
1703#endif
1704 free(x);
1705 }
1706}
1707
1708#ifndef HAVE_MEMSET
1709 void *
1710vim_memset(ptr, c, size)
1711 void *ptr;
1712 int c;
1713 size_t size;
1714{
1715 char *p = ptr;
1716
1717 while (size-- > 0)
1718 *p++ = c;
1719 return ptr;
1720}
1721#endif
1722
1723#ifdef VIM_MEMCMP
1724/*
1725 * Return zero when "b1" and "b2" are the same for "len" bytes.
1726 * Return non-zero otherwise.
1727 */
1728 int
1729vim_memcmp(b1, b2, len)
1730 void *b1;
1731 void *b2;
1732 size_t len;
1733{
1734 char_u *p1 = (char_u *)b1, *p2 = (char_u *)b2;
1735
1736 for ( ; len > 0; --len)
1737 {
1738 if (*p1 != *p2)
1739 return 1;
1740 ++p1;
1741 ++p2;
1742 }
1743 return 0;
1744}
1745#endif
1746
1747#ifdef VIM_MEMMOVE
1748/*
1749 * Version of memmove() that handles overlapping source and destination.
1750 * For systems that don't have a function that is guaranteed to do that (SYSV).
1751 */
1752 void
1753mch_memmove(dst_arg, src_arg, len)
1754 void *src_arg, *dst_arg;
1755 size_t len;
1756{
1757 /*
1758 * A void doesn't have a size, we use char pointers.
1759 */
1760 char *dst = dst_arg, *src = src_arg;
1761
1762 /* overlap, copy backwards */
1763 if (dst > src && dst < src + len)
1764 {
1765 src += len;
1766 dst += len;
1767 while (len-- > 0)
1768 *--dst = *--src;
1769 }
1770 else /* copy forwards */
1771 while (len-- > 0)
1772 *dst++ = *src++;
1773}
1774#endif
1775
1776#if (!defined(HAVE_STRCASECMP) && !defined(HAVE_STRICMP)) || defined(PROTO)
1777/*
1778 * Compare two strings, ignoring case, using current locale.
1779 * Doesn't work for multi-byte characters.
1780 * return 0 for match, < 0 for smaller, > 0 for bigger
1781 */
1782 int
1783vim_stricmp(s1, s2)
1784 char *s1;
1785 char *s2;
1786{
1787 int i;
1788
1789 for (;;)
1790 {
1791 i = (int)TOLOWER_LOC(*s1) - (int)TOLOWER_LOC(*s2);
1792 if (i != 0)
1793 return i; /* this character different */
1794 if (*s1 == NUL)
1795 break; /* strings match until NUL */
1796 ++s1;
1797 ++s2;
1798 }
1799 return 0; /* strings match */
1800}
1801#endif
1802
1803#if (!defined(HAVE_STRNCASECMP) && !defined(HAVE_STRNICMP)) || defined(PROTO)
1804/*
1805 * Compare two strings, for length "len", ignoring case, using current locale.
1806 * Doesn't work for multi-byte characters.
1807 * return 0 for match, < 0 for smaller, > 0 for bigger
1808 */
1809 int
1810vim_strnicmp(s1, s2, len)
1811 char *s1;
1812 char *s2;
1813 size_t len;
1814{
1815 int i;
1816
1817 while (len > 0)
1818 {
1819 i = (int)TOLOWER_LOC(*s1) - (int)TOLOWER_LOC(*s2);
1820 if (i != 0)
1821 return i; /* this character different */
1822 if (*s1 == NUL)
1823 break; /* strings match until NUL */
1824 ++s1;
1825 ++s2;
1826 --len;
1827 }
1828 return 0; /* strings match */
1829}
1830#endif
1831
Bram Moolenaar071d4272004-06-13 20:20:40 +00001832/*
1833 * Version of strchr() and strrchr() that handle unsigned char strings
Bram Moolenaar05159a02005-02-26 23:04:13 +00001834 * with characters from 128 to 255 correctly. It also doesn't return a
1835 * pointer to the NUL at the end of the string.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001836 */
1837 char_u *
1838vim_strchr(string, c)
1839 char_u *string;
1840 int c;
1841{
1842 char_u *p;
1843 int b;
1844
1845 p = string;
1846#ifdef FEAT_MBYTE
1847 if (enc_utf8 && c >= 0x80)
1848 {
1849 while (*p != NUL)
1850 {
1851 if (utf_ptr2char(p) == c)
1852 return p;
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00001853 p += (*mb_ptr2len)(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001854 }
1855 return NULL;
1856 }
1857 if (enc_dbcs != 0 && c > 255)
1858 {
1859 int n2 = c & 0xff;
1860
1861 c = ((unsigned)c >> 8) & 0xff;
1862 while ((b = *p) != NUL)
1863 {
1864 if (b == c && p[1] == n2)
1865 return p;
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00001866 p += (*mb_ptr2len)(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001867 }
1868 return NULL;
1869 }
1870 if (has_mbyte)
1871 {
1872 while ((b = *p) != NUL)
1873 {
1874 if (b == c)
1875 return p;
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00001876 p += (*mb_ptr2len)(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001877 }
1878 return NULL;
1879 }
1880#endif
1881 while ((b = *p) != NUL)
1882 {
1883 if (b == c)
1884 return p;
1885 ++p;
1886 }
1887 return NULL;
1888}
1889
1890/*
Bram Moolenaar05159a02005-02-26 23:04:13 +00001891 * Version of strchr() that only works for bytes and handles unsigned char
1892 * strings with characters above 128 correctly. It also doesn't return a
1893 * pointer to the NUL at the end of the string.
1894 */
1895 char_u *
1896vim_strbyte(string, c)
1897 char_u *string;
1898 int c;
1899{
1900 char_u *p = string;
1901
1902 while (*p != NUL)
1903 {
1904 if (*p == c)
1905 return p;
1906 ++p;
1907 }
1908 return NULL;
1909}
1910
1911/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001912 * Search for last occurrence of "c" in "string".
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00001913 * Return NULL if not found.
Bram Moolenaar05159a02005-02-26 23:04:13 +00001914 * Does not handle multi-byte char for "c"!
Bram Moolenaar071d4272004-06-13 20:20:40 +00001915 */
1916 char_u *
1917vim_strrchr(string, c)
1918 char_u *string;
1919 int c;
1920{
1921 char_u *retval = NULL;
Bram Moolenaar05159a02005-02-26 23:04:13 +00001922 char_u *p = string;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001923
Bram Moolenaar05159a02005-02-26 23:04:13 +00001924 while (*p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001925 {
Bram Moolenaar05159a02005-02-26 23:04:13 +00001926 if (*p == c)
1927 retval = p;
1928 mb_ptr_adv(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001929 }
1930 return retval;
1931}
1932
1933/*
1934 * Vim's version of strpbrk(), in case it's missing.
1935 * Don't generate a prototype for this, causes problems when it's not used.
1936 */
1937#ifndef PROTO
1938# ifndef HAVE_STRPBRK
1939# ifdef vim_strpbrk
1940# undef vim_strpbrk
1941# endif
1942 char_u *
1943vim_strpbrk(s, charset)
1944 char_u *s;
1945 char_u *charset;
1946{
1947 while (*s)
1948 {
1949 if (vim_strchr(charset, *s) != NULL)
1950 return s;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001951 mb_ptr_adv(s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001952 }
1953 return NULL;
1954}
1955# endif
1956#endif
1957
1958/*
1959 * Vim has its own isspace() function, because on some machines isspace()
1960 * can't handle characters above 128.
1961 */
1962 int
1963vim_isspace(x)
1964 int x;
1965{
1966 return ((x >= 9 && x <= 13) || x == ' ');
1967}
1968
1969/************************************************************************
Bram Moolenaar383f9bc2005-01-19 22:18:32 +00001970 * Functions for handling growing arrays.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001971 */
1972
1973/*
1974 * Clear an allocated growing array.
1975 */
1976 void
1977ga_clear(gap)
1978 garray_T *gap;
1979{
1980 vim_free(gap->ga_data);
1981 ga_init(gap);
1982}
1983
1984/*
1985 * Clear a growing array that contains a list of strings.
1986 */
1987 void
1988ga_clear_strings(gap)
1989 garray_T *gap;
1990{
1991 int i;
1992
1993 for (i = 0; i < gap->ga_len; ++i)
1994 vim_free(((char_u **)(gap->ga_data))[i]);
1995 ga_clear(gap);
1996}
1997
1998/*
1999 * Initialize a growing array. Don't forget to set ga_itemsize and
2000 * ga_growsize! Or use ga_init2().
2001 */
2002 void
2003ga_init(gap)
2004 garray_T *gap;
2005{
2006 gap->ga_data = NULL;
Bram Moolenaar86b68352004-12-27 21:59:20 +00002007 gap->ga_maxlen = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002008 gap->ga_len = 0;
2009}
2010
2011 void
2012ga_init2(gap, itemsize, growsize)
2013 garray_T *gap;
2014 int itemsize;
2015 int growsize;
2016{
2017 ga_init(gap);
2018 gap->ga_itemsize = itemsize;
2019 gap->ga_growsize = growsize;
2020}
2021
2022/*
2023 * Make room in growing array "gap" for at least "n" items.
2024 * Return FAIL for failure, OK otherwise.
2025 */
2026 int
2027ga_grow(gap, n)
2028 garray_T *gap;
2029 int n;
2030{
2031 size_t len;
2032 char_u *pp;
2033
Bram Moolenaar86b68352004-12-27 21:59:20 +00002034 if (gap->ga_maxlen - gap->ga_len < n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002035 {
2036 if (n < gap->ga_growsize)
2037 n = gap->ga_growsize;
2038 len = gap->ga_itemsize * (gap->ga_len + n);
2039 pp = alloc_clear((unsigned)len);
2040 if (pp == NULL)
2041 return FAIL;
Bram Moolenaar86b68352004-12-27 21:59:20 +00002042 gap->ga_maxlen = gap->ga_len + n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002043 if (gap->ga_data != NULL)
2044 {
2045 mch_memmove(pp, gap->ga_data,
2046 (size_t)(gap->ga_itemsize * gap->ga_len));
2047 vim_free(gap->ga_data);
2048 }
2049 gap->ga_data = pp;
2050 }
2051 return OK;
2052}
2053
2054/*
Bram Moolenaar80a7dcf2010-08-04 17:07:20 +02002055 * For a growing array that contains a list of strings: concatenate all the
2056 * strings with a separating comma.
2057 * Returns NULL when out of memory.
2058 */
2059 char_u *
2060ga_concat_strings(gap)
2061 garray_T *gap;
2062{
2063 int i;
2064 int len = 0;
2065 char_u *s;
2066
2067 for (i = 0; i < gap->ga_len; ++i)
2068 len += (int)STRLEN(((char_u **)(gap->ga_data))[i]) + 1;
2069
2070 s = alloc(len + 1);
2071 if (s != NULL)
2072 {
2073 *s = NUL;
2074 for (i = 0; i < gap->ga_len; ++i)
2075 {
2076 if (*s != NUL)
2077 STRCAT(s, ",");
2078 STRCAT(s, ((char_u **)(gap->ga_data))[i]);
2079 }
2080 }
2081 return s;
2082}
2083
2084/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00002085 * Concatenate a string to a growarray which contains characters.
2086 * Note: Does NOT copy the NUL at the end!
2087 */
2088 void
2089ga_concat(gap, s)
2090 garray_T *gap;
2091 char_u *s;
2092{
2093 int len = (int)STRLEN(s);
2094
2095 if (ga_grow(gap, len) == OK)
2096 {
2097 mch_memmove((char *)gap->ga_data + gap->ga_len, s, (size_t)len);
2098 gap->ga_len += len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002099 }
2100}
2101
2102/*
2103 * Append one byte to a growarray which contains bytes.
2104 */
2105 void
2106ga_append(gap, c)
2107 garray_T *gap;
2108 int c;
2109{
2110 if (ga_grow(gap, 1) == OK)
2111 {
2112 *((char *)gap->ga_data + gap->ga_len) = c;
2113 ++gap->ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002114 }
2115}
2116
2117/************************************************************************
2118 * functions that use lookup tables for various things, generally to do with
2119 * special key codes.
2120 */
2121
2122/*
2123 * Some useful tables.
2124 */
2125
2126static struct modmasktable
2127{
2128 short mod_mask; /* Bit-mask for particular key modifier */
2129 short mod_flag; /* Bit(s) for particular key modifier */
2130 char_u name; /* Single letter name of modifier */
2131} mod_mask_table[] =
2132{
2133 {MOD_MASK_ALT, MOD_MASK_ALT, (char_u)'M'},
Bram Moolenaar19a09a12005-03-04 23:39:37 +00002134 {MOD_MASK_META, MOD_MASK_META, (char_u)'T'},
Bram Moolenaar071d4272004-06-13 20:20:40 +00002135 {MOD_MASK_CTRL, MOD_MASK_CTRL, (char_u)'C'},
2136 {MOD_MASK_SHIFT, MOD_MASK_SHIFT, (char_u)'S'},
2137 {MOD_MASK_MULTI_CLICK, MOD_MASK_2CLICK, (char_u)'2'},
2138 {MOD_MASK_MULTI_CLICK, MOD_MASK_3CLICK, (char_u)'3'},
2139 {MOD_MASK_MULTI_CLICK, MOD_MASK_4CLICK, (char_u)'4'},
2140#ifdef MACOS
2141 {MOD_MASK_CMD, MOD_MASK_CMD, (char_u)'D'},
2142#endif
2143 /* 'A' must be the last one */
2144 {MOD_MASK_ALT, MOD_MASK_ALT, (char_u)'A'},
2145 {0, 0, NUL}
2146};
2147
2148/*
2149 * Shifted key terminal codes and their unshifted equivalent.
Bram Moolenaar7aa9f6a2007-05-10 18:00:30 +00002150 * Don't add mouse codes here, they are handled separately!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002151 */
2152#define MOD_KEYS_ENTRY_SIZE 5
2153
2154static char_u modifier_keys_table[] =
2155{
2156/* mod mask with modifier without modifier */
2157 MOD_MASK_SHIFT, '&', '9', '@', '1', /* begin */
2158 MOD_MASK_SHIFT, '&', '0', '@', '2', /* cancel */
2159 MOD_MASK_SHIFT, '*', '1', '@', '4', /* command */
2160 MOD_MASK_SHIFT, '*', '2', '@', '5', /* copy */
2161 MOD_MASK_SHIFT, '*', '3', '@', '6', /* create */
2162 MOD_MASK_SHIFT, '*', '4', 'k', 'D', /* delete char */
2163 MOD_MASK_SHIFT, '*', '5', 'k', 'L', /* delete line */
2164 MOD_MASK_SHIFT, '*', '7', '@', '7', /* end */
2165 MOD_MASK_CTRL, KS_EXTRA, (int)KE_C_END, '@', '7', /* end */
2166 MOD_MASK_SHIFT, '*', '9', '@', '9', /* exit */
2167 MOD_MASK_SHIFT, '*', '0', '@', '0', /* find */
2168 MOD_MASK_SHIFT, '#', '1', '%', '1', /* help */
2169 MOD_MASK_SHIFT, '#', '2', 'k', 'h', /* home */
2170 MOD_MASK_CTRL, KS_EXTRA, (int)KE_C_HOME, 'k', 'h', /* home */
2171 MOD_MASK_SHIFT, '#', '3', 'k', 'I', /* insert */
2172 MOD_MASK_SHIFT, '#', '4', 'k', 'l', /* left arrow */
2173 MOD_MASK_CTRL, KS_EXTRA, (int)KE_C_LEFT, 'k', 'l', /* left arrow */
2174 MOD_MASK_SHIFT, '%', 'a', '%', '3', /* message */
2175 MOD_MASK_SHIFT, '%', 'b', '%', '4', /* move */
2176 MOD_MASK_SHIFT, '%', 'c', '%', '5', /* next */
2177 MOD_MASK_SHIFT, '%', 'd', '%', '7', /* options */
2178 MOD_MASK_SHIFT, '%', 'e', '%', '8', /* previous */
2179 MOD_MASK_SHIFT, '%', 'f', '%', '9', /* print */
2180 MOD_MASK_SHIFT, '%', 'g', '%', '0', /* redo */
2181 MOD_MASK_SHIFT, '%', 'h', '&', '3', /* replace */
2182 MOD_MASK_SHIFT, '%', 'i', 'k', 'r', /* right arr. */
2183 MOD_MASK_CTRL, KS_EXTRA, (int)KE_C_RIGHT, 'k', 'r', /* right arr. */
2184 MOD_MASK_SHIFT, '%', 'j', '&', '5', /* resume */
2185 MOD_MASK_SHIFT, '!', '1', '&', '6', /* save */
2186 MOD_MASK_SHIFT, '!', '2', '&', '7', /* suspend */
2187 MOD_MASK_SHIFT, '!', '3', '&', '8', /* undo */
2188 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_UP, 'k', 'u', /* up arrow */
2189 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_DOWN, 'k', 'd', /* down arrow */
2190
2191 /* vt100 F1 */
2192 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF1, KS_EXTRA, (int)KE_XF1,
2193 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF2, KS_EXTRA, (int)KE_XF2,
2194 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF3, KS_EXTRA, (int)KE_XF3,
2195 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF4, KS_EXTRA, (int)KE_XF4,
2196
2197 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F1, 'k', '1', /* F1 */
2198 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F2, 'k', '2',
2199 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F3, 'k', '3',
2200 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F4, 'k', '4',
2201 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F5, 'k', '5',
2202 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F6, 'k', '6',
2203 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F7, 'k', '7',
2204 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F8, 'k', '8',
2205 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F9, 'k', '9',
2206 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F10, 'k', ';', /* F10 */
2207
2208 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F11, 'F', '1',
2209 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F12, 'F', '2',
2210 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F13, 'F', '3',
2211 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F14, 'F', '4',
2212 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F15, 'F', '5',
2213 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F16, 'F', '6',
2214 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F17, 'F', '7',
2215 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F18, 'F', '8',
2216 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F19, 'F', '9',
2217 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F20, 'F', 'A',
2218
2219 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F21, 'F', 'B',
2220 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F22, 'F', 'C',
2221 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F23, 'F', 'D',
2222 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F24, 'F', 'E',
2223 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F25, 'F', 'F',
2224 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F26, 'F', 'G',
2225 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F27, 'F', 'H',
2226 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F28, 'F', 'I',
2227 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F29, 'F', 'J',
2228 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F30, 'F', 'K',
2229
2230 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F31, 'F', 'L',
2231 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F32, 'F', 'M',
2232 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F33, 'F', 'N',
2233 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F34, 'F', 'O',
2234 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F35, 'F', 'P',
2235 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F36, 'F', 'Q',
2236 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F37, 'F', 'R',
2237
2238 /* TAB pseudo code*/
2239 MOD_MASK_SHIFT, 'k', 'B', KS_EXTRA, (int)KE_TAB,
2240
2241 NUL
2242};
2243
2244static struct key_name_entry
2245{
2246 int key; /* Special key code or ascii value */
2247 char_u *name; /* Name of key */
2248} key_names_table[] =
2249{
2250 {' ', (char_u *)"Space"},
2251 {TAB, (char_u *)"Tab"},
2252 {K_TAB, (char_u *)"Tab"},
2253 {NL, (char_u *)"NL"},
2254 {NL, (char_u *)"NewLine"}, /* Alternative name */
2255 {NL, (char_u *)"LineFeed"}, /* Alternative name */
2256 {NL, (char_u *)"LF"}, /* Alternative name */
2257 {CAR, (char_u *)"CR"},
2258 {CAR, (char_u *)"Return"}, /* Alternative name */
2259 {CAR, (char_u *)"Enter"}, /* Alternative name */
2260 {K_BS, (char_u *)"BS"},
2261 {K_BS, (char_u *)"BackSpace"}, /* Alternative name */
2262 {ESC, (char_u *)"Esc"},
2263 {CSI, (char_u *)"CSI"},
2264 {K_CSI, (char_u *)"xCSI"},
2265 {'|', (char_u *)"Bar"},
2266 {'\\', (char_u *)"Bslash"},
2267 {K_DEL, (char_u *)"Del"},
2268 {K_DEL, (char_u *)"Delete"}, /* Alternative name */
2269 {K_KDEL, (char_u *)"kDel"},
2270 {K_UP, (char_u *)"Up"},
2271 {K_DOWN, (char_u *)"Down"},
2272 {K_LEFT, (char_u *)"Left"},
2273 {K_RIGHT, (char_u *)"Right"},
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002274 {K_XUP, (char_u *)"xUp"},
2275 {K_XDOWN, (char_u *)"xDown"},
2276 {K_XLEFT, (char_u *)"xLeft"},
2277 {K_XRIGHT, (char_u *)"xRight"},
Bram Moolenaar071d4272004-06-13 20:20:40 +00002278
2279 {K_F1, (char_u *)"F1"},
2280 {K_F2, (char_u *)"F2"},
2281 {K_F3, (char_u *)"F3"},
2282 {K_F4, (char_u *)"F4"},
2283 {K_F5, (char_u *)"F5"},
2284 {K_F6, (char_u *)"F6"},
2285 {K_F7, (char_u *)"F7"},
2286 {K_F8, (char_u *)"F8"},
2287 {K_F9, (char_u *)"F9"},
2288 {K_F10, (char_u *)"F10"},
2289
2290 {K_F11, (char_u *)"F11"},
2291 {K_F12, (char_u *)"F12"},
2292 {K_F13, (char_u *)"F13"},
2293 {K_F14, (char_u *)"F14"},
2294 {K_F15, (char_u *)"F15"},
2295 {K_F16, (char_u *)"F16"},
2296 {K_F17, (char_u *)"F17"},
2297 {K_F18, (char_u *)"F18"},
2298 {K_F19, (char_u *)"F19"},
2299 {K_F20, (char_u *)"F20"},
2300
2301 {K_F21, (char_u *)"F21"},
2302 {K_F22, (char_u *)"F22"},
2303 {K_F23, (char_u *)"F23"},
2304 {K_F24, (char_u *)"F24"},
2305 {K_F25, (char_u *)"F25"},
2306 {K_F26, (char_u *)"F26"},
2307 {K_F27, (char_u *)"F27"},
2308 {K_F28, (char_u *)"F28"},
2309 {K_F29, (char_u *)"F29"},
2310 {K_F30, (char_u *)"F30"},
2311
2312 {K_F31, (char_u *)"F31"},
2313 {K_F32, (char_u *)"F32"},
2314 {K_F33, (char_u *)"F33"},
2315 {K_F34, (char_u *)"F34"},
2316 {K_F35, (char_u *)"F35"},
2317 {K_F36, (char_u *)"F36"},
2318 {K_F37, (char_u *)"F37"},
2319
2320 {K_XF1, (char_u *)"xF1"},
2321 {K_XF2, (char_u *)"xF2"},
2322 {K_XF3, (char_u *)"xF3"},
2323 {K_XF4, (char_u *)"xF4"},
2324
2325 {K_HELP, (char_u *)"Help"},
2326 {K_UNDO, (char_u *)"Undo"},
2327 {K_INS, (char_u *)"Insert"},
2328 {K_INS, (char_u *)"Ins"}, /* Alternative name */
2329 {K_KINS, (char_u *)"kInsert"},
2330 {K_HOME, (char_u *)"Home"},
2331 {K_KHOME, (char_u *)"kHome"},
2332 {K_XHOME, (char_u *)"xHome"},
Bram Moolenaar68b76a62005-03-25 21:53:48 +00002333 {K_ZHOME, (char_u *)"zHome"},
Bram Moolenaar071d4272004-06-13 20:20:40 +00002334 {K_END, (char_u *)"End"},
2335 {K_KEND, (char_u *)"kEnd"},
2336 {K_XEND, (char_u *)"xEnd"},
Bram Moolenaar68b76a62005-03-25 21:53:48 +00002337 {K_ZEND, (char_u *)"zEnd"},
Bram Moolenaar071d4272004-06-13 20:20:40 +00002338 {K_PAGEUP, (char_u *)"PageUp"},
2339 {K_PAGEDOWN, (char_u *)"PageDown"},
2340 {K_KPAGEUP, (char_u *)"kPageUp"},
2341 {K_KPAGEDOWN, (char_u *)"kPageDown"},
2342
2343 {K_KPLUS, (char_u *)"kPlus"},
2344 {K_KMINUS, (char_u *)"kMinus"},
2345 {K_KDIVIDE, (char_u *)"kDivide"},
2346 {K_KMULTIPLY, (char_u *)"kMultiply"},
2347 {K_KENTER, (char_u *)"kEnter"},
2348 {K_KPOINT, (char_u *)"kPoint"},
2349
2350 {K_K0, (char_u *)"k0"},
2351 {K_K1, (char_u *)"k1"},
2352 {K_K2, (char_u *)"k2"},
2353 {K_K3, (char_u *)"k3"},
2354 {K_K4, (char_u *)"k4"},
2355 {K_K5, (char_u *)"k5"},
2356 {K_K6, (char_u *)"k6"},
2357 {K_K7, (char_u *)"k7"},
2358 {K_K8, (char_u *)"k8"},
2359 {K_K9, (char_u *)"k9"},
2360
2361 {'<', (char_u *)"lt"},
2362
2363 {K_MOUSE, (char_u *)"Mouse"},
2364 {K_NETTERM_MOUSE, (char_u *)"NetMouse"},
2365 {K_DEC_MOUSE, (char_u *)"DecMouse"},
2366 {K_JSBTERM_MOUSE, (char_u *)"JsbMouse"},
2367 {K_PTERM_MOUSE, (char_u *)"PtermMouse"},
2368 {K_LEFTMOUSE, (char_u *)"LeftMouse"},
2369 {K_LEFTMOUSE_NM, (char_u *)"LeftMouseNM"},
2370 {K_LEFTDRAG, (char_u *)"LeftDrag"},
2371 {K_LEFTRELEASE, (char_u *)"LeftRelease"},
2372 {K_LEFTRELEASE_NM, (char_u *)"LeftReleaseNM"},
2373 {K_MIDDLEMOUSE, (char_u *)"MiddleMouse"},
2374 {K_MIDDLEDRAG, (char_u *)"MiddleDrag"},
2375 {K_MIDDLERELEASE, (char_u *)"MiddleRelease"},
2376 {K_RIGHTMOUSE, (char_u *)"RightMouse"},
2377 {K_RIGHTDRAG, (char_u *)"RightDrag"},
2378 {K_RIGHTRELEASE, (char_u *)"RightRelease"},
Bram Moolenaar8d9b40e2010-07-25 15:49:07 +02002379 {K_MOUSEDOWN, (char_u *)"ScrollWheelUp"},
2380 {K_MOUSEUP, (char_u *)"ScrollWheelDown"},
2381 {K_MOUSELEFT, (char_u *)"ScrollWheelRight"},
2382 {K_MOUSERIGHT, (char_u *)"ScrollWheelLeft"},
2383 {K_MOUSEDOWN, (char_u *)"MouseDown"}, /* OBSOLETE: Use */
2384 {K_MOUSEUP, (char_u *)"MouseUp"}, /* ScrollWheelXXX instead */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002385 {K_X1MOUSE, (char_u *)"X1Mouse"},
2386 {K_X1DRAG, (char_u *)"X1Drag"},
2387 {K_X1RELEASE, (char_u *)"X1Release"},
2388 {K_X2MOUSE, (char_u *)"X2Mouse"},
2389 {K_X2DRAG, (char_u *)"X2Drag"},
2390 {K_X2RELEASE, (char_u *)"X2Release"},
2391 {K_DROP, (char_u *)"Drop"},
2392 {K_ZERO, (char_u *)"Nul"},
2393#ifdef FEAT_EVAL
2394 {K_SNR, (char_u *)"SNR"},
2395#endif
2396 {K_PLUG, (char_u *)"Plug"},
2397 {0, NULL}
2398};
2399
2400#define KEY_NAMES_TABLE_LEN (sizeof(key_names_table) / sizeof(struct key_name_entry))
2401
2402#ifdef FEAT_MOUSE
2403static struct mousetable
2404{
2405 int pseudo_code; /* Code for pseudo mouse event */
2406 int button; /* Which mouse button is it? */
2407 int is_click; /* Is it a mouse button click event? */
2408 int is_drag; /* Is it a mouse drag event? */
2409} mouse_table[] =
2410{
2411 {(int)KE_LEFTMOUSE, MOUSE_LEFT, TRUE, FALSE},
2412#ifdef FEAT_GUI
2413 {(int)KE_LEFTMOUSE_NM, MOUSE_LEFT, TRUE, FALSE},
2414#endif
2415 {(int)KE_LEFTDRAG, MOUSE_LEFT, FALSE, TRUE},
2416 {(int)KE_LEFTRELEASE, MOUSE_LEFT, FALSE, FALSE},
2417#ifdef FEAT_GUI
2418 {(int)KE_LEFTRELEASE_NM, MOUSE_LEFT, FALSE, FALSE},
2419#endif
2420 {(int)KE_MIDDLEMOUSE, MOUSE_MIDDLE, TRUE, FALSE},
2421 {(int)KE_MIDDLEDRAG, MOUSE_MIDDLE, FALSE, TRUE},
2422 {(int)KE_MIDDLERELEASE, MOUSE_MIDDLE, FALSE, FALSE},
2423 {(int)KE_RIGHTMOUSE, MOUSE_RIGHT, TRUE, FALSE},
2424 {(int)KE_RIGHTDRAG, MOUSE_RIGHT, FALSE, TRUE},
2425 {(int)KE_RIGHTRELEASE, MOUSE_RIGHT, FALSE, FALSE},
2426 {(int)KE_X1MOUSE, MOUSE_X1, TRUE, FALSE},
2427 {(int)KE_X1DRAG, MOUSE_X1, FALSE, TRUE},
2428 {(int)KE_X1RELEASE, MOUSE_X1, FALSE, FALSE},
2429 {(int)KE_X2MOUSE, MOUSE_X2, TRUE, FALSE},
2430 {(int)KE_X2DRAG, MOUSE_X2, FALSE, TRUE},
2431 {(int)KE_X2RELEASE, MOUSE_X2, FALSE, FALSE},
2432 /* DRAG without CLICK */
2433 {(int)KE_IGNORE, MOUSE_RELEASE, FALSE, TRUE},
2434 /* RELEASE without CLICK */
2435 {(int)KE_IGNORE, MOUSE_RELEASE, FALSE, FALSE},
2436 {0, 0, 0, 0},
2437};
2438#endif /* FEAT_MOUSE */
2439
2440/*
2441 * Return the modifier mask bit (MOD_MASK_*) which corresponds to the given
2442 * modifier name ('S' for Shift, 'C' for Ctrl etc).
2443 */
2444 int
2445name_to_mod_mask(c)
2446 int c;
2447{
2448 int i;
2449
2450 c = TOUPPER_ASC(c);
2451 for (i = 0; mod_mask_table[i].mod_mask != 0; i++)
2452 if (c == mod_mask_table[i].name)
2453 return mod_mask_table[i].mod_flag;
2454 return 0;
2455}
2456
Bram Moolenaar071d4272004-06-13 20:20:40 +00002457/*
2458 * Check if if there is a special key code for "key" that includes the
2459 * modifiers specified.
2460 */
2461 int
2462simplify_key(key, modifiers)
2463 int key;
2464 int *modifiers;
2465{
2466 int i;
2467 int key0;
2468 int key1;
2469
2470 if (*modifiers & (MOD_MASK_SHIFT | MOD_MASK_CTRL | MOD_MASK_ALT))
2471 {
2472 /* TAB is a special case */
2473 if (key == TAB && (*modifiers & MOD_MASK_SHIFT))
2474 {
2475 *modifiers &= ~MOD_MASK_SHIFT;
2476 return K_S_TAB;
2477 }
2478 key0 = KEY2TERMCAP0(key);
2479 key1 = KEY2TERMCAP1(key);
2480 for (i = 0; modifier_keys_table[i] != NUL; i += MOD_KEYS_ENTRY_SIZE)
2481 if (key0 == modifier_keys_table[i + 3]
2482 && key1 == modifier_keys_table[i + 4]
2483 && (*modifiers & modifier_keys_table[i]))
2484 {
2485 *modifiers &= ~modifier_keys_table[i];
2486 return TERMCAP2KEY(modifier_keys_table[i + 1],
2487 modifier_keys_table[i + 2]);
2488 }
2489 }
2490 return key;
2491}
2492
2493/*
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002494 * Change <xHome> to <Home>, <xUp> to <Up>, etc.
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002495 */
2496 int
2497handle_x_keys(key)
2498 int key;
2499{
2500 switch (key)
2501 {
2502 case K_XUP: return K_UP;
2503 case K_XDOWN: return K_DOWN;
2504 case K_XLEFT: return K_LEFT;
2505 case K_XRIGHT: return K_RIGHT;
2506 case K_XHOME: return K_HOME;
Bram Moolenaar68b76a62005-03-25 21:53:48 +00002507 case K_ZHOME: return K_HOME;
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002508 case K_XEND: return K_END;
Bram Moolenaar68b76a62005-03-25 21:53:48 +00002509 case K_ZEND: return K_END;
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002510 case K_XF1: return K_F1;
2511 case K_XF2: return K_F2;
2512 case K_XF3: return K_F3;
2513 case K_XF4: return K_F4;
2514 case K_S_XF1: return K_S_F1;
2515 case K_S_XF2: return K_S_F2;
2516 case K_S_XF3: return K_S_F3;
2517 case K_S_XF4: return K_S_F4;
2518 }
2519 return key;
2520}
2521
2522/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00002523 * Return a string which contains the name of the given key when the given
2524 * modifiers are down.
2525 */
2526 char_u *
2527get_special_key_name(c, modifiers)
2528 int c;
2529 int modifiers;
2530{
2531 static char_u string[MAX_KEY_NAME_LEN + 1];
2532
2533 int i, idx;
2534 int table_idx;
2535 char_u *s;
2536
2537 string[0] = '<';
2538 idx = 1;
2539
2540 /* Key that stands for a normal character. */
2541 if (IS_SPECIAL(c) && KEY2TERMCAP0(c) == KS_KEY)
2542 c = KEY2TERMCAP1(c);
2543
2544 /*
2545 * Translate shifted special keys into unshifted keys and set modifier.
2546 * Same for CTRL and ALT modifiers.
2547 */
2548 if (IS_SPECIAL(c))
2549 {
2550 for (i = 0; modifier_keys_table[i] != 0; i += MOD_KEYS_ENTRY_SIZE)
2551 if ( KEY2TERMCAP0(c) == (int)modifier_keys_table[i + 1]
2552 && (int)KEY2TERMCAP1(c) == (int)modifier_keys_table[i + 2])
2553 {
2554 modifiers |= modifier_keys_table[i];
2555 c = TERMCAP2KEY(modifier_keys_table[i + 3],
2556 modifier_keys_table[i + 4]);
2557 break;
2558 }
2559 }
2560
2561 /* try to find the key in the special key table */
2562 table_idx = find_special_key_in_table(c);
2563
2564 /*
2565 * When not a known special key, and not a printable character, try to
2566 * extract modifiers.
2567 */
2568 if (c > 0
2569#ifdef FEAT_MBYTE
2570 && (*mb_char2len)(c) == 1
2571#endif
2572 )
2573 {
2574 if (table_idx < 0
2575 && (!vim_isprintc(c) || (c & 0x7f) == ' ')
2576 && (c & 0x80))
2577 {
2578 c &= 0x7f;
2579 modifiers |= MOD_MASK_ALT;
2580 /* try again, to find the un-alted key in the special key table */
2581 table_idx = find_special_key_in_table(c);
2582 }
2583 if (table_idx < 0 && !vim_isprintc(c) && c < ' ')
2584 {
2585#ifdef EBCDIC
2586 c = CtrlChar(c);
2587#else
2588 c += '@';
2589#endif
2590 modifiers |= MOD_MASK_CTRL;
2591 }
2592 }
2593
2594 /* translate the modifier into a string */
2595 for (i = 0; mod_mask_table[i].name != 'A'; i++)
2596 if ((modifiers & mod_mask_table[i].mod_mask)
2597 == mod_mask_table[i].mod_flag)
2598 {
2599 string[idx++] = mod_mask_table[i].name;
2600 string[idx++] = (char_u)'-';
2601 }
2602
2603 if (table_idx < 0) /* unknown special key, may output t_xx */
2604 {
2605 if (IS_SPECIAL(c))
2606 {
2607 string[idx++] = 't';
2608 string[idx++] = '_';
2609 string[idx++] = KEY2TERMCAP0(c);
2610 string[idx++] = KEY2TERMCAP1(c);
2611 }
2612 /* Not a special key, only modifiers, output directly */
2613 else
2614 {
2615#ifdef FEAT_MBYTE
2616 if (has_mbyte && (*mb_char2len)(c) > 1)
2617 idx += (*mb_char2bytes)(c, string + idx);
2618 else
2619#endif
2620 if (vim_isprintc(c))
2621 string[idx++] = c;
2622 else
2623 {
2624 s = transchar(c);
2625 while (*s)
2626 string[idx++] = *s++;
2627 }
2628 }
2629 }
2630 else /* use name of special key */
2631 {
2632 STRCPY(string + idx, key_names_table[table_idx].name);
2633 idx = (int)STRLEN(string);
2634 }
2635 string[idx++] = '>';
2636 string[idx] = NUL;
2637 return string;
2638}
2639
2640/*
2641 * Try translating a <> name at (*srcp)[] to dst[].
2642 * Return the number of characters added to dst[], zero for no match.
2643 * If there is a match, srcp is advanced to after the <> name.
2644 * dst[] must be big enough to hold the result (up to six characters)!
2645 */
2646 int
2647trans_special(srcp, dst, keycode)
2648 char_u **srcp;
2649 char_u *dst;
2650 int keycode; /* prefer key code, e.g. K_DEL instead of DEL */
2651{
2652 int modifiers = 0;
2653 int key;
2654 int dlen = 0;
2655
Bram Moolenaar2a8ced02008-12-24 11:54:31 +00002656 key = find_special_key(srcp, &modifiers, keycode, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002657 if (key == 0)
2658 return 0;
2659
2660 /* Put the appropriate modifier in a string */
2661 if (modifiers != 0)
2662 {
2663 dst[dlen++] = K_SPECIAL;
2664 dst[dlen++] = KS_MODIFIER;
2665 dst[dlen++] = modifiers;
2666 }
2667
2668 if (IS_SPECIAL(key))
2669 {
2670 dst[dlen++] = K_SPECIAL;
2671 dst[dlen++] = KEY2TERMCAP0(key);
2672 dst[dlen++] = KEY2TERMCAP1(key);
2673 }
2674#ifdef FEAT_MBYTE
2675 else if (has_mbyte && !keycode)
2676 dlen += (*mb_char2bytes)(key, dst + dlen);
2677#endif
2678 else if (keycode)
2679 dlen = (int)(add_char2buf(key, dst + dlen) - dst);
2680 else
2681 dst[dlen++] = key;
2682
2683 return dlen;
2684}
2685
2686/*
2687 * Try translating a <> name at (*srcp)[], return the key and modifiers.
2688 * srcp is advanced to after the <> name.
2689 * returns 0 if there is no match.
2690 */
2691 int
Bram Moolenaar2a8ced02008-12-24 11:54:31 +00002692find_special_key(srcp, modp, keycode, keep_x_key)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002693 char_u **srcp;
2694 int *modp;
Bram Moolenaar2a8ced02008-12-24 11:54:31 +00002695 int keycode; /* prefer key code, e.g. K_DEL instead of DEL */
2696 int keep_x_key; /* don't translate xHome to Home key */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002697{
2698 char_u *last_dash;
2699 char_u *end_of_name;
2700 char_u *src;
2701 char_u *bp;
2702 int modifiers;
2703 int bit;
2704 int key;
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002705 unsigned long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002706
2707 src = *srcp;
2708 if (src[0] != '<')
2709 return 0;
2710
2711 /* Find end of modifier list */
2712 last_dash = src;
2713 for (bp = src + 1; *bp == '-' || vim_isIDc(*bp); bp++)
2714 {
2715 if (*bp == '-')
2716 {
2717 last_dash = bp;
2718 if (bp[1] != NUL && bp[2] == '>')
2719 ++bp; /* anything accepted, like <C-?> */
2720 }
2721 if (bp[0] == 't' && bp[1] == '_' && bp[2] && bp[3])
2722 bp += 3; /* skip t_xx, xx may be '-' or '>' */
2723 }
2724
2725 if (*bp == '>') /* found matching '>' */
2726 {
2727 end_of_name = bp + 1;
2728
2729 if (STRNICMP(src + 1, "char-", 5) == 0 && VIM_ISDIGIT(src[6]))
2730 {
2731 /* <Char-123> or <Char-033> or <Char-0x33> */
2732 vim_str2nr(src + 6, NULL, NULL, TRUE, TRUE, NULL, &n);
2733 *modp = 0;
2734 *srcp = end_of_name;
2735 return (int)n;
2736 }
2737
2738 /* Which modifiers are given? */
2739 modifiers = 0x0;
2740 for (bp = src + 1; bp < last_dash; bp++)
2741 {
2742 if (*bp != '-')
2743 {
2744 bit = name_to_mod_mask(*bp);
2745 if (bit == 0x0)
2746 break; /* Illegal modifier name */
2747 modifiers |= bit;
2748 }
2749 }
2750
2751 /*
2752 * Legal modifier name.
2753 */
2754 if (bp >= last_dash)
2755 {
2756 /*
2757 * Modifier with single letter, or special key name.
2758 */
2759 if (modifiers != 0 && last_dash[2] == '>')
2760 key = last_dash[1];
2761 else
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002762 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002763 key = get_special_key_code(last_dash + 1);
Bram Moolenaar2a8ced02008-12-24 11:54:31 +00002764 if (!keep_x_key)
2765 key = handle_x_keys(key);
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002766 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002767
2768 /*
2769 * get_special_key_code() may return NUL for invalid
2770 * special key name.
2771 */
2772 if (key != NUL)
2773 {
2774 /*
2775 * Only use a modifier when there is no special key code that
2776 * includes the modifier.
2777 */
2778 key = simplify_key(key, &modifiers);
2779
2780 if (!keycode)
2781 {
2782 /* don't want keycode, use single byte code */
2783 if (key == K_BS)
2784 key = BS;
2785 else if (key == K_DEL || key == K_KDEL)
2786 key = DEL;
2787 }
2788
2789 /*
2790 * Normal Key with modifier: Try to make a single byte code.
2791 */
2792 if (!IS_SPECIAL(key))
2793 key = extract_modifiers(key, &modifiers);
2794
2795 *modp = modifiers;
2796 *srcp = end_of_name;
2797 return key;
2798 }
2799 }
2800 }
2801 return 0;
2802}
2803
2804/*
2805 * Try to include modifiers in the key.
2806 * Changes "Shift-a" to 'A', "Alt-A" to 0xc0, etc.
2807 */
2808 int
2809extract_modifiers(key, modp)
2810 int key;
2811 int *modp;
2812{
2813 int modifiers = *modp;
2814
2815#ifdef MACOS
2816 /* Command-key really special, No fancynest */
2817 if (!(modifiers & MOD_MASK_CMD))
2818#endif
2819 if ((modifiers & MOD_MASK_SHIFT) && ASCII_ISALPHA(key))
2820 {
2821 key = TOUPPER_ASC(key);
2822 modifiers &= ~MOD_MASK_SHIFT;
2823 }
2824 if ((modifiers & MOD_MASK_CTRL)
2825#ifdef EBCDIC
2826 /* * TODO: EBCDIC Better use:
2827 * && (Ctrl_chr(key) || key == '?')
2828 * ??? */
2829 && strchr("?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_", key)
2830 != NULL
2831#else
2832 && ((key >= '?' && key <= '_') || ASCII_ISALPHA(key))
2833#endif
2834 )
2835 {
2836 key = Ctrl_chr(key);
2837 modifiers &= ~MOD_MASK_CTRL;
2838 /* <C-@> is <Nul> */
2839 if (key == 0)
2840 key = K_ZERO;
2841 }
2842#ifdef MACOS
2843 /* Command-key really special, No fancynest */
2844 if (!(modifiers & MOD_MASK_CMD))
2845#endif
2846 if ((modifiers & MOD_MASK_ALT) && key < 0x80
2847#ifdef FEAT_MBYTE
2848 && !enc_dbcs /* avoid creating a lead byte */
2849#endif
2850 )
2851 {
2852 key |= 0x80;
2853 modifiers &= ~MOD_MASK_ALT; /* remove the META modifier */
2854 }
2855
2856 *modp = modifiers;
2857 return key;
2858}
2859
2860/*
2861 * Try to find key "c" in the special key table.
2862 * Return the index when found, -1 when not found.
2863 */
2864 int
2865find_special_key_in_table(c)
2866 int c;
2867{
2868 int i;
2869
2870 for (i = 0; key_names_table[i].name != NULL; i++)
2871 if (c == key_names_table[i].key)
2872 break;
2873 if (key_names_table[i].name == NULL)
2874 i = -1;
2875 return i;
2876}
2877
2878/*
2879 * Find the special key with the given name (the given string does not have to
2880 * end with NUL, the name is assumed to end before the first non-idchar).
2881 * If the name starts with "t_" the next two characters are interpreted as a
2882 * termcap name.
2883 * Return the key code, or 0 if not found.
2884 */
2885 int
2886get_special_key_code(name)
2887 char_u *name;
2888{
2889 char_u *table_name;
2890 char_u string[3];
2891 int i, j;
2892
2893 /*
2894 * If it's <t_xx> we get the code for xx from the termcap
2895 */
2896 if (name[0] == 't' && name[1] == '_' && name[2] != NUL && name[3] != NUL)
2897 {
2898 string[0] = name[2];
2899 string[1] = name[3];
2900 string[2] = NUL;
2901 if (add_termcap_entry(string, FALSE) == OK)
2902 return TERMCAP2KEY(name[2], name[3]);
2903 }
2904 else
2905 for (i = 0; key_names_table[i].name != NULL; i++)
2906 {
2907 table_name = key_names_table[i].name;
2908 for (j = 0; vim_isIDc(name[j]) && table_name[j] != NUL; j++)
2909 if (TOLOWER_ASC(table_name[j]) != TOLOWER_ASC(name[j]))
2910 break;
2911 if (!vim_isIDc(name[j]) && table_name[j] == NUL)
2912 return key_names_table[i].key;
2913 }
2914 return 0;
2915}
2916
Bram Moolenaar05bb9532008-07-04 09:44:11 +00002917#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002918 char_u *
2919get_key_name(i)
2920 int i;
2921{
Bram Moolenaare1fbddc2009-05-16 19:07:03 +00002922 if (i >= (int)KEY_NAMES_TABLE_LEN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002923 return NULL;
2924 return key_names_table[i].name;
2925}
2926#endif
2927
Bram Moolenaar05bb9532008-07-04 09:44:11 +00002928#if defined(FEAT_MOUSE) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002929/*
2930 * Look up the given mouse code to return the relevant information in the other
2931 * arguments. Return which button is down or was released.
2932 */
2933 int
2934get_mouse_button(code, is_click, is_drag)
2935 int code;
2936 int *is_click;
2937 int *is_drag;
2938{
2939 int i;
2940
2941 for (i = 0; mouse_table[i].pseudo_code; i++)
2942 if (code == mouse_table[i].pseudo_code)
2943 {
2944 *is_click = mouse_table[i].is_click;
2945 *is_drag = mouse_table[i].is_drag;
2946 return mouse_table[i].button;
2947 }
2948 return 0; /* Shouldn't get here */
2949}
2950
2951/*
2952 * Return the appropriate pseudo mouse event token (KE_LEFTMOUSE etc) based on
2953 * the given information about which mouse button is down, and whether the
2954 * mouse was clicked, dragged or released.
2955 */
2956 int
2957get_pseudo_mouse_code(button, is_click, is_drag)
2958 int button; /* eg MOUSE_LEFT */
2959 int is_click;
2960 int is_drag;
2961{
2962 int i;
2963
2964 for (i = 0; mouse_table[i].pseudo_code; i++)
2965 if (button == mouse_table[i].button
2966 && is_click == mouse_table[i].is_click
2967 && is_drag == mouse_table[i].is_drag)
2968 {
2969#ifdef FEAT_GUI
Bram Moolenaarc91506a2005-04-24 22:04:21 +00002970 /* Trick: a non mappable left click and release has mouse_col -1
2971 * or added MOUSE_COLOFF. Used for 'mousefocus' in
2972 * gui_mouse_moved() */
2973 if (mouse_col < 0 || mouse_col > MOUSE_COLOFF)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002974 {
Bram Moolenaarc91506a2005-04-24 22:04:21 +00002975 if (mouse_col < 0)
2976 mouse_col = 0;
2977 else
2978 mouse_col -= MOUSE_COLOFF;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002979 if (mouse_table[i].pseudo_code == (int)KE_LEFTMOUSE)
2980 return (int)KE_LEFTMOUSE_NM;
2981 if (mouse_table[i].pseudo_code == (int)KE_LEFTRELEASE)
2982 return (int)KE_LEFTRELEASE_NM;
2983 }
2984#endif
2985 return mouse_table[i].pseudo_code;
2986 }
Bram Moolenaar7aa9f6a2007-05-10 18:00:30 +00002987 return (int)KE_IGNORE; /* not recognized, ignore it */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002988}
2989#endif /* FEAT_MOUSE */
2990
2991/*
2992 * Return the current end-of-line type: EOL_DOS, EOL_UNIX or EOL_MAC.
2993 */
2994 int
2995get_fileformat(buf)
2996 buf_T *buf;
2997{
2998 int c = *buf->b_p_ff;
2999
3000 if (buf->b_p_bin || c == 'u')
3001 return EOL_UNIX;
3002 if (c == 'm')
3003 return EOL_MAC;
3004 return EOL_DOS;
3005}
3006
3007/*
3008 * Like get_fileformat(), but override 'fileformat' with "p" for "++opt=val"
3009 * argument.
3010 */
3011 int
3012get_fileformat_force(buf, eap)
3013 buf_T *buf;
3014 exarg_T *eap; /* can be NULL! */
3015{
3016 int c;
3017
3018 if (eap != NULL && eap->force_ff != 0)
3019 c = eap->cmd[eap->force_ff];
3020 else
3021 {
3022 if ((eap != NULL && eap->force_bin != 0)
3023 ? (eap->force_bin == FORCE_BIN) : buf->b_p_bin)
3024 return EOL_UNIX;
3025 c = *buf->b_p_ff;
3026 }
3027 if (c == 'u')
3028 return EOL_UNIX;
3029 if (c == 'm')
3030 return EOL_MAC;
3031 return EOL_DOS;
3032}
3033
3034/*
3035 * Set the current end-of-line type to EOL_DOS, EOL_UNIX or EOL_MAC.
3036 * Sets both 'textmode' and 'fileformat'.
3037 * Note: Does _not_ set global value of 'textmode'!
3038 */
3039 void
3040set_fileformat(t, opt_flags)
3041 int t;
3042 int opt_flags; /* OPT_LOCAL and/or OPT_GLOBAL */
3043{
3044 char *p = NULL;
3045
3046 switch (t)
3047 {
3048 case EOL_DOS:
3049 p = FF_DOS;
3050 curbuf->b_p_tx = TRUE;
3051 break;
3052 case EOL_UNIX:
3053 p = FF_UNIX;
3054 curbuf->b_p_tx = FALSE;
3055 break;
3056 case EOL_MAC:
3057 p = FF_MAC;
3058 curbuf->b_p_tx = FALSE;
3059 break;
3060 }
3061 if (p != NULL)
3062 set_string_option_direct((char_u *)"ff", -1, (char_u *)p,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00003063 OPT_FREE | opt_flags, 0);
3064
Bram Moolenaar071d4272004-06-13 20:20:40 +00003065#ifdef FEAT_WINDOWS
Bram Moolenaarf740b292006-02-16 22:11:02 +00003066 /* This may cause the buffer to become (un)modified. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003067 check_status(curbuf);
Bram Moolenaar997fb4b2006-02-17 21:53:23 +00003068 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003069#endif
3070#ifdef FEAT_TITLE
3071 need_maketitle = TRUE; /* set window title later */
3072#endif
3073}
3074
3075/*
3076 * Return the default fileformat from 'fileformats'.
3077 */
3078 int
3079default_fileformat()
3080{
3081 switch (*p_ffs)
3082 {
3083 case 'm': return EOL_MAC;
3084 case 'd': return EOL_DOS;
3085 }
3086 return EOL_UNIX;
3087}
3088
3089/*
3090 * Call shell. Calls mch_call_shell, with 'shellxquote' added.
3091 */
3092 int
3093call_shell(cmd, opt)
3094 char_u *cmd;
3095 int opt;
3096{
3097 char_u *ncmd;
3098 int retval;
Bram Moolenaar05159a02005-02-26 23:04:13 +00003099#ifdef FEAT_PROFILE
3100 proftime_T wait_time;
3101#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003102
3103 if (p_verbose > 3)
3104 {
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00003105 verbose_enter();
Bram Moolenaar051b7822005-05-19 21:00:46 +00003106 smsg((char_u *)_("Calling shell to execute: \"%s\""),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003107 cmd == NULL ? p_sh : cmd);
3108 out_char('\n');
3109 cursor_on();
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00003110 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003111 }
3112
Bram Moolenaar05159a02005-02-26 23:04:13 +00003113#ifdef FEAT_PROFILE
Bram Moolenaar01265852006-03-20 21:50:15 +00003114 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00003115 prof_child_enter(&wait_time);
3116#endif
3117
Bram Moolenaar071d4272004-06-13 20:20:40 +00003118 if (*p_sh == NUL)
3119 {
3120 EMSG(_(e_shellempty));
3121 retval = -1;
3122 }
3123 else
3124 {
3125#ifdef FEAT_GUI_MSWIN
3126 /* Don't hide the pointer while executing a shell command. */
3127 gui_mch_mousehide(FALSE);
3128#endif
3129#ifdef FEAT_GUI
3130 ++hold_gui_events;
3131#endif
3132 /* The external command may update a tags file, clear cached tags. */
3133 tag_freematch();
3134
3135 if (cmd == NULL || *p_sxq == NUL)
3136 retval = mch_call_shell(cmd, opt);
3137 else
3138 {
3139 ncmd = alloc((unsigned)(STRLEN(cmd) + STRLEN(p_sxq) * 2 + 1));
3140 if (ncmd != NULL)
3141 {
3142 STRCPY(ncmd, p_sxq);
3143 STRCAT(ncmd, cmd);
3144 STRCAT(ncmd, p_sxq);
3145 retval = mch_call_shell(ncmd, opt);
3146 vim_free(ncmd);
3147 }
3148 else
3149 retval = -1;
3150 }
3151#ifdef FEAT_GUI
3152 --hold_gui_events;
3153#endif
3154 /*
3155 * Check the window size, in case it changed while executing the
3156 * external command.
3157 */
3158 shell_resized_check();
3159 }
3160
3161#ifdef FEAT_EVAL
3162 set_vim_var_nr(VV_SHELL_ERROR, (long)retval);
Bram Moolenaar05159a02005-02-26 23:04:13 +00003163# ifdef FEAT_PROFILE
Bram Moolenaar01265852006-03-20 21:50:15 +00003164 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00003165 prof_child_exit(&wait_time);
3166# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003167#endif
3168
3169 return retval;
3170}
3171
3172/*
Bram Moolenaar01265852006-03-20 21:50:15 +00003173 * VISUAL, SELECTMODE and OP_PENDING State are never set, they are equal to
3174 * NORMAL State with a condition. This function returns the real State.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003175 */
3176 int
3177get_real_state()
3178{
3179 if (State & NORMAL)
3180 {
3181#ifdef FEAT_VISUAL
3182 if (VIsual_active)
Bram Moolenaar01265852006-03-20 21:50:15 +00003183 {
3184 if (VIsual_select)
3185 return SELECTMODE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003186 return VISUAL;
Bram Moolenaar01265852006-03-20 21:50:15 +00003187 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003188 else
3189#endif
3190 if (finish_op)
Bram Moolenaar01265852006-03-20 21:50:15 +00003191 return OP_PENDING;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003192 }
3193 return State;
3194}
3195
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003196#if defined(FEAT_MBYTE) || defined(PROTO)
3197/*
3198 * Return TRUE if "p" points to just after a path separator.
3199 * Take care of multi-byte characters.
3200 * "b" must point to the start of the file name
3201 */
3202 int
3203after_pathsep(b, p)
3204 char_u *b;
3205 char_u *p;
3206{
3207 return vim_ispathsep(p[-1])
3208 && (!has_mbyte || (*mb_head_off)(b, p - 1) == 0);
3209}
3210#endif
3211
3212/*
3213 * Return TRUE if file names "f1" and "f2" are in the same directory.
3214 * "f1" may be a short name, "f2" must be a full path.
3215 */
3216 int
3217same_directory(f1, f2)
3218 char_u *f1;
3219 char_u *f2;
3220{
3221 char_u ffname[MAXPATHL];
3222 char_u *t1;
3223 char_u *t2;
3224
3225 /* safety check */
3226 if (f1 == NULL || f2 == NULL)
3227 return FALSE;
3228
3229 (void)vim_FullName(f1, ffname, MAXPATHL, FALSE);
3230 t1 = gettail_sep(ffname);
3231 t2 = gettail_sep(f2);
3232 return (t1 - ffname == t2 - f2
3233 && pathcmp((char *)ffname, (char *)f2, (int)(t1 - ffname)) == 0);
3234}
3235
Bram Moolenaar071d4272004-06-13 20:20:40 +00003236#if defined(FEAT_SESSION) || defined(MSWIN) || defined(FEAT_GUI_MAC) \
Bram Moolenaar9372a112005-12-06 19:59:18 +00003237 || ((defined(FEAT_GUI_GTK)) \
Bram Moolenaar843ee412004-06-30 16:16:41 +00003238 && ( defined(FEAT_WINDOWS) || defined(FEAT_DND)) ) \
Bram Moolenaar071d4272004-06-13 20:20:40 +00003239 || defined(FEAT_SUN_WORKSHOP) || defined(FEAT_NETBEANS_INTG) \
3240 || defined(PROTO)
3241/*
3242 * Change to a file's directory.
3243 * Caller must call shorten_fnames()!
3244 * Return OK or FAIL.
3245 */
3246 int
3247vim_chdirfile(fname)
3248 char_u *fname;
3249{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003250 char_u dir[MAXPATHL];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003251
Bram Moolenaarbbebc852005-07-18 21:47:53 +00003252 vim_strncpy(dir, fname, MAXPATHL - 1);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003253 *gettail_sep(dir) = NUL;
3254 return mch_chdir((char *)dir) == 0 ? OK : FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003255}
3256#endif
3257
3258#if defined(STAT_IGNORES_SLASH) || defined(PROTO)
3259/*
3260 * Check if "name" ends in a slash and is not a directory.
3261 * Used for systems where stat() ignores a trailing slash on a file name.
3262 * The Vim code assumes a trailing slash is only ignored for a directory.
3263 */
3264 int
3265illegal_slash(name)
3266 char *name;
3267{
3268 if (name[0] == NUL)
3269 return FALSE; /* no file name is not illegal */
3270 if (name[strlen(name) - 1] != '/')
3271 return FALSE; /* no trailing slash */
3272 if (mch_isdir((char_u *)name))
3273 return FALSE; /* trailing slash for a directory */
3274 return TRUE;
3275}
3276#endif
3277
3278#if defined(CURSOR_SHAPE) || defined(PROTO)
3279
3280/*
3281 * Handling of cursor and mouse pointer shapes in various modes.
3282 */
3283
3284cursorentry_T shape_table[SHAPE_IDX_COUNT] =
3285{
3286 /* The values will be filled in from the 'guicursor' and 'mouseshape'
3287 * defaults when Vim starts.
3288 * Adjust the SHAPE_IDX_ defines when making changes! */
3289 {0, 0, 0, 700L, 400L, 250L, 0, 0, "n", SHAPE_CURSOR+SHAPE_MOUSE},
3290 {0, 0, 0, 700L, 400L, 250L, 0, 0, "v", SHAPE_CURSOR+SHAPE_MOUSE},
3291 {0, 0, 0, 700L, 400L, 250L, 0, 0, "i", SHAPE_CURSOR+SHAPE_MOUSE},
3292 {0, 0, 0, 700L, 400L, 250L, 0, 0, "r", SHAPE_CURSOR+SHAPE_MOUSE},
3293 {0, 0, 0, 700L, 400L, 250L, 0, 0, "c", SHAPE_CURSOR+SHAPE_MOUSE},
3294 {0, 0, 0, 700L, 400L, 250L, 0, 0, "ci", SHAPE_CURSOR+SHAPE_MOUSE},
3295 {0, 0, 0, 700L, 400L, 250L, 0, 0, "cr", SHAPE_CURSOR+SHAPE_MOUSE},
3296 {0, 0, 0, 700L, 400L, 250L, 0, 0, "o", SHAPE_CURSOR+SHAPE_MOUSE},
3297 {0, 0, 0, 700L, 400L, 250L, 0, 0, "ve", SHAPE_CURSOR+SHAPE_MOUSE},
3298 {0, 0, 0, 0L, 0L, 0L, 0, 0, "e", SHAPE_MOUSE},
3299 {0, 0, 0, 0L, 0L, 0L, 0, 0, "s", SHAPE_MOUSE},
3300 {0, 0, 0, 0L, 0L, 0L, 0, 0, "sd", SHAPE_MOUSE},
3301 {0, 0, 0, 0L, 0L, 0L, 0, 0, "vs", SHAPE_MOUSE},
3302 {0, 0, 0, 0L, 0L, 0L, 0, 0, "vd", SHAPE_MOUSE},
3303 {0, 0, 0, 0L, 0L, 0L, 0, 0, "m", SHAPE_MOUSE},
3304 {0, 0, 0, 0L, 0L, 0L, 0, 0, "ml", SHAPE_MOUSE},
3305 {0, 0, 0, 100L, 100L, 100L, 0, 0, "sm", SHAPE_CURSOR},
3306};
3307
3308#ifdef FEAT_MOUSESHAPE
3309/*
3310 * Table with names for mouse shapes. Keep in sync with all the tables for
3311 * mch_set_mouse_shape()!.
3312 */
3313static char * mshape_names[] =
3314{
3315 "arrow", /* default, must be the first one */
3316 "blank", /* hidden */
3317 "beam",
3318 "updown",
3319 "udsizing",
3320 "leftright",
3321 "lrsizing",
3322 "busy",
3323 "no",
3324 "crosshair",
3325 "hand1",
3326 "hand2",
3327 "pencil",
3328 "question",
3329 "rightup-arrow",
3330 "up-arrow",
3331 NULL
3332};
3333#endif
3334
3335/*
3336 * Parse the 'guicursor' option ("what" is SHAPE_CURSOR) or 'mouseshape'
3337 * ("what" is SHAPE_MOUSE).
3338 * Returns error message for an illegal option, NULL otherwise.
3339 */
3340 char_u *
3341parse_shape_opt(what)
3342 int what;
3343{
3344 char_u *modep;
3345 char_u *colonp;
3346 char_u *commap;
3347 char_u *slashp;
3348 char_u *p, *endp;
3349 int idx = 0; /* init for GCC */
3350 int all_idx;
3351 int len;
3352 int i;
3353 long n;
3354 int found_ve = FALSE; /* found "ve" flag */
3355 int round;
3356
3357 /*
3358 * First round: check for errors; second round: do it for real.
3359 */
3360 for (round = 1; round <= 2; ++round)
3361 {
3362 /*
3363 * Repeat for all comma separated parts.
3364 */
3365#ifdef FEAT_MOUSESHAPE
3366 if (what == SHAPE_MOUSE)
3367 modep = p_mouseshape;
3368 else
3369#endif
3370 modep = p_guicursor;
3371 while (*modep != NUL)
3372 {
3373 colonp = vim_strchr(modep, ':');
3374 if (colonp == NULL)
3375 return (char_u *)N_("E545: Missing colon");
3376 if (colonp == modep)
3377 return (char_u *)N_("E546: Illegal mode");
3378 commap = vim_strchr(modep, ',');
3379
3380 /*
3381 * Repeat for all mode's before the colon.
3382 * For the 'a' mode, we loop to handle all the modes.
3383 */
3384 all_idx = -1;
3385 while (modep < colonp || all_idx >= 0)
3386 {
3387 if (all_idx < 0)
3388 {
3389 /* Find the mode. */
3390 if (modep[1] == '-' || modep[1] == ':')
3391 len = 1;
3392 else
3393 len = 2;
3394 if (len == 1 && TOLOWER_ASC(modep[0]) == 'a')
3395 all_idx = SHAPE_IDX_COUNT - 1;
3396 else
3397 {
3398 for (idx = 0; idx < SHAPE_IDX_COUNT; ++idx)
3399 if (STRNICMP(modep, shape_table[idx].name, len)
3400 == 0)
3401 break;
3402 if (idx == SHAPE_IDX_COUNT
3403 || (shape_table[idx].used_for & what) == 0)
3404 return (char_u *)N_("E546: Illegal mode");
3405 if (len == 2 && modep[0] == 'v' && modep[1] == 'e')
3406 found_ve = TRUE;
3407 }
3408 modep += len + 1;
3409 }
3410
3411 if (all_idx >= 0)
3412 idx = all_idx--;
3413 else if (round == 2)
3414 {
3415#ifdef FEAT_MOUSESHAPE
3416 if (what == SHAPE_MOUSE)
3417 {
3418 /* Set the default, for the missing parts */
3419 shape_table[idx].mshape = 0;
3420 }
3421 else
3422#endif
3423 {
3424 /* Set the defaults, for the missing parts */
3425 shape_table[idx].shape = SHAPE_BLOCK;
3426 shape_table[idx].blinkwait = 700L;
3427 shape_table[idx].blinkon = 400L;
3428 shape_table[idx].blinkoff = 250L;
3429 }
3430 }
3431
3432 /* Parse the part after the colon */
3433 for (p = colonp + 1; *p && *p != ','; )
3434 {
3435#ifdef FEAT_MOUSESHAPE
3436 if (what == SHAPE_MOUSE)
3437 {
3438 for (i = 0; ; ++i)
3439 {
3440 if (mshape_names[i] == NULL)
3441 {
3442 if (!VIM_ISDIGIT(*p))
3443 return (char_u *)N_("E547: Illegal mouseshape");
3444 if (round == 2)
3445 shape_table[idx].mshape =
3446 getdigits(&p) + MSHAPE_NUMBERED;
3447 else
3448 (void)getdigits(&p);
3449 break;
3450 }
3451 len = (int)STRLEN(mshape_names[i]);
3452 if (STRNICMP(p, mshape_names[i], len) == 0)
3453 {
3454 if (round == 2)
3455 shape_table[idx].mshape = i;
3456 p += len;
3457 break;
3458 }
3459 }
3460 }
3461 else /* if (what == SHAPE_MOUSE) */
3462#endif
3463 {
3464 /*
3465 * First handle the ones with a number argument.
3466 */
3467 i = *p;
3468 len = 0;
3469 if (STRNICMP(p, "ver", 3) == 0)
3470 len = 3;
3471 else if (STRNICMP(p, "hor", 3) == 0)
3472 len = 3;
3473 else if (STRNICMP(p, "blinkwait", 9) == 0)
3474 len = 9;
3475 else if (STRNICMP(p, "blinkon", 7) == 0)
3476 len = 7;
3477 else if (STRNICMP(p, "blinkoff", 8) == 0)
3478 len = 8;
3479 if (len != 0)
3480 {
3481 p += len;
3482 if (!VIM_ISDIGIT(*p))
3483 return (char_u *)N_("E548: digit expected");
3484 n = getdigits(&p);
3485 if (len == 3) /* "ver" or "hor" */
3486 {
3487 if (n == 0)
3488 return (char_u *)N_("E549: Illegal percentage");
3489 if (round == 2)
3490 {
3491 if (TOLOWER_ASC(i) == 'v')
3492 shape_table[idx].shape = SHAPE_VER;
3493 else
3494 shape_table[idx].shape = SHAPE_HOR;
3495 shape_table[idx].percentage = n;
3496 }
3497 }
3498 else if (round == 2)
3499 {
3500 if (len == 9)
3501 shape_table[idx].blinkwait = n;
3502 else if (len == 7)
3503 shape_table[idx].blinkon = n;
3504 else
3505 shape_table[idx].blinkoff = n;
3506 }
3507 }
3508 else if (STRNICMP(p, "block", 5) == 0)
3509 {
3510 if (round == 2)
3511 shape_table[idx].shape = SHAPE_BLOCK;
3512 p += 5;
3513 }
3514 else /* must be a highlight group name then */
3515 {
3516 endp = vim_strchr(p, '-');
3517 if (commap == NULL) /* last part */
3518 {
3519 if (endp == NULL)
3520 endp = p + STRLEN(p); /* find end of part */
3521 }
3522 else if (endp > commap || endp == NULL)
3523 endp = commap;
3524 slashp = vim_strchr(p, '/');
3525 if (slashp != NULL && slashp < endp)
3526 {
3527 /* "group/langmap_group" */
3528 i = syn_check_group(p, (int)(slashp - p));
3529 p = slashp + 1;
3530 }
3531 if (round == 2)
3532 {
3533 shape_table[idx].id = syn_check_group(p,
3534 (int)(endp - p));
3535 shape_table[idx].id_lm = shape_table[idx].id;
3536 if (slashp != NULL && slashp < endp)
3537 shape_table[idx].id = i;
3538 }
3539 p = endp;
3540 }
3541 } /* if (what != SHAPE_MOUSE) */
3542
3543 if (*p == '-')
3544 ++p;
3545 }
3546 }
3547 modep = p;
3548 if (*modep == ',')
3549 ++modep;
3550 }
3551 }
3552
3553 /* If the 's' flag is not given, use the 'v' cursor for 's' */
3554 if (!found_ve)
3555 {
3556#ifdef FEAT_MOUSESHAPE
3557 if (what == SHAPE_MOUSE)
3558 {
3559 shape_table[SHAPE_IDX_VE].mshape = shape_table[SHAPE_IDX_V].mshape;
3560 }
3561 else
3562#endif
3563 {
3564 shape_table[SHAPE_IDX_VE].shape = shape_table[SHAPE_IDX_V].shape;
3565 shape_table[SHAPE_IDX_VE].percentage =
3566 shape_table[SHAPE_IDX_V].percentage;
3567 shape_table[SHAPE_IDX_VE].blinkwait =
3568 shape_table[SHAPE_IDX_V].blinkwait;
3569 shape_table[SHAPE_IDX_VE].blinkon =
3570 shape_table[SHAPE_IDX_V].blinkon;
3571 shape_table[SHAPE_IDX_VE].blinkoff =
3572 shape_table[SHAPE_IDX_V].blinkoff;
3573 shape_table[SHAPE_IDX_VE].id = shape_table[SHAPE_IDX_V].id;
3574 shape_table[SHAPE_IDX_VE].id_lm = shape_table[SHAPE_IDX_V].id_lm;
3575 }
3576 }
3577
3578 return NULL;
3579}
3580
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00003581# if defined(MCH_CURSOR_SHAPE) || defined(FEAT_GUI) \
3582 || defined(FEAT_MOUSESHAPE) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003583/*
3584 * Return the index into shape_table[] for the current mode.
3585 * When "mouse" is TRUE, consider indexes valid for the mouse pointer.
3586 */
3587 int
3588get_shape_idx(mouse)
3589 int mouse;
3590{
3591#ifdef FEAT_MOUSESHAPE
3592 if (mouse && (State == HITRETURN || State == ASKMORE))
3593 {
3594# ifdef FEAT_GUI
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00003595 int x, y;
3596 gui_mch_getmouse(&x, &y);
3597 if (Y_2_ROW(y) == Rows - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003598 return SHAPE_IDX_MOREL;
3599# endif
3600 return SHAPE_IDX_MORE;
3601 }
3602 if (mouse && drag_status_line)
3603 return SHAPE_IDX_SDRAG;
3604# ifdef FEAT_VERTSPLIT
3605 if (mouse && drag_sep_line)
3606 return SHAPE_IDX_VDRAG;
3607# endif
3608#endif
3609 if (!mouse && State == SHOWMATCH)
3610 return SHAPE_IDX_SM;
3611#ifdef FEAT_VREPLACE
3612 if (State & VREPLACE_FLAG)
3613 return SHAPE_IDX_R;
3614#endif
3615 if (State & REPLACE_FLAG)
3616 return SHAPE_IDX_R;
3617 if (State & INSERT)
3618 return SHAPE_IDX_I;
3619 if (State & CMDLINE)
3620 {
3621 if (cmdline_at_end())
3622 return SHAPE_IDX_C;
3623 if (cmdline_overstrike())
3624 return SHAPE_IDX_CR;
3625 return SHAPE_IDX_CI;
3626 }
3627 if (finish_op)
3628 return SHAPE_IDX_O;
3629#ifdef FEAT_VISUAL
3630 if (VIsual_active)
3631 {
3632 if (*p_sel == 'e')
3633 return SHAPE_IDX_VE;
3634 else
3635 return SHAPE_IDX_V;
3636 }
3637#endif
3638 return SHAPE_IDX_N;
3639}
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00003640#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003641
3642# if defined(FEAT_MOUSESHAPE) || defined(PROTO)
3643static int old_mouse_shape = 0;
3644
3645/*
3646 * Set the mouse shape:
3647 * If "shape" is -1, use shape depending on the current mode,
3648 * depending on the current state.
3649 * If "shape" is -2, only update the shape when it's CLINE or STATUS (used
3650 * when the mouse moves off the status or command line).
3651 */
3652 void
3653update_mouseshape(shape_idx)
3654 int shape_idx;
3655{
3656 int new_mouse_shape;
3657
3658 /* Only works in GUI mode. */
Bram Moolenaar6bb68362005-03-22 23:03:44 +00003659 if (!gui.in_use || gui.starting)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003660 return;
3661
3662 /* Postpone the updating when more is to come. Speeds up executing of
3663 * mappings. */
3664 if (shape_idx == -1 && char_avail())
3665 {
3666 postponed_mouseshape = TRUE;
3667 return;
3668 }
3669
Bram Moolenaar14716812006-05-04 21:54:08 +00003670 /* When ignoring the mouse don't change shape on the statusline. */
3671 if (*p_mouse == NUL
3672 && (shape_idx == SHAPE_IDX_CLINE
3673 || shape_idx == SHAPE_IDX_STATUS
3674 || shape_idx == SHAPE_IDX_VSEP))
3675 shape_idx = -2;
3676
Bram Moolenaar071d4272004-06-13 20:20:40 +00003677 if (shape_idx == -2
3678 && old_mouse_shape != shape_table[SHAPE_IDX_CLINE].mshape
3679 && old_mouse_shape != shape_table[SHAPE_IDX_STATUS].mshape
3680 && old_mouse_shape != shape_table[SHAPE_IDX_VSEP].mshape)
3681 return;
3682 if (shape_idx < 0)
3683 new_mouse_shape = shape_table[get_shape_idx(TRUE)].mshape;
3684 else
3685 new_mouse_shape = shape_table[shape_idx].mshape;
3686 if (new_mouse_shape != old_mouse_shape)
3687 {
3688 mch_set_mouse_shape(new_mouse_shape);
3689 old_mouse_shape = new_mouse_shape;
3690 }
3691 postponed_mouseshape = FALSE;
3692}
3693# endif
3694
3695#endif /* CURSOR_SHAPE */
3696
3697
3698#ifdef FEAT_CRYPT
3699/*
Bram Moolenaar7aa9f6a2007-05-10 18:00:30 +00003700 * Optional encryption support.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003701 * Mohsin Ahmed, mosh@sasi.com, 98-09-24
3702 * Based on zip/crypt sources.
3703 *
3704 * NOTE FOR USA: Since 2000 exporting this code from the USA is allowed to
3705 * most countries. There are a few exceptions, but that still should not be a
3706 * problem since this code was originally created in Europe and India.
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003707 *
3708 * Blowfish addition originally made by Mohsin Ahmed,
3709 * http://www.cs.albany.edu/~mosh 2010-03-14
3710 * Based on blowfish by Bruce Schneier (http://www.schneier.com/blowfish.html)
3711 * and sha256 by Christophe Devine.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003712 */
3713
3714/* from zip.h */
3715
3716typedef unsigned short ush; /* unsigned 16-bit value */
3717typedef unsigned long ulg; /* unsigned 32-bit value */
3718
3719static void make_crc_tab __ARGS((void));
3720
Bram Moolenaard6f676d2005-06-01 21:51:55 +00003721static ulg crc_32_tab[256];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003722
3723/*
3724 * Fill the CRC table.
3725 */
3726 static void
3727make_crc_tab()
3728{
3729 ulg s,t,v;
3730 static int done = FALSE;
3731
3732 if (done)
3733 return;
3734 for (t = 0; t < 256; t++)
3735 {
3736 v = t;
3737 for (s = 0; s < 8; s++)
3738 v = (v >> 1) ^ ((v & 1) * (ulg)0xedb88320L);
3739 crc_32_tab[t] = v;
3740 }
3741 done = TRUE;
3742}
3743
3744#define CRC32(c, b) (crc_32_tab[((int)(c) ^ (b)) & 0xff] ^ ((c) >> 8))
3745
Bram Moolenaar071d4272004-06-13 20:20:40 +00003746static ulg keys[3]; /* keys defining the pseudo-random sequence */
3747
3748/*
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02003749 * Return the next byte in the pseudo-random sequence.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003750 */
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02003751#define DECRYPT_BYTE_ZIP(t) { \
3752 ush temp; \
3753 \
3754 temp = (ush)keys[2] | 2; \
3755 t = (int)(((unsigned)(temp * (temp ^ 1)) >> 8) & 0xff); \
Bram Moolenaar071d4272004-06-13 20:20:40 +00003756}
3757
3758/*
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02003759 * Update the encryption keys with the next byte of plain text.
3760 */
3761#define UPDATE_KEYS_ZIP(c) { \
3762 keys[0] = CRC32(keys[0], (c)); \
3763 keys[1] += keys[0] & 0xff; \
3764 keys[1] = keys[1] * 134775813L + 1; \
3765 keys[2] = CRC32(keys[2], (int)(keys[1] >> 24)); \
3766}
3767
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003768static int crypt_busy = 0;
3769static ulg saved_keys[3];
3770static int saved_crypt_method;
3771
3772/*
Bram Moolenaar49771f42010-07-20 17:32:38 +02003773 * Return int value for crypt method string:
3774 * 0 for "zip", the old method. Also for any non-valid value.
3775 * 1 for "blowfish".
3776 */
3777 int
3778crypt_method_from_string(s)
3779 char_u *s;
3780{
3781 return *s == 'b' ? 1 : 0;
3782}
3783
3784/*
3785 * Get the crypt method for buffer "buf" as a number.
3786 */
3787 int
3788get_crypt_method(buf)
3789 buf_T *buf;
3790{
3791 return crypt_method_from_string(*buf->b_p_cm == NUL ? p_cm : buf->b_p_cm);
3792}
3793
3794/*
3795 * Set the crypt method for buffer "buf" to "method" using the int value as
3796 * returned by crypt_method_from_string().
3797 */
3798 void
3799set_crypt_method(buf, method)
3800 buf_T *buf;
3801 int method;
3802{
3803 free_string_option(buf->b_p_cm);
3804 buf->b_p_cm = vim_strsave((char_u *)(method == 0 ? "zip" : "blowfish"));
3805}
3806
3807/*
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003808 * Prepare for initializing encryption. If already doing encryption then save
3809 * the state.
Bram Moolenaar2f1e0502010-08-13 11:18:02 +02003810 * Must always be called symmetrically with crypt_pop_state().
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003811 */
3812 void
3813crypt_push_state()
3814{
3815 if (crypt_busy == 1)
3816 {
3817 /* save the state */
3818 if (use_crypt_method == 0)
3819 {
3820 saved_keys[0] = keys[0];
3821 saved_keys[1] = keys[1];
3822 saved_keys[2] = keys[2];
3823 }
3824 else
3825 bf_crypt_save();
3826 saved_crypt_method = use_crypt_method;
3827 }
3828 else if (crypt_busy > 1)
3829 EMSG2(_(e_intern2), "crypt_push_state()");
3830 ++crypt_busy;
3831}
3832
3833/*
3834 * End encryption. If doing encryption before crypt_push_state() then restore
3835 * the saved state.
Bram Moolenaar2f1e0502010-08-13 11:18:02 +02003836 * Must always be called symmetrically with crypt_push_state().
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003837 */
3838 void
3839crypt_pop_state()
3840{
3841 --crypt_busy;
3842 if (crypt_busy == 1)
3843 {
3844 use_crypt_method = saved_crypt_method;
3845 if (use_crypt_method == 0)
3846 {
3847 keys[0] = saved_keys[0];
3848 keys[1] = saved_keys[1];
3849 keys[2] = saved_keys[2];
3850 }
3851 else
3852 bf_crypt_restore();
3853 }
3854}
3855
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02003856/*
3857 * Encrypt "from[len]" into "to[len]".
3858 * "from" and "to" can be equal to encrypt in place.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003859 */
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003860 void
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02003861crypt_encode(from, len, to)
3862 char_u *from;
3863 size_t len;
3864 char_u *to;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003865{
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02003866 size_t i;
3867 int ztemp, t;
3868
3869 if (use_crypt_method == 0)
3870 for (i = 0; i < len; ++i)
3871 {
3872 ztemp = from[i];
3873 DECRYPT_BYTE_ZIP(t);
3874 UPDATE_KEYS_ZIP(ztemp);
3875 to[i] = t ^ ztemp;
3876 }
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003877 else
Bram Moolenaarbbd6afe2010-06-02 20:32:23 +02003878 bf_crypt_encode(from, len, to);
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02003879}
3880
3881/*
3882 * Decrypt "ptr[len]" in place.
3883 */
3884 void
3885crypt_decode(ptr, len)
3886 char_u *ptr;
3887 long len;
3888{
3889 char_u *p;
3890
3891 if (use_crypt_method == 0)
3892 for (p = ptr; p < ptr + len; ++p)
3893 {
3894 ush temp;
3895
3896 temp = (ush)keys[2] | 2;
3897 temp = (int)(((unsigned)(temp * (temp ^ 1)) >> 8) & 0xff);
3898 UPDATE_KEYS_ZIP(*p ^= temp);
3899 }
3900 else
Bram Moolenaarbbd6afe2010-06-02 20:32:23 +02003901 bf_crypt_decode(ptr, len);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003902}
3903
3904/*
3905 * Initialize the encryption keys and the random header according to
3906 * the given password.
3907 * If "passwd" is NULL or empty, don't do anything.
3908 */
3909 void
3910crypt_init_keys(passwd)
3911 char_u *passwd; /* password string with which to modify keys */
3912{
3913 if (passwd != NULL && *passwd != NUL)
3914 {
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02003915 if (use_crypt_method == 0)
Bram Moolenaarbbd6afe2010-06-02 20:32:23 +02003916 {
3917 char_u *p;
3918
3919 make_crc_tab();
3920 keys[0] = 305419896L;
3921 keys[1] = 591751049L;
3922 keys[2] = 878082192L;
3923 for (p = passwd; *p!= NUL; ++p)
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02003924 {
Bram Moolenaarbbd6afe2010-06-02 20:32:23 +02003925 UPDATE_KEYS_ZIP((int)*p);
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02003926 }
Bram Moolenaarbbd6afe2010-06-02 20:32:23 +02003927 }
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02003928 else
Bram Moolenaarbbd6afe2010-06-02 20:32:23 +02003929 bf_crypt_init_keys(passwd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003930 }
3931}
3932
3933/*
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003934 * Free an allocated crypt key. Clear the text to make sure it doesn't stay
3935 * in memory anywhere.
3936 */
3937 void
3938free_crypt_key(key)
3939 char_u *key;
3940{
3941 char_u *p;
3942
3943 if (key != NULL)
3944 {
3945 for (p = key; *p != NUL; ++p)
Bram Moolenaarbe18d102010-05-22 21:37:53 +02003946 *p = 0;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003947 vim_free(key);
3948 }
3949}
3950
3951/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003952 * Ask the user for a crypt key.
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003953 * When "store" is TRUE, the new key is stored in the 'key' option, and the
Bram Moolenaar071d4272004-06-13 20:20:40 +00003954 * 'key' option value is returned: Don't free it.
3955 * When "store" is FALSE, the typed key is returned in allocated memory.
3956 * Returns NULL on failure.
3957 */
3958 char_u *
3959get_crypt_key(store, twice)
3960 int store;
3961 int twice; /* Ask for the key twice. */
3962{
3963 char_u *p1, *p2 = NULL;
3964 int round;
3965
3966 for (round = 0; ; ++round)
3967 {
3968 cmdline_star = TRUE;
3969 cmdline_row = msg_row;
3970 p1 = getcmdline_prompt(NUL, round == 0
3971 ? (char_u *)_("Enter encryption key: ")
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00003972 : (char_u *)_("Enter same key again: "), 0, EXPAND_NOTHING,
3973 NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003974 cmdline_star = FALSE;
3975
3976 if (p1 == NULL)
3977 break;
3978
3979 if (round == twice)
3980 {
3981 if (p2 != NULL && STRCMP(p1, p2) != 0)
3982 {
3983 MSG(_("Keys don't match!"));
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003984 free_crypt_key(p1);
3985 free_crypt_key(p2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003986 p2 = NULL;
3987 round = -1; /* do it again */
3988 continue;
3989 }
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003990
Bram Moolenaar071d4272004-06-13 20:20:40 +00003991 if (store)
3992 {
3993 set_option_value((char_u *)"key", 0L, p1, OPT_LOCAL);
Bram Moolenaar40e6a712010-05-16 22:32:54 +02003994 free_crypt_key(p1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003995 p1 = curbuf->b_p_key;
3996 }
3997 break;
3998 }
3999 p2 = p1;
4000 }
4001
4002 /* since the user typed this, no need to wait for return */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004003 if (msg_didout)
4004 msg_putchar('\n');
Bram Moolenaare4ce65d2010-08-04 20:12:32 +02004005 need_wait_return = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004006 msg_didout = FALSE;
4007
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004008 free_crypt_key(p2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004009 return p1;
4010}
4011
4012#endif /* FEAT_CRYPT */
4013
4014/* TODO: make some #ifdef for this */
4015/*--------[ file searching ]-------------------------------------------------*/
4016/*
4017 * File searching functions for 'path', 'tags' and 'cdpath' options.
4018 * External visible functions:
4019 * vim_findfile_init() creates/initialises the search context
4020 * vim_findfile_free_visited() free list of visited files/dirs of search
4021 * context
4022 * vim_findfile() find a file in the search context
4023 * vim_findfile_cleanup() cleanup/free search context created by
4024 * vim_findfile_init()
4025 *
4026 * All static functions and variables start with 'ff_'
4027 *
4028 * In general it works like this:
4029 * First you create yourself a search context by calling vim_findfile_init().
4030 * It is possible to give a search context from a previous call to
4031 * vim_findfile_init(), so it can be reused. After this you call vim_findfile()
4032 * until you are satisfied with the result or it returns NULL. On every call it
4033 * returns the next file which matches the conditions given to
4034 * vim_findfile_init(). If it doesn't find a next file it returns NULL.
4035 *
4036 * It is possible to call vim_findfile_init() again to reinitialise your search
4037 * with some new parameters. Don't forget to pass your old search context to
4038 * it, so it can reuse it and especially reuse the list of already visited
4039 * directories. If you want to delete the list of already visited directories
4040 * simply call vim_findfile_free_visited().
4041 *
4042 * When you are done call vim_findfile_cleanup() to free the search context.
4043 *
4044 * The function vim_findfile_init() has a long comment, which describes the
4045 * needed parameters.
4046 *
4047 *
4048 *
4049 * ATTENTION:
4050 * ==========
Bram Moolenaar77f66d62007-02-20 02:16:18 +00004051 * Also we use an allocated search context here, this functions are NOT
Bram Moolenaar071d4272004-06-13 20:20:40 +00004052 * thread-safe!!!!!
4053 *
4054 * To minimize parameter passing (or because I'm to lazy), only the
4055 * external visible functions get a search context as a parameter. This is
4056 * then assigned to a static global, which is used throughout the local
4057 * functions.
4058 */
4059
4060/*
4061 * type for the directory search stack
4062 */
4063typedef struct ff_stack
4064{
4065 struct ff_stack *ffs_prev;
4066
4067 /* the fix part (no wildcards) and the part containing the wildcards
4068 * of the search path
4069 */
4070 char_u *ffs_fix_path;
4071#ifdef FEAT_PATH_EXTRA
4072 char_u *ffs_wc_path;
4073#endif
4074
4075 /* files/dirs found in the above directory, matched by the first wildcard
4076 * of wc_part
4077 */
4078 char_u **ffs_filearray;
4079 int ffs_filearray_size;
4080 char_u ffs_filearray_cur; /* needed for partly handled dirs */
4081
4082 /* to store status of partly handled directories
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004083 * 0: we work on this directory for the first time
Bram Moolenaar071d4272004-06-13 20:20:40 +00004084 * 1: this directory was partly searched in an earlier step
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004085 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004086 int ffs_stage;
4087
4088 /* How deep are we in the directory tree?
4089 * Counts backward from value of level parameter to vim_findfile_init
4090 */
4091 int ffs_level;
4092
4093 /* Did we already expand '**' to an empty string? */
4094 int ffs_star_star_empty;
4095} ff_stack_T;
4096
4097/*
4098 * type for already visited directories or files.
4099 */
4100typedef struct ff_visited
4101{
4102 struct ff_visited *ffv_next;
4103
4104#ifdef FEAT_PATH_EXTRA
4105 /* Visited directories are different if the wildcard string are
4106 * different. So we have to save it.
4107 */
4108 char_u *ffv_wc_path;
4109#endif
4110 /* for unix use inode etc for comparison (needed because of links), else
4111 * use filename.
4112 */
4113#ifdef UNIX
Bram Moolenaare1fbddc2009-05-16 19:07:03 +00004114 int ffv_dev_valid; /* ffv_dev and ffv_ino were set */
4115 dev_t ffv_dev; /* device number */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004116 ino_t ffv_ino; /* inode number */
4117#endif
4118 /* The memory for this struct is allocated according to the length of
4119 * ffv_fname.
4120 */
4121 char_u ffv_fname[1]; /* actually longer */
4122} ff_visited_T;
4123
4124/*
4125 * We might have to manage several visited lists during a search.
Bram Moolenaar7aa9f6a2007-05-10 18:00:30 +00004126 * This is especially needed for the tags option. If tags is set to:
Bram Moolenaar071d4272004-06-13 20:20:40 +00004127 * "./++/tags,./++/TAGS,++/tags" (replace + with *)
4128 * So we have to do 3 searches:
4129 * 1) search from the current files directory downward for the file "tags"
4130 * 2) search from the current files directory downward for the file "TAGS"
4131 * 3) search from Vims current directory downwards for the file "tags"
4132 * As you can see, the first and the third search are for the same file, so for
4133 * the third search we can use the visited list of the first search. For the
4134 * second search we must start from a empty visited list.
4135 * The struct ff_visited_list_hdr is used to manage a linked list of already
4136 * visited lists.
4137 */
4138typedef struct ff_visited_list_hdr
4139{
4140 struct ff_visited_list_hdr *ffvl_next;
4141
4142 /* the filename the attached visited list is for */
4143 char_u *ffvl_filename;
4144
4145 ff_visited_T *ffvl_visited_list;
4146
4147} ff_visited_list_hdr_T;
4148
4149
4150/*
4151 * '**' can be expanded to several directory levels.
Bram Moolenaar7aa9f6a2007-05-10 18:00:30 +00004152 * Set the default maximum depth.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004153 */
4154#define FF_MAX_STAR_STAR_EXPAND ((char_u)30)
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004155
Bram Moolenaar071d4272004-06-13 20:20:40 +00004156/*
4157 * The search context:
4158 * ffsc_stack_ptr: the stack for the dirs to search
4159 * ffsc_visited_list: the currently active visited list
4160 * ffsc_dir_visited_list: the currently active visited list for search dirs
4161 * ffsc_visited_lists_list: the list of all visited lists
4162 * ffsc_dir_visited_lists_list: the list of all visited lists for search dirs
4163 * ffsc_file_to_search: the file to search for
4164 * ffsc_start_dir: the starting directory, if search path was relative
4165 * ffsc_fix_path: the fix part of the given path (without wildcards)
4166 * Needed for upward search.
4167 * ffsc_wc_path: the part of the given path containing wildcards
4168 * ffsc_level: how many levels of dirs to search downwards
4169 * ffsc_stopdirs_v: array of stop directories for upward search
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004170 * ffsc_find_what: FINDFILE_BOTH, FINDFILE_DIR or FINDFILE_FILE
Bram Moolenaar463ee342010-08-08 18:17:52 +02004171 * ffsc_tagfile: searching for tags file, don't use 'suffixesadd'
Bram Moolenaar071d4272004-06-13 20:20:40 +00004172 */
4173typedef struct ff_search_ctx_T
4174{
4175 ff_stack_T *ffsc_stack_ptr;
4176 ff_visited_list_hdr_T *ffsc_visited_list;
4177 ff_visited_list_hdr_T *ffsc_dir_visited_list;
4178 ff_visited_list_hdr_T *ffsc_visited_lists_list;
4179 ff_visited_list_hdr_T *ffsc_dir_visited_lists_list;
4180 char_u *ffsc_file_to_search;
4181 char_u *ffsc_start_dir;
4182 char_u *ffsc_fix_path;
4183#ifdef FEAT_PATH_EXTRA
4184 char_u *ffsc_wc_path;
4185 int ffsc_level;
4186 char_u **ffsc_stopdirs_v;
4187#endif
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004188 int ffsc_find_what;
Bram Moolenaar463ee342010-08-08 18:17:52 +02004189 int ffsc_tagfile;
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00004190} ff_search_ctx_T;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004191
Bram Moolenaar071d4272004-06-13 20:20:40 +00004192/* locally needed functions */
4193#ifdef FEAT_PATH_EXTRA
4194static int ff_check_visited __ARGS((ff_visited_T **, char_u *, char_u *));
4195#else
4196static int ff_check_visited __ARGS((ff_visited_T **, char_u *));
4197#endif
4198static void vim_findfile_free_visited_list __ARGS((ff_visited_list_hdr_T **list_headp));
4199static void ff_free_visited_list __ARGS((ff_visited_T *vl));
4200static ff_visited_list_hdr_T* ff_get_visited_list __ARGS((char_u *, ff_visited_list_hdr_T **list_headp));
4201#ifdef FEAT_PATH_EXTRA
4202static int ff_wc_equal __ARGS((char_u *s1, char_u *s2));
4203#endif
4204
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004205static void ff_push __ARGS((ff_search_ctx_T *search_ctx, ff_stack_T *stack_ptr));
4206static ff_stack_T *ff_pop __ARGS((ff_search_ctx_T *search_ctx));
4207static void ff_clear __ARGS((ff_search_ctx_T *search_ctx));
4208static void ff_free_stack_element __ARGS((ff_stack_T *stack_ptr));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004209#ifdef FEAT_PATH_EXTRA
4210static ff_stack_T *ff_create_stack_element __ARGS((char_u *, char_u *, int, int));
4211#else
4212static ff_stack_T *ff_create_stack_element __ARGS((char_u *, int, int));
4213#endif
4214#ifdef FEAT_PATH_EXTRA
4215static int ff_path_in_stoplist __ARGS((char_u *, int, char_u **));
4216#endif
4217
Bram Moolenaar071d4272004-06-13 20:20:40 +00004218#if 0
4219/*
4220 * if someone likes findfirst/findnext, here are the functions
4221 * NOT TESTED!!
4222 */
4223
4224static void *ff_fn_search_context = NULL;
4225
4226 char_u *
4227vim_findfirst(path, filename, level)
4228 char_u *path;
4229 char_u *filename;
4230 int level;
4231{
4232 ff_fn_search_context =
4233 vim_findfile_init(path, filename, NULL, level, TRUE, FALSE,
4234 ff_fn_search_context, rel_fname);
4235 if (NULL == ff_fn_search_context)
4236 return NULL;
4237 else
4238 return vim_findnext()
4239}
4240
4241 char_u *
4242vim_findnext()
4243{
4244 char_u *ret = vim_findfile(ff_fn_search_context);
4245
4246 if (NULL == ret)
4247 {
4248 vim_findfile_cleanup(ff_fn_search_context);
4249 ff_fn_search_context = NULL;
4250 }
4251 return ret;
4252}
4253#endif
4254
4255/*
Bram Moolenaare2b590e2010-08-08 18:29:48 +02004256 * Initialization routine for vim_findfile().
Bram Moolenaar071d4272004-06-13 20:20:40 +00004257 *
Bram Moolenaarbe18d102010-05-22 21:37:53 +02004258 * Returns the newly allocated search context or NULL if an error occurred.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004259 *
4260 * Don't forget to clean up by calling vim_findfile_cleanup() if you are done
4261 * with the search context.
4262 *
4263 * Find the file 'filename' in the directory 'path'.
4264 * The parameter 'path' may contain wildcards. If so only search 'level'
4265 * directories deep. The parameter 'level' is the absolute maximum and is
4266 * not related to restricts given to the '**' wildcard. If 'level' is 100
4267 * and you use '**200' vim_findfile() will stop after 100 levels.
4268 *
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004269 * 'filename' cannot contain wildcards! It is used as-is, no backslashes to
4270 * escape special characters.
4271 *
Bram Moolenaar071d4272004-06-13 20:20:40 +00004272 * If 'stopdirs' is not NULL and nothing is found downward, the search is
4273 * restarted on the next higher directory level. This is repeated until the
4274 * start-directory of a search is contained in 'stopdirs'. 'stopdirs' has the
4275 * format ";*<dirname>*\(;<dirname>\)*;\=$".
4276 *
4277 * If the 'path' is relative, the starting dir for the search is either VIM's
4278 * current dir or if the path starts with "./" the current files dir.
Bram Moolenaarbe18d102010-05-22 21:37:53 +02004279 * If the 'path' is absolute, the starting dir is that part of the path before
Bram Moolenaar071d4272004-06-13 20:20:40 +00004280 * the first wildcard.
4281 *
4282 * Upward search is only done on the starting dir.
4283 *
4284 * If 'free_visited' is TRUE the list of already visited files/directories is
4285 * cleared. Set this to FALSE if you just want to search from another
4286 * directory, but want to be sure that no directory from a previous search is
4287 * searched again. This is useful if you search for a file at different places.
4288 * The list of visited files/dirs can also be cleared with the function
4289 * vim_findfile_free_visited().
4290 *
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004291 * Set the parameter 'find_what' to FINDFILE_DIR if you want to search for
4292 * directories only, FINDFILE_FILE for files only, FINDFILE_BOTH for both.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004293 *
4294 * A search context returned by a previous call to vim_findfile_init() can be
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004295 * passed in the parameter "search_ctx_arg". This context is reused and
4296 * reinitialized with the new parameters. The list of already visited
Bram Moolenaar071d4272004-06-13 20:20:40 +00004297 * directories from this context is only deleted if the parameter
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004298 * "free_visited" is true. Be aware that the passed "search_ctx_arg" is freed
4299 * if the reinitialization fails.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004300 *
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004301 * If you don't have a search context from a previous call "search_ctx_arg"
4302 * must be NULL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004303 *
4304 * This function silently ignores a few errors, vim_findfile() will have
4305 * limited functionality then.
4306 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004307 void *
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004308vim_findfile_init(path, filename, stopdirs, level, free_visited, find_what,
4309 search_ctx_arg, tagfile, rel_fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004310 char_u *path;
4311 char_u *filename;
Bram Moolenaare1fbddc2009-05-16 19:07:03 +00004312 char_u *stopdirs UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004313 int level;
4314 int free_visited;
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004315 int find_what;
4316 void *search_ctx_arg;
Bram Moolenaar463ee342010-08-08 18:17:52 +02004317 int tagfile; /* expanding names of tags files */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004318 char_u *rel_fname; /* file name to use for "." */
4319{
4320#ifdef FEAT_PATH_EXTRA
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004321 char_u *wc_part;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004322#endif
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004323 ff_stack_T *sptr;
4324 ff_search_ctx_T *search_ctx;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004325
4326 /* If a search context is given by the caller, reuse it, else allocate a
4327 * new one.
4328 */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004329 if (search_ctx_arg != NULL)
4330 search_ctx = search_ctx_arg;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004331 else
4332 {
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004333 search_ctx = (ff_search_ctx_T*)alloc((unsigned)sizeof(ff_search_ctx_T));
4334 if (search_ctx == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004335 goto error_return;
Bram Moolenaar7db5fc82010-05-24 11:59:29 +02004336 vim_memset(search_ctx, 0, sizeof(ff_search_ctx_T));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004337 }
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004338 search_ctx->ffsc_find_what = find_what;
Bram Moolenaar463ee342010-08-08 18:17:52 +02004339 search_ctx->ffsc_tagfile = tagfile;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004340
4341 /* clear the search context, but NOT the visited lists */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004342 ff_clear(search_ctx);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004343
4344 /* clear visited list if wanted */
4345 if (free_visited == TRUE)
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004346 vim_findfile_free_visited(search_ctx);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004347 else
4348 {
4349 /* Reuse old visited lists. Get the visited list for the given
4350 * filename. If no list for the current filename exists, creates a new
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004351 * one. */
4352 search_ctx->ffsc_visited_list = ff_get_visited_list(filename,
4353 &search_ctx->ffsc_visited_lists_list);
4354 if (search_ctx->ffsc_visited_list == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004355 goto error_return;
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004356 search_ctx->ffsc_dir_visited_list = ff_get_visited_list(filename,
4357 &search_ctx->ffsc_dir_visited_lists_list);
4358 if (search_ctx->ffsc_dir_visited_list == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004359 goto error_return;
4360 }
4361
4362 if (ff_expand_buffer == NULL)
4363 {
4364 ff_expand_buffer = (char_u*)alloc(MAXPATHL);
4365 if (ff_expand_buffer == NULL)
4366 goto error_return;
4367 }
4368
4369 /* Store information on starting dir now if path is relative.
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00004370 * If path is absolute, we do that later. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004371 if (path[0] == '.'
4372 && (vim_ispathsep(path[1]) || path[1] == NUL)
4373 && (!tagfile || vim_strchr(p_cpo, CPO_DOTTAG) == NULL)
4374 && rel_fname != NULL)
4375 {
4376 int len = (int)(gettail(rel_fname) - rel_fname);
4377
4378 if (!vim_isAbsName(rel_fname) && len + 1 < MAXPATHL)
4379 {
4380 /* Make the start dir an absolute path name. */
Bram Moolenaarbbebc852005-07-18 21:47:53 +00004381 vim_strncpy(ff_expand_buffer, rel_fname, len);
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004382 search_ctx->ffsc_start_dir = FullName_save(ff_expand_buffer, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004383 }
4384 else
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004385 search_ctx->ffsc_start_dir = vim_strnsave(rel_fname, len);
4386 if (search_ctx->ffsc_start_dir == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004387 goto error_return;
4388 if (*++path != NUL)
4389 ++path;
4390 }
4391 else if (*path == NUL || !vim_isAbsName(path))
4392 {
4393#ifdef BACKSLASH_IN_FILENAME
4394 /* "c:dir" needs "c:" to be expanded, otherwise use current dir */
4395 if (*path != NUL && path[1] == ':')
4396 {
4397 char_u drive[3];
4398
4399 drive[0] = path[0];
4400 drive[1] = ':';
4401 drive[2] = NUL;
4402 if (vim_FullName(drive, ff_expand_buffer, MAXPATHL, TRUE) == FAIL)
4403 goto error_return;
4404 path += 2;
4405 }
4406 else
4407#endif
4408 if (mch_dirname(ff_expand_buffer, MAXPATHL) == FAIL)
4409 goto error_return;
4410
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004411 search_ctx->ffsc_start_dir = vim_strsave(ff_expand_buffer);
4412 if (search_ctx->ffsc_start_dir == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004413 goto error_return;
4414
4415#ifdef BACKSLASH_IN_FILENAME
4416 /* A path that starts with "/dir" is relative to the drive, not to the
4417 * directory (but not for "//machine/dir"). Only use the drive name. */
4418 if ((*path == '/' || *path == '\\')
4419 && path[1] != path[0]
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004420 && search_ctx->ffsc_start_dir[1] == ':')
4421 search_ctx->ffsc_start_dir[2] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004422#endif
4423 }
4424
4425#ifdef FEAT_PATH_EXTRA
4426 /*
4427 * If stopdirs are given, split them into an array of pointers.
4428 * If this fails (mem allocation), there is no upward search at all or a
4429 * stop directory is not recognized -> continue silently.
4430 * If stopdirs just contains a ";" or is empty,
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004431 * search_ctx->ffsc_stopdirs_v will only contain a NULL pointer. This
Bram Moolenaar071d4272004-06-13 20:20:40 +00004432 * is handled as unlimited upward search. See function
4433 * ff_path_in_stoplist() for details.
4434 */
4435 if (stopdirs != NULL)
4436 {
4437 char_u *walker = stopdirs;
4438 int dircount;
4439
4440 while (*walker == ';')
4441 walker++;
4442
4443 dircount = 1;
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004444 search_ctx->ffsc_stopdirs_v =
4445 (char_u **)alloc((unsigned)sizeof(char_u *));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004446
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004447 if (search_ctx->ffsc_stopdirs_v != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004448 {
4449 do
4450 {
4451 char_u *helper;
4452 void *ptr;
4453
4454 helper = walker;
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004455 ptr = vim_realloc(search_ctx->ffsc_stopdirs_v,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004456 (dircount + 1) * sizeof(char_u *));
4457 if (ptr)
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004458 search_ctx->ffsc_stopdirs_v = ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004459 else
4460 /* ignore, keep what we have and continue */
4461 break;
4462 walker = vim_strchr(walker, ';');
4463 if (walker)
4464 {
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004465 search_ctx->ffsc_stopdirs_v[dircount-1] =
4466 vim_strnsave(helper, (int)(walker - helper));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004467 walker++;
4468 }
4469 else
4470 /* this might be "", which means ascent till top
4471 * of directory tree.
4472 */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004473 search_ctx->ffsc_stopdirs_v[dircount-1] =
4474 vim_strsave(helper);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004475
4476 dircount++;
4477
4478 } while (walker != NULL);
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004479 search_ctx->ffsc_stopdirs_v[dircount-1] = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004480 }
4481 }
4482#endif
4483
4484#ifdef FEAT_PATH_EXTRA
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004485 search_ctx->ffsc_level = level;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004486
4487 /* split into:
4488 * -fix path
4489 * -wildcard_stuff (might be NULL)
4490 */
4491 wc_part = vim_strchr(path, '*');
4492 if (wc_part != NULL)
4493 {
4494 int llevel;
4495 int len;
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00004496 char *errpt;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004497
4498 /* save the fix part of the path */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004499 search_ctx->ffsc_fix_path = vim_strnsave(path, (int)(wc_part - path));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004500
4501 /*
4502 * copy wc_path and add restricts to the '**' wildcard.
Bram Moolenaar7aa9f6a2007-05-10 18:00:30 +00004503 * The octet after a '**' is used as a (binary) counter.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004504 * So '**3' is transposed to '**^C' ('^C' is ASCII value 3)
4505 * or '**76' is transposed to '**N'( 'N' is ASCII value 76).
4506 * For EBCDIC you get different character values.
4507 * If no restrict is given after '**' the default is used.
Bram Moolenaar21160b92009-11-11 15:56:10 +00004508 * Due to this technique the path looks awful if you print it as a
Bram Moolenaar071d4272004-06-13 20:20:40 +00004509 * string.
4510 */
4511 len = 0;
4512 while (*wc_part != NUL)
4513 {
4514 if (STRNCMP(wc_part, "**", 2) == 0)
4515 {
4516 ff_expand_buffer[len++] = *wc_part++;
4517 ff_expand_buffer[len++] = *wc_part++;
4518
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00004519 llevel = strtol((char *)wc_part, &errpt, 10);
4520 if ((char_u *)errpt != wc_part && llevel > 0 && llevel < 255)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004521 ff_expand_buffer[len++] = llevel;
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00004522 else if ((char_u *)errpt != wc_part && llevel == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004523 /* restrict is 0 -> remove already added '**' */
4524 len -= 2;
4525 else
4526 ff_expand_buffer[len++] = FF_MAX_STAR_STAR_EXPAND;
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00004527 wc_part = (char_u *)errpt;
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00004528 if (*wc_part != NUL && !vim_ispathsep(*wc_part))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004529 {
4530 EMSG2(_("E343: Invalid path: '**[number]' must be at the end of the path or be followed by '%s'."), PATHSEPSTR);
4531 goto error_return;
4532 }
4533 }
4534 else
4535 ff_expand_buffer[len++] = *wc_part++;
4536 }
4537 ff_expand_buffer[len] = NUL;
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004538 search_ctx->ffsc_wc_path = vim_strsave(ff_expand_buffer);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004539
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004540 if (search_ctx->ffsc_wc_path == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004541 goto error_return;
4542 }
4543 else
4544#endif
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004545 search_ctx->ffsc_fix_path = vim_strsave(path);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004546
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004547 if (search_ctx->ffsc_start_dir == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004548 {
4549 /* store the fix part as startdir.
4550 * This is needed if the parameter path is fully qualified.
4551 */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004552 search_ctx->ffsc_start_dir = vim_strsave(search_ctx->ffsc_fix_path);
Bram Moolenaara9d52e32010-07-31 16:44:19 +02004553 if (search_ctx->ffsc_start_dir == NULL)
4554 goto error_return;
4555 search_ctx->ffsc_fix_path[0] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004556 }
4557
4558 /* create an absolute path */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004559 STRCPY(ff_expand_buffer, search_ctx->ffsc_start_dir);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004560 add_pathsep(ff_expand_buffer);
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004561 STRCAT(ff_expand_buffer, search_ctx->ffsc_fix_path);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004562 add_pathsep(ff_expand_buffer);
4563
4564 sptr = ff_create_stack_element(ff_expand_buffer,
4565#ifdef FEAT_PATH_EXTRA
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004566 search_ctx->ffsc_wc_path,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004567#endif
4568 level, 0);
4569
4570 if (sptr == NULL)
4571 goto error_return;
4572
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004573 ff_push(search_ctx, sptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004574
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004575 search_ctx->ffsc_file_to_search = vim_strsave(filename);
4576 if (search_ctx->ffsc_file_to_search == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004577 goto error_return;
4578
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004579 return search_ctx;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004580
4581error_return:
4582 /*
4583 * We clear the search context now!
4584 * Even when the caller gave us a (perhaps valid) context we free it here,
4585 * as we might have already destroyed it.
4586 */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004587 vim_findfile_cleanup(search_ctx);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004588 return NULL;
4589}
4590
4591#if defined(FEAT_PATH_EXTRA) || defined(PROTO)
4592/*
4593 * Get the stopdir string. Check that ';' is not escaped.
4594 */
4595 char_u *
4596vim_findfile_stopdir(buf)
4597 char_u *buf;
4598{
4599 char_u *r_ptr = buf;
4600
4601 while (*r_ptr != NUL && *r_ptr != ';')
4602 {
4603 if (r_ptr[0] == '\\' && r_ptr[1] == ';')
4604 {
4605 /* overwrite the escape char,
4606 * use STRLEN(r_ptr) to move the trailing '\0'
4607 */
Bram Moolenaar446cb832008-06-24 21:56:24 +00004608 STRMOVE(r_ptr, r_ptr + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004609 r_ptr++;
4610 }
4611 r_ptr++;
4612 }
4613 if (*r_ptr == ';')
4614 {
4615 *r_ptr = 0;
4616 r_ptr++;
4617 }
4618 else if (*r_ptr == NUL)
4619 r_ptr = NULL;
4620 return r_ptr;
4621}
4622#endif
4623
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004624/*
4625 * Clean up the given search context. Can handle a NULL pointer.
4626 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004627 void
4628vim_findfile_cleanup(ctx)
4629 void *ctx;
4630{
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00004631 if (ctx == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004632 return;
4633
Bram Moolenaar071d4272004-06-13 20:20:40 +00004634 vim_findfile_free_visited(ctx);
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004635 ff_clear(ctx);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004636 vim_free(ctx);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004637}
4638
4639/*
4640 * Find a file in a search context.
4641 * The search context was created with vim_findfile_init() above.
4642 * Return a pointer to an allocated file name or NULL if nothing found.
4643 * To get all matching files call this function until you get NULL.
4644 *
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00004645 * If the passed search_context is NULL, NULL is returned.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004646 *
4647 * The search algorithm is depth first. To change this replace the
4648 * stack with a list (don't forget to leave partly searched directories on the
4649 * top of the list).
4650 */
4651 char_u *
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004652vim_findfile(search_ctx_arg)
4653 void *search_ctx_arg;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004654{
4655 char_u *file_path;
4656#ifdef FEAT_PATH_EXTRA
4657 char_u *rest_of_wildcards;
4658 char_u *path_end = NULL;
4659#endif
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004660 ff_stack_T *stackp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004661#if defined(FEAT_SEARCHPATH) || defined(FEAT_PATH_EXTRA)
4662 int len;
4663#endif
4664 int i;
4665 char_u *p;
4666#ifdef FEAT_SEARCHPATH
4667 char_u *suf;
4668#endif
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004669 ff_search_ctx_T *search_ctx;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004670
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004671 if (search_ctx_arg == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004672 return NULL;
4673
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004674 search_ctx = (ff_search_ctx_T *)search_ctx_arg;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004675
4676 /*
4677 * filepath is used as buffer for various actions and as the storage to
4678 * return a found filename.
4679 */
4680 if ((file_path = alloc((int)MAXPATHL)) == NULL)
4681 return NULL;
4682
4683#ifdef FEAT_PATH_EXTRA
4684 /* store the end of the start dir -- needed for upward search */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004685 if (search_ctx->ffsc_start_dir != NULL)
4686 path_end = &search_ctx->ffsc_start_dir[
4687 STRLEN(search_ctx->ffsc_start_dir)];
Bram Moolenaar071d4272004-06-13 20:20:40 +00004688#endif
4689
4690#ifdef FEAT_PATH_EXTRA
4691 /* upward search loop */
4692 for (;;)
4693 {
4694#endif
4695 /* downward search loop */
4696 for (;;)
4697 {
4698 /* check if user user wants to stop the search*/
4699 ui_breakcheck();
4700 if (got_int)
4701 break;
4702
4703 /* get directory to work on from stack */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004704 stackp = ff_pop(search_ctx);
4705 if (stackp == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004706 break;
4707
4708 /*
4709 * TODO: decide if we leave this test in
4710 *
4711 * GOOD: don't search a directory(-tree) twice.
4712 * BAD: - check linked list for every new directory entered.
4713 * - check for double files also done below
4714 *
4715 * Here we check if we already searched this directory.
4716 * We already searched a directory if:
4717 * 1) The directory is the same.
4718 * 2) We would use the same wildcard string.
4719 *
4720 * Good if you have links on same directory via several ways
4721 * or you have selfreferences in directories (e.g. SuSE Linux 6.3:
4722 * /etc/rc.d/init.d is linked to /etc/rc.d -> endless loop)
4723 *
4724 * This check is only needed for directories we work on for the
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004725 * first time (hence stackp->ff_filearray == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004726 */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004727 if (stackp->ffs_filearray == NULL
4728 && ff_check_visited(&search_ctx->ffsc_dir_visited_list
Bram Moolenaar071d4272004-06-13 20:20:40 +00004729 ->ffvl_visited_list,
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004730 stackp->ffs_fix_path
Bram Moolenaar071d4272004-06-13 20:20:40 +00004731#ifdef FEAT_PATH_EXTRA
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004732 , stackp->ffs_wc_path
Bram Moolenaar071d4272004-06-13 20:20:40 +00004733#endif
4734 ) == FAIL)
4735 {
4736#ifdef FF_VERBOSE
4737 if (p_verbose >= 5)
4738 {
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004739 verbose_enter_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004740 smsg((char_u *)"Already Searched: %s (%s)",
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004741 stackp->ffs_fix_path, stackp->ffs_wc_path);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004742 /* don't overwrite this either */
4743 msg_puts((char_u *)"\n");
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004744 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004745 }
4746#endif
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004747 ff_free_stack_element(stackp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004748 continue;
4749 }
4750#ifdef FF_VERBOSE
4751 else if (p_verbose >= 5)
4752 {
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004753 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00004754 smsg((char_u *)"Searching: %s (%s)",
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004755 stackp->ffs_fix_path, stackp->ffs_wc_path);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004756 /* don't overwrite this either */
4757 msg_puts((char_u *)"\n");
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004758 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004759 }
4760#endif
4761
4762 /* check depth */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004763 if (stackp->ffs_level <= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004764 {
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004765 ff_free_stack_element(stackp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004766 continue;
4767 }
4768
4769 file_path[0] = NUL;
4770
4771 /*
4772 * If no filearray till now expand wildcards
4773 * The function expand_wildcards() can handle an array of paths
4774 * and all possible expands are returned in one array. We use this
4775 * to handle the expansion of '**' into an empty string.
4776 */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004777 if (stackp->ffs_filearray == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004778 {
4779 char_u *dirptrs[2];
4780
4781 /* we use filepath to build the path expand_wildcards() should
4782 * expand.
4783 */
4784 dirptrs[0] = file_path;
4785 dirptrs[1] = NULL;
4786
4787 /* if we have a start dir copy it in */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004788 if (!vim_isAbsName(stackp->ffs_fix_path)
4789 && search_ctx->ffsc_start_dir)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004790 {
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004791 STRCPY(file_path, search_ctx->ffsc_start_dir);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004792 add_pathsep(file_path);
4793 }
4794
4795 /* append the fix part of the search path */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004796 STRCAT(file_path, stackp->ffs_fix_path);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004797 add_pathsep(file_path);
4798
4799#ifdef FEAT_PATH_EXTRA
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004800 rest_of_wildcards = stackp->ffs_wc_path;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004801 if (*rest_of_wildcards != NUL)
4802 {
4803 len = (int)STRLEN(file_path);
4804 if (STRNCMP(rest_of_wildcards, "**", 2) == 0)
4805 {
4806 /* pointer to the restrict byte
4807 * The restrict byte is not a character!
4808 */
4809 p = rest_of_wildcards + 2;
4810
4811 if (*p > 0)
4812 {
4813 (*p)--;
4814 file_path[len++] = '*';
4815 }
4816
4817 if (*p == 0)
4818 {
4819 /* remove '**<numb> from wildcards */
Bram Moolenaar446cb832008-06-24 21:56:24 +00004820 STRMOVE(rest_of_wildcards, rest_of_wildcards + 3);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004821 }
4822 else
4823 rest_of_wildcards += 3;
4824
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004825 if (stackp->ffs_star_star_empty == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004826 {
4827 /* if not done before, expand '**' to empty */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004828 stackp->ffs_star_star_empty = 1;
4829 dirptrs[1] = stackp->ffs_fix_path;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004830 }
4831 }
4832
4833 /*
4834 * Here we copy until the next path separator or the end of
4835 * the path. If we stop at a path separator, there is
Bram Moolenaar7aa9f6a2007-05-10 18:00:30 +00004836 * still something else left. This is handled below by
Bram Moolenaar071d4272004-06-13 20:20:40 +00004837 * pushing every directory returned from expand_wildcards()
4838 * on the stack again for further search.
4839 */
4840 while (*rest_of_wildcards
4841 && !vim_ispathsep(*rest_of_wildcards))
4842 file_path[len++] = *rest_of_wildcards++;
4843
4844 file_path[len] = NUL;
4845 if (vim_ispathsep(*rest_of_wildcards))
4846 rest_of_wildcards++;
4847 }
4848#endif
4849
4850 /*
4851 * Expand wildcards like "*" and "$VAR".
4852 * If the path is a URL don't try this.
4853 */
4854 if (path_with_url(dirptrs[0]))
4855 {
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004856 stackp->ffs_filearray = (char_u **)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004857 alloc((unsigned)sizeof(char *));
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004858 if (stackp->ffs_filearray != NULL
4859 && (stackp->ffs_filearray[0]
Bram Moolenaar071d4272004-06-13 20:20:40 +00004860 = vim_strsave(dirptrs[0])) != NULL)
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004861 stackp->ffs_filearray_size = 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004862 else
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004863 stackp->ffs_filearray_size = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004864 }
4865 else
4866 expand_wildcards((dirptrs[1] == NULL) ? 1 : 2, dirptrs,
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004867 &stackp->ffs_filearray_size,
4868 &stackp->ffs_filearray,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004869 EW_DIR|EW_ADDSLASH|EW_SILENT);
4870
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004871 stackp->ffs_filearray_cur = 0;
4872 stackp->ffs_stage = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004873 }
4874#ifdef FEAT_PATH_EXTRA
4875 else
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004876 rest_of_wildcards = &stackp->ffs_wc_path[
4877 STRLEN(stackp->ffs_wc_path)];
Bram Moolenaar071d4272004-06-13 20:20:40 +00004878#endif
4879
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004880 if (stackp->ffs_stage == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004881 {
4882 /* this is the first time we work on this directory */
4883#ifdef FEAT_PATH_EXTRA
4884 if (*rest_of_wildcards == NUL)
4885#endif
4886 {
4887 /*
4888 * we don't have further wildcards to expand, so we have to
4889 * check for the final file now
4890 */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004891 for (i = stackp->ffs_filearray_cur;
4892 i < stackp->ffs_filearray_size; ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004893 {
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004894 if (!path_with_url(stackp->ffs_filearray[i])
4895 && !mch_isdir(stackp->ffs_filearray[i]))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004896 continue; /* not a directory */
4897
Bram Moolenaar21160b92009-11-11 15:56:10 +00004898 /* prepare the filename to be checked for existence
Bram Moolenaar071d4272004-06-13 20:20:40 +00004899 * below */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004900 STRCPY(file_path, stackp->ffs_filearray[i]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004901 add_pathsep(file_path);
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004902 STRCAT(file_path, search_ctx->ffsc_file_to_search);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004903
4904 /*
4905 * Try without extra suffix and then with suffixes
4906 * from 'suffixesadd'.
4907 */
4908#ifdef FEAT_SEARCHPATH
4909 len = (int)STRLEN(file_path);
Bram Moolenaar463ee342010-08-08 18:17:52 +02004910 if (search_ctx->ffsc_tagfile)
4911 suf = (char_u *)"";
4912 else
4913 suf = curbuf->b_p_sua;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004914 for (;;)
4915#endif
4916 {
4917 /* if file exists and we didn't already find it */
4918 if ((path_with_url(file_path)
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004919 || (mch_getperm(file_path) >= 0
4920 && (search_ctx->ffsc_find_what
4921 == FINDFILE_BOTH
4922 || ((search_ctx->ffsc_find_what
4923 == FINDFILE_DIR)
4924 == mch_isdir(file_path)))))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004925#ifndef FF_VERBOSE
4926 && (ff_check_visited(
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004927 &search_ctx->ffsc_visited_list->ffvl_visited_list,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004928 file_path
4929#ifdef FEAT_PATH_EXTRA
4930 , (char_u *)""
4931#endif
4932 ) == OK)
4933#endif
4934 )
4935 {
4936#ifdef FF_VERBOSE
4937 if (ff_check_visited(
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004938 &search_ctx->ffsc_visited_list->ffvl_visited_list,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004939 file_path
4940#ifdef FEAT_PATH_EXTRA
4941 , (char_u *)""
4942#endif
4943 ) == FAIL)
4944 {
4945 if (p_verbose >= 5)
4946 {
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004947 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00004948 smsg((char_u *)"Already: %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004949 file_path);
4950 /* don't overwrite this either */
4951 msg_puts((char_u *)"\n");
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004952 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004953 }
4954 continue;
4955 }
4956#endif
4957
4958 /* push dir to examine rest of subdirs later */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004959 stackp->ffs_filearray_cur = i + 1;
4960 ff_push(search_ctx, stackp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004961
Bram Moolenaar6bab9fa2009-01-22 20:32:12 +00004962 if (!path_with_url(file_path))
4963 simplify_filename(file_path);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004964 if (mch_dirname(ff_expand_buffer, MAXPATHL)
4965 == OK)
4966 {
4967 p = shorten_fname(file_path,
4968 ff_expand_buffer);
4969 if (p != NULL)
Bram Moolenaar446cb832008-06-24 21:56:24 +00004970 STRMOVE(file_path, p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004971 }
4972#ifdef FF_VERBOSE
4973 if (p_verbose >= 5)
4974 {
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004975 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00004976 smsg((char_u *)"HIT: %s", file_path);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004977 /* don't overwrite this either */
4978 msg_puts((char_u *)"\n");
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004979 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004980 }
4981#endif
4982 return file_path;
4983 }
4984
4985#ifdef FEAT_SEARCHPATH
4986 /* Not found or found already, try next suffix. */
4987 if (*suf == NUL)
4988 break;
4989 copy_option_part(&suf, file_path + len,
4990 MAXPATHL - len, ",");
4991#endif
4992 }
4993 }
4994 }
4995#ifdef FEAT_PATH_EXTRA
4996 else
4997 {
4998 /*
4999 * still wildcards left, push the directories for further
5000 * search
5001 */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005002 for (i = stackp->ffs_filearray_cur;
5003 i < stackp->ffs_filearray_size; ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005004 {
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005005 if (!mch_isdir(stackp->ffs_filearray[i]))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005006 continue; /* not a directory */
5007
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005008 ff_push(search_ctx,
5009 ff_create_stack_element(
5010 stackp->ffs_filearray[i],
5011 rest_of_wildcards,
5012 stackp->ffs_level - 1, 0));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005013 }
5014 }
5015#endif
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005016 stackp->ffs_filearray_cur = 0;
5017 stackp->ffs_stage = 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005018 }
5019
5020#ifdef FEAT_PATH_EXTRA
5021 /*
5022 * if wildcards contains '**' we have to descent till we reach the
5023 * leaves of the directory tree.
5024 */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005025 if (STRNCMP(stackp->ffs_wc_path, "**", 2) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005026 {
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005027 for (i = stackp->ffs_filearray_cur;
5028 i < stackp->ffs_filearray_size; ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005029 {
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005030 if (fnamecmp(stackp->ffs_filearray[i],
5031 stackp->ffs_fix_path) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005032 continue; /* don't repush same directory */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005033 if (!mch_isdir(stackp->ffs_filearray[i]))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005034 continue; /* not a directory */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005035 ff_push(search_ctx,
5036 ff_create_stack_element(stackp->ffs_filearray[i],
5037 stackp->ffs_wc_path, stackp->ffs_level - 1, 1));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005038 }
5039 }
5040#endif
5041
5042 /* we are done with the current directory */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005043 ff_free_stack_element(stackp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005044
5045 }
5046
5047#ifdef FEAT_PATH_EXTRA
5048 /* If we reached this, we didn't find anything downwards.
5049 * Let's check if we should do an upward search.
5050 */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005051 if (search_ctx->ffsc_start_dir
5052 && search_ctx->ffsc_stopdirs_v != NULL && !got_int)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005053 {
5054 ff_stack_T *sptr;
5055
5056 /* is the last starting directory in the stop list? */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005057 if (ff_path_in_stoplist(search_ctx->ffsc_start_dir,
5058 (int)(path_end - search_ctx->ffsc_start_dir),
5059 search_ctx->ffsc_stopdirs_v) == TRUE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005060 break;
5061
5062 /* cut of last dir */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005063 while (path_end > search_ctx->ffsc_start_dir
5064 && vim_ispathsep(*path_end))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005065 path_end--;
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005066 while (path_end > search_ctx->ffsc_start_dir
5067 && !vim_ispathsep(path_end[-1]))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005068 path_end--;
5069 *path_end = 0;
5070 path_end--;
5071
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005072 if (*search_ctx->ffsc_start_dir == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005073 break;
5074
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005075 STRCPY(file_path, search_ctx->ffsc_start_dir);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005076 add_pathsep(file_path);
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005077 STRCAT(file_path, search_ctx->ffsc_fix_path);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005078
5079 /* create a new stack entry */
5080 sptr = ff_create_stack_element(file_path,
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005081 search_ctx->ffsc_wc_path, search_ctx->ffsc_level, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005082 if (sptr == NULL)
5083 break;
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005084 ff_push(search_ctx, sptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005085 }
5086 else
5087 break;
5088 }
5089#endif
5090
5091 vim_free(file_path);
5092 return NULL;
5093}
5094
5095/*
5096 * Free the list of lists of visited files and directories
5097 * Can handle it if the passed search_context is NULL;
5098 */
5099 void
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005100vim_findfile_free_visited(search_ctx_arg)
5101 void *search_ctx_arg;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005102{
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005103 ff_search_ctx_T *search_ctx;
5104
5105 if (search_ctx_arg == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005106 return;
5107
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005108 search_ctx = (ff_search_ctx_T *)search_ctx_arg;
5109 vim_findfile_free_visited_list(&search_ctx->ffsc_visited_lists_list);
5110 vim_findfile_free_visited_list(&search_ctx->ffsc_dir_visited_lists_list);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005111}
5112
5113 static void
5114vim_findfile_free_visited_list(list_headp)
5115 ff_visited_list_hdr_T **list_headp;
5116{
5117 ff_visited_list_hdr_T *vp;
5118
5119 while (*list_headp != NULL)
5120 {
5121 vp = (*list_headp)->ffvl_next;
5122 ff_free_visited_list((*list_headp)->ffvl_visited_list);
5123
5124 vim_free((*list_headp)->ffvl_filename);
5125 vim_free(*list_headp);
5126 *list_headp = vp;
5127 }
5128 *list_headp = NULL;
5129}
5130
5131 static void
5132ff_free_visited_list(vl)
5133 ff_visited_T *vl;
5134{
5135 ff_visited_T *vp;
5136
5137 while (vl != NULL)
5138 {
5139 vp = vl->ffv_next;
5140#ifdef FEAT_PATH_EXTRA
5141 vim_free(vl->ffv_wc_path);
5142#endif
5143 vim_free(vl);
5144 vl = vp;
5145 }
5146 vl = NULL;
5147}
5148
5149/*
5150 * Returns the already visited list for the given filename. If none is found it
5151 * allocates a new one.
5152 */
5153 static ff_visited_list_hdr_T*
5154ff_get_visited_list(filename, list_headp)
5155 char_u *filename;
5156 ff_visited_list_hdr_T **list_headp;
5157{
5158 ff_visited_list_hdr_T *retptr = NULL;
5159
5160 /* check if a visited list for the given filename exists */
5161 if (*list_headp != NULL)
5162 {
5163 retptr = *list_headp;
5164 while (retptr != NULL)
5165 {
5166 if (fnamecmp(filename, retptr->ffvl_filename) == 0)
5167 {
5168#ifdef FF_VERBOSE
5169 if (p_verbose >= 5)
5170 {
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00005171 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00005172 smsg((char_u *)"ff_get_visited_list: FOUND list for %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005173 filename);
5174 /* don't overwrite this either */
5175 msg_puts((char_u *)"\n");
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00005176 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005177 }
5178#endif
5179 return retptr;
5180 }
5181 retptr = retptr->ffvl_next;
5182 }
5183 }
5184
5185#ifdef FF_VERBOSE
5186 if (p_verbose >= 5)
5187 {
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00005188 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00005189 smsg((char_u *)"ff_get_visited_list: new list for %s", filename);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005190 /* don't overwrite this either */
5191 msg_puts((char_u *)"\n");
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00005192 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005193 }
5194#endif
5195
5196 /*
5197 * if we reach this we didn't find a list and we have to allocate new list
5198 */
5199 retptr = (ff_visited_list_hdr_T*)alloc((unsigned)sizeof(*retptr));
5200 if (retptr == NULL)
5201 return NULL;
5202
5203 retptr->ffvl_visited_list = NULL;
5204 retptr->ffvl_filename = vim_strsave(filename);
5205 if (retptr->ffvl_filename == NULL)
5206 {
5207 vim_free(retptr);
5208 return NULL;
5209 }
5210 retptr->ffvl_next = *list_headp;
5211 *list_headp = retptr;
5212
5213 return retptr;
5214}
5215
5216#ifdef FEAT_PATH_EXTRA
5217/*
5218 * check if two wildcard paths are equal. Returns TRUE or FALSE.
5219 * They are equal if:
5220 * - both paths are NULL
5221 * - they have the same length
5222 * - char by char comparison is OK
5223 * - the only differences are in the counters behind a '**', so
5224 * '**\20' is equal to '**\24'
5225 */
5226 static int
5227ff_wc_equal(s1, s2)
5228 char_u *s1;
5229 char_u *s2;
5230{
5231 int i;
5232
5233 if (s1 == s2)
5234 return TRUE;
5235
5236 if (s1 == NULL || s2 == NULL)
5237 return FALSE;
5238
5239 if (STRLEN(s1) != STRLEN(s2))
5240 return FAIL;
5241
5242 for (i = 0; s1[i] != NUL && s2[i] != NUL; i++)
5243 {
5244 if (s1[i] != s2[i]
5245#ifdef CASE_INSENSITIVE_FILENAME
5246 && TOUPPER_LOC(s1[i]) != TOUPPER_LOC(s2[i])
5247#endif
5248 )
5249 {
5250 if (i >= 2)
5251 if (s1[i-1] == '*' && s1[i-2] == '*')
5252 continue;
5253 else
5254 return FAIL;
5255 else
5256 return FAIL;
5257 }
5258 }
5259 return TRUE;
5260}
5261#endif
5262
5263/*
5264 * maintains the list of already visited files and dirs
5265 * returns FAIL if the given file/dir is already in the list
5266 * returns OK if it is newly added
5267 *
5268 * TODO: What to do on memory allocation problems?
5269 * -> return TRUE - Better the file is found several times instead of
5270 * never.
5271 */
5272 static int
5273ff_check_visited(visited_list, fname
5274#ifdef FEAT_PATH_EXTRA
5275 , wc_path
5276#endif
5277 )
5278 ff_visited_T **visited_list;
5279 char_u *fname;
5280#ifdef FEAT_PATH_EXTRA
5281 char_u *wc_path;
5282#endif
5283{
5284 ff_visited_T *vp;
5285#ifdef UNIX
5286 struct stat st;
5287 int url = FALSE;
5288#endif
5289
5290 /* For an URL we only compare the name, otherwise we compare the
5291 * device/inode (unix) or the full path name (not Unix). */
5292 if (path_with_url(fname))
5293 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00005294 vim_strncpy(ff_expand_buffer, fname, MAXPATHL - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005295#ifdef UNIX
5296 url = TRUE;
5297#endif
5298 }
5299 else
5300 {
5301 ff_expand_buffer[0] = NUL;
5302#ifdef UNIX
5303 if (mch_stat((char *)fname, &st) < 0)
5304#else
5305 if (vim_FullName(fname, ff_expand_buffer, MAXPATHL, TRUE) == FAIL)
5306#endif
5307 return FAIL;
5308 }
5309
5310 /* check against list of already visited files */
5311 for (vp = *visited_list; vp != NULL; vp = vp->ffv_next)
5312 {
5313 if (
5314#ifdef UNIX
Bram Moolenaare1fbddc2009-05-16 19:07:03 +00005315 !url ? (vp->ffv_dev_valid && vp->ffv_dev == st.st_dev
5316 && vp->ffv_ino == st.st_ino)
5317 :
Bram Moolenaar071d4272004-06-13 20:20:40 +00005318#endif
5319 fnamecmp(vp->ffv_fname, ff_expand_buffer) == 0
5320 )
5321 {
5322#ifdef FEAT_PATH_EXTRA
5323 /* are the wildcard parts equal */
5324 if (ff_wc_equal(vp->ffv_wc_path, wc_path) == TRUE)
5325#endif
5326 /* already visited */
5327 return FAIL;
5328 }
5329 }
5330
5331 /*
5332 * New file/dir. Add it to the list of visited files/dirs.
5333 */
5334 vp = (ff_visited_T *)alloc((unsigned)(sizeof(ff_visited_T)
5335 + STRLEN(ff_expand_buffer)));
5336
5337 if (vp != NULL)
5338 {
5339#ifdef UNIX
5340 if (!url)
5341 {
Bram Moolenaare1fbddc2009-05-16 19:07:03 +00005342 vp->ffv_dev_valid = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005343 vp->ffv_ino = st.st_ino;
5344 vp->ffv_dev = st.st_dev;
5345 vp->ffv_fname[0] = NUL;
5346 }
5347 else
5348 {
Bram Moolenaare1fbddc2009-05-16 19:07:03 +00005349 vp->ffv_dev_valid = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005350#endif
5351 STRCPY(vp->ffv_fname, ff_expand_buffer);
5352#ifdef UNIX
5353 }
5354#endif
5355#ifdef FEAT_PATH_EXTRA
5356 if (wc_path != NULL)
5357 vp->ffv_wc_path = vim_strsave(wc_path);
5358 else
5359 vp->ffv_wc_path = NULL;
5360#endif
5361
5362 vp->ffv_next = *visited_list;
5363 *visited_list = vp;
5364 }
5365
5366 return OK;
5367}
5368
5369/*
5370 * create stack element from given path pieces
5371 */
5372 static ff_stack_T *
5373ff_create_stack_element(fix_part,
5374#ifdef FEAT_PATH_EXTRA
5375 wc_part,
5376#endif
5377 level, star_star_empty)
5378 char_u *fix_part;
5379#ifdef FEAT_PATH_EXTRA
5380 char_u *wc_part;
5381#endif
5382 int level;
5383 int star_star_empty;
5384{
5385 ff_stack_T *new;
5386
5387 new = (ff_stack_T *)alloc((unsigned)sizeof(ff_stack_T));
5388 if (new == NULL)
5389 return NULL;
5390
5391 new->ffs_prev = NULL;
5392 new->ffs_filearray = NULL;
5393 new->ffs_filearray_size = 0;
5394 new->ffs_filearray_cur = 0;
5395 new->ffs_stage = 0;
5396 new->ffs_level = level;
5397 new->ffs_star_star_empty = star_star_empty;;
5398
5399 /* the following saves NULL pointer checks in vim_findfile */
5400 if (fix_part == NULL)
5401 fix_part = (char_u *)"";
5402 new->ffs_fix_path = vim_strsave(fix_part);
5403
5404#ifdef FEAT_PATH_EXTRA
5405 if (wc_part == NULL)
5406 wc_part = (char_u *)"";
5407 new->ffs_wc_path = vim_strsave(wc_part);
5408#endif
5409
5410 if (new->ffs_fix_path == NULL
5411#ifdef FEAT_PATH_EXTRA
5412 || new->ffs_wc_path == NULL
5413#endif
5414 )
5415 {
5416 ff_free_stack_element(new);
5417 new = NULL;
5418 }
5419
5420 return new;
5421}
5422
5423/*
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005424 * Push a dir on the directory stack.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005425 */
5426 static void
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005427ff_push(search_ctx, stack_ptr)
5428 ff_search_ctx_T *search_ctx;
5429 ff_stack_T *stack_ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005430{
5431 /* check for NULL pointer, not to return an error to the user, but
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005432 * to prevent a crash */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005433 if (stack_ptr != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005434 {
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005435 stack_ptr->ffs_prev = search_ctx->ffsc_stack_ptr;
5436 search_ctx->ffsc_stack_ptr = stack_ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005437 }
5438}
5439
5440/*
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005441 * Pop a dir from the directory stack.
5442 * Returns NULL if stack is empty.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005443 */
5444 static ff_stack_T *
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005445ff_pop(search_ctx)
5446 ff_search_ctx_T *search_ctx;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005447{
5448 ff_stack_T *sptr;
5449
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005450 sptr = search_ctx->ffsc_stack_ptr;
5451 if (search_ctx->ffsc_stack_ptr != NULL)
5452 search_ctx->ffsc_stack_ptr = search_ctx->ffsc_stack_ptr->ffs_prev;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005453
5454 return sptr;
5455}
5456
5457/*
5458 * free the given stack element
5459 */
5460 static void
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005461ff_free_stack_element(stack_ptr)
5462 ff_stack_T *stack_ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005463{
5464 /* vim_free handles possible NULL pointers */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005465 vim_free(stack_ptr->ffs_fix_path);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005466#ifdef FEAT_PATH_EXTRA
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005467 vim_free(stack_ptr->ffs_wc_path);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005468#endif
5469
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005470 if (stack_ptr->ffs_filearray != NULL)
5471 FreeWild(stack_ptr->ffs_filearray_size, stack_ptr->ffs_filearray);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005472
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005473 vim_free(stack_ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005474}
5475
5476/*
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005477 * Clear the search context, but NOT the visited list.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005478 */
5479 static void
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005480ff_clear(search_ctx)
5481 ff_search_ctx_T *search_ctx;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005482{
5483 ff_stack_T *sptr;
5484
5485 /* clear up stack */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005486 while ((sptr = ff_pop(search_ctx)) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005487 ff_free_stack_element(sptr);
5488
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005489 vim_free(search_ctx->ffsc_file_to_search);
5490 vim_free(search_ctx->ffsc_start_dir);
5491 vim_free(search_ctx->ffsc_fix_path);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005492#ifdef FEAT_PATH_EXTRA
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005493 vim_free(search_ctx->ffsc_wc_path);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005494#endif
5495
5496#ifdef FEAT_PATH_EXTRA
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005497 if (search_ctx->ffsc_stopdirs_v != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005498 {
5499 int i = 0;
5500
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005501 while (search_ctx->ffsc_stopdirs_v[i] != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005502 {
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005503 vim_free(search_ctx->ffsc_stopdirs_v[i]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005504 i++;
5505 }
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005506 vim_free(search_ctx->ffsc_stopdirs_v);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005507 }
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005508 search_ctx->ffsc_stopdirs_v = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005509#endif
5510
5511 /* reset everything */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005512 search_ctx->ffsc_file_to_search = NULL;
5513 search_ctx->ffsc_start_dir = NULL;
5514 search_ctx->ffsc_fix_path = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005515#ifdef FEAT_PATH_EXTRA
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005516 search_ctx->ffsc_wc_path = NULL;
5517 search_ctx->ffsc_level = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005518#endif
5519}
5520
5521#ifdef FEAT_PATH_EXTRA
5522/*
5523 * check if the given path is in the stopdirs
5524 * returns TRUE if yes else FALSE
5525 */
5526 static int
5527ff_path_in_stoplist(path, path_len, stopdirs_v)
5528 char_u *path;
5529 int path_len;
5530 char_u **stopdirs_v;
5531{
5532 int i = 0;
5533
5534 /* eat up trailing path separators, except the first */
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00005535 while (path_len > 1 && vim_ispathsep(path[path_len - 1]))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005536 path_len--;
5537
5538 /* if no path consider it as match */
5539 if (path_len == 0)
5540 return TRUE;
5541
5542 for (i = 0; stopdirs_v[i] != NULL; i++)
5543 {
5544 if ((int)STRLEN(stopdirs_v[i]) > path_len)
5545 {
5546 /* match for parent directory. So '/home' also matches
5547 * '/home/rks'. Check for PATHSEP in stopdirs_v[i], else
5548 * '/home/r' would also match '/home/rks'
5549 */
5550 if (fnamencmp(stopdirs_v[i], path, path_len) == 0
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00005551 && vim_ispathsep(stopdirs_v[i][path_len]))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005552 return TRUE;
5553 }
5554 else
5555 {
5556 if (fnamecmp(stopdirs_v[i], path) == 0)
5557 return TRUE;
5558 }
5559 }
5560 return FALSE;
5561}
5562#endif
5563
5564#if defined(FEAT_SEARCHPATH) || defined(PROTO)
5565/*
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005566 * Find the file name "ptr[len]" in the path. Also finds directory names.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005567 *
5568 * On the first call set the parameter 'first' to TRUE to initialize
5569 * the search. For repeating calls to FALSE.
5570 *
5571 * Repeating calls will return other files called 'ptr[len]' from the path.
5572 *
5573 * Only on the first call 'ptr' and 'len' are used. For repeating calls they
5574 * don't need valid values.
5575 *
5576 * If nothing found on the first call the option FNAME_MESS will issue the
5577 * message:
5578 * 'Can't find file "<file>" in path'
5579 * On repeating calls:
5580 * 'No more file "<file>" found in path'
5581 *
5582 * options:
5583 * FNAME_MESS give error message when not found
5584 *
5585 * Uses NameBuff[]!
5586 *
5587 * Returns an allocated string for the file name. NULL for error.
5588 *
5589 */
5590 char_u *
5591find_file_in_path(ptr, len, options, first, rel_fname)
5592 char_u *ptr; /* file name */
5593 int len; /* length of file name */
5594 int options;
5595 int first; /* use count'th matching file name */
5596 char_u *rel_fname; /* file name searching relative to */
5597{
5598 return find_file_in_path_option(ptr, len, options, first,
5599 *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path,
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005600 FINDFILE_BOTH, rel_fname, curbuf->b_p_sua);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005601}
5602
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005603static char_u *ff_file_to_find = NULL;
5604static void *fdip_search_ctx = NULL;
5605
5606#if defined(EXITFREE)
5607 static void
5608free_findfile()
5609{
5610 vim_free(ff_file_to_find);
5611 vim_findfile_cleanup(fdip_search_ctx);
5612}
5613#endif
5614
Bram Moolenaar071d4272004-06-13 20:20:40 +00005615/*
5616 * Find the directory name "ptr[len]" in the path.
5617 *
5618 * options:
5619 * FNAME_MESS give error message when not found
5620 *
5621 * Uses NameBuff[]!
5622 *
5623 * Returns an allocated string for the file name. NULL for error.
5624 */
5625 char_u *
5626find_directory_in_path(ptr, len, options, rel_fname)
5627 char_u *ptr; /* file name */
5628 int len; /* length of file name */
5629 int options;
5630 char_u *rel_fname; /* file name searching relative to */
5631{
5632 return find_file_in_path_option(ptr, len, options, TRUE, p_cdpath,
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005633 FINDFILE_DIR, rel_fname, (char_u *)"");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005634}
5635
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00005636 char_u *
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005637find_file_in_path_option(ptr, len, options, first, path_option, find_what, rel_fname, suffixes)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005638 char_u *ptr; /* file name */
5639 int len; /* length of file name */
5640 int options;
5641 int first; /* use count'th matching file name */
5642 char_u *path_option; /* p_path or p_cdpath */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005643 int find_what; /* FINDFILE_FILE, _DIR or _BOTH */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005644 char_u *rel_fname; /* file name we are looking relative to. */
Bram Moolenaar433f7c82006-03-21 21:29:36 +00005645 char_u *suffixes; /* list of suffixes, 'suffixesadd' option */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005646{
Bram Moolenaar071d4272004-06-13 20:20:40 +00005647 static char_u *dir;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005648 static int did_findfile_init = FALSE;
5649 char_u save_char;
5650 char_u *file_name = NULL;
5651 char_u *buf = NULL;
5652 int rel_to_curdir;
5653#ifdef AMIGA
5654 struct Process *proc = (struct Process *)FindTask(0L);
5655 APTR save_winptr = proc->pr_WindowPtr;
5656
5657 /* Avoid a requester here for a volume that doesn't exist. */
5658 proc->pr_WindowPtr = (APTR)-1L;
5659#endif
5660
5661 if (first == TRUE)
5662 {
5663 /* copy file name into NameBuff, expanding environment variables */
5664 save_char = ptr[len];
5665 ptr[len] = NUL;
5666 expand_env(ptr, NameBuff, MAXPATHL);
5667 ptr[len] = save_char;
5668
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005669 vim_free(ff_file_to_find);
5670 ff_file_to_find = vim_strsave(NameBuff);
5671 if (ff_file_to_find == NULL) /* out of memory */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005672 {
5673 file_name = NULL;
5674 goto theend;
5675 }
5676 }
5677
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005678 rel_to_curdir = (ff_file_to_find[0] == '.'
5679 && (ff_file_to_find[1] == NUL
5680 || vim_ispathsep(ff_file_to_find[1])
5681 || (ff_file_to_find[1] == '.'
5682 && (ff_file_to_find[2] == NUL
5683 || vim_ispathsep(ff_file_to_find[2])))));
5684 if (vim_isAbsName(ff_file_to_find)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005685 /* "..", "../path", "." and "./path": don't use the path_option */
5686 || rel_to_curdir
5687#if defined(MSWIN) || defined(MSDOS) || defined(OS2)
5688 /* handle "\tmp" as absolute path */
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005689 || vim_ispathsep(ff_file_to_find[0])
Bram Moolenaar21160b92009-11-11 15:56:10 +00005690 /* handle "c:name" as absolute path */
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005691 || (ff_file_to_find[0] != NUL && ff_file_to_find[1] == ':')
Bram Moolenaar071d4272004-06-13 20:20:40 +00005692#endif
5693#ifdef AMIGA
5694 /* handle ":tmp" as absolute path */
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005695 || ff_file_to_find[0] == ':'
Bram Moolenaar071d4272004-06-13 20:20:40 +00005696#endif
5697 )
5698 {
5699 /*
5700 * Absolute path, no need to use "path_option".
5701 * If this is not a first call, return NULL. We already returned a
5702 * filename on the first call.
5703 */
5704 if (first == TRUE)
5705 {
5706 int l;
5707 int run;
5708
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005709 if (path_with_url(ff_file_to_find))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005710 {
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005711 file_name = vim_strsave(ff_file_to_find);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005712 goto theend;
5713 }
5714
5715 /* When FNAME_REL flag given first use the directory of the file.
5716 * Otherwise or when this fails use the current directory. */
5717 for (run = 1; run <= 2; ++run)
5718 {
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005719 l = (int)STRLEN(ff_file_to_find);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005720 if (run == 1
5721 && rel_to_curdir
5722 && (options & FNAME_REL)
5723 && rel_fname != NULL
5724 && STRLEN(rel_fname) + l < MAXPATHL)
5725 {
5726 STRCPY(NameBuff, rel_fname);
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005727 STRCPY(gettail(NameBuff), ff_file_to_find);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005728 l = (int)STRLEN(NameBuff);
5729 }
5730 else
5731 {
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005732 STRCPY(NameBuff, ff_file_to_find);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005733 run = 2;
5734 }
5735
5736 /* When the file doesn't exist, try adding parts of
5737 * 'suffixesadd'. */
Bram Moolenaar433f7c82006-03-21 21:29:36 +00005738 buf = suffixes;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005739 for (;;)
5740 {
5741 if (
5742#ifdef DJGPP
5743 /* "C:" by itself will fail for mch_getperm(),
5744 * assume it's always valid. */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005745 (find_what != FINDFILE_FILE && NameBuff[0] != NUL
Bram Moolenaar071d4272004-06-13 20:20:40 +00005746 && NameBuff[1] == ':'
5747 && NameBuff[2] == NUL) ||
5748#endif
5749 (mch_getperm(NameBuff) >= 0
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005750 && (find_what == FINDFILE_BOTH
5751 || ((find_what == FINDFILE_DIR)
5752 == mch_isdir(NameBuff)))))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005753 {
5754 file_name = vim_strsave(NameBuff);
5755 goto theend;
5756 }
5757 if (*buf == NUL)
5758 break;
5759 copy_option_part(&buf, NameBuff + l, MAXPATHL - l, ",");
5760 }
5761 }
5762 }
5763 }
5764 else
5765 {
5766 /*
5767 * Loop over all paths in the 'path' or 'cdpath' option.
5768 * When "first" is set, first setup to the start of the option.
5769 * Otherwise continue to find the next match.
5770 */
5771 if (first == TRUE)
5772 {
5773 /* vim_findfile_free_visited can handle a possible NULL pointer */
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005774 vim_findfile_free_visited(fdip_search_ctx);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005775 dir = path_option;
5776 did_findfile_init = FALSE;
5777 }
5778
5779 for (;;)
5780 {
5781 if (did_findfile_init)
5782 {
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005783 file_name = vim_findfile(fdip_search_ctx);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005784 if (file_name != NULL)
5785 break;
5786
5787 did_findfile_init = FALSE;
5788 }
5789 else
5790 {
5791 char_u *r_ptr;
5792
5793 if (dir == NULL || *dir == NUL)
5794 {
5795 /* We searched all paths of the option, now we can
5796 * free the search context. */
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005797 vim_findfile_cleanup(fdip_search_ctx);
5798 fdip_search_ctx = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005799 break;
5800 }
5801
5802 if ((buf = alloc((int)(MAXPATHL))) == NULL)
5803 break;
5804
5805 /* copy next path */
5806 buf[0] = 0;
5807 copy_option_part(&dir, buf, MAXPATHL, " ,");
5808
5809#ifdef FEAT_PATH_EXTRA
5810 /* get the stopdir string */
5811 r_ptr = vim_findfile_stopdir(buf);
5812#else
5813 r_ptr = NULL;
5814#endif
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005815 fdip_search_ctx = vim_findfile_init(buf, ff_file_to_find,
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005816 r_ptr, 100, FALSE, find_what,
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005817 fdip_search_ctx, FALSE, rel_fname);
5818 if (fdip_search_ctx != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005819 did_findfile_init = TRUE;
5820 vim_free(buf);
5821 }
5822 }
5823 }
5824 if (file_name == NULL && (options & FNAME_MESS))
5825 {
5826 if (first == TRUE)
5827 {
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005828 if (find_what == FINDFILE_DIR)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005829 EMSG2(_("E344: Can't find directory \"%s\" in cdpath"),
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005830 ff_file_to_find);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005831 else
5832 EMSG2(_("E345: Can't find file \"%s\" in path"),
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005833 ff_file_to_find);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005834 }
5835 else
5836 {
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005837 if (find_what == FINDFILE_DIR)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005838 EMSG2(_("E346: No more directory \"%s\" found in cdpath"),
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005839 ff_file_to_find);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005840 else
5841 EMSG2(_("E347: No more file \"%s\" found in path"),
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005842 ff_file_to_find);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005843 }
5844 }
5845
5846theend:
5847#ifdef AMIGA
5848 proc->pr_WindowPtr = save_winptr;
5849#endif
5850 return file_name;
5851}
5852
5853#endif /* FEAT_SEARCHPATH */
5854
5855/*
5856 * Change directory to "new_dir". If FEAT_SEARCHPATH is defined, search
5857 * 'cdpath' for relative directory names, otherwise just mch_chdir().
5858 */
5859 int
5860vim_chdir(new_dir)
5861 char_u *new_dir;
5862{
5863#ifndef FEAT_SEARCHPATH
5864 return mch_chdir((char *)new_dir);
5865#else
5866 char_u *dir_name;
5867 int r;
5868
5869 dir_name = find_directory_in_path(new_dir, (int)STRLEN(new_dir),
5870 FNAME_MESS, curbuf->b_ffname);
5871 if (dir_name == NULL)
5872 return -1;
5873 r = mch_chdir((char *)dir_name);
5874 vim_free(dir_name);
5875 return r;
5876#endif
5877}
5878
5879/*
Bram Moolenaarbbebc852005-07-18 21:47:53 +00005880 * Get user name from machine-specific function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005881 * Returns the user name in "buf[len]".
Bram Moolenaarbbebc852005-07-18 21:47:53 +00005882 * Some systems are quite slow in obtaining the user name (Windows NT), thus
5883 * cache the result.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005884 * Returns OK or FAIL.
5885 */
5886 int
5887get_user_name(buf, len)
5888 char_u *buf;
5889 int len;
5890{
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005891 if (username == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005892 {
5893 if (mch_get_user_name(buf, len) == FAIL)
5894 return FAIL;
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005895 username = vim_strsave(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005896 }
5897 else
Bram Moolenaarbbebc852005-07-18 21:47:53 +00005898 vim_strncpy(buf, username, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005899 return OK;
5900}
5901
5902#ifndef HAVE_QSORT
5903/*
5904 * Our own qsort(), for systems that don't have it.
5905 * It's simple and slow. From the K&R C book.
5906 */
5907 void
5908qsort(base, elm_count, elm_size, cmp)
5909 void *base;
5910 size_t elm_count;
5911 size_t elm_size;
5912 int (*cmp) __ARGS((const void *, const void *));
5913{
5914 char_u *buf;
5915 char_u *p1;
5916 char_u *p2;
5917 int i, j;
5918 int gap;
5919
5920 buf = alloc((unsigned)elm_size);
5921 if (buf == NULL)
5922 return;
5923
5924 for (gap = elm_count / 2; gap > 0; gap /= 2)
5925 for (i = gap; i < elm_count; ++i)
5926 for (j = i - gap; j >= 0; j -= gap)
5927 {
5928 /* Compare the elements. */
5929 p1 = (char_u *)base + j * elm_size;
5930 p2 = (char_u *)base + (j + gap) * elm_size;
5931 if ((*cmp)((void *)p1, (void *)p2) <= 0)
5932 break;
Bram Moolenaar21160b92009-11-11 15:56:10 +00005933 /* Exchange the elements. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005934 mch_memmove(buf, p1, elm_size);
5935 mch_memmove(p1, p2, elm_size);
5936 mch_memmove(p2, buf, elm_size);
5937 }
5938
5939 vim_free(buf);
5940}
5941#endif
5942
Bram Moolenaar071d4272004-06-13 20:20:40 +00005943/*
5944 * Sort an array of strings.
5945 */
5946static int
5947#ifdef __BORLANDC__
5948_RTLENTRYF
5949#endif
5950sort_compare __ARGS((const void *s1, const void *s2));
5951
5952 static int
5953#ifdef __BORLANDC__
5954_RTLENTRYF
5955#endif
5956sort_compare(s1, s2)
5957 const void *s1;
5958 const void *s2;
5959{
5960 return STRCMP(*(char **)s1, *(char **)s2);
5961}
5962
5963 void
5964sort_strings(files, count)
5965 char_u **files;
5966 int count;
5967{
5968 qsort((void *)files, (size_t)count, sizeof(char_u *), sort_compare);
5969}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005970
5971#if !defined(NO_EXPANDPATH) || defined(PROTO)
5972/*
5973 * Compare path "p[]" to "q[]".
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005974 * If "maxlen" >= 0 compare "p[maxlen]" to "q[maxlen]"
Bram Moolenaar071d4272004-06-13 20:20:40 +00005975 * Return value like strcmp(p, q), but consider path separators.
5976 */
5977 int
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005978pathcmp(p, q, maxlen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005979 const char *p, *q;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005980 int maxlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005981{
5982 int i;
Bram Moolenaar86b68352004-12-27 21:59:20 +00005983 const char *s = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005984
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005985 for (i = 0; maxlen < 0 || i < maxlen; ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005986 {
5987 /* End of "p": check if "q" also ends or just has a slash. */
5988 if (p[i] == NUL)
5989 {
5990 if (q[i] == NUL) /* full match */
5991 return 0;
5992 s = q;
5993 break;
5994 }
5995
5996 /* End of "q": check if "p" just has a slash. */
5997 if (q[i] == NUL)
5998 {
5999 s = p;
6000 break;
6001 }
6002
6003 if (
6004#ifdef CASE_INSENSITIVE_FILENAME
6005 TOUPPER_LOC(p[i]) != TOUPPER_LOC(q[i])
6006#else
6007 p[i] != q[i]
6008#endif
6009#ifdef BACKSLASH_IN_FILENAME
6010 /* consider '/' and '\\' to be equal */
6011 && !((p[i] == '/' && q[i] == '\\')
6012 || (p[i] == '\\' && q[i] == '/'))
6013#endif
6014 )
6015 {
6016 if (vim_ispathsep(p[i]))
6017 return -1;
6018 if (vim_ispathsep(q[i]))
6019 return 1;
6020 return ((char_u *)p)[i] - ((char_u *)q)[i]; /* no match */
6021 }
6022 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00006023 if (s == NULL) /* "i" ran into "maxlen" */
6024 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006025
6026 /* ignore a trailing slash, but not "//" or ":/" */
Bram Moolenaar86b68352004-12-27 21:59:20 +00006027 if (s[i + 1] == NUL
6028 && i > 0
6029 && !after_pathsep((char_u *)s, (char_u *)s + i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006030#ifdef BACKSLASH_IN_FILENAME
Bram Moolenaar86b68352004-12-27 21:59:20 +00006031 && (s[i] == '/' || s[i] == '\\')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006032#else
Bram Moolenaar86b68352004-12-27 21:59:20 +00006033 && s[i] == '/'
Bram Moolenaar071d4272004-06-13 20:20:40 +00006034#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00006035 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00006036 return 0; /* match with trailing slash */
6037 if (s == q)
6038 return -1; /* no match */
6039 return 1;
6040}
6041#endif
6042
Bram Moolenaar071d4272004-06-13 20:20:40 +00006043/*
6044 * The putenv() implementation below comes from the "screen" program.
6045 * Included with permission from Juergen Weigert.
6046 * See pty.c for the copyright notice.
6047 */
6048
6049/*
6050 * putenv -- put value into environment
6051 *
6052 * Usage: i = putenv (string)
6053 * int i;
6054 * char *string;
6055 *
6056 * where string is of the form <name>=<value>.
6057 * Putenv returns 0 normally, -1 on error (not enough core for malloc).
6058 *
6059 * Putenv may need to add a new name into the environment, or to
6060 * associate a value longer than the current value with a particular
6061 * name. So, to make life simpler, putenv() copies your entire
6062 * environment into the heap (i.e. malloc()) from the stack
6063 * (i.e. where it resides when your process is initiated) the first
6064 * time you call it.
6065 *
6066 * (history removed, not very interesting. See the "screen" sources.)
6067 */
6068
6069#if !defined(HAVE_SETENV) && !defined(HAVE_PUTENV)
6070
6071#define EXTRASIZE 5 /* increment to add to env. size */
6072
6073static int envsize = -1; /* current size of environment */
6074#ifndef MACOS_CLASSIC
6075extern
6076#endif
6077 char **environ; /* the global which is your env. */
6078
6079static int findenv __ARGS((char *name)); /* look for a name in the env. */
6080static int newenv __ARGS((void)); /* copy env. from stack to heap */
6081static int moreenv __ARGS((void)); /* incr. size of env. */
6082
6083 int
6084putenv(string)
6085 const char *string;
6086{
6087 int i;
6088 char *p;
6089
6090 if (envsize < 0)
6091 { /* first time putenv called */
6092 if (newenv() < 0) /* copy env. to heap */
6093 return -1;
6094 }
6095
6096 i = findenv((char *)string); /* look for name in environment */
6097
6098 if (i < 0)
6099 { /* name must be added */
6100 for (i = 0; environ[i]; i++);
6101 if (i >= (envsize - 1))
6102 { /* need new slot */
6103 if (moreenv() < 0)
6104 return -1;
6105 }
6106 p = (char *)alloc((unsigned)(strlen(string) + 1));
6107 if (p == NULL) /* not enough core */
6108 return -1;
6109 environ[i + 1] = 0; /* new end of env. */
6110 }
6111 else
6112 { /* name already in env. */
6113 p = vim_realloc(environ[i], strlen(string) + 1);
6114 if (p == NULL)
6115 return -1;
6116 }
6117 sprintf(p, "%s", string); /* copy into env. */
6118 environ[i] = p;
6119
6120 return 0;
6121}
6122
6123 static int
6124findenv(name)
6125 char *name;
6126{
6127 char *namechar, *envchar;
6128 int i, found;
6129
6130 found = 0;
6131 for (i = 0; environ[i] && !found; i++)
6132 {
6133 envchar = environ[i];
6134 namechar = name;
6135 while (*namechar && *namechar != '=' && (*namechar == *envchar))
6136 {
6137 namechar++;
6138 envchar++;
6139 }
6140 found = ((*namechar == '\0' || *namechar == '=') && *envchar == '=');
6141 }
6142 return found ? i - 1 : -1;
6143}
6144
6145 static int
6146newenv()
6147{
6148 char **env, *elem;
6149 int i, esize;
6150
6151#ifdef MACOS
6152 /* for Mac a new, empty environment is created */
6153 i = 0;
6154#else
6155 for (i = 0; environ[i]; i++)
6156 ;
6157#endif
6158 esize = i + EXTRASIZE + 1;
6159 env = (char **)alloc((unsigned)(esize * sizeof (elem)));
6160 if (env == NULL)
6161 return -1;
6162
6163#ifndef MACOS
6164 for (i = 0; environ[i]; i++)
6165 {
6166 elem = (char *)alloc((unsigned)(strlen(environ[i]) + 1));
6167 if (elem == NULL)
6168 return -1;
6169 env[i] = elem;
6170 strcpy(elem, environ[i]);
6171 }
6172#endif
6173
6174 env[i] = 0;
6175 environ = env;
6176 envsize = esize;
6177 return 0;
6178}
6179
6180 static int
6181moreenv()
6182{
6183 int esize;
6184 char **env;
6185
6186 esize = envsize + EXTRASIZE;
6187 env = (char **)vim_realloc((char *)environ, esize * sizeof (*env));
6188 if (env == 0)
6189 return -1;
6190 environ = env;
6191 envsize = esize;
6192 return 0;
6193}
6194
6195# ifdef USE_VIMPTY_GETENV
6196 char_u *
6197vimpty_getenv(string)
6198 const char_u *string;
6199{
6200 int i;
6201 char_u *p;
6202
6203 if (envsize < 0)
6204 return NULL;
6205
6206 i = findenv((char *)string);
6207
6208 if (i < 0)
6209 return NULL;
6210
6211 p = vim_strchr((char_u *)environ[i], '=');
6212 return (p + 1);
6213}
6214# endif
6215
6216#endif /* !defined(HAVE_SETENV) && !defined(HAVE_PUTENV) */
Bram Moolenaarc4a06d32005-06-07 21:04:49 +00006217
Bram Moolenaarc4956c82006-03-12 21:58:43 +00006218#if defined(FEAT_EVAL) || defined(FEAT_SPELL) || defined(PROTO)
Bram Moolenaarc4a06d32005-06-07 21:04:49 +00006219/*
6220 * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
6221 * rights to write into.
6222 */
6223 int
6224filewritable(fname)
6225 char_u *fname;
6226{
6227 int retval = 0;
6228#if defined(UNIX) || defined(VMS)
6229 int perm = 0;
6230#endif
6231
6232#if defined(UNIX) || defined(VMS)
6233 perm = mch_getperm(fname);
6234#endif
6235#ifndef MACOS_CLASSIC /* TODO: get either mch_writable or mch_access */
6236 if (
6237# ifdef WIN3264
6238 mch_writable(fname) &&
6239# else
6240# if defined(UNIX) || defined(VMS)
6241 (perm & 0222) &&
6242# endif
6243# endif
6244 mch_access((char *)fname, W_OK) == 0
6245 )
6246#endif
6247 {
6248 ++retval;
6249 if (mch_isdir(fname))
6250 ++retval;
6251 }
6252 return retval;
6253}
6254#endif
Bram Moolenaar6bab4d12005-06-16 21:53:56 +00006255
6256/*
6257 * Print an error message with one or two "%s" and one or two string arguments.
6258 * This is not in message.c to avoid a warning for prototypes.
6259 */
6260 int
6261emsg3(s, a1, a2)
6262 char_u *s, *a1, *a2;
6263{
Bram Moolenaareb3593b2006-04-22 22:33:57 +00006264 if (emsg_not_now())
Bram Moolenaar6bab4d12005-06-16 21:53:56 +00006265 return TRUE; /* no error messages at the moment */
Bram Moolenaar6f192452007-11-08 19:49:02 +00006266#ifdef HAVE_STDARG_H
6267 vim_snprintf((char *)IObuff, IOSIZE, (char *)s, a1, a2);
6268#else
Bram Moolenaareb3593b2006-04-22 22:33:57 +00006269 vim_snprintf((char *)IObuff, IOSIZE, (char *)s, (long_u)a1, (long_u)a2);
Bram Moolenaar6f192452007-11-08 19:49:02 +00006270#endif
Bram Moolenaar6bab4d12005-06-16 21:53:56 +00006271 return emsg(IObuff);
6272}
6273
6274/*
6275 * Print an error message with one "%ld" and one long int argument.
6276 * This is not in message.c to avoid a warning for prototypes.
6277 */
6278 int
6279emsgn(s, n)
6280 char_u *s;
6281 long n;
6282{
Bram Moolenaareb3593b2006-04-22 22:33:57 +00006283 if (emsg_not_now())
Bram Moolenaar6bab4d12005-06-16 21:53:56 +00006284 return TRUE; /* no error messages at the moment */
6285 vim_snprintf((char *)IObuff, IOSIZE, (char *)s, n);
6286 return emsg(IObuff);
6287}
Bram Moolenaarcdf04202010-05-29 15:11:47 +02006288
6289#if defined(FEAT_SPELL) || defined(FEAT_PERSISTENT_UNDO) || defined(PROTO)
6290/*
6291 * Read 2 bytes from "fd" and turn them into an int, MSB first.
6292 */
6293 int
6294get2c(fd)
6295 FILE *fd;
6296{
Bram Moolenaar9db58062010-05-29 20:33:07 +02006297 int n;
Bram Moolenaarcdf04202010-05-29 15:11:47 +02006298
6299 n = getc(fd);
6300 n = (n << 8) + getc(fd);
6301 return n;
6302}
6303
6304/*
6305 * Read 3 bytes from "fd" and turn them into an int, MSB first.
6306 */
6307 int
6308get3c(fd)
6309 FILE *fd;
6310{
Bram Moolenaar9db58062010-05-29 20:33:07 +02006311 int n;
Bram Moolenaarcdf04202010-05-29 15:11:47 +02006312
6313 n = getc(fd);
6314 n = (n << 8) + getc(fd);
6315 n = (n << 8) + getc(fd);
6316 return n;
6317}
6318
6319/*
6320 * Read 4 bytes from "fd" and turn them into an int, MSB first.
6321 */
6322 int
6323get4c(fd)
6324 FILE *fd;
6325{
Bram Moolenaar9db58062010-05-29 20:33:07 +02006326 int n;
Bram Moolenaarcdf04202010-05-29 15:11:47 +02006327
6328 n = getc(fd);
6329 n = (n << 8) + getc(fd);
6330 n = (n << 8) + getc(fd);
6331 n = (n << 8) + getc(fd);
6332 return n;
6333}
6334
6335/*
6336 * Read 8 bytes from "fd" and turn them into a time_t, MSB first.
6337 */
6338 time_t
6339get8ctime(fd)
6340 FILE *fd;
6341{
6342 time_t n = 0;
6343 int i;
6344
6345 for (i = 0; i < 8; ++i)
6346 n = (n << 8) + getc(fd);
6347 return n;
6348}
6349
6350/*
6351 * Read a string of length "cnt" from "fd" into allocated memory.
6352 * Returns NULL when out of memory or unable to read that many bytes.
6353 */
6354 char_u *
6355read_string(fd, cnt)
6356 FILE *fd;
6357 int cnt;
6358{
6359 char_u *str;
6360 int i;
6361 int c;
6362
6363 /* allocate memory */
6364 str = alloc((unsigned)cnt + 1);
6365 if (str != NULL)
6366 {
6367 /* Read the string. Quit when running into the EOF. */
6368 for (i = 0; i < cnt; ++i)
6369 {
6370 c = getc(fd);
6371 if (c == EOF)
6372 {
6373 vim_free(str);
6374 return NULL;
6375 }
6376 str[i] = c;
6377 }
6378 str[i] = NUL;
6379 }
6380 return str;
6381}
6382
6383/*
6384 * Write a number to file "fd", MSB first, in "len" bytes.
6385 */
6386 int
6387put_bytes(fd, nr, len)
6388 FILE *fd;
6389 long_u nr;
6390 int len;
6391{
6392 int i;
6393
6394 for (i = len - 1; i >= 0; --i)
6395 if (putc((int)(nr >> (i * 8)), fd) == EOF)
6396 return FAIL;
6397 return OK;
6398}
6399
6400#ifdef _MSC_VER
6401# if (_MSC_VER <= 1200)
6402/* This line is required for VC6 without the service pack. Also see the
6403 * matching #pragma below. */
6404 # pragma optimize("", off)
6405# endif
6406#endif
6407
6408/*
6409 * Write time_t to file "fd" in 8 bytes.
6410 */
6411 void
6412put_time(fd, the_time)
6413 FILE *fd;
6414 time_t the_time;
6415{
6416 int c;
6417 int i;
6418 time_t wtime = the_time;
6419
6420 /* time_t can be up to 8 bytes in size, more than long_u, thus we
6421 * can't use put_bytes() here.
6422 * Another problem is that ">>" may do an arithmetic shift that keeps the
Bram Moolenaar644fdff2010-05-30 13:26:21 +02006423 * sign. This happens for large values of wtime. A cast to long_u may
6424 * truncate if time_t is 8 bytes. So only use a cast when it is 4 bytes,
6425 * it's safe to assume that long_u is 4 bytes or more and when using 8
6426 * bytes the top bit won't be set. */
Bram Moolenaarcdf04202010-05-29 15:11:47 +02006427 for (i = 7; i >= 0; --i)
6428 {
6429 if (i + 1 > (int)sizeof(time_t))
6430 /* ">>" doesn't work well when shifting more bits than avail */
6431 putc(0, fd);
6432 else
6433 {
Bram Moolenaar644fdff2010-05-30 13:26:21 +02006434#if defined(SIZEOF_TIME_T) && SIZEOF_TIME_T > 4
Bram Moolenaarbbd6afe2010-06-02 20:32:23 +02006435 c = (int)(wtime >> (i * 8));
Bram Moolenaar644fdff2010-05-30 13:26:21 +02006436#else
Bram Moolenaarbbd6afe2010-06-02 20:32:23 +02006437 c = (int)((long_u)wtime >> (i * 8));
Bram Moolenaar644fdff2010-05-30 13:26:21 +02006438#endif
Bram Moolenaarcdf04202010-05-29 15:11:47 +02006439 putc(c, fd);
6440 }
6441 }
6442}
6443
6444#ifdef _MSC_VER
6445# if (_MSC_VER <= 1200)
6446 # pragma optimize("", on)
6447# endif
6448#endif
6449
6450#endif