blob: 6775932c8daf9a8a5c879e1d5a6d2821e0163992 [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
15#ifdef HAVE_FCNTL_H
16# include <fcntl.h> /* for chdir() */
17#endif
18
19#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/*
71 * Go to column "wcol", and add/insert white space as neccessary to get the
72 * 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? */
136 int finetune; /* change char offset for the excact column */
137 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
150 one_more = (State & INSERT) || restart_edit != NUL
151#ifdef FEAT_VISUAL
152 || (VIsual_active && *p_sel != 'o')
153#endif
154 ;
155 line = ml_get_curline();
156
157 if (wcol >= MAXCOL)
158 {
159 idx = (int)STRLEN(line) - 1 + one_more;
160 col = wcol;
161
162#ifdef FEAT_VIRTUALEDIT
163 if ((addspaces || finetune) && !VIsual_active)
164 {
165 curwin->w_curswant = linetabsize(line) + one_more;
166 if (curwin->w_curswant > 0)
167 --curwin->w_curswant;
168 }
169#endif
170 }
171 else
172 {
173#ifdef FEAT_VIRTUALEDIT
174 int width = W_WIDTH(curwin) - win_col_off(curwin);
175
176 if ((addspaces || finetune)
177 && curwin->w_p_wrap
178# ifdef FEAT_VERTSPLIT
179 && curwin->w_width != 0
180# endif
181 && wcol >= (colnr_T)width)
182 {
183 csize = linetabsize(line);
184 if (csize > 0)
185 csize--;
186
187 if (wcol / width > (colnr_T)csize / width)
188 {
189 /* In case of line wrapping don't move the cursor beyond the
190 * right screen edge. */
191 wcol = (csize / width + 1) * width - 1;
192 }
193 }
194#endif
195
196 idx = -1;
197 ptr = line;
198 while (col <= wcol && *ptr != NUL)
199 {
200 /* Count a tab for what it's worth (if list mode not on) */
201#ifdef FEAT_LINEBREAK
202 csize = win_lbr_chartabsize(curwin, ptr, col, &head);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000203 mb_ptr_adv(ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000204#else
205 csize = lbr_chartabsize_adv(&ptr, col);
206#endif
207 col += csize;
208 }
209 idx = (int)(ptr - line);
210 /*
211 * Handle all the special cases. The virtual_active() check
212 * is needed to ensure that a virtual position off the end of
213 * a line has the correct indexing. The one_more comparison
214 * replaces an explicit add of one_more later on.
215 */
216 if (col > wcol || (!virtual_active() && one_more == 0))
217 {
218 idx -= 1;
219# ifdef FEAT_LINEBREAK
220 /* Don't count the chars from 'showbreak'. */
221 csize -= head;
222# endif
223 col -= csize;
224 }
225
226#ifdef FEAT_VIRTUALEDIT
227 if (virtual_active()
228 && addspaces
229 && ((col != wcol && col != wcol + 1) || csize > 1))
230 {
231 /* 'virtualedit' is set: The difference between wcol and col is
232 * filled with spaces. */
233
234 if (line[idx] == NUL)
235 {
236 /* Append spaces */
237 int correct = wcol - col;
238 char_u *newline = alloc(idx + correct + 1);
239 int t;
240
241 if (newline == NULL)
242 return FAIL;
243
244 for (t = 0; t < idx; ++t)
245 newline[t] = line[t];
246
247 for (t = 0; t < correct; ++t)
248 newline[t + idx] = ' ';
249
250 newline[idx + correct] = NUL;
251
252 ml_replace(pos->lnum, newline, FALSE);
253 changed_bytes(pos->lnum, (colnr_T)idx);
254 idx += correct;
255 col = wcol;
256 }
257 else
258 {
259 /* Break a tab */
260 int linelen = (int)STRLEN(line);
261 int correct = wcol - col - csize + 1; /* negative!! */
262 char_u *newline = alloc(linelen + csize);
263 int t, s = 0;
264 int v;
265
266 /*
267 * break a tab
268 */
269 if (newline == NULL || -correct > csize)
270 return FAIL;
271
272 for (t = 0; t < linelen; t++)
273 {
274 if (t != idx)
275 newline[s++] = line[t];
276 else
277 for (v = 0; v < csize; v++)
278 newline[s++] = ' ';
279 }
280
281 newline[linelen + csize - 1] = NUL;
282
283 ml_replace(pos->lnum, newline, FALSE);
284 changed_bytes(pos->lnum, idx);
285 idx += (csize - 1 + correct);
286 col += correct;
287 }
288 }
289#endif
290 }
291
292 if (idx < 0)
293 pos->col = 0;
294 else
295 pos->col = idx;
296
297#ifdef FEAT_VIRTUALEDIT
298 pos->coladd = 0;
299
300 if (finetune)
301 {
302 if (wcol == MAXCOL)
303 {
304 /* The width of the last character is used to set coladd. */
305 if (!one_more)
306 {
307 colnr_T scol, ecol;
308
309 getvcol(curwin, pos, &scol, NULL, &ecol);
310 pos->coladd = ecol - scol;
311 }
312 }
313 else
314 {
315 int b = (int)wcol - (int)col;
316
317 /* The difference between wcol and col is used to set coladd. */
318 if (b > 0 && b < (MAXCOL - 2 * W_WIDTH(curwin)))
319 pos->coladd = b;
320
321 col += b;
322 }
323 }
324#endif
325
326#ifdef FEAT_MBYTE
327 /* prevent cursor from moving on the trail byte */
328 if (has_mbyte)
329 mb_adjust_cursor();
330#endif
331
332 if (col < wcol)
333 return FAIL;
334 return OK;
335}
336
337/*
338 * inc(p)
339 *
340 * Increment the line pointer 'p' crossing line boundaries as necessary.
341 * Return 1 when going to the next line.
342 * Return 2 when moving forward onto a NUL at the end of the line).
343 * Return -1 when at the end of file.
344 * Return 0 otherwise.
345 */
346 int
347inc_cursor()
348{
349 return inc(&curwin->w_cursor);
350}
351
352 int
353inc(lp)
354 pos_T *lp;
355{
356 char_u *p = ml_get_pos(lp);
357
358 if (*p != NUL) /* still within line, move to next char (may be NUL) */
359 {
360#ifdef FEAT_MBYTE
361 if (has_mbyte)
362 {
363 int l = (*mb_ptr2len_check)(p);
364
365 lp->col += l;
366 return ((p[l] != NUL) ? 0 : 2);
367 }
368#endif
369 lp->col++;
370#ifdef FEAT_VIRTUALEDIT
371 lp->coladd = 0;
372#endif
373 return ((p[1] != NUL) ? 0 : 2);
374 }
375 if (lp->lnum != curbuf->b_ml.ml_line_count) /* there is a next line */
376 {
377 lp->col = 0;
378 lp->lnum++;
379#ifdef FEAT_VIRTUALEDIT
380 lp->coladd = 0;
381#endif
382 return 1;
383 }
384 return -1;
385}
386
387/*
388 * incl(lp): same as inc(), but skip the NUL at the end of non-empty lines
389 */
390 int
391incl(lp)
392 pos_T *lp;
393{
394 int r;
395
396 if ((r = inc(lp)) >= 1 && lp->col)
397 r = inc(lp);
398 return r;
399}
400
401/*
402 * dec(p)
403 *
404 * Decrement the line pointer 'p' crossing line boundaries as necessary.
405 * Return 1 when crossing a line, -1 when at start of file, 0 otherwise.
406 */
407 int
408dec_cursor()
409{
410 return dec(&curwin->w_cursor);
411}
412
413 int
414dec(lp)
415 pos_T *lp;
416{
417 char_u *p;
418
419#ifdef FEAT_VIRTUALEDIT
420 lp->coladd = 0;
421#endif
422 if (lp->col > 0) /* still within line */
423 {
424 lp->col--;
425#ifdef FEAT_MBYTE
426 if (has_mbyte)
427 {
428 p = ml_get(lp->lnum);
429 lp->col -= (*mb_head_off)(p, p + lp->col);
430 }
431#endif
432 return 0;
433 }
434 if (lp->lnum > 1) /* there is a prior line */
435 {
436 lp->lnum--;
437 p = ml_get(lp->lnum);
438 lp->col = (colnr_T)STRLEN(p);
439#ifdef FEAT_MBYTE
440 if (has_mbyte)
441 lp->col -= (*mb_head_off)(p, p + lp->col);
442#endif
443 return 1;
444 }
445 return -1; /* at start of file */
446}
447
448/*
449 * decl(lp): same as dec(), but skip the NUL at the end of non-empty lines
450 */
451 int
452decl(lp)
453 pos_T *lp;
454{
455 int r;
456
457 if ((r = dec(lp)) == 1 && lp->col)
458 r = dec(lp);
459 return r;
460}
461
462/*
463 * Make sure curwin->w_cursor.lnum is valid.
464 */
465 void
466check_cursor_lnum()
467{
468 if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
469 {
470#ifdef FEAT_FOLDING
471 /* If there is a closed fold at the end of the file, put the cursor in
472 * its first line. Otherwise in the last line. */
473 if (!hasFolding(curbuf->b_ml.ml_line_count,
474 &curwin->w_cursor.lnum, NULL))
475#endif
476 curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
477 }
478 if (curwin->w_cursor.lnum <= 0)
479 curwin->w_cursor.lnum = 1;
480}
481
482/*
483 * Make sure curwin->w_cursor.col is valid.
484 */
485 void
486check_cursor_col()
487{
488 colnr_T len;
489#ifdef FEAT_VIRTUALEDIT
490 colnr_T oldcol = curwin->w_cursor.col + curwin->w_cursor.coladd;
491#endif
492
493 len = (colnr_T)STRLEN(ml_get_curline());
494 if (len == 0)
495 curwin->w_cursor.col = 0;
496 else if (curwin->w_cursor.col >= len)
497 {
498 /* Allow cursor past end-of-line in Insert mode, restarting Insert
499 * mode or when in Visual mode and 'selection' isn't "old" */
500 if (State & INSERT || restart_edit
501#ifdef FEAT_VISUAL
502 || (VIsual_active && *p_sel != 'o')
503#endif
504 || virtual_active())
505 curwin->w_cursor.col = len;
506 else
507 curwin->w_cursor.col = len - 1;
508 }
509
510#ifdef FEAT_VIRTUALEDIT
511 /* If virtual editing is on, we can leave the cursor on the old position,
512 * only we must set it to virtual. But don't do it when at the end of the
513 * line. */
514 if (oldcol == MAXCOL)
515 curwin->w_cursor.coladd = 0;
516 else if (ve_flags == VE_ALL)
517 curwin->w_cursor.coladd = oldcol - curwin->w_cursor.col;
518#endif
519}
520
521/*
522 * make sure curwin->w_cursor in on a valid character
523 */
524 void
525check_cursor()
526{
527 check_cursor_lnum();
528 check_cursor_col();
529}
530
531#if defined(FEAT_TEXTOBJ) || defined(PROTO)
532/*
533 * Make sure curwin->w_cursor is not on the NUL at the end of the line.
534 * Allow it when in Visual mode and 'selection' is not "old".
535 */
536 void
537adjust_cursor_col()
538{
539 if (curwin->w_cursor.col > 0
540# ifdef FEAT_VISUAL
541 && (!VIsual_active || *p_sel == 'o')
542# endif
543 && gchar_cursor() == NUL)
544 --curwin->w_cursor.col;
545}
546#endif
547
548/*
549 * When curwin->w_leftcol has changed, adjust the cursor position.
550 * Return TRUE if the cursor was moved.
551 */
552 int
553leftcol_changed()
554{
555 long lastcol;
556 colnr_T s, e;
557 int retval = FALSE;
558
559 changed_cline_bef_curs();
560 lastcol = curwin->w_leftcol + W_WIDTH(curwin) - curwin_col_off() - 1;
561 validate_virtcol();
562
563 /*
564 * If the cursor is right or left of the screen, move it to last or first
565 * character.
566 */
567 if (curwin->w_virtcol > (colnr_T)(lastcol - p_siso))
568 {
569 retval = TRUE;
570 coladvance((colnr_T)(lastcol - p_siso));
571 }
572 else if (curwin->w_virtcol < curwin->w_leftcol + p_siso)
573 {
574 retval = TRUE;
575 (void)coladvance((colnr_T)(curwin->w_leftcol + p_siso));
576 }
577
578 /*
579 * If the start of the character under the cursor is not on the screen,
580 * advance the cursor one more char. If this fails (last char of the
581 * line) adjust the scrolling.
582 */
583 getvvcol(curwin, &curwin->w_cursor, &s, NULL, &e);
584 if (e > (colnr_T)lastcol)
585 {
586 retval = TRUE;
587 coladvance(s - 1);
588 }
589 else if (s < curwin->w_leftcol)
590 {
591 retval = TRUE;
592 if (coladvance(e + 1) == FAIL) /* there isn't another character */
593 {
594 curwin->w_leftcol = s; /* adjust w_leftcol instead */
595 changed_cline_bef_curs();
596 }
597 }
598
599 if (retval)
600 curwin->w_set_curswant = TRUE;
601 redraw_later(NOT_VALID);
602 return retval;
603}
604
605/**********************************************************************
606 * Various routines dealing with allocation and deallocation of memory.
607 */
608
609#if defined(MEM_PROFILE) || defined(PROTO)
610
611# define MEM_SIZES 8200
612static long_u mem_allocs[MEM_SIZES];
613static long_u mem_frees[MEM_SIZES];
614static long_u mem_allocated;
615static long_u mem_freed;
616static long_u mem_peak;
617static long_u num_alloc;
618static long_u num_freed;
619
620static void mem_pre_alloc_s __ARGS((size_t *sizep));
621static void mem_pre_alloc_l __ARGS((long_u *sizep));
622static void mem_post_alloc __ARGS((void **pp, size_t size));
623static void mem_pre_free __ARGS((void **pp));
624
625 static void
626mem_pre_alloc_s(sizep)
627 size_t *sizep;
628{
629 *sizep += sizeof(size_t);
630}
631
632 static void
633mem_pre_alloc_l(sizep)
634 long_u *sizep;
635{
636 *sizep += sizeof(size_t);
637}
638
639 static void
640mem_post_alloc(pp, size)
641 void **pp;
642 size_t size;
643{
644 if (*pp == NULL)
645 return;
646 size -= sizeof(size_t);
647 *(long_u *)*pp = size;
648 if (size <= MEM_SIZES-1)
649 mem_allocs[size-1]++;
650 else
651 mem_allocs[MEM_SIZES-1]++;
652 mem_allocated += size;
653 if (mem_allocated - mem_freed > mem_peak)
654 mem_peak = mem_allocated - mem_freed;
655 num_alloc++;
656 *pp = (void *)((char *)*pp + sizeof(size_t));
657}
658
659 static void
660mem_pre_free(pp)
661 void **pp;
662{
663 long_u size;
664
665 *pp = (void *)((char *)*pp - sizeof(size_t));
666 size = *(size_t *)*pp;
667 if (size <= MEM_SIZES-1)
668 mem_frees[size-1]++;
669 else
670 mem_frees[MEM_SIZES-1]++;
671 mem_freed += size;
672 num_freed++;
673}
674
675/*
676 * called on exit via atexit()
677 */
678 void
679vim_mem_profile_dump()
680{
681 int i, j;
682
683 printf("\r\n");
684 j = 0;
685 for (i = 0; i < MEM_SIZES - 1; i++)
686 {
687 if (mem_allocs[i] || mem_frees[i])
688 {
689 if (mem_frees[i] > mem_allocs[i])
690 printf("\r\n%s", _("ERROR: "));
691 printf("[%4d / %4lu-%-4lu] ", i + 1, mem_allocs[i], mem_frees[i]);
692 j++;
693 if (j > 3)
694 {
695 j = 0;
696 printf("\r\n");
697 }
698 }
699 }
700
701 i = MEM_SIZES - 1;
702 if (mem_allocs[i])
703 {
704 printf("\r\n");
705 if (mem_frees[i] > mem_allocs[i])
706 printf(_("ERROR: "));
707 printf("[>%d / %4lu-%-4lu]", i, mem_allocs[i], mem_frees[i]);
708 }
709
710 printf(_("\n[bytes] total alloc-freed %lu-%lu, in use %lu, peak use %lu\n"),
711 mem_allocated, mem_freed, mem_allocated - mem_freed, mem_peak);
712 printf(_("[calls] total re/malloc()'s %lu, total free()'s %lu\n\n"),
713 num_alloc, num_freed);
714}
715
716#endif /* MEM_PROFILE */
717
718/*
719 * Some memory is reserved for error messages and for being able to
720 * call mf_release_all(), which needs some memory for mf_trans_add().
721 */
722#if defined(MSDOS) && !defined(DJGPP)
723# define SMALL_MEM
724# define KEEP_ROOM 8192L
725#else
726# define KEEP_ROOM (2 * 8192L)
727#endif
728
729/*
730 * Note: if unsinged is 16 bits we can only allocate up to 64K with alloc().
731 * Use lalloc for larger blocks.
732 */
733 char_u *
734alloc(size)
735 unsigned size;
736{
737 return (lalloc((long_u)size, TRUE));
738}
739
740/*
741 * Allocate memory and set all bytes to zero.
742 */
743 char_u *
744alloc_clear(size)
745 unsigned size;
746{
747 char_u *p;
748
749 p = (lalloc((long_u)size, TRUE));
750 if (p != NULL)
751 (void)vim_memset(p, 0, (size_t)size);
752 return p;
753}
754
755/*
756 * alloc() with check for maximum line length
757 */
758 char_u *
759alloc_check(size)
760 unsigned size;
761{
762#if !defined(UNIX) && !defined(__EMX__)
763 if (sizeof(int) == 2 && size > 0x7fff)
764 {
765 /* Don't hide this message */
766 emsg_silent = 0;
767 EMSG(_("E340: Line is becoming too long"));
768 return NULL;
769 }
770#endif
771 return (lalloc((long_u)size, TRUE));
772}
773
774/*
775 * Allocate memory like lalloc() and set all bytes to zero.
776 */
777 char_u *
778lalloc_clear(size, message)
779 long_u size;
780 int message;
781{
782 char_u *p;
783
784 p = (lalloc(size, message));
785 if (p != NULL)
786 (void)vim_memset(p, 0, (size_t)size);
787 return p;
788}
789
790/*
791 * Low level memory allocation function.
792 * This is used often, KEEP IT FAST!
793 */
794 char_u *
795lalloc(size, message)
796 long_u size;
797 int message;
798{
799 char_u *p; /* pointer to new storage space */
800 static int releasing = FALSE; /* don't do mf_release_all() recursive */
801 int try_again;
802#if defined(HAVE_AVAIL_MEM) && !defined(SMALL_MEM)
803 static long_u allocated = 0; /* allocated since last avail check */
804#endif
805
806 /* Safety check for allocating zero bytes */
807 if (size == 0)
808 {
809 /* Don't hide this message */
810 emsg_silent = 0;
811 EMSGN(_("E341: Internal error: lalloc(%ld, )"), size);
812 return NULL;
813 }
814
815#ifdef MEM_PROFILE
816 mem_pre_alloc_l(&size);
817#endif
818
819#if defined(MSDOS) && !defined(DJGPP)
820 if (size >= 0xfff0) /* in MSDOS we can't deal with >64K blocks */
821 p = NULL;
822 else
823#endif
824
825 /*
826 * Loop when out of memory: Try to release some memfile blocks and
827 * if some blocks are released call malloc again.
828 */
829 for (;;)
830 {
831 /*
832 * Handle three kind of systems:
833 * 1. No check for available memory: Just return.
834 * 2. Slow check for available memory: call mch_avail_mem() after
835 * allocating KEEP_ROOM amount of memory.
836 * 3. Strict check for available memory: call mch_avail_mem()
837 */
838 if ((p = (char_u *)malloc((size_t)size)) != NULL)
839 {
840#ifndef HAVE_AVAIL_MEM
841 /* 1. No check for available memory: Just return. */
842 goto theend;
843#else
844# ifndef SMALL_MEM
845 /* 2. Slow check for available memory: call mch_avail_mem() after
846 * allocating (KEEP_ROOM / 2) amount of memory. */
847 allocated += size;
848 if (allocated < KEEP_ROOM / 2)
849 goto theend;
850 allocated = 0;
851# endif
852 /* 3. check for available memory: call mch_avail_mem() */
853 if (mch_avail_mem(TRUE) < KEEP_ROOM && !releasing)
854 {
855 vim_free((char *)p); /* System is low... no go! */
856 p = NULL;
857 }
858 else
859 goto theend;
860#endif
861 }
862 /*
863 * Remember that mf_release_all() is being called to avoid an endless
864 * loop, because mf_release_all() may call alloc() recursively.
865 */
866 if (releasing)
867 break;
868 releasing = TRUE;
869 try_again = mf_release_all();
870 releasing = FALSE;
871 if (!try_again)
872 break;
873 }
874
875 if (message && p == NULL)
876 do_outofmem_msg(size);
877
878theend:
879#ifdef MEM_PROFILE
880 mem_post_alloc((void **)&p, (size_t)size);
881#endif
882 return p;
883}
884
885#if defined(MEM_PROFILE) || defined(PROTO)
886/*
887 * realloc() with memory profiling.
888 */
889 void *
890mem_realloc(ptr, size)
891 void *ptr;
892 size_t size;
893{
894 void *p;
895
896 mem_pre_free(&ptr);
897 mem_pre_alloc_s(&size);
898
899 p = realloc(ptr, size);
900
901 mem_post_alloc(&p, size);
902
903 return p;
904}
905#endif
906
907/*
908* Avoid repeating the error message many times (they take 1 second each).
909* Did_outofmem_msg is reset when a character is read.
910*/
911 void
912do_outofmem_msg(size)
913 long_u size;
914{
915 if (!did_outofmem_msg)
916 {
917 /* Don't hide this message */
918 emsg_silent = 0;
919 EMSGN(_("E342: Out of memory! (allocating %lu bytes)"), size);
920 did_outofmem_msg = TRUE;
921 }
922}
923
924/*
925 * copy a string into newly allocated memory
926 */
927 char_u *
928vim_strsave(string)
929 char_u *string;
930{
931 char_u *p;
932 unsigned len;
933
934 len = (unsigned)STRLEN(string) + 1;
935 p = alloc(len);
936 if (p != NULL)
937 mch_memmove(p, string, (size_t)len);
938 return p;
939}
940
941 char_u *
942vim_strnsave(string, len)
943 char_u *string;
944 int len;
945{
946 char_u *p;
947
948 p = alloc((unsigned)(len + 1));
949 if (p != NULL)
950 {
951 STRNCPY(p, string, len);
952 p[len] = NUL;
953 }
954 return p;
955}
956
Bram Moolenaar071d4272004-06-13 20:20:40 +0000957/*
958 * Same as vim_strsave(), but any characters found in esc_chars are preceded
959 * by a backslash.
960 */
961 char_u *
962vim_strsave_escaped(string, esc_chars)
963 char_u *string;
964 char_u *esc_chars;
965{
Bram Moolenaar2df6dcc2004-07-12 15:53:54 +0000966 return vim_strsave_escaped_ext(string, esc_chars, '\\', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000967}
968
969/*
970 * Same as vim_strsave_escaped(), but when "bsl" is TRUE also escape
971 * characters where rem_backslash() would remove the backslash.
Bram Moolenaar2df6dcc2004-07-12 15:53:54 +0000972 * Escape the characters with "cc".
Bram Moolenaar071d4272004-06-13 20:20:40 +0000973 */
974 char_u *
Bram Moolenaar2df6dcc2004-07-12 15:53:54 +0000975vim_strsave_escaped_ext(string, esc_chars, cc, bsl)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000976 char_u *string;
977 char_u *esc_chars;
Bram Moolenaar2df6dcc2004-07-12 15:53:54 +0000978 int cc;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000979 int bsl;
980{
981 char_u *p;
982 char_u *p2;
983 char_u *escaped_string;
984 unsigned length;
985#ifdef FEAT_MBYTE
986 int l;
987#endif
988
989 /*
990 * First count the number of backslashes required.
991 * Then allocate the memory and insert them.
992 */
993 length = 1; /* count the trailing NUL */
994 for (p = string; *p; p++)
995 {
996#ifdef FEAT_MBYTE
997 if (has_mbyte && (l = (*mb_ptr2len_check)(p)) > 1)
998 {
999 length += l; /* count a multibyte char */
1000 p += l - 1;
1001 continue;
1002 }
1003#endif
1004 if (vim_strchr(esc_chars, *p) != NULL || (bsl && rem_backslash(p)))
1005 ++length; /* count a backslash */
1006 ++length; /* count an ordinary char */
1007 }
1008 escaped_string = alloc(length);
1009 if (escaped_string != NULL)
1010 {
1011 p2 = escaped_string;
1012 for (p = string; *p; p++)
1013 {
1014#ifdef FEAT_MBYTE
1015 if (has_mbyte && (l = (*mb_ptr2len_check)(p)) > 1)
1016 {
1017 mch_memmove(p2, p, (size_t)l);
1018 p2 += l;
1019 p += l - 1; /* skip multibyte char */
1020 continue;
1021 }
1022#endif
1023 if (vim_strchr(esc_chars, *p) != NULL || (bsl && rem_backslash(p)))
Bram Moolenaar2df6dcc2004-07-12 15:53:54 +00001024 *p2++ = cc;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001025 *p2++ = *p;
1026 }
1027 *p2 = NUL;
1028 }
1029 return escaped_string;
1030}
1031
1032/*
1033 * Like vim_strsave(), but make all characters uppercase.
1034 * This uses ASCII lower-to-upper case translation, language independent.
1035 */
1036 char_u *
1037vim_strsave_up(string)
1038 char_u *string;
1039{
1040 char_u *p1;
1041
1042 p1 = vim_strsave(string);
1043 vim_strup(p1);
1044 return p1;
1045}
1046
1047/*
1048 * Like vim_strnsave(), but make all characters uppercase.
1049 * This uses ASCII lower-to-upper case translation, language independent.
1050 */
1051 char_u *
1052vim_strnsave_up(string, len)
1053 char_u *string;
1054 int len;
1055{
1056 char_u *p1;
1057
1058 p1 = vim_strnsave(string, len);
1059 vim_strup(p1);
1060 return p1;
1061}
1062
1063/*
1064 * ASCII lower-to-upper case translation, language independent.
1065 */
1066 void
1067vim_strup(p)
1068 char_u *p;
1069{
1070 char_u *p2;
1071 int c;
1072
1073 if (p != NULL)
1074 {
1075 p2 = p;
1076 while ((c = *p2) != NUL)
1077#ifdef EBCDIC
1078 *p2++ = isalpha(c) ? toupper(c) : c;
1079#else
1080 *p2++ = (c < 'a' || c > 'z') ? c : (c - 0x20);
1081#endif
1082 }
1083}
1084
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001085#if defined(FEAT_EVAL) || defined(FEAT_SYN_HL) || defined(PROTO)
1086/*
1087 * Make string "s" all upper-case and return it in allocated memory.
1088 * Handles multi-byte characters as well as possible.
1089 * Returns NULL when out of memory.
1090 */
1091 char_u *
1092strup_save(orig)
1093 char_u *orig;
1094{
1095 char_u *p;
1096 char_u *res;
1097
1098 res = p = vim_strsave(orig);
1099
1100 if (res != NULL)
1101 while (*p != NUL)
1102 {
1103# ifdef FEAT_MBYTE
1104 int l;
1105
1106 if (enc_utf8)
1107 {
1108 int c, uc;
1109 int nl;
1110 char_u *s;
1111
1112 c = utf_ptr2char(p);
1113 uc = utf_toupper(c);
1114
1115 /* Reallocate string when byte count changes. This is rare,
1116 * thus it's OK to do another malloc()/free(). */
1117 l = utf_ptr2len_check(p);
1118 nl = utf_char2len(uc);
1119 if (nl != l)
1120 {
1121 s = alloc((unsigned)STRLEN(res) + 1 + nl - l);
1122 if (s == NULL)
1123 break;
1124 mch_memmove(s, res, p - res);
1125 STRCPY(s + (p - res) + nl, p + l);
1126 p = s + (p - res);
1127 vim_free(res);
1128 res = s;
1129 }
1130
1131 utf_char2bytes(uc, p);
1132 p += nl;
1133 }
1134 else if (has_mbyte && (l = (*mb_ptr2len_check)(p)) > 1)
1135 p += l; /* skip multi-byte character */
1136 else
1137# endif
1138 {
1139 *p = TOUPPER_LOC(*p); /* note that toupper() can be a macro */
1140 p++;
1141 }
1142 }
1143
1144 return res;
1145}
1146#endif
1147
Bram Moolenaar071d4272004-06-13 20:20:40 +00001148/*
1149 * copy a space a number of times
1150 */
1151 void
1152copy_spaces(ptr, count)
1153 char_u *ptr;
1154 size_t count;
1155{
1156 size_t i = count;
1157 char_u *p = ptr;
1158
1159 while (i--)
1160 *p++ = ' ';
1161}
1162
1163#if defined(FEAT_VISUALEXTRA) || defined(PROTO)
1164/*
1165 * Copy a character a number of times.
1166 * Does not work for multi-byte charactes!
1167 */
1168 void
1169copy_chars(ptr, count, c)
1170 char_u *ptr;
1171 size_t count;
1172 int c;
1173{
1174 size_t i = count;
1175 char_u *p = ptr;
1176
1177 while (i--)
1178 *p++ = c;
1179}
1180#endif
1181
1182/*
1183 * delete spaces at the end of a string
1184 */
1185 void
1186del_trailing_spaces(ptr)
1187 char_u *ptr;
1188{
1189 char_u *q;
1190
1191 q = ptr + STRLEN(ptr);
1192 while (--q > ptr && vim_iswhite(q[0]) && q[-1] != '\\' && q[-1] != Ctrl_V)
1193 *q = NUL;
1194}
1195
1196/*
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001197 * Like strncpy(), but always terminate the result with one NUL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001198 */
1199 void
1200vim_strncpy(to, from, len)
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001201 char_u *to;
1202 char_u *from;
1203 int len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001204{
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001205 STRNCPY(to, from, len);
1206 to[len] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001207}
1208
1209/*
1210 * Isolate one part of a string option where parts are separated with
1211 * "sep_chars".
1212 * The part is copied into buf[maxlen].
1213 * "*option" is advanced to the next part.
1214 * The length is returned.
1215 */
1216 int
1217copy_option_part(option, buf, maxlen, sep_chars)
1218 char_u **option;
1219 char_u *buf;
1220 int maxlen;
1221 char *sep_chars;
1222{
1223 int len = 0;
1224 char_u *p = *option;
1225
1226 /* skip '.' at start of option part, for 'suffixes' */
1227 if (*p == '.')
1228 buf[len++] = *p++;
1229 while (*p != NUL && vim_strchr((char_u *)sep_chars, *p) == NULL)
1230 {
1231 /*
1232 * Skip backslash before a separator character and space.
1233 */
1234 if (p[0] == '\\' && vim_strchr((char_u *)sep_chars, p[1]) != NULL)
1235 ++p;
1236 if (len < maxlen - 1)
1237 buf[len++] = *p;
1238 ++p;
1239 }
1240 buf[len] = NUL;
1241
1242 if (*p != NUL && *p != ',') /* skip non-standard separator */
1243 ++p;
1244 p = skip_to_option_part(p); /* p points to next file name */
1245
1246 *option = p;
1247 return len;
1248}
1249
1250/*
1251 * replacement for free() that ignores NULL pointers
1252 */
1253 void
1254vim_free(x)
1255 void *x;
1256{
1257 if (x != NULL)
1258 {
1259#ifdef MEM_PROFILE
1260 mem_pre_free(&x);
1261#endif
1262 free(x);
1263 }
1264}
1265
1266#ifndef HAVE_MEMSET
1267 void *
1268vim_memset(ptr, c, size)
1269 void *ptr;
1270 int c;
1271 size_t size;
1272{
1273 char *p = ptr;
1274
1275 while (size-- > 0)
1276 *p++ = c;
1277 return ptr;
1278}
1279#endif
1280
1281#ifdef VIM_MEMCMP
1282/*
1283 * Return zero when "b1" and "b2" are the same for "len" bytes.
1284 * Return non-zero otherwise.
1285 */
1286 int
1287vim_memcmp(b1, b2, len)
1288 void *b1;
1289 void *b2;
1290 size_t len;
1291{
1292 char_u *p1 = (char_u *)b1, *p2 = (char_u *)b2;
1293
1294 for ( ; len > 0; --len)
1295 {
1296 if (*p1 != *p2)
1297 return 1;
1298 ++p1;
1299 ++p2;
1300 }
1301 return 0;
1302}
1303#endif
1304
1305#ifdef VIM_MEMMOVE
1306/*
1307 * Version of memmove() that handles overlapping source and destination.
1308 * For systems that don't have a function that is guaranteed to do that (SYSV).
1309 */
1310 void
1311mch_memmove(dst_arg, src_arg, len)
1312 void *src_arg, *dst_arg;
1313 size_t len;
1314{
1315 /*
1316 * A void doesn't have a size, we use char pointers.
1317 */
1318 char *dst = dst_arg, *src = src_arg;
1319
1320 /* overlap, copy backwards */
1321 if (dst > src && dst < src + len)
1322 {
1323 src += len;
1324 dst += len;
1325 while (len-- > 0)
1326 *--dst = *--src;
1327 }
1328 else /* copy forwards */
1329 while (len-- > 0)
1330 *dst++ = *src++;
1331}
1332#endif
1333
1334#if (!defined(HAVE_STRCASECMP) && !defined(HAVE_STRICMP)) || defined(PROTO)
1335/*
1336 * Compare two strings, ignoring case, using current locale.
1337 * Doesn't work for multi-byte characters.
1338 * return 0 for match, < 0 for smaller, > 0 for bigger
1339 */
1340 int
1341vim_stricmp(s1, s2)
1342 char *s1;
1343 char *s2;
1344{
1345 int i;
1346
1347 for (;;)
1348 {
1349 i = (int)TOLOWER_LOC(*s1) - (int)TOLOWER_LOC(*s2);
1350 if (i != 0)
1351 return i; /* this character different */
1352 if (*s1 == NUL)
1353 break; /* strings match until NUL */
1354 ++s1;
1355 ++s2;
1356 }
1357 return 0; /* strings match */
1358}
1359#endif
1360
1361#if (!defined(HAVE_STRNCASECMP) && !defined(HAVE_STRNICMP)) || defined(PROTO)
1362/*
1363 * Compare two strings, for length "len", ignoring case, using current locale.
1364 * Doesn't work for multi-byte characters.
1365 * return 0 for match, < 0 for smaller, > 0 for bigger
1366 */
1367 int
1368vim_strnicmp(s1, s2, len)
1369 char *s1;
1370 char *s2;
1371 size_t len;
1372{
1373 int i;
1374
1375 while (len > 0)
1376 {
1377 i = (int)TOLOWER_LOC(*s1) - (int)TOLOWER_LOC(*s2);
1378 if (i != 0)
1379 return i; /* this character different */
1380 if (*s1 == NUL)
1381 break; /* strings match until NUL */
1382 ++s1;
1383 ++s2;
1384 --len;
1385 }
1386 return 0; /* strings match */
1387}
1388#endif
1389
1390#if 0 /* currently not used */
1391/*
1392 * Check if string "s2" appears somewhere in "s1" while ignoring case.
1393 * Return NULL if not, a pointer to the first occurrence if it does.
1394 */
1395 char_u *
1396vim_stristr(s1, s2)
1397 char_u *s1;
1398 char_u *s2;
1399{
1400 char_u *p;
1401 int len = STRLEN(s2);
1402 char_u *end = s1 + STRLEN(s1) - len;
1403
1404 for (p = s1; p <= end; ++p)
1405 if (STRNICMP(p, s2, len) == 0)
1406 return p;
1407 return NULL;
1408}
1409#endif
1410
1411/*
1412 * Version of strchr() and strrchr() that handle unsigned char strings
Bram Moolenaar05159a02005-02-26 23:04:13 +00001413 * with characters from 128 to 255 correctly. It also doesn't return a
1414 * pointer to the NUL at the end of the string.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001415 */
1416 char_u *
1417vim_strchr(string, c)
1418 char_u *string;
1419 int c;
1420{
1421 char_u *p;
1422 int b;
1423
1424 p = string;
1425#ifdef FEAT_MBYTE
1426 if (enc_utf8 && c >= 0x80)
1427 {
1428 while (*p != NUL)
1429 {
1430 if (utf_ptr2char(p) == c)
1431 return p;
1432 p += (*mb_ptr2len_check)(p);
1433 }
1434 return NULL;
1435 }
1436 if (enc_dbcs != 0 && c > 255)
1437 {
1438 int n2 = c & 0xff;
1439
1440 c = ((unsigned)c >> 8) & 0xff;
1441 while ((b = *p) != NUL)
1442 {
1443 if (b == c && p[1] == n2)
1444 return p;
1445 p += (*mb_ptr2len_check)(p);
1446 }
1447 return NULL;
1448 }
1449 if (has_mbyte)
1450 {
1451 while ((b = *p) != NUL)
1452 {
1453 if (b == c)
1454 return p;
1455 p += (*mb_ptr2len_check)(p);
1456 }
1457 return NULL;
1458 }
1459#endif
1460 while ((b = *p) != NUL)
1461 {
1462 if (b == c)
1463 return p;
1464 ++p;
1465 }
1466 return NULL;
1467}
1468
1469/*
Bram Moolenaar05159a02005-02-26 23:04:13 +00001470 * Version of strchr() that only works for bytes and handles unsigned char
1471 * strings with characters above 128 correctly. It also doesn't return a
1472 * pointer to the NUL at the end of the string.
1473 */
1474 char_u *
1475vim_strbyte(string, c)
1476 char_u *string;
1477 int c;
1478{
1479 char_u *p = string;
1480
1481 while (*p != NUL)
1482 {
1483 if (*p == c)
1484 return p;
1485 ++p;
1486 }
1487 return NULL;
1488}
1489
1490/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001491 * Search for last occurrence of "c" in "string".
1492 * return NULL if not found.
Bram Moolenaar05159a02005-02-26 23:04:13 +00001493 * Does not handle multi-byte char for "c"!
Bram Moolenaar071d4272004-06-13 20:20:40 +00001494 */
1495 char_u *
1496vim_strrchr(string, c)
1497 char_u *string;
1498 int c;
1499{
1500 char_u *retval = NULL;
Bram Moolenaar05159a02005-02-26 23:04:13 +00001501 char_u *p = string;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001502
Bram Moolenaar05159a02005-02-26 23:04:13 +00001503 while (*p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001504 {
Bram Moolenaar05159a02005-02-26 23:04:13 +00001505 if (*p == c)
1506 retval = p;
1507 mb_ptr_adv(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001508 }
1509 return retval;
1510}
1511
1512/*
1513 * Vim's version of strpbrk(), in case it's missing.
1514 * Don't generate a prototype for this, causes problems when it's not used.
1515 */
1516#ifndef PROTO
1517# ifndef HAVE_STRPBRK
1518# ifdef vim_strpbrk
1519# undef vim_strpbrk
1520# endif
1521 char_u *
1522vim_strpbrk(s, charset)
1523 char_u *s;
1524 char_u *charset;
1525{
1526 while (*s)
1527 {
1528 if (vim_strchr(charset, *s) != NULL)
1529 return s;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001530 mb_ptr_adv(s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001531 }
1532 return NULL;
1533}
1534# endif
1535#endif
1536
1537/*
1538 * Vim has its own isspace() function, because on some machines isspace()
1539 * can't handle characters above 128.
1540 */
1541 int
1542vim_isspace(x)
1543 int x;
1544{
1545 return ((x >= 9 && x <= 13) || x == ' ');
1546}
1547
1548/************************************************************************
Bram Moolenaar383f9bc2005-01-19 22:18:32 +00001549 * Functions for handling growing arrays.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001550 */
1551
1552/*
1553 * Clear an allocated growing array.
1554 */
1555 void
1556ga_clear(gap)
1557 garray_T *gap;
1558{
1559 vim_free(gap->ga_data);
1560 ga_init(gap);
1561}
1562
1563/*
1564 * Clear a growing array that contains a list of strings.
1565 */
1566 void
1567ga_clear_strings(gap)
1568 garray_T *gap;
1569{
1570 int i;
1571
1572 for (i = 0; i < gap->ga_len; ++i)
1573 vim_free(((char_u **)(gap->ga_data))[i]);
1574 ga_clear(gap);
1575}
1576
1577/*
1578 * Initialize a growing array. Don't forget to set ga_itemsize and
1579 * ga_growsize! Or use ga_init2().
1580 */
1581 void
1582ga_init(gap)
1583 garray_T *gap;
1584{
1585 gap->ga_data = NULL;
Bram Moolenaar86b68352004-12-27 21:59:20 +00001586 gap->ga_maxlen = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001587 gap->ga_len = 0;
1588}
1589
1590 void
1591ga_init2(gap, itemsize, growsize)
1592 garray_T *gap;
1593 int itemsize;
1594 int growsize;
1595{
1596 ga_init(gap);
1597 gap->ga_itemsize = itemsize;
1598 gap->ga_growsize = growsize;
1599}
1600
1601/*
1602 * Make room in growing array "gap" for at least "n" items.
1603 * Return FAIL for failure, OK otherwise.
1604 */
1605 int
1606ga_grow(gap, n)
1607 garray_T *gap;
1608 int n;
1609{
1610 size_t len;
1611 char_u *pp;
1612
Bram Moolenaar86b68352004-12-27 21:59:20 +00001613 if (gap->ga_maxlen - gap->ga_len < n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001614 {
1615 if (n < gap->ga_growsize)
1616 n = gap->ga_growsize;
1617 len = gap->ga_itemsize * (gap->ga_len + n);
1618 pp = alloc_clear((unsigned)len);
1619 if (pp == NULL)
1620 return FAIL;
Bram Moolenaar86b68352004-12-27 21:59:20 +00001621 gap->ga_maxlen = gap->ga_len + n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001622 if (gap->ga_data != NULL)
1623 {
1624 mch_memmove(pp, gap->ga_data,
1625 (size_t)(gap->ga_itemsize * gap->ga_len));
1626 vim_free(gap->ga_data);
1627 }
1628 gap->ga_data = pp;
1629 }
1630 return OK;
1631}
1632
1633/*
1634 * Concatenate a string to a growarray which contains characters.
1635 * Note: Does NOT copy the NUL at the end!
1636 */
1637 void
1638ga_concat(gap, s)
1639 garray_T *gap;
1640 char_u *s;
1641{
1642 int len = (int)STRLEN(s);
1643
1644 if (ga_grow(gap, len) == OK)
1645 {
1646 mch_memmove((char *)gap->ga_data + gap->ga_len, s, (size_t)len);
1647 gap->ga_len += len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001648 }
1649}
1650
1651/*
1652 * Append one byte to a growarray which contains bytes.
1653 */
1654 void
1655ga_append(gap, c)
1656 garray_T *gap;
1657 int c;
1658{
1659 if (ga_grow(gap, 1) == OK)
1660 {
1661 *((char *)gap->ga_data + gap->ga_len) = c;
1662 ++gap->ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001663 }
1664}
1665
1666/************************************************************************
1667 * functions that use lookup tables for various things, generally to do with
1668 * special key codes.
1669 */
1670
1671/*
1672 * Some useful tables.
1673 */
1674
1675static struct modmasktable
1676{
1677 short mod_mask; /* Bit-mask for particular key modifier */
1678 short mod_flag; /* Bit(s) for particular key modifier */
1679 char_u name; /* Single letter name of modifier */
1680} mod_mask_table[] =
1681{
1682 {MOD_MASK_ALT, MOD_MASK_ALT, (char_u)'M'},
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001683 {MOD_MASK_META, MOD_MASK_META, (char_u)'T'},
Bram Moolenaar071d4272004-06-13 20:20:40 +00001684 {MOD_MASK_CTRL, MOD_MASK_CTRL, (char_u)'C'},
1685 {MOD_MASK_SHIFT, MOD_MASK_SHIFT, (char_u)'S'},
1686 {MOD_MASK_MULTI_CLICK, MOD_MASK_2CLICK, (char_u)'2'},
1687 {MOD_MASK_MULTI_CLICK, MOD_MASK_3CLICK, (char_u)'3'},
1688 {MOD_MASK_MULTI_CLICK, MOD_MASK_4CLICK, (char_u)'4'},
1689#ifdef MACOS
1690 {MOD_MASK_CMD, MOD_MASK_CMD, (char_u)'D'},
1691#endif
1692 /* 'A' must be the last one */
1693 {MOD_MASK_ALT, MOD_MASK_ALT, (char_u)'A'},
1694 {0, 0, NUL}
1695};
1696
1697/*
1698 * Shifted key terminal codes and their unshifted equivalent.
1699 * Don't add mouse codes here, they are handled seperately!
1700 */
1701#define MOD_KEYS_ENTRY_SIZE 5
1702
1703static char_u modifier_keys_table[] =
1704{
1705/* mod mask with modifier without modifier */
1706 MOD_MASK_SHIFT, '&', '9', '@', '1', /* begin */
1707 MOD_MASK_SHIFT, '&', '0', '@', '2', /* cancel */
1708 MOD_MASK_SHIFT, '*', '1', '@', '4', /* command */
1709 MOD_MASK_SHIFT, '*', '2', '@', '5', /* copy */
1710 MOD_MASK_SHIFT, '*', '3', '@', '6', /* create */
1711 MOD_MASK_SHIFT, '*', '4', 'k', 'D', /* delete char */
1712 MOD_MASK_SHIFT, '*', '5', 'k', 'L', /* delete line */
1713 MOD_MASK_SHIFT, '*', '7', '@', '7', /* end */
1714 MOD_MASK_CTRL, KS_EXTRA, (int)KE_C_END, '@', '7', /* end */
1715 MOD_MASK_SHIFT, '*', '9', '@', '9', /* exit */
1716 MOD_MASK_SHIFT, '*', '0', '@', '0', /* find */
1717 MOD_MASK_SHIFT, '#', '1', '%', '1', /* help */
1718 MOD_MASK_SHIFT, '#', '2', 'k', 'h', /* home */
1719 MOD_MASK_CTRL, KS_EXTRA, (int)KE_C_HOME, 'k', 'h', /* home */
1720 MOD_MASK_SHIFT, '#', '3', 'k', 'I', /* insert */
1721 MOD_MASK_SHIFT, '#', '4', 'k', 'l', /* left arrow */
1722 MOD_MASK_CTRL, KS_EXTRA, (int)KE_C_LEFT, 'k', 'l', /* left arrow */
1723 MOD_MASK_SHIFT, '%', 'a', '%', '3', /* message */
1724 MOD_MASK_SHIFT, '%', 'b', '%', '4', /* move */
1725 MOD_MASK_SHIFT, '%', 'c', '%', '5', /* next */
1726 MOD_MASK_SHIFT, '%', 'd', '%', '7', /* options */
1727 MOD_MASK_SHIFT, '%', 'e', '%', '8', /* previous */
1728 MOD_MASK_SHIFT, '%', 'f', '%', '9', /* print */
1729 MOD_MASK_SHIFT, '%', 'g', '%', '0', /* redo */
1730 MOD_MASK_SHIFT, '%', 'h', '&', '3', /* replace */
1731 MOD_MASK_SHIFT, '%', 'i', 'k', 'r', /* right arr. */
1732 MOD_MASK_CTRL, KS_EXTRA, (int)KE_C_RIGHT, 'k', 'r', /* right arr. */
1733 MOD_MASK_SHIFT, '%', 'j', '&', '5', /* resume */
1734 MOD_MASK_SHIFT, '!', '1', '&', '6', /* save */
1735 MOD_MASK_SHIFT, '!', '2', '&', '7', /* suspend */
1736 MOD_MASK_SHIFT, '!', '3', '&', '8', /* undo */
1737 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_UP, 'k', 'u', /* up arrow */
1738 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_DOWN, 'k', 'd', /* down arrow */
1739
1740 /* vt100 F1 */
1741 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF1, KS_EXTRA, (int)KE_XF1,
1742 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF2, KS_EXTRA, (int)KE_XF2,
1743 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF3, KS_EXTRA, (int)KE_XF3,
1744 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF4, KS_EXTRA, (int)KE_XF4,
1745
1746 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F1, 'k', '1', /* F1 */
1747 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F2, 'k', '2',
1748 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F3, 'k', '3',
1749 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F4, 'k', '4',
1750 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F5, 'k', '5',
1751 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F6, 'k', '6',
1752 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F7, 'k', '7',
1753 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F8, 'k', '8',
1754 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F9, 'k', '9',
1755 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F10, 'k', ';', /* F10 */
1756
1757 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F11, 'F', '1',
1758 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F12, 'F', '2',
1759 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F13, 'F', '3',
1760 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F14, 'F', '4',
1761 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F15, 'F', '5',
1762 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F16, 'F', '6',
1763 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F17, 'F', '7',
1764 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F18, 'F', '8',
1765 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F19, 'F', '9',
1766 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F20, 'F', 'A',
1767
1768 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F21, 'F', 'B',
1769 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F22, 'F', 'C',
1770 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F23, 'F', 'D',
1771 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F24, 'F', 'E',
1772 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F25, 'F', 'F',
1773 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F26, 'F', 'G',
1774 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F27, 'F', 'H',
1775 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F28, 'F', 'I',
1776 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F29, 'F', 'J',
1777 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F30, 'F', 'K',
1778
1779 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F31, 'F', 'L',
1780 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F32, 'F', 'M',
1781 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F33, 'F', 'N',
1782 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F34, 'F', 'O',
1783 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F35, 'F', 'P',
1784 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F36, 'F', 'Q',
1785 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F37, 'F', 'R',
1786
1787 /* TAB pseudo code*/
1788 MOD_MASK_SHIFT, 'k', 'B', KS_EXTRA, (int)KE_TAB,
1789
1790 NUL
1791};
1792
1793static struct key_name_entry
1794{
1795 int key; /* Special key code or ascii value */
1796 char_u *name; /* Name of key */
1797} key_names_table[] =
1798{
1799 {' ', (char_u *)"Space"},
1800 {TAB, (char_u *)"Tab"},
1801 {K_TAB, (char_u *)"Tab"},
1802 {NL, (char_u *)"NL"},
1803 {NL, (char_u *)"NewLine"}, /* Alternative name */
1804 {NL, (char_u *)"LineFeed"}, /* Alternative name */
1805 {NL, (char_u *)"LF"}, /* Alternative name */
1806 {CAR, (char_u *)"CR"},
1807 {CAR, (char_u *)"Return"}, /* Alternative name */
1808 {CAR, (char_u *)"Enter"}, /* Alternative name */
1809 {K_BS, (char_u *)"BS"},
1810 {K_BS, (char_u *)"BackSpace"}, /* Alternative name */
1811 {ESC, (char_u *)"Esc"},
1812 {CSI, (char_u *)"CSI"},
1813 {K_CSI, (char_u *)"xCSI"},
1814 {'|', (char_u *)"Bar"},
1815 {'\\', (char_u *)"Bslash"},
1816 {K_DEL, (char_u *)"Del"},
1817 {K_DEL, (char_u *)"Delete"}, /* Alternative name */
1818 {K_KDEL, (char_u *)"kDel"},
1819 {K_UP, (char_u *)"Up"},
1820 {K_DOWN, (char_u *)"Down"},
1821 {K_LEFT, (char_u *)"Left"},
1822 {K_RIGHT, (char_u *)"Right"},
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00001823 {K_XUP, (char_u *)"xUp"},
1824 {K_XDOWN, (char_u *)"xDown"},
1825 {K_XLEFT, (char_u *)"xLeft"},
1826 {K_XRIGHT, (char_u *)"xRight"},
Bram Moolenaar071d4272004-06-13 20:20:40 +00001827
1828 {K_F1, (char_u *)"F1"},
1829 {K_F2, (char_u *)"F2"},
1830 {K_F3, (char_u *)"F3"},
1831 {K_F4, (char_u *)"F4"},
1832 {K_F5, (char_u *)"F5"},
1833 {K_F6, (char_u *)"F6"},
1834 {K_F7, (char_u *)"F7"},
1835 {K_F8, (char_u *)"F8"},
1836 {K_F9, (char_u *)"F9"},
1837 {K_F10, (char_u *)"F10"},
1838
1839 {K_F11, (char_u *)"F11"},
1840 {K_F12, (char_u *)"F12"},
1841 {K_F13, (char_u *)"F13"},
1842 {K_F14, (char_u *)"F14"},
1843 {K_F15, (char_u *)"F15"},
1844 {K_F16, (char_u *)"F16"},
1845 {K_F17, (char_u *)"F17"},
1846 {K_F18, (char_u *)"F18"},
1847 {K_F19, (char_u *)"F19"},
1848 {K_F20, (char_u *)"F20"},
1849
1850 {K_F21, (char_u *)"F21"},
1851 {K_F22, (char_u *)"F22"},
1852 {K_F23, (char_u *)"F23"},
1853 {K_F24, (char_u *)"F24"},
1854 {K_F25, (char_u *)"F25"},
1855 {K_F26, (char_u *)"F26"},
1856 {K_F27, (char_u *)"F27"},
1857 {K_F28, (char_u *)"F28"},
1858 {K_F29, (char_u *)"F29"},
1859 {K_F30, (char_u *)"F30"},
1860
1861 {K_F31, (char_u *)"F31"},
1862 {K_F32, (char_u *)"F32"},
1863 {K_F33, (char_u *)"F33"},
1864 {K_F34, (char_u *)"F34"},
1865 {K_F35, (char_u *)"F35"},
1866 {K_F36, (char_u *)"F36"},
1867 {K_F37, (char_u *)"F37"},
1868
1869 {K_XF1, (char_u *)"xF1"},
1870 {K_XF2, (char_u *)"xF2"},
1871 {K_XF3, (char_u *)"xF3"},
1872 {K_XF4, (char_u *)"xF4"},
1873
1874 {K_HELP, (char_u *)"Help"},
1875 {K_UNDO, (char_u *)"Undo"},
1876 {K_INS, (char_u *)"Insert"},
1877 {K_INS, (char_u *)"Ins"}, /* Alternative name */
1878 {K_KINS, (char_u *)"kInsert"},
1879 {K_HOME, (char_u *)"Home"},
1880 {K_KHOME, (char_u *)"kHome"},
1881 {K_XHOME, (char_u *)"xHome"},
Bram Moolenaar68b76a62005-03-25 21:53:48 +00001882 {K_ZHOME, (char_u *)"zHome"},
Bram Moolenaar071d4272004-06-13 20:20:40 +00001883 {K_END, (char_u *)"End"},
1884 {K_KEND, (char_u *)"kEnd"},
1885 {K_XEND, (char_u *)"xEnd"},
Bram Moolenaar68b76a62005-03-25 21:53:48 +00001886 {K_ZEND, (char_u *)"zEnd"},
Bram Moolenaar071d4272004-06-13 20:20:40 +00001887 {K_PAGEUP, (char_u *)"PageUp"},
1888 {K_PAGEDOWN, (char_u *)"PageDown"},
1889 {K_KPAGEUP, (char_u *)"kPageUp"},
1890 {K_KPAGEDOWN, (char_u *)"kPageDown"},
1891
1892 {K_KPLUS, (char_u *)"kPlus"},
1893 {K_KMINUS, (char_u *)"kMinus"},
1894 {K_KDIVIDE, (char_u *)"kDivide"},
1895 {K_KMULTIPLY, (char_u *)"kMultiply"},
1896 {K_KENTER, (char_u *)"kEnter"},
1897 {K_KPOINT, (char_u *)"kPoint"},
1898
1899 {K_K0, (char_u *)"k0"},
1900 {K_K1, (char_u *)"k1"},
1901 {K_K2, (char_u *)"k2"},
1902 {K_K3, (char_u *)"k3"},
1903 {K_K4, (char_u *)"k4"},
1904 {K_K5, (char_u *)"k5"},
1905 {K_K6, (char_u *)"k6"},
1906 {K_K7, (char_u *)"k7"},
1907 {K_K8, (char_u *)"k8"},
1908 {K_K9, (char_u *)"k9"},
1909
1910 {'<', (char_u *)"lt"},
1911
1912 {K_MOUSE, (char_u *)"Mouse"},
1913 {K_NETTERM_MOUSE, (char_u *)"NetMouse"},
1914 {K_DEC_MOUSE, (char_u *)"DecMouse"},
1915 {K_JSBTERM_MOUSE, (char_u *)"JsbMouse"},
1916 {K_PTERM_MOUSE, (char_u *)"PtermMouse"},
1917 {K_LEFTMOUSE, (char_u *)"LeftMouse"},
1918 {K_LEFTMOUSE_NM, (char_u *)"LeftMouseNM"},
1919 {K_LEFTDRAG, (char_u *)"LeftDrag"},
1920 {K_LEFTRELEASE, (char_u *)"LeftRelease"},
1921 {K_LEFTRELEASE_NM, (char_u *)"LeftReleaseNM"},
1922 {K_MIDDLEMOUSE, (char_u *)"MiddleMouse"},
1923 {K_MIDDLEDRAG, (char_u *)"MiddleDrag"},
1924 {K_MIDDLERELEASE, (char_u *)"MiddleRelease"},
1925 {K_RIGHTMOUSE, (char_u *)"RightMouse"},
1926 {K_RIGHTDRAG, (char_u *)"RightDrag"},
1927 {K_RIGHTRELEASE, (char_u *)"RightRelease"},
1928 {K_MOUSEDOWN, (char_u *)"MouseDown"},
1929 {K_MOUSEUP, (char_u *)"MouseUp"},
1930 {K_X1MOUSE, (char_u *)"X1Mouse"},
1931 {K_X1DRAG, (char_u *)"X1Drag"},
1932 {K_X1RELEASE, (char_u *)"X1Release"},
1933 {K_X2MOUSE, (char_u *)"X2Mouse"},
1934 {K_X2DRAG, (char_u *)"X2Drag"},
1935 {K_X2RELEASE, (char_u *)"X2Release"},
1936 {K_DROP, (char_u *)"Drop"},
1937 {K_ZERO, (char_u *)"Nul"},
1938#ifdef FEAT_EVAL
1939 {K_SNR, (char_u *)"SNR"},
1940#endif
1941 {K_PLUG, (char_u *)"Plug"},
1942 {0, NULL}
1943};
1944
1945#define KEY_NAMES_TABLE_LEN (sizeof(key_names_table) / sizeof(struct key_name_entry))
1946
1947#ifdef FEAT_MOUSE
1948static struct mousetable
1949{
1950 int pseudo_code; /* Code for pseudo mouse event */
1951 int button; /* Which mouse button is it? */
1952 int is_click; /* Is it a mouse button click event? */
1953 int is_drag; /* Is it a mouse drag event? */
1954} mouse_table[] =
1955{
1956 {(int)KE_LEFTMOUSE, MOUSE_LEFT, TRUE, FALSE},
1957#ifdef FEAT_GUI
1958 {(int)KE_LEFTMOUSE_NM, MOUSE_LEFT, TRUE, FALSE},
1959#endif
1960 {(int)KE_LEFTDRAG, MOUSE_LEFT, FALSE, TRUE},
1961 {(int)KE_LEFTRELEASE, MOUSE_LEFT, FALSE, FALSE},
1962#ifdef FEAT_GUI
1963 {(int)KE_LEFTRELEASE_NM, MOUSE_LEFT, FALSE, FALSE},
1964#endif
1965 {(int)KE_MIDDLEMOUSE, MOUSE_MIDDLE, TRUE, FALSE},
1966 {(int)KE_MIDDLEDRAG, MOUSE_MIDDLE, FALSE, TRUE},
1967 {(int)KE_MIDDLERELEASE, MOUSE_MIDDLE, FALSE, FALSE},
1968 {(int)KE_RIGHTMOUSE, MOUSE_RIGHT, TRUE, FALSE},
1969 {(int)KE_RIGHTDRAG, MOUSE_RIGHT, FALSE, TRUE},
1970 {(int)KE_RIGHTRELEASE, MOUSE_RIGHT, FALSE, FALSE},
1971 {(int)KE_X1MOUSE, MOUSE_X1, TRUE, FALSE},
1972 {(int)KE_X1DRAG, MOUSE_X1, FALSE, TRUE},
1973 {(int)KE_X1RELEASE, MOUSE_X1, FALSE, FALSE},
1974 {(int)KE_X2MOUSE, MOUSE_X2, TRUE, FALSE},
1975 {(int)KE_X2DRAG, MOUSE_X2, FALSE, TRUE},
1976 {(int)KE_X2RELEASE, MOUSE_X2, FALSE, FALSE},
1977 /* DRAG without CLICK */
1978 {(int)KE_IGNORE, MOUSE_RELEASE, FALSE, TRUE},
1979 /* RELEASE without CLICK */
1980 {(int)KE_IGNORE, MOUSE_RELEASE, FALSE, FALSE},
1981 {0, 0, 0, 0},
1982};
1983#endif /* FEAT_MOUSE */
1984
1985/*
1986 * Return the modifier mask bit (MOD_MASK_*) which corresponds to the given
1987 * modifier name ('S' for Shift, 'C' for Ctrl etc).
1988 */
1989 int
1990name_to_mod_mask(c)
1991 int c;
1992{
1993 int i;
1994
1995 c = TOUPPER_ASC(c);
1996 for (i = 0; mod_mask_table[i].mod_mask != 0; i++)
1997 if (c == mod_mask_table[i].name)
1998 return mod_mask_table[i].mod_flag;
1999 return 0;
2000}
2001
Bram Moolenaar071d4272004-06-13 20:20:40 +00002002/*
2003 * Check if if there is a special key code for "key" that includes the
2004 * modifiers specified.
2005 */
2006 int
2007simplify_key(key, modifiers)
2008 int key;
2009 int *modifiers;
2010{
2011 int i;
2012 int key0;
2013 int key1;
2014
2015 if (*modifiers & (MOD_MASK_SHIFT | MOD_MASK_CTRL | MOD_MASK_ALT))
2016 {
2017 /* TAB is a special case */
2018 if (key == TAB && (*modifiers & MOD_MASK_SHIFT))
2019 {
2020 *modifiers &= ~MOD_MASK_SHIFT;
2021 return K_S_TAB;
2022 }
2023 key0 = KEY2TERMCAP0(key);
2024 key1 = KEY2TERMCAP1(key);
2025 for (i = 0; modifier_keys_table[i] != NUL; i += MOD_KEYS_ENTRY_SIZE)
2026 if (key0 == modifier_keys_table[i + 3]
2027 && key1 == modifier_keys_table[i + 4]
2028 && (*modifiers & modifier_keys_table[i]))
2029 {
2030 *modifiers &= ~modifier_keys_table[i];
2031 return TERMCAP2KEY(modifier_keys_table[i + 1],
2032 modifier_keys_table[i + 2]);
2033 }
2034 }
2035 return key;
2036}
2037
2038/*
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002039 * Change <xHome> to <Home>, <xUp> to <Up>, etc.
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002040 */
2041 int
2042handle_x_keys(key)
2043 int key;
2044{
2045 switch (key)
2046 {
2047 case K_XUP: return K_UP;
2048 case K_XDOWN: return K_DOWN;
2049 case K_XLEFT: return K_LEFT;
2050 case K_XRIGHT: return K_RIGHT;
2051 case K_XHOME: return K_HOME;
Bram Moolenaar68b76a62005-03-25 21:53:48 +00002052 case K_ZHOME: return K_HOME;
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002053 case K_XEND: return K_END;
Bram Moolenaar68b76a62005-03-25 21:53:48 +00002054 case K_ZEND: return K_END;
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002055 case K_XF1: return K_F1;
2056 case K_XF2: return K_F2;
2057 case K_XF3: return K_F3;
2058 case K_XF4: return K_F4;
2059 case K_S_XF1: return K_S_F1;
2060 case K_S_XF2: return K_S_F2;
2061 case K_S_XF3: return K_S_F3;
2062 case K_S_XF4: return K_S_F4;
2063 }
2064 return key;
2065}
2066
2067/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00002068 * Return a string which contains the name of the given key when the given
2069 * modifiers are down.
2070 */
2071 char_u *
2072get_special_key_name(c, modifiers)
2073 int c;
2074 int modifiers;
2075{
2076 static char_u string[MAX_KEY_NAME_LEN + 1];
2077
2078 int i, idx;
2079 int table_idx;
2080 char_u *s;
2081
2082 string[0] = '<';
2083 idx = 1;
2084
2085 /* Key that stands for a normal character. */
2086 if (IS_SPECIAL(c) && KEY2TERMCAP0(c) == KS_KEY)
2087 c = KEY2TERMCAP1(c);
2088
2089 /*
2090 * Translate shifted special keys into unshifted keys and set modifier.
2091 * Same for CTRL and ALT modifiers.
2092 */
2093 if (IS_SPECIAL(c))
2094 {
2095 for (i = 0; modifier_keys_table[i] != 0; i += MOD_KEYS_ENTRY_SIZE)
2096 if ( KEY2TERMCAP0(c) == (int)modifier_keys_table[i + 1]
2097 && (int)KEY2TERMCAP1(c) == (int)modifier_keys_table[i + 2])
2098 {
2099 modifiers |= modifier_keys_table[i];
2100 c = TERMCAP2KEY(modifier_keys_table[i + 3],
2101 modifier_keys_table[i + 4]);
2102 break;
2103 }
2104 }
2105
2106 /* try to find the key in the special key table */
2107 table_idx = find_special_key_in_table(c);
2108
2109 /*
2110 * When not a known special key, and not a printable character, try to
2111 * extract modifiers.
2112 */
2113 if (c > 0
2114#ifdef FEAT_MBYTE
2115 && (*mb_char2len)(c) == 1
2116#endif
2117 )
2118 {
2119 if (table_idx < 0
2120 && (!vim_isprintc(c) || (c & 0x7f) == ' ')
2121 && (c & 0x80))
2122 {
2123 c &= 0x7f;
2124 modifiers |= MOD_MASK_ALT;
2125 /* try again, to find the un-alted key in the special key table */
2126 table_idx = find_special_key_in_table(c);
2127 }
2128 if (table_idx < 0 && !vim_isprintc(c) && c < ' ')
2129 {
2130#ifdef EBCDIC
2131 c = CtrlChar(c);
2132#else
2133 c += '@';
2134#endif
2135 modifiers |= MOD_MASK_CTRL;
2136 }
2137 }
2138
2139 /* translate the modifier into a string */
2140 for (i = 0; mod_mask_table[i].name != 'A'; i++)
2141 if ((modifiers & mod_mask_table[i].mod_mask)
2142 == mod_mask_table[i].mod_flag)
2143 {
2144 string[idx++] = mod_mask_table[i].name;
2145 string[idx++] = (char_u)'-';
2146 }
2147
2148 if (table_idx < 0) /* unknown special key, may output t_xx */
2149 {
2150 if (IS_SPECIAL(c))
2151 {
2152 string[idx++] = 't';
2153 string[idx++] = '_';
2154 string[idx++] = KEY2TERMCAP0(c);
2155 string[idx++] = KEY2TERMCAP1(c);
2156 }
2157 /* Not a special key, only modifiers, output directly */
2158 else
2159 {
2160#ifdef FEAT_MBYTE
2161 if (has_mbyte && (*mb_char2len)(c) > 1)
2162 idx += (*mb_char2bytes)(c, string + idx);
2163 else
2164#endif
2165 if (vim_isprintc(c))
2166 string[idx++] = c;
2167 else
2168 {
2169 s = transchar(c);
2170 while (*s)
2171 string[idx++] = *s++;
2172 }
2173 }
2174 }
2175 else /* use name of special key */
2176 {
2177 STRCPY(string + idx, key_names_table[table_idx].name);
2178 idx = (int)STRLEN(string);
2179 }
2180 string[idx++] = '>';
2181 string[idx] = NUL;
2182 return string;
2183}
2184
2185/*
2186 * Try translating a <> name at (*srcp)[] to dst[].
2187 * Return the number of characters added to dst[], zero for no match.
2188 * If there is a match, srcp is advanced to after the <> name.
2189 * dst[] must be big enough to hold the result (up to six characters)!
2190 */
2191 int
2192trans_special(srcp, dst, keycode)
2193 char_u **srcp;
2194 char_u *dst;
2195 int keycode; /* prefer key code, e.g. K_DEL instead of DEL */
2196{
2197 int modifiers = 0;
2198 int key;
2199 int dlen = 0;
2200
2201 key = find_special_key(srcp, &modifiers, keycode);
2202 if (key == 0)
2203 return 0;
2204
2205 /* Put the appropriate modifier in a string */
2206 if (modifiers != 0)
2207 {
2208 dst[dlen++] = K_SPECIAL;
2209 dst[dlen++] = KS_MODIFIER;
2210 dst[dlen++] = modifiers;
2211 }
2212
2213 if (IS_SPECIAL(key))
2214 {
2215 dst[dlen++] = K_SPECIAL;
2216 dst[dlen++] = KEY2TERMCAP0(key);
2217 dst[dlen++] = KEY2TERMCAP1(key);
2218 }
2219#ifdef FEAT_MBYTE
2220 else if (has_mbyte && !keycode)
2221 dlen += (*mb_char2bytes)(key, dst + dlen);
2222#endif
2223 else if (keycode)
2224 dlen = (int)(add_char2buf(key, dst + dlen) - dst);
2225 else
2226 dst[dlen++] = key;
2227
2228 return dlen;
2229}
2230
2231/*
2232 * Try translating a <> name at (*srcp)[], return the key and modifiers.
2233 * srcp is advanced to after the <> name.
2234 * returns 0 if there is no match.
2235 */
2236 int
2237find_special_key(srcp, modp, keycode)
2238 char_u **srcp;
2239 int *modp;
2240 int keycode; /* prefer key code, e.g. K_DEL instead of DEL */
2241{
2242 char_u *last_dash;
2243 char_u *end_of_name;
2244 char_u *src;
2245 char_u *bp;
2246 int modifiers;
2247 int bit;
2248 int key;
2249 long_u n;
2250
2251 src = *srcp;
2252 if (src[0] != '<')
2253 return 0;
2254
2255 /* Find end of modifier list */
2256 last_dash = src;
2257 for (bp = src + 1; *bp == '-' || vim_isIDc(*bp); bp++)
2258 {
2259 if (*bp == '-')
2260 {
2261 last_dash = bp;
2262 if (bp[1] != NUL && bp[2] == '>')
2263 ++bp; /* anything accepted, like <C-?> */
2264 }
2265 if (bp[0] == 't' && bp[1] == '_' && bp[2] && bp[3])
2266 bp += 3; /* skip t_xx, xx may be '-' or '>' */
2267 }
2268
2269 if (*bp == '>') /* found matching '>' */
2270 {
2271 end_of_name = bp + 1;
2272
2273 if (STRNICMP(src + 1, "char-", 5) == 0 && VIM_ISDIGIT(src[6]))
2274 {
2275 /* <Char-123> or <Char-033> or <Char-0x33> */
2276 vim_str2nr(src + 6, NULL, NULL, TRUE, TRUE, NULL, &n);
2277 *modp = 0;
2278 *srcp = end_of_name;
2279 return (int)n;
2280 }
2281
2282 /* Which modifiers are given? */
2283 modifiers = 0x0;
2284 for (bp = src + 1; bp < last_dash; bp++)
2285 {
2286 if (*bp != '-')
2287 {
2288 bit = name_to_mod_mask(*bp);
2289 if (bit == 0x0)
2290 break; /* Illegal modifier name */
2291 modifiers |= bit;
2292 }
2293 }
2294
2295 /*
2296 * Legal modifier name.
2297 */
2298 if (bp >= last_dash)
2299 {
2300 /*
2301 * Modifier with single letter, or special key name.
2302 */
2303 if (modifiers != 0 && last_dash[2] == '>')
2304 key = last_dash[1];
2305 else
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002306 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002307 key = get_special_key_code(last_dash + 1);
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002308 key = handle_x_keys(key);
2309 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002310
2311 /*
2312 * get_special_key_code() may return NUL for invalid
2313 * special key name.
2314 */
2315 if (key != NUL)
2316 {
2317 /*
2318 * Only use a modifier when there is no special key code that
2319 * includes the modifier.
2320 */
2321 key = simplify_key(key, &modifiers);
2322
2323 if (!keycode)
2324 {
2325 /* don't want keycode, use single byte code */
2326 if (key == K_BS)
2327 key = BS;
2328 else if (key == K_DEL || key == K_KDEL)
2329 key = DEL;
2330 }
2331
2332 /*
2333 * Normal Key with modifier: Try to make a single byte code.
2334 */
2335 if (!IS_SPECIAL(key))
2336 key = extract_modifiers(key, &modifiers);
2337
2338 *modp = modifiers;
2339 *srcp = end_of_name;
2340 return key;
2341 }
2342 }
2343 }
2344 return 0;
2345}
2346
2347/*
2348 * Try to include modifiers in the key.
2349 * Changes "Shift-a" to 'A', "Alt-A" to 0xc0, etc.
2350 */
2351 int
2352extract_modifiers(key, modp)
2353 int key;
2354 int *modp;
2355{
2356 int modifiers = *modp;
2357
2358#ifdef MACOS
2359 /* Command-key really special, No fancynest */
2360 if (!(modifiers & MOD_MASK_CMD))
2361#endif
2362 if ((modifiers & MOD_MASK_SHIFT) && ASCII_ISALPHA(key))
2363 {
2364 key = TOUPPER_ASC(key);
2365 modifiers &= ~MOD_MASK_SHIFT;
2366 }
2367 if ((modifiers & MOD_MASK_CTRL)
2368#ifdef EBCDIC
2369 /* * TODO: EBCDIC Better use:
2370 * && (Ctrl_chr(key) || key == '?')
2371 * ??? */
2372 && strchr("?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_", key)
2373 != NULL
2374#else
2375 && ((key >= '?' && key <= '_') || ASCII_ISALPHA(key))
2376#endif
2377 )
2378 {
2379 key = Ctrl_chr(key);
2380 modifiers &= ~MOD_MASK_CTRL;
2381 /* <C-@> is <Nul> */
2382 if (key == 0)
2383 key = K_ZERO;
2384 }
2385#ifdef MACOS
2386 /* Command-key really special, No fancynest */
2387 if (!(modifiers & MOD_MASK_CMD))
2388#endif
2389 if ((modifiers & MOD_MASK_ALT) && key < 0x80
2390#ifdef FEAT_MBYTE
2391 && !enc_dbcs /* avoid creating a lead byte */
2392#endif
2393 )
2394 {
2395 key |= 0x80;
2396 modifiers &= ~MOD_MASK_ALT; /* remove the META modifier */
2397 }
2398
2399 *modp = modifiers;
2400 return key;
2401}
2402
2403/*
2404 * Try to find key "c" in the special key table.
2405 * Return the index when found, -1 when not found.
2406 */
2407 int
2408find_special_key_in_table(c)
2409 int c;
2410{
2411 int i;
2412
2413 for (i = 0; key_names_table[i].name != NULL; i++)
2414 if (c == key_names_table[i].key)
2415 break;
2416 if (key_names_table[i].name == NULL)
2417 i = -1;
2418 return i;
2419}
2420
2421/*
2422 * Find the special key with the given name (the given string does not have to
2423 * end with NUL, the name is assumed to end before the first non-idchar).
2424 * If the name starts with "t_" the next two characters are interpreted as a
2425 * termcap name.
2426 * Return the key code, or 0 if not found.
2427 */
2428 int
2429get_special_key_code(name)
2430 char_u *name;
2431{
2432 char_u *table_name;
2433 char_u string[3];
2434 int i, j;
2435
2436 /*
2437 * If it's <t_xx> we get the code for xx from the termcap
2438 */
2439 if (name[0] == 't' && name[1] == '_' && name[2] != NUL && name[3] != NUL)
2440 {
2441 string[0] = name[2];
2442 string[1] = name[3];
2443 string[2] = NUL;
2444 if (add_termcap_entry(string, FALSE) == OK)
2445 return TERMCAP2KEY(name[2], name[3]);
2446 }
2447 else
2448 for (i = 0; key_names_table[i].name != NULL; i++)
2449 {
2450 table_name = key_names_table[i].name;
2451 for (j = 0; vim_isIDc(name[j]) && table_name[j] != NUL; j++)
2452 if (TOLOWER_ASC(table_name[j]) != TOLOWER_ASC(name[j]))
2453 break;
2454 if (!vim_isIDc(name[j]) && table_name[j] == NUL)
2455 return key_names_table[i].key;
2456 }
2457 return 0;
2458}
2459
2460#ifdef FEAT_CMDL_COMPL
2461 char_u *
2462get_key_name(i)
2463 int i;
2464{
2465 if (i >= KEY_NAMES_TABLE_LEN)
2466 return NULL;
2467 return key_names_table[i].name;
2468}
2469#endif
2470
2471#ifdef FEAT_MOUSE
2472/*
2473 * Look up the given mouse code to return the relevant information in the other
2474 * arguments. Return which button is down or was released.
2475 */
2476 int
2477get_mouse_button(code, is_click, is_drag)
2478 int code;
2479 int *is_click;
2480 int *is_drag;
2481{
2482 int i;
2483
2484 for (i = 0; mouse_table[i].pseudo_code; i++)
2485 if (code == mouse_table[i].pseudo_code)
2486 {
2487 *is_click = mouse_table[i].is_click;
2488 *is_drag = mouse_table[i].is_drag;
2489 return mouse_table[i].button;
2490 }
2491 return 0; /* Shouldn't get here */
2492}
2493
2494/*
2495 * Return the appropriate pseudo mouse event token (KE_LEFTMOUSE etc) based on
2496 * the given information about which mouse button is down, and whether the
2497 * mouse was clicked, dragged or released.
2498 */
2499 int
2500get_pseudo_mouse_code(button, is_click, is_drag)
2501 int button; /* eg MOUSE_LEFT */
2502 int is_click;
2503 int is_drag;
2504{
2505 int i;
2506
2507 for (i = 0; mouse_table[i].pseudo_code; i++)
2508 if (button == mouse_table[i].button
2509 && is_click == mouse_table[i].is_click
2510 && is_drag == mouse_table[i].is_drag)
2511 {
2512#ifdef FEAT_GUI
Bram Moolenaarc91506a2005-04-24 22:04:21 +00002513 /* Trick: a non mappable left click and release has mouse_col -1
2514 * or added MOUSE_COLOFF. Used for 'mousefocus' in
2515 * gui_mouse_moved() */
2516 if (mouse_col < 0 || mouse_col > MOUSE_COLOFF)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002517 {
Bram Moolenaarc91506a2005-04-24 22:04:21 +00002518 if (mouse_col < 0)
2519 mouse_col = 0;
2520 else
2521 mouse_col -= MOUSE_COLOFF;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002522 if (mouse_table[i].pseudo_code == (int)KE_LEFTMOUSE)
2523 return (int)KE_LEFTMOUSE_NM;
2524 if (mouse_table[i].pseudo_code == (int)KE_LEFTRELEASE)
2525 return (int)KE_LEFTRELEASE_NM;
2526 }
2527#endif
2528 return mouse_table[i].pseudo_code;
2529 }
2530 return (int)KE_IGNORE; /* not recongnized, ignore it */
2531}
2532#endif /* FEAT_MOUSE */
2533
2534/*
2535 * Return the current end-of-line type: EOL_DOS, EOL_UNIX or EOL_MAC.
2536 */
2537 int
2538get_fileformat(buf)
2539 buf_T *buf;
2540{
2541 int c = *buf->b_p_ff;
2542
2543 if (buf->b_p_bin || c == 'u')
2544 return EOL_UNIX;
2545 if (c == 'm')
2546 return EOL_MAC;
2547 return EOL_DOS;
2548}
2549
2550/*
2551 * Like get_fileformat(), but override 'fileformat' with "p" for "++opt=val"
2552 * argument.
2553 */
2554 int
2555get_fileformat_force(buf, eap)
2556 buf_T *buf;
2557 exarg_T *eap; /* can be NULL! */
2558{
2559 int c;
2560
2561 if (eap != NULL && eap->force_ff != 0)
2562 c = eap->cmd[eap->force_ff];
2563 else
2564 {
2565 if ((eap != NULL && eap->force_bin != 0)
2566 ? (eap->force_bin == FORCE_BIN) : buf->b_p_bin)
2567 return EOL_UNIX;
2568 c = *buf->b_p_ff;
2569 }
2570 if (c == 'u')
2571 return EOL_UNIX;
2572 if (c == 'm')
2573 return EOL_MAC;
2574 return EOL_DOS;
2575}
2576
2577/*
2578 * Set the current end-of-line type to EOL_DOS, EOL_UNIX or EOL_MAC.
2579 * Sets both 'textmode' and 'fileformat'.
2580 * Note: Does _not_ set global value of 'textmode'!
2581 */
2582 void
2583set_fileformat(t, opt_flags)
2584 int t;
2585 int opt_flags; /* OPT_LOCAL and/or OPT_GLOBAL */
2586{
2587 char *p = NULL;
2588
2589 switch (t)
2590 {
2591 case EOL_DOS:
2592 p = FF_DOS;
2593 curbuf->b_p_tx = TRUE;
2594 break;
2595 case EOL_UNIX:
2596 p = FF_UNIX;
2597 curbuf->b_p_tx = FALSE;
2598 break;
2599 case EOL_MAC:
2600 p = FF_MAC;
2601 curbuf->b_p_tx = FALSE;
2602 break;
2603 }
2604 if (p != NULL)
2605 set_string_option_direct((char_u *)"ff", -1, (char_u *)p,
2606 OPT_FREE | opt_flags);
2607#ifdef FEAT_WINDOWS
2608 check_status(curbuf);
2609#endif
2610#ifdef FEAT_TITLE
2611 need_maketitle = TRUE; /* set window title later */
2612#endif
2613}
2614
2615/*
2616 * Return the default fileformat from 'fileformats'.
2617 */
2618 int
2619default_fileformat()
2620{
2621 switch (*p_ffs)
2622 {
2623 case 'm': return EOL_MAC;
2624 case 'd': return EOL_DOS;
2625 }
2626 return EOL_UNIX;
2627}
2628
2629/*
2630 * Call shell. Calls mch_call_shell, with 'shellxquote' added.
2631 */
2632 int
2633call_shell(cmd, opt)
2634 char_u *cmd;
2635 int opt;
2636{
2637 char_u *ncmd;
2638 int retval;
Bram Moolenaar05159a02005-02-26 23:04:13 +00002639#ifdef FEAT_PROFILE
2640 proftime_T wait_time;
2641#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002642
2643 if (p_verbose > 3)
2644 {
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00002645 verbose_enter();
Bram Moolenaar051b7822005-05-19 21:00:46 +00002646 smsg((char_u *)_("Calling shell to execute: \"%s\""),
Bram Moolenaar071d4272004-06-13 20:20:40 +00002647 cmd == NULL ? p_sh : cmd);
2648 out_char('\n');
2649 cursor_on();
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00002650 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002651 }
2652
Bram Moolenaar05159a02005-02-26 23:04:13 +00002653#ifdef FEAT_PROFILE
2654 if (do_profiling)
2655 prof_child_enter(&wait_time);
2656#endif
2657
Bram Moolenaar071d4272004-06-13 20:20:40 +00002658 if (*p_sh == NUL)
2659 {
2660 EMSG(_(e_shellempty));
2661 retval = -1;
2662 }
2663 else
2664 {
2665#ifdef FEAT_GUI_MSWIN
2666 /* Don't hide the pointer while executing a shell command. */
2667 gui_mch_mousehide(FALSE);
2668#endif
2669#ifdef FEAT_GUI
2670 ++hold_gui_events;
2671#endif
2672 /* The external command may update a tags file, clear cached tags. */
2673 tag_freematch();
2674
2675 if (cmd == NULL || *p_sxq == NUL)
2676 retval = mch_call_shell(cmd, opt);
2677 else
2678 {
2679 ncmd = alloc((unsigned)(STRLEN(cmd) + STRLEN(p_sxq) * 2 + 1));
2680 if (ncmd != NULL)
2681 {
2682 STRCPY(ncmd, p_sxq);
2683 STRCAT(ncmd, cmd);
2684 STRCAT(ncmd, p_sxq);
2685 retval = mch_call_shell(ncmd, opt);
2686 vim_free(ncmd);
2687 }
2688 else
2689 retval = -1;
2690 }
2691#ifdef FEAT_GUI
2692 --hold_gui_events;
2693#endif
2694 /*
2695 * Check the window size, in case it changed while executing the
2696 * external command.
2697 */
2698 shell_resized_check();
2699 }
2700
2701#ifdef FEAT_EVAL
2702 set_vim_var_nr(VV_SHELL_ERROR, (long)retval);
Bram Moolenaar05159a02005-02-26 23:04:13 +00002703# ifdef FEAT_PROFILE
2704 if (do_profiling)
2705 prof_child_exit(&wait_time);
2706# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002707#endif
2708
2709 return retval;
2710}
2711
2712/*
2713 * VISUAL and OP_PENDING State are never set, they are equal to NORMAL State
2714 * with a condition. This function returns the real State.
2715 */
2716 int
2717get_real_state()
2718{
2719 if (State & NORMAL)
2720 {
2721#ifdef FEAT_VISUAL
2722 if (VIsual_active)
2723 return VISUAL;
2724 else
2725#endif
2726 if (finish_op)
2727 return OP_PENDING;
2728 }
2729 return State;
2730}
2731
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002732#if defined(FEAT_MBYTE) || defined(PROTO)
2733/*
2734 * Return TRUE if "p" points to just after a path separator.
2735 * Take care of multi-byte characters.
2736 * "b" must point to the start of the file name
2737 */
2738 int
2739after_pathsep(b, p)
2740 char_u *b;
2741 char_u *p;
2742{
2743 return vim_ispathsep(p[-1])
2744 && (!has_mbyte || (*mb_head_off)(b, p - 1) == 0);
2745}
2746#endif
2747
2748/*
2749 * Return TRUE if file names "f1" and "f2" are in the same directory.
2750 * "f1" may be a short name, "f2" must be a full path.
2751 */
2752 int
2753same_directory(f1, f2)
2754 char_u *f1;
2755 char_u *f2;
2756{
2757 char_u ffname[MAXPATHL];
2758 char_u *t1;
2759 char_u *t2;
2760
2761 /* safety check */
2762 if (f1 == NULL || f2 == NULL)
2763 return FALSE;
2764
2765 (void)vim_FullName(f1, ffname, MAXPATHL, FALSE);
2766 t1 = gettail_sep(ffname);
2767 t2 = gettail_sep(f2);
2768 return (t1 - ffname == t2 - f2
2769 && pathcmp((char *)ffname, (char *)f2, (int)(t1 - ffname)) == 0);
2770}
2771
Bram Moolenaar071d4272004-06-13 20:20:40 +00002772#if defined(FEAT_SESSION) || defined(MSWIN) || defined(FEAT_GUI_MAC) \
Bram Moolenaar843ee412004-06-30 16:16:41 +00002773 || ((defined(FEAT_GUI_GTK) || defined(FEAT_GUI_KDE)) \
2774 && ( defined(FEAT_WINDOWS) || defined(FEAT_DND)) ) \
Bram Moolenaar071d4272004-06-13 20:20:40 +00002775 || defined(FEAT_SUN_WORKSHOP) || defined(FEAT_NETBEANS_INTG) \
2776 || defined(PROTO)
2777/*
2778 * Change to a file's directory.
2779 * Caller must call shorten_fnames()!
2780 * Return OK or FAIL.
2781 */
2782 int
2783vim_chdirfile(fname)
2784 char_u *fname;
2785{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002786 char_u dir[MAXPATHL];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002787
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002788 STRNCPY(dir, fname, MAXPATHL);
2789 dir[MAXPATHL - 1] = NUL;
2790 *gettail_sep(dir) = NUL;
2791 return mch_chdir((char *)dir) == 0 ? OK : FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002792}
2793#endif
2794
2795#if defined(STAT_IGNORES_SLASH) || defined(PROTO)
2796/*
2797 * Check if "name" ends in a slash and is not a directory.
2798 * Used for systems where stat() ignores a trailing slash on a file name.
2799 * The Vim code assumes a trailing slash is only ignored for a directory.
2800 */
2801 int
2802illegal_slash(name)
2803 char *name;
2804{
2805 if (name[0] == NUL)
2806 return FALSE; /* no file name is not illegal */
2807 if (name[strlen(name) - 1] != '/')
2808 return FALSE; /* no trailing slash */
2809 if (mch_isdir((char_u *)name))
2810 return FALSE; /* trailing slash for a directory */
2811 return TRUE;
2812}
2813#endif
2814
2815#if defined(CURSOR_SHAPE) || defined(PROTO)
2816
2817/*
2818 * Handling of cursor and mouse pointer shapes in various modes.
2819 */
2820
2821cursorentry_T shape_table[SHAPE_IDX_COUNT] =
2822{
2823 /* The values will be filled in from the 'guicursor' and 'mouseshape'
2824 * defaults when Vim starts.
2825 * Adjust the SHAPE_IDX_ defines when making changes! */
2826 {0, 0, 0, 700L, 400L, 250L, 0, 0, "n", SHAPE_CURSOR+SHAPE_MOUSE},
2827 {0, 0, 0, 700L, 400L, 250L, 0, 0, "v", SHAPE_CURSOR+SHAPE_MOUSE},
2828 {0, 0, 0, 700L, 400L, 250L, 0, 0, "i", SHAPE_CURSOR+SHAPE_MOUSE},
2829 {0, 0, 0, 700L, 400L, 250L, 0, 0, "r", SHAPE_CURSOR+SHAPE_MOUSE},
2830 {0, 0, 0, 700L, 400L, 250L, 0, 0, "c", SHAPE_CURSOR+SHAPE_MOUSE},
2831 {0, 0, 0, 700L, 400L, 250L, 0, 0, "ci", SHAPE_CURSOR+SHAPE_MOUSE},
2832 {0, 0, 0, 700L, 400L, 250L, 0, 0, "cr", SHAPE_CURSOR+SHAPE_MOUSE},
2833 {0, 0, 0, 700L, 400L, 250L, 0, 0, "o", SHAPE_CURSOR+SHAPE_MOUSE},
2834 {0, 0, 0, 700L, 400L, 250L, 0, 0, "ve", SHAPE_CURSOR+SHAPE_MOUSE},
2835 {0, 0, 0, 0L, 0L, 0L, 0, 0, "e", SHAPE_MOUSE},
2836 {0, 0, 0, 0L, 0L, 0L, 0, 0, "s", SHAPE_MOUSE},
2837 {0, 0, 0, 0L, 0L, 0L, 0, 0, "sd", SHAPE_MOUSE},
2838 {0, 0, 0, 0L, 0L, 0L, 0, 0, "vs", SHAPE_MOUSE},
2839 {0, 0, 0, 0L, 0L, 0L, 0, 0, "vd", SHAPE_MOUSE},
2840 {0, 0, 0, 0L, 0L, 0L, 0, 0, "m", SHAPE_MOUSE},
2841 {0, 0, 0, 0L, 0L, 0L, 0, 0, "ml", SHAPE_MOUSE},
2842 {0, 0, 0, 100L, 100L, 100L, 0, 0, "sm", SHAPE_CURSOR},
2843};
2844
2845#ifdef FEAT_MOUSESHAPE
2846/*
2847 * Table with names for mouse shapes. Keep in sync with all the tables for
2848 * mch_set_mouse_shape()!.
2849 */
2850static char * mshape_names[] =
2851{
2852 "arrow", /* default, must be the first one */
2853 "blank", /* hidden */
2854 "beam",
2855 "updown",
2856 "udsizing",
2857 "leftright",
2858 "lrsizing",
2859 "busy",
2860 "no",
2861 "crosshair",
2862 "hand1",
2863 "hand2",
2864 "pencil",
2865 "question",
2866 "rightup-arrow",
2867 "up-arrow",
2868 NULL
2869};
2870#endif
2871
2872/*
2873 * Parse the 'guicursor' option ("what" is SHAPE_CURSOR) or 'mouseshape'
2874 * ("what" is SHAPE_MOUSE).
2875 * Returns error message for an illegal option, NULL otherwise.
2876 */
2877 char_u *
2878parse_shape_opt(what)
2879 int what;
2880{
2881 char_u *modep;
2882 char_u *colonp;
2883 char_u *commap;
2884 char_u *slashp;
2885 char_u *p, *endp;
2886 int idx = 0; /* init for GCC */
2887 int all_idx;
2888 int len;
2889 int i;
2890 long n;
2891 int found_ve = FALSE; /* found "ve" flag */
2892 int round;
2893
2894 /*
2895 * First round: check for errors; second round: do it for real.
2896 */
2897 for (round = 1; round <= 2; ++round)
2898 {
2899 /*
2900 * Repeat for all comma separated parts.
2901 */
2902#ifdef FEAT_MOUSESHAPE
2903 if (what == SHAPE_MOUSE)
2904 modep = p_mouseshape;
2905 else
2906#endif
2907 modep = p_guicursor;
2908 while (*modep != NUL)
2909 {
2910 colonp = vim_strchr(modep, ':');
2911 if (colonp == NULL)
2912 return (char_u *)N_("E545: Missing colon");
2913 if (colonp == modep)
2914 return (char_u *)N_("E546: Illegal mode");
2915 commap = vim_strchr(modep, ',');
2916
2917 /*
2918 * Repeat for all mode's before the colon.
2919 * For the 'a' mode, we loop to handle all the modes.
2920 */
2921 all_idx = -1;
2922 while (modep < colonp || all_idx >= 0)
2923 {
2924 if (all_idx < 0)
2925 {
2926 /* Find the mode. */
2927 if (modep[1] == '-' || modep[1] == ':')
2928 len = 1;
2929 else
2930 len = 2;
2931 if (len == 1 && TOLOWER_ASC(modep[0]) == 'a')
2932 all_idx = SHAPE_IDX_COUNT - 1;
2933 else
2934 {
2935 for (idx = 0; idx < SHAPE_IDX_COUNT; ++idx)
2936 if (STRNICMP(modep, shape_table[idx].name, len)
2937 == 0)
2938 break;
2939 if (idx == SHAPE_IDX_COUNT
2940 || (shape_table[idx].used_for & what) == 0)
2941 return (char_u *)N_("E546: Illegal mode");
2942 if (len == 2 && modep[0] == 'v' && modep[1] == 'e')
2943 found_ve = TRUE;
2944 }
2945 modep += len + 1;
2946 }
2947
2948 if (all_idx >= 0)
2949 idx = all_idx--;
2950 else if (round == 2)
2951 {
2952#ifdef FEAT_MOUSESHAPE
2953 if (what == SHAPE_MOUSE)
2954 {
2955 /* Set the default, for the missing parts */
2956 shape_table[idx].mshape = 0;
2957 }
2958 else
2959#endif
2960 {
2961 /* Set the defaults, for the missing parts */
2962 shape_table[idx].shape = SHAPE_BLOCK;
2963 shape_table[idx].blinkwait = 700L;
2964 shape_table[idx].blinkon = 400L;
2965 shape_table[idx].blinkoff = 250L;
2966 }
2967 }
2968
2969 /* Parse the part after the colon */
2970 for (p = colonp + 1; *p && *p != ','; )
2971 {
2972#ifdef FEAT_MOUSESHAPE
2973 if (what == SHAPE_MOUSE)
2974 {
2975 for (i = 0; ; ++i)
2976 {
2977 if (mshape_names[i] == NULL)
2978 {
2979 if (!VIM_ISDIGIT(*p))
2980 return (char_u *)N_("E547: Illegal mouseshape");
2981 if (round == 2)
2982 shape_table[idx].mshape =
2983 getdigits(&p) + MSHAPE_NUMBERED;
2984 else
2985 (void)getdigits(&p);
2986 break;
2987 }
2988 len = (int)STRLEN(mshape_names[i]);
2989 if (STRNICMP(p, mshape_names[i], len) == 0)
2990 {
2991 if (round == 2)
2992 shape_table[idx].mshape = i;
2993 p += len;
2994 break;
2995 }
2996 }
2997 }
2998 else /* if (what == SHAPE_MOUSE) */
2999#endif
3000 {
3001 /*
3002 * First handle the ones with a number argument.
3003 */
3004 i = *p;
3005 len = 0;
3006 if (STRNICMP(p, "ver", 3) == 0)
3007 len = 3;
3008 else if (STRNICMP(p, "hor", 3) == 0)
3009 len = 3;
3010 else if (STRNICMP(p, "blinkwait", 9) == 0)
3011 len = 9;
3012 else if (STRNICMP(p, "blinkon", 7) == 0)
3013 len = 7;
3014 else if (STRNICMP(p, "blinkoff", 8) == 0)
3015 len = 8;
3016 if (len != 0)
3017 {
3018 p += len;
3019 if (!VIM_ISDIGIT(*p))
3020 return (char_u *)N_("E548: digit expected");
3021 n = getdigits(&p);
3022 if (len == 3) /* "ver" or "hor" */
3023 {
3024 if (n == 0)
3025 return (char_u *)N_("E549: Illegal percentage");
3026 if (round == 2)
3027 {
3028 if (TOLOWER_ASC(i) == 'v')
3029 shape_table[idx].shape = SHAPE_VER;
3030 else
3031 shape_table[idx].shape = SHAPE_HOR;
3032 shape_table[idx].percentage = n;
3033 }
3034 }
3035 else if (round == 2)
3036 {
3037 if (len == 9)
3038 shape_table[idx].blinkwait = n;
3039 else if (len == 7)
3040 shape_table[idx].blinkon = n;
3041 else
3042 shape_table[idx].blinkoff = n;
3043 }
3044 }
3045 else if (STRNICMP(p, "block", 5) == 0)
3046 {
3047 if (round == 2)
3048 shape_table[idx].shape = SHAPE_BLOCK;
3049 p += 5;
3050 }
3051 else /* must be a highlight group name then */
3052 {
3053 endp = vim_strchr(p, '-');
3054 if (commap == NULL) /* last part */
3055 {
3056 if (endp == NULL)
3057 endp = p + STRLEN(p); /* find end of part */
3058 }
3059 else if (endp > commap || endp == NULL)
3060 endp = commap;
3061 slashp = vim_strchr(p, '/');
3062 if (slashp != NULL && slashp < endp)
3063 {
3064 /* "group/langmap_group" */
3065 i = syn_check_group(p, (int)(slashp - p));
3066 p = slashp + 1;
3067 }
3068 if (round == 2)
3069 {
3070 shape_table[idx].id = syn_check_group(p,
3071 (int)(endp - p));
3072 shape_table[idx].id_lm = shape_table[idx].id;
3073 if (slashp != NULL && slashp < endp)
3074 shape_table[idx].id = i;
3075 }
3076 p = endp;
3077 }
3078 } /* if (what != SHAPE_MOUSE) */
3079
3080 if (*p == '-')
3081 ++p;
3082 }
3083 }
3084 modep = p;
3085 if (*modep == ',')
3086 ++modep;
3087 }
3088 }
3089
3090 /* If the 's' flag is not given, use the 'v' cursor for 's' */
3091 if (!found_ve)
3092 {
3093#ifdef FEAT_MOUSESHAPE
3094 if (what == SHAPE_MOUSE)
3095 {
3096 shape_table[SHAPE_IDX_VE].mshape = shape_table[SHAPE_IDX_V].mshape;
3097 }
3098 else
3099#endif
3100 {
3101 shape_table[SHAPE_IDX_VE].shape = shape_table[SHAPE_IDX_V].shape;
3102 shape_table[SHAPE_IDX_VE].percentage =
3103 shape_table[SHAPE_IDX_V].percentage;
3104 shape_table[SHAPE_IDX_VE].blinkwait =
3105 shape_table[SHAPE_IDX_V].blinkwait;
3106 shape_table[SHAPE_IDX_VE].blinkon =
3107 shape_table[SHAPE_IDX_V].blinkon;
3108 shape_table[SHAPE_IDX_VE].blinkoff =
3109 shape_table[SHAPE_IDX_V].blinkoff;
3110 shape_table[SHAPE_IDX_VE].id = shape_table[SHAPE_IDX_V].id;
3111 shape_table[SHAPE_IDX_VE].id_lm = shape_table[SHAPE_IDX_V].id_lm;
3112 }
3113 }
3114
3115 return NULL;
3116}
3117
3118/*
3119 * Return the index into shape_table[] for the current mode.
3120 * When "mouse" is TRUE, consider indexes valid for the mouse pointer.
3121 */
3122 int
3123get_shape_idx(mouse)
3124 int mouse;
3125{
3126#ifdef FEAT_MOUSESHAPE
3127 if (mouse && (State == HITRETURN || State == ASKMORE))
3128 {
3129# ifdef FEAT_GUI
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00003130 int x, y;
3131 gui_mch_getmouse(&x, &y);
3132 if (Y_2_ROW(y) == Rows - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003133 return SHAPE_IDX_MOREL;
3134# endif
3135 return SHAPE_IDX_MORE;
3136 }
3137 if (mouse && drag_status_line)
3138 return SHAPE_IDX_SDRAG;
3139# ifdef FEAT_VERTSPLIT
3140 if (mouse && drag_sep_line)
3141 return SHAPE_IDX_VDRAG;
3142# endif
3143#endif
3144 if (!mouse && State == SHOWMATCH)
3145 return SHAPE_IDX_SM;
3146#ifdef FEAT_VREPLACE
3147 if (State & VREPLACE_FLAG)
3148 return SHAPE_IDX_R;
3149#endif
3150 if (State & REPLACE_FLAG)
3151 return SHAPE_IDX_R;
3152 if (State & INSERT)
3153 return SHAPE_IDX_I;
3154 if (State & CMDLINE)
3155 {
3156 if (cmdline_at_end())
3157 return SHAPE_IDX_C;
3158 if (cmdline_overstrike())
3159 return SHAPE_IDX_CR;
3160 return SHAPE_IDX_CI;
3161 }
3162 if (finish_op)
3163 return SHAPE_IDX_O;
3164#ifdef FEAT_VISUAL
3165 if (VIsual_active)
3166 {
3167 if (*p_sel == 'e')
3168 return SHAPE_IDX_VE;
3169 else
3170 return SHAPE_IDX_V;
3171 }
3172#endif
3173 return SHAPE_IDX_N;
3174}
3175
3176# if defined(FEAT_MOUSESHAPE) || defined(PROTO)
3177static int old_mouse_shape = 0;
3178
3179/*
3180 * Set the mouse shape:
3181 * If "shape" is -1, use shape depending on the current mode,
3182 * depending on the current state.
3183 * If "shape" is -2, only update the shape when it's CLINE or STATUS (used
3184 * when the mouse moves off the status or command line).
3185 */
3186 void
3187update_mouseshape(shape_idx)
3188 int shape_idx;
3189{
3190 int new_mouse_shape;
3191
3192 /* Only works in GUI mode. */
Bram Moolenaar6bb68362005-03-22 23:03:44 +00003193 if (!gui.in_use || gui.starting)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003194 return;
3195
3196 /* Postpone the updating when more is to come. Speeds up executing of
3197 * mappings. */
3198 if (shape_idx == -1 && char_avail())
3199 {
3200 postponed_mouseshape = TRUE;
3201 return;
3202 }
3203
3204 if (shape_idx == -2
3205 && old_mouse_shape != shape_table[SHAPE_IDX_CLINE].mshape
3206 && old_mouse_shape != shape_table[SHAPE_IDX_STATUS].mshape
3207 && old_mouse_shape != shape_table[SHAPE_IDX_VSEP].mshape)
3208 return;
3209 if (shape_idx < 0)
3210 new_mouse_shape = shape_table[get_shape_idx(TRUE)].mshape;
3211 else
3212 new_mouse_shape = shape_table[shape_idx].mshape;
3213 if (new_mouse_shape != old_mouse_shape)
3214 {
3215 mch_set_mouse_shape(new_mouse_shape);
3216 old_mouse_shape = new_mouse_shape;
3217 }
3218 postponed_mouseshape = FALSE;
3219}
3220# endif
3221
3222#endif /* CURSOR_SHAPE */
3223
3224
3225#ifdef FEAT_CRYPT
3226/*
3227 * Optional encryption suypport.
3228 * Mohsin Ahmed, mosh@sasi.com, 98-09-24
3229 * Based on zip/crypt sources.
3230 *
3231 * NOTE FOR USA: Since 2000 exporting this code from the USA is allowed to
3232 * most countries. There are a few exceptions, but that still should not be a
3233 * problem since this code was originally created in Europe and India.
3234 */
3235
3236/* from zip.h */
3237
3238typedef unsigned short ush; /* unsigned 16-bit value */
3239typedef unsigned long ulg; /* unsigned 32-bit value */
3240
3241static void make_crc_tab __ARGS((void));
3242
Bram Moolenaard6f676d2005-06-01 21:51:55 +00003243static ulg crc_32_tab[256];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003244
3245/*
3246 * Fill the CRC table.
3247 */
3248 static void
3249make_crc_tab()
3250{
3251 ulg s,t,v;
3252 static int done = FALSE;
3253
3254 if (done)
3255 return;
3256 for (t = 0; t < 256; t++)
3257 {
3258 v = t;
3259 for (s = 0; s < 8; s++)
3260 v = (v >> 1) ^ ((v & 1) * (ulg)0xedb88320L);
3261 crc_32_tab[t] = v;
3262 }
3263 done = TRUE;
3264}
3265
3266#define CRC32(c, b) (crc_32_tab[((int)(c) ^ (b)) & 0xff] ^ ((c) >> 8))
3267
3268
3269static ulg keys[3]; /* keys defining the pseudo-random sequence */
3270
3271/*
3272 * Return the next byte in the pseudo-random sequence
3273 */
3274 int
3275decrypt_byte()
3276{
3277 ush temp;
3278
3279 temp = (ush)keys[2] | 2;
3280 return (int)(((unsigned)(temp * (temp ^ 1)) >> 8) & 0xff);
3281}
3282
3283/*
3284 * Update the encryption keys with the next byte of plain text
3285 */
3286 int
3287update_keys(c)
3288 int c; /* byte of plain text */
3289{
3290 keys[0] = CRC32(keys[0], c);
3291 keys[1] += keys[0] & 0xff;
3292 keys[1] = keys[1] * 134775813L + 1;
3293 keys[2] = CRC32(keys[2], (int)(keys[1] >> 24));
3294 return c;
3295}
3296
3297/*
3298 * Initialize the encryption keys and the random header according to
3299 * the given password.
3300 * If "passwd" is NULL or empty, don't do anything.
3301 */
3302 void
3303crypt_init_keys(passwd)
3304 char_u *passwd; /* password string with which to modify keys */
3305{
3306 if (passwd != NULL && *passwd != NUL)
3307 {
3308 make_crc_tab();
3309 keys[0] = 305419896L;
3310 keys[1] = 591751049L;
3311 keys[2] = 878082192L;
3312 while (*passwd != '\0')
3313 update_keys((int)*passwd++);
3314 }
3315}
3316
3317/*
3318 * Ask the user for a crypt key.
3319 * When "store" is TRUE, the new key in stored in the 'key' option, and the
3320 * 'key' option value is returned: Don't free it.
3321 * When "store" is FALSE, the typed key is returned in allocated memory.
3322 * Returns NULL on failure.
3323 */
3324 char_u *
3325get_crypt_key(store, twice)
3326 int store;
3327 int twice; /* Ask for the key twice. */
3328{
3329 char_u *p1, *p2 = NULL;
3330 int round;
3331
3332 for (round = 0; ; ++round)
3333 {
3334 cmdline_star = TRUE;
3335 cmdline_row = msg_row;
3336 p1 = getcmdline_prompt(NUL, round == 0
3337 ? (char_u *)_("Enter encryption key: ")
3338 : (char_u *)_("Enter same key again: "), 0);
3339 cmdline_star = FALSE;
3340
3341 if (p1 == NULL)
3342 break;
3343
3344 if (round == twice)
3345 {
3346 if (p2 != NULL && STRCMP(p1, p2) != 0)
3347 {
3348 MSG(_("Keys don't match!"));
3349 vim_free(p1);
3350 vim_free(p2);
3351 p2 = NULL;
3352 round = -1; /* do it again */
3353 continue;
3354 }
3355 if (store)
3356 {
3357 set_option_value((char_u *)"key", 0L, p1, OPT_LOCAL);
3358 vim_free(p1);
3359 p1 = curbuf->b_p_key;
3360 }
3361 break;
3362 }
3363 p2 = p1;
3364 }
3365
3366 /* since the user typed this, no need to wait for return */
3367 need_wait_return = FALSE;
3368 msg_didout = FALSE;
3369
3370 vim_free(p2);
3371 return p1;
3372}
3373
3374#endif /* FEAT_CRYPT */
3375
3376/* TODO: make some #ifdef for this */
3377/*--------[ file searching ]-------------------------------------------------*/
3378/*
3379 * File searching functions for 'path', 'tags' and 'cdpath' options.
3380 * External visible functions:
3381 * vim_findfile_init() creates/initialises the search context
3382 * vim_findfile_free_visited() free list of visited files/dirs of search
3383 * context
3384 * vim_findfile() find a file in the search context
3385 * vim_findfile_cleanup() cleanup/free search context created by
3386 * vim_findfile_init()
3387 *
3388 * All static functions and variables start with 'ff_'
3389 *
3390 * In general it works like this:
3391 * First you create yourself a search context by calling vim_findfile_init().
3392 * It is possible to give a search context from a previous call to
3393 * vim_findfile_init(), so it can be reused. After this you call vim_findfile()
3394 * until you are satisfied with the result or it returns NULL. On every call it
3395 * returns the next file which matches the conditions given to
3396 * vim_findfile_init(). If it doesn't find a next file it returns NULL.
3397 *
3398 * It is possible to call vim_findfile_init() again to reinitialise your search
3399 * with some new parameters. Don't forget to pass your old search context to
3400 * it, so it can reuse it and especially reuse the list of already visited
3401 * directories. If you want to delete the list of already visited directories
3402 * simply call vim_findfile_free_visited().
3403 *
3404 * When you are done call vim_findfile_cleanup() to free the search context.
3405 *
3406 * The function vim_findfile_init() has a long comment, which describes the
3407 * needed parameters.
3408 *
3409 *
3410 *
3411 * ATTENTION:
3412 * ==========
3413 * Also we use an allocated search context here, this functions ARE NOT
3414 * thread-safe!!!!!
3415 *
3416 * To minimize parameter passing (or because I'm to lazy), only the
3417 * external visible functions get a search context as a parameter. This is
3418 * then assigned to a static global, which is used throughout the local
3419 * functions.
3420 */
3421
3422/*
3423 * type for the directory search stack
3424 */
3425typedef struct ff_stack
3426{
3427 struct ff_stack *ffs_prev;
3428
3429 /* the fix part (no wildcards) and the part containing the wildcards
3430 * of the search path
3431 */
3432 char_u *ffs_fix_path;
3433#ifdef FEAT_PATH_EXTRA
3434 char_u *ffs_wc_path;
3435#endif
3436
3437 /* files/dirs found in the above directory, matched by the first wildcard
3438 * of wc_part
3439 */
3440 char_u **ffs_filearray;
3441 int ffs_filearray_size;
3442 char_u ffs_filearray_cur; /* needed for partly handled dirs */
3443
3444 /* to store status of partly handled directories
3445 * 0: we work the on this directory for the first time
3446 * 1: this directory was partly searched in an earlier step
3447 */
3448 int ffs_stage;
3449
3450 /* How deep are we in the directory tree?
3451 * Counts backward from value of level parameter to vim_findfile_init
3452 */
3453 int ffs_level;
3454
3455 /* Did we already expand '**' to an empty string? */
3456 int ffs_star_star_empty;
3457} ff_stack_T;
3458
3459/*
3460 * type for already visited directories or files.
3461 */
3462typedef struct ff_visited
3463{
3464 struct ff_visited *ffv_next;
3465
3466#ifdef FEAT_PATH_EXTRA
3467 /* Visited directories are different if the wildcard string are
3468 * different. So we have to save it.
3469 */
3470 char_u *ffv_wc_path;
3471#endif
3472 /* for unix use inode etc for comparison (needed because of links), else
3473 * use filename.
3474 */
3475#ifdef UNIX
3476 int ffv_dev; /* device number (-1 if not set) */
3477 ino_t ffv_ino; /* inode number */
3478#endif
3479 /* The memory for this struct is allocated according to the length of
3480 * ffv_fname.
3481 */
3482 char_u ffv_fname[1]; /* actually longer */
3483} ff_visited_T;
3484
3485/*
3486 * We might have to manage several visited lists during a search.
3487 * This is expecially needed for the tags option. If tags is set to:
3488 * "./++/tags,./++/TAGS,++/tags" (replace + with *)
3489 * So we have to do 3 searches:
3490 * 1) search from the current files directory downward for the file "tags"
3491 * 2) search from the current files directory downward for the file "TAGS"
3492 * 3) search from Vims current directory downwards for the file "tags"
3493 * As you can see, the first and the third search are for the same file, so for
3494 * the third search we can use the visited list of the first search. For the
3495 * second search we must start from a empty visited list.
3496 * The struct ff_visited_list_hdr is used to manage a linked list of already
3497 * visited lists.
3498 */
3499typedef struct ff_visited_list_hdr
3500{
3501 struct ff_visited_list_hdr *ffvl_next;
3502
3503 /* the filename the attached visited list is for */
3504 char_u *ffvl_filename;
3505
3506 ff_visited_T *ffvl_visited_list;
3507
3508} ff_visited_list_hdr_T;
3509
3510
3511/*
3512 * '**' can be expanded to several directory levels.
3513 * Set the default maximium depth.
3514 */
3515#define FF_MAX_STAR_STAR_EXPAND ((char_u)30)
3516/*
3517 * The search context:
3518 * ffsc_stack_ptr: the stack for the dirs to search
3519 * ffsc_visited_list: the currently active visited list
3520 * ffsc_dir_visited_list: the currently active visited list for search dirs
3521 * ffsc_visited_lists_list: the list of all visited lists
3522 * ffsc_dir_visited_lists_list: the list of all visited lists for search dirs
3523 * ffsc_file_to_search: the file to search for
3524 * ffsc_start_dir: the starting directory, if search path was relative
3525 * ffsc_fix_path: the fix part of the given path (without wildcards)
3526 * Needed for upward search.
3527 * ffsc_wc_path: the part of the given path containing wildcards
3528 * ffsc_level: how many levels of dirs to search downwards
3529 * ffsc_stopdirs_v: array of stop directories for upward search
3530 * ffsc_need_dir: TRUE if we search for a directory
3531 */
3532typedef struct ff_search_ctx_T
3533{
3534 ff_stack_T *ffsc_stack_ptr;
3535 ff_visited_list_hdr_T *ffsc_visited_list;
3536 ff_visited_list_hdr_T *ffsc_dir_visited_list;
3537 ff_visited_list_hdr_T *ffsc_visited_lists_list;
3538 ff_visited_list_hdr_T *ffsc_dir_visited_lists_list;
3539 char_u *ffsc_file_to_search;
3540 char_u *ffsc_start_dir;
3541 char_u *ffsc_fix_path;
3542#ifdef FEAT_PATH_EXTRA
3543 char_u *ffsc_wc_path;
3544 int ffsc_level;
3545 char_u **ffsc_stopdirs_v;
3546#endif
3547 int ffsc_need_dir;
3548}ff_search_ctx_T;
3549static ff_search_ctx_T *ff_search_ctx = NULL;
3550
3551/* used for expanding filenames */
3552static char_u *ff_expand_buffer = NULL;
3553
3554/* locally needed functions */
3555#ifdef FEAT_PATH_EXTRA
3556static int ff_check_visited __ARGS((ff_visited_T **, char_u *, char_u *));
3557#else
3558static int ff_check_visited __ARGS((ff_visited_T **, char_u *));
3559#endif
3560static void vim_findfile_free_visited_list __ARGS((ff_visited_list_hdr_T **list_headp));
3561static void ff_free_visited_list __ARGS((ff_visited_T *vl));
3562static ff_visited_list_hdr_T* ff_get_visited_list __ARGS((char_u *, ff_visited_list_hdr_T **list_headp));
3563#ifdef FEAT_PATH_EXTRA
3564static int ff_wc_equal __ARGS((char_u *s1, char_u *s2));
3565#endif
3566
3567static void ff_push __ARGS((ff_stack_T *));
3568static ff_stack_T * ff_pop __ARGS((void));
3569static void ff_clear __ARGS((void));
3570static void ff_free_stack_element __ARGS((ff_stack_T *));
3571#ifdef FEAT_PATH_EXTRA
3572static ff_stack_T *ff_create_stack_element __ARGS((char_u *, char_u *, int, int));
3573#else
3574static ff_stack_T *ff_create_stack_element __ARGS((char_u *, int, int));
3575#endif
3576#ifdef FEAT_PATH_EXTRA
3577static int ff_path_in_stoplist __ARGS((char_u *, int, char_u **));
3578#endif
3579
Bram Moolenaar071d4272004-06-13 20:20:40 +00003580#if 0
3581/*
3582 * if someone likes findfirst/findnext, here are the functions
3583 * NOT TESTED!!
3584 */
3585
3586static void *ff_fn_search_context = NULL;
3587
3588 char_u *
3589vim_findfirst(path, filename, level)
3590 char_u *path;
3591 char_u *filename;
3592 int level;
3593{
3594 ff_fn_search_context =
3595 vim_findfile_init(path, filename, NULL, level, TRUE, FALSE,
3596 ff_fn_search_context, rel_fname);
3597 if (NULL == ff_fn_search_context)
3598 return NULL;
3599 else
3600 return vim_findnext()
3601}
3602
3603 char_u *
3604vim_findnext()
3605{
3606 char_u *ret = vim_findfile(ff_fn_search_context);
3607
3608 if (NULL == ret)
3609 {
3610 vim_findfile_cleanup(ff_fn_search_context);
3611 ff_fn_search_context = NULL;
3612 }
3613 return ret;
3614}
3615#endif
3616
3617/*
3618 * Initialization routine for vim_findfile.
3619 *
3620 * Returns the newly allocated search context or NULL if an error occured.
3621 *
3622 * Don't forget to clean up by calling vim_findfile_cleanup() if you are done
3623 * with the search context.
3624 *
3625 * Find the file 'filename' in the directory 'path'.
3626 * The parameter 'path' may contain wildcards. If so only search 'level'
3627 * directories deep. The parameter 'level' is the absolute maximum and is
3628 * not related to restricts given to the '**' wildcard. If 'level' is 100
3629 * and you use '**200' vim_findfile() will stop after 100 levels.
3630 *
3631 * If 'stopdirs' is not NULL and nothing is found downward, the search is
3632 * restarted on the next higher directory level. This is repeated until the
3633 * start-directory of a search is contained in 'stopdirs'. 'stopdirs' has the
3634 * format ";*<dirname>*\(;<dirname>\)*;\=$".
3635 *
3636 * If the 'path' is relative, the starting dir for the search is either VIM's
3637 * current dir or if the path starts with "./" the current files dir.
3638 * If the 'path' is absolut, the starting dir is that part of the path before
3639 * the first wildcard.
3640 *
3641 * Upward search is only done on the starting dir.
3642 *
3643 * If 'free_visited' is TRUE the list of already visited files/directories is
3644 * cleared. Set this to FALSE if you just want to search from another
3645 * directory, but want to be sure that no directory from a previous search is
3646 * searched again. This is useful if you search for a file at different places.
3647 * The list of visited files/dirs can also be cleared with the function
3648 * vim_findfile_free_visited().
3649 *
3650 * Set the parameter 'need_dir' to TRUE if you want to search for a directory
3651 * instead of a file.
3652 *
3653 * A search context returned by a previous call to vim_findfile_init() can be
3654 * passed in the parameter 'search_ctx'. This context is than reused and
3655 * reinitialized with the new parameters. The list of already viseted
3656 * directories from this context is only deleted if the parameter
3657 * 'free_visited' is true. Be aware that the passed search_context is freed if
3658 * the reinitialization fails.
3659 *
3660 * If you don't have a search context from a previous call 'search_ctx' must be
3661 * NULL.
3662 *
3663 * This function silently ignores a few errors, vim_findfile() will have
3664 * limited functionality then.
3665 */
3666/*ARGSUSED*/
3667 void *
3668vim_findfile_init(path, filename, stopdirs, level, free_visited, need_dir,
3669 search_ctx, tagfile, rel_fname)
3670 char_u *path;
3671 char_u *filename;
3672 char_u *stopdirs;
3673 int level;
3674 int free_visited;
3675 int need_dir;
3676 void *search_ctx;
3677 int tagfile;
3678 char_u *rel_fname; /* file name to use for "." */
3679{
3680#ifdef FEAT_PATH_EXTRA
3681 char_u *wc_part;
3682#endif
3683 ff_stack_T *sptr;
3684
3685 /* If a search context is given by the caller, reuse it, else allocate a
3686 * new one.
3687 */
3688 if (search_ctx != NULL)
3689 ff_search_ctx = search_ctx;
3690 else
3691 {
3692 ff_search_ctx = (ff_search_ctx_T*)alloc(
3693 (unsigned)sizeof(ff_search_ctx_T));
3694 if (ff_search_ctx == NULL)
3695 goto error_return;
3696 memset(ff_search_ctx, 0, sizeof(ff_search_ctx_T));
3697 }
3698
3699 /* clear the search context, but NOT the visited lists */
3700 ff_clear();
3701
3702 /* clear visited list if wanted */
3703 if (free_visited == TRUE)
3704 vim_findfile_free_visited(ff_search_ctx);
3705 else
3706 {
3707 /* Reuse old visited lists. Get the visited list for the given
3708 * filename. If no list for the current filename exists, creates a new
3709 * one.
3710 */
3711 ff_search_ctx->ffsc_visited_list = ff_get_visited_list(filename,
3712 &ff_search_ctx->ffsc_visited_lists_list);
3713 if (ff_search_ctx->ffsc_visited_list == NULL)
3714 goto error_return;
3715 ff_search_ctx->ffsc_dir_visited_list = ff_get_visited_list(filename,
3716 &ff_search_ctx->ffsc_dir_visited_lists_list);
3717 if (ff_search_ctx->ffsc_dir_visited_list == NULL)
3718 goto error_return;
3719 }
3720
3721 if (ff_expand_buffer == NULL)
3722 {
3723 ff_expand_buffer = (char_u*)alloc(MAXPATHL);
3724 if (ff_expand_buffer == NULL)
3725 goto error_return;
3726 }
3727
3728 /* Store information on starting dir now if path is relative.
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00003729 * If path is absolute, we do that later. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003730 if (path[0] == '.'
3731 && (vim_ispathsep(path[1]) || path[1] == NUL)
3732 && (!tagfile || vim_strchr(p_cpo, CPO_DOTTAG) == NULL)
3733 && rel_fname != NULL)
3734 {
3735 int len = (int)(gettail(rel_fname) - rel_fname);
3736
3737 if (!vim_isAbsName(rel_fname) && len + 1 < MAXPATHL)
3738 {
3739 /* Make the start dir an absolute path name. */
3740 STRNCPY(ff_expand_buffer, rel_fname, len);
3741 ff_expand_buffer[len] = NUL;
3742 ff_search_ctx->ffsc_start_dir = FullName_save(ff_expand_buffer,
3743 FALSE);
3744 }
3745 else
3746 ff_search_ctx->ffsc_start_dir = vim_strnsave(rel_fname, len);
3747 if (ff_search_ctx->ffsc_start_dir == NULL)
3748 goto error_return;
3749 if (*++path != NUL)
3750 ++path;
3751 }
3752 else if (*path == NUL || !vim_isAbsName(path))
3753 {
3754#ifdef BACKSLASH_IN_FILENAME
3755 /* "c:dir" needs "c:" to be expanded, otherwise use current dir */
3756 if (*path != NUL && path[1] == ':')
3757 {
3758 char_u drive[3];
3759
3760 drive[0] = path[0];
3761 drive[1] = ':';
3762 drive[2] = NUL;
3763 if (vim_FullName(drive, ff_expand_buffer, MAXPATHL, TRUE) == FAIL)
3764 goto error_return;
3765 path += 2;
3766 }
3767 else
3768#endif
3769 if (mch_dirname(ff_expand_buffer, MAXPATHL) == FAIL)
3770 goto error_return;
3771
3772 ff_search_ctx->ffsc_start_dir = vim_strsave(ff_expand_buffer);
3773 if (ff_search_ctx->ffsc_start_dir == NULL)
3774 goto error_return;
3775
3776#ifdef BACKSLASH_IN_FILENAME
3777 /* A path that starts with "/dir" is relative to the drive, not to the
3778 * directory (but not for "//machine/dir"). Only use the drive name. */
3779 if ((*path == '/' || *path == '\\')
3780 && path[1] != path[0]
3781 && ff_search_ctx->ffsc_start_dir[1] == ':')
3782 ff_search_ctx->ffsc_start_dir[2] = NUL;
3783#endif
3784 }
3785
3786#ifdef FEAT_PATH_EXTRA
3787 /*
3788 * If stopdirs are given, split them into an array of pointers.
3789 * If this fails (mem allocation), there is no upward search at all or a
3790 * stop directory is not recognized -> continue silently.
3791 * If stopdirs just contains a ";" or is empty,
3792 * ff_search_ctx->ffsc_stopdirs_v will only contain a NULL pointer. This
3793 * is handled as unlimited upward search. See function
3794 * ff_path_in_stoplist() for details.
3795 */
3796 if (stopdirs != NULL)
3797 {
3798 char_u *walker = stopdirs;
3799 int dircount;
3800
3801 while (*walker == ';')
3802 walker++;
3803
3804 dircount = 1;
3805 ff_search_ctx->ffsc_stopdirs_v =
3806 (char_u **)alloc((unsigned)sizeof(char_u *));
3807
3808 if (ff_search_ctx->ffsc_stopdirs_v != NULL)
3809 {
3810 do
3811 {
3812 char_u *helper;
3813 void *ptr;
3814
3815 helper = walker;
3816 ptr = vim_realloc(ff_search_ctx->ffsc_stopdirs_v,
3817 (dircount + 1) * sizeof(char_u *));
3818 if (ptr)
3819 ff_search_ctx->ffsc_stopdirs_v = ptr;
3820 else
3821 /* ignore, keep what we have and continue */
3822 break;
3823 walker = vim_strchr(walker, ';');
3824 if (walker)
3825 {
3826 ff_search_ctx->ffsc_stopdirs_v[dircount-1] =
3827 vim_strnsave(helper, (int)(walker - helper));
3828 walker++;
3829 }
3830 else
3831 /* this might be "", which means ascent till top
3832 * of directory tree.
3833 */
3834 ff_search_ctx->ffsc_stopdirs_v[dircount-1] =
3835 vim_strsave(helper);
3836
3837 dircount++;
3838
3839 } while (walker != NULL);
3840 ff_search_ctx->ffsc_stopdirs_v[dircount-1] = NULL;
3841 }
3842 }
3843#endif
3844
3845#ifdef FEAT_PATH_EXTRA
3846 ff_search_ctx->ffsc_level = level;
3847
3848 /* split into:
3849 * -fix path
3850 * -wildcard_stuff (might be NULL)
3851 */
3852 wc_part = vim_strchr(path, '*');
3853 if (wc_part != NULL)
3854 {
3855 int llevel;
3856 int len;
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00003857 char *errpt;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003858
3859 /* save the fix part of the path */
3860 ff_search_ctx->ffsc_fix_path = vim_strnsave(path,
3861 (int)(wc_part - path));
3862
3863 /*
3864 * copy wc_path and add restricts to the '**' wildcard.
3865 * The octett after a '**' is used as a (binary) counter.
3866 * So '**3' is transposed to '**^C' ('^C' is ASCII value 3)
3867 * or '**76' is transposed to '**N'( 'N' is ASCII value 76).
3868 * For EBCDIC you get different character values.
3869 * If no restrict is given after '**' the default is used.
3870 * Due to this technic the path looks awful if you print it as a
3871 * string.
3872 */
3873 len = 0;
3874 while (*wc_part != NUL)
3875 {
3876 if (STRNCMP(wc_part, "**", 2) == 0)
3877 {
3878 ff_expand_buffer[len++] = *wc_part++;
3879 ff_expand_buffer[len++] = *wc_part++;
3880
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00003881 llevel = strtol((char *)wc_part, &errpt, 10);
3882 if ((char_u *)errpt != wc_part && llevel > 0 && llevel < 255)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003883 ff_expand_buffer[len++] = llevel;
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00003884 else if ((char_u *)errpt != wc_part && llevel == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003885 /* restrict is 0 -> remove already added '**' */
3886 len -= 2;
3887 else
3888 ff_expand_buffer[len++] = FF_MAX_STAR_STAR_EXPAND;
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00003889 wc_part = (char_u *)errpt;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003890 if (*wc_part != PATHSEP && *wc_part != NUL)
3891 {
3892 EMSG2(_("E343: Invalid path: '**[number]' must be at the end of the path or be followed by '%s'."), PATHSEPSTR);
3893 goto error_return;
3894 }
3895 }
3896 else
3897 ff_expand_buffer[len++] = *wc_part++;
3898 }
3899 ff_expand_buffer[len] = NUL;
3900 ff_search_ctx->ffsc_wc_path =
3901 vim_strsave(ff_expand_buffer);
3902
3903 if (ff_search_ctx->ffsc_wc_path == NULL)
3904 goto error_return;
3905 }
3906 else
3907#endif
3908 ff_search_ctx->ffsc_fix_path = vim_strsave(path);
3909
3910 if (ff_search_ctx->ffsc_start_dir == NULL)
3911 {
3912 /* store the fix part as startdir.
3913 * This is needed if the parameter path is fully qualified.
3914 */
3915 ff_search_ctx->ffsc_start_dir = vim_strsave(ff_search_ctx->ffsc_fix_path);
3916 if (ff_search_ctx->ffsc_start_dir)
3917 ff_search_ctx->ffsc_fix_path[0] = NUL;
3918 }
3919
3920 /* create an absolute path */
3921 STRCPY(ff_expand_buffer, ff_search_ctx->ffsc_start_dir);
3922 add_pathsep(ff_expand_buffer);
3923 STRCAT(ff_expand_buffer, ff_search_ctx->ffsc_fix_path);
3924 add_pathsep(ff_expand_buffer);
3925
3926 sptr = ff_create_stack_element(ff_expand_buffer,
3927#ifdef FEAT_PATH_EXTRA
3928 ff_search_ctx->ffsc_wc_path,
3929#endif
3930 level, 0);
3931
3932 if (sptr == NULL)
3933 goto error_return;
3934
3935 ff_push(sptr);
3936
3937 ff_search_ctx->ffsc_file_to_search = vim_strsave(filename);
3938 if (ff_search_ctx->ffsc_file_to_search == NULL)
3939 goto error_return;
3940
3941 return ff_search_ctx;
3942
3943error_return:
3944 /*
3945 * We clear the search context now!
3946 * Even when the caller gave us a (perhaps valid) context we free it here,
3947 * as we might have already destroyed it.
3948 */
3949 vim_findfile_cleanup(ff_search_ctx);
3950 return NULL;
3951}
3952
3953#if defined(FEAT_PATH_EXTRA) || defined(PROTO)
3954/*
3955 * Get the stopdir string. Check that ';' is not escaped.
3956 */
3957 char_u *
3958vim_findfile_stopdir(buf)
3959 char_u *buf;
3960{
3961 char_u *r_ptr = buf;
3962
3963 while (*r_ptr != NUL && *r_ptr != ';')
3964 {
3965 if (r_ptr[0] == '\\' && r_ptr[1] == ';')
3966 {
3967 /* overwrite the escape char,
3968 * use STRLEN(r_ptr) to move the trailing '\0'
3969 */
3970 mch_memmove(r_ptr, r_ptr + 1, STRLEN(r_ptr));
3971 r_ptr++;
3972 }
3973 r_ptr++;
3974 }
3975 if (*r_ptr == ';')
3976 {
3977 *r_ptr = 0;
3978 r_ptr++;
3979 }
3980 else if (*r_ptr == NUL)
3981 r_ptr = NULL;
3982 return r_ptr;
3983}
3984#endif
3985
3986/* Clean up the given search context. Can handle a NULL pointer */
3987 void
3988vim_findfile_cleanup(ctx)
3989 void *ctx;
3990{
3991 if (NULL == ctx)
3992 return;
3993
3994 ff_search_ctx = ctx;
3995
3996 vim_findfile_free_visited(ctx);
3997 ff_clear();
3998 vim_free(ctx);
3999 ff_search_ctx = NULL;
4000}
4001
4002/*
4003 * Find a file in a search context.
4004 * The search context was created with vim_findfile_init() above.
4005 * Return a pointer to an allocated file name or NULL if nothing found.
4006 * To get all matching files call this function until you get NULL.
4007 *
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00004008 * If the passed search_context is NULL, NULL is returned.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004009 *
4010 * The search algorithm is depth first. To change this replace the
4011 * stack with a list (don't forget to leave partly searched directories on the
4012 * top of the list).
4013 */
4014 char_u *
4015vim_findfile(search_ctx)
4016 void *search_ctx;
4017{
4018 char_u *file_path;
4019#ifdef FEAT_PATH_EXTRA
4020 char_u *rest_of_wildcards;
4021 char_u *path_end = NULL;
4022#endif
4023 ff_stack_T *ctx;
4024#if defined(FEAT_SEARCHPATH) || defined(FEAT_PATH_EXTRA)
4025 int len;
4026#endif
4027 int i;
4028 char_u *p;
4029#ifdef FEAT_SEARCHPATH
4030 char_u *suf;
4031#endif
4032
4033 if (search_ctx == NULL)
4034 return NULL;
4035
4036 ff_search_ctx = (ff_search_ctx_T*)search_ctx;
4037
4038 /*
4039 * filepath is used as buffer for various actions and as the storage to
4040 * return a found filename.
4041 */
4042 if ((file_path = alloc((int)MAXPATHL)) == NULL)
4043 return NULL;
4044
4045#ifdef FEAT_PATH_EXTRA
4046 /* store the end of the start dir -- needed for upward search */
4047 if (ff_search_ctx->ffsc_start_dir != NULL)
4048 path_end = &ff_search_ctx->ffsc_start_dir[STRLEN(ff_search_ctx->ffsc_start_dir)];
4049#endif
4050
4051#ifdef FEAT_PATH_EXTRA
4052 /* upward search loop */
4053 for (;;)
4054 {
4055#endif
4056 /* downward search loop */
4057 for (;;)
4058 {
4059 /* check if user user wants to stop the search*/
4060 ui_breakcheck();
4061 if (got_int)
4062 break;
4063
4064 /* get directory to work on from stack */
4065 ctx = ff_pop();
4066 if (ctx == NULL)
4067 break;
4068
4069 /*
4070 * TODO: decide if we leave this test in
4071 *
4072 * GOOD: don't search a directory(-tree) twice.
4073 * BAD: - check linked list for every new directory entered.
4074 * - check for double files also done below
4075 *
4076 * Here we check if we already searched this directory.
4077 * We already searched a directory if:
4078 * 1) The directory is the same.
4079 * 2) We would use the same wildcard string.
4080 *
4081 * Good if you have links on same directory via several ways
4082 * or you have selfreferences in directories (e.g. SuSE Linux 6.3:
4083 * /etc/rc.d/init.d is linked to /etc/rc.d -> endless loop)
4084 *
4085 * This check is only needed for directories we work on for the
4086 * first time (hence ctx->ff_filearray == NULL)
4087 */
4088 if (ctx->ffs_filearray == NULL
4089 && ff_check_visited(&ff_search_ctx->ffsc_dir_visited_list
4090 ->ffvl_visited_list,
4091 ctx->ffs_fix_path
4092#ifdef FEAT_PATH_EXTRA
4093 , ctx->ffs_wc_path
4094#endif
4095 ) == FAIL)
4096 {
4097#ifdef FF_VERBOSE
4098 if (p_verbose >= 5)
4099 {
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004100 verbose_enter_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004101 smsg((char_u *)"Already Searched: %s (%s)",
4102 ctx->ffs_fix_path, ctx->ffs_wc_path);
4103 /* don't overwrite this either */
4104 msg_puts((char_u *)"\n");
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004105 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004106 }
4107#endif
4108 ff_free_stack_element(ctx);
4109 continue;
4110 }
4111#ifdef FF_VERBOSE
4112 else if (p_verbose >= 5)
4113 {
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004114 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00004115 smsg((char_u *)"Searching: %s (%s)",
4116 ctx->ffs_fix_path, ctx->ffs_wc_path);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004117 /* don't overwrite this either */
4118 msg_puts((char_u *)"\n");
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004119 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004120 }
4121#endif
4122
4123 /* check depth */
4124 if (ctx->ffs_level <= 0)
4125 {
4126 ff_free_stack_element(ctx);
4127 continue;
4128 }
4129
4130 file_path[0] = NUL;
4131
4132 /*
4133 * If no filearray till now expand wildcards
4134 * The function expand_wildcards() can handle an array of paths
4135 * and all possible expands are returned in one array. We use this
4136 * to handle the expansion of '**' into an empty string.
4137 */
4138 if (ctx->ffs_filearray == NULL)
4139 {
4140 char_u *dirptrs[2];
4141
4142 /* we use filepath to build the path expand_wildcards() should
4143 * expand.
4144 */
4145 dirptrs[0] = file_path;
4146 dirptrs[1] = NULL;
4147
4148 /* if we have a start dir copy it in */
4149 if (!vim_isAbsName(ctx->ffs_fix_path)
4150 && ff_search_ctx->ffsc_start_dir)
4151 {
4152 STRCPY(file_path, ff_search_ctx->ffsc_start_dir);
4153 add_pathsep(file_path);
4154 }
4155
4156 /* append the fix part of the search path */
4157 STRCAT(file_path, ctx->ffs_fix_path);
4158 add_pathsep(file_path);
4159
4160#ifdef FEAT_PATH_EXTRA
4161 rest_of_wildcards = ctx->ffs_wc_path;
4162 if (*rest_of_wildcards != NUL)
4163 {
4164 len = (int)STRLEN(file_path);
4165 if (STRNCMP(rest_of_wildcards, "**", 2) == 0)
4166 {
4167 /* pointer to the restrict byte
4168 * The restrict byte is not a character!
4169 */
4170 p = rest_of_wildcards + 2;
4171
4172 if (*p > 0)
4173 {
4174 (*p)--;
4175 file_path[len++] = '*';
4176 }
4177
4178 if (*p == 0)
4179 {
4180 /* remove '**<numb> from wildcards */
4181 mch_memmove(rest_of_wildcards,
4182 rest_of_wildcards + 3,
4183 STRLEN(rest_of_wildcards + 3) + 1);
4184 }
4185 else
4186 rest_of_wildcards += 3;
4187
4188 if (ctx->ffs_star_star_empty == 0)
4189 {
4190 /* if not done before, expand '**' to empty */
4191 ctx->ffs_star_star_empty = 1;
4192 dirptrs[1] = ctx->ffs_fix_path;
4193 }
4194 }
4195
4196 /*
4197 * Here we copy until the next path separator or the end of
4198 * the path. If we stop at a path separator, there is
4199 * still somthing else left. This is handled below by
4200 * pushing every directory returned from expand_wildcards()
4201 * on the stack again for further search.
4202 */
4203 while (*rest_of_wildcards
4204 && !vim_ispathsep(*rest_of_wildcards))
4205 file_path[len++] = *rest_of_wildcards++;
4206
4207 file_path[len] = NUL;
4208 if (vim_ispathsep(*rest_of_wildcards))
4209 rest_of_wildcards++;
4210 }
4211#endif
4212
4213 /*
4214 * Expand wildcards like "*" and "$VAR".
4215 * If the path is a URL don't try this.
4216 */
4217 if (path_with_url(dirptrs[0]))
4218 {
4219 ctx->ffs_filearray = (char_u **)
4220 alloc((unsigned)sizeof(char *));
4221 if (ctx->ffs_filearray != NULL
4222 && (ctx->ffs_filearray[0]
4223 = vim_strsave(dirptrs[0])) != NULL)
4224 ctx->ffs_filearray_size = 1;
4225 else
4226 ctx->ffs_filearray_size = 0;
4227 }
4228 else
4229 expand_wildcards((dirptrs[1] == NULL) ? 1 : 2, dirptrs,
4230 &ctx->ffs_filearray_size,
4231 &ctx->ffs_filearray,
4232 EW_DIR|EW_ADDSLASH|EW_SILENT);
4233
4234 ctx->ffs_filearray_cur = 0;
4235 ctx->ffs_stage = 0;
4236 }
4237#ifdef FEAT_PATH_EXTRA
4238 else
4239 rest_of_wildcards = &ctx->ffs_wc_path[STRLEN(ctx->ffs_wc_path)];
4240#endif
4241
4242 if (ctx->ffs_stage == 0)
4243 {
4244 /* this is the first time we work on this directory */
4245#ifdef FEAT_PATH_EXTRA
4246 if (*rest_of_wildcards == NUL)
4247#endif
4248 {
4249 /*
4250 * we don't have further wildcards to expand, so we have to
4251 * check for the final file now
4252 */
4253 for (i = ctx->ffs_filearray_cur;
4254 i < ctx->ffs_filearray_size; ++i)
4255 {
4256 if (!path_with_url(ctx->ffs_filearray[i])
4257 && !mch_isdir(ctx->ffs_filearray[i]))
4258 continue; /* not a directory */
4259
4260 /* prepare the filename to be checked for existance
4261 * below */
4262 STRCPY(file_path, ctx->ffs_filearray[i]);
4263 add_pathsep(file_path);
4264 STRCAT(file_path, ff_search_ctx->ffsc_file_to_search);
4265
4266 /*
4267 * Try without extra suffix and then with suffixes
4268 * from 'suffixesadd'.
4269 */
4270#ifdef FEAT_SEARCHPATH
4271 len = (int)STRLEN(file_path);
4272 suf = curbuf->b_p_sua;
4273 for (;;)
4274#endif
4275 {
4276 /* if file exists and we didn't already find it */
4277 if ((path_with_url(file_path)
4278 || (mch_getperm(file_path) >= 0
4279 && (!ff_search_ctx->ffsc_need_dir
4280 || mch_isdir(file_path))))
4281#ifndef FF_VERBOSE
4282 && (ff_check_visited(
4283 &ff_search_ctx->ffsc_visited_list->ffvl_visited_list,
4284 file_path
4285#ifdef FEAT_PATH_EXTRA
4286 , (char_u *)""
4287#endif
4288 ) == OK)
4289#endif
4290 )
4291 {
4292#ifdef FF_VERBOSE
4293 if (ff_check_visited(
4294 &ff_search_ctx->ffsc_visited_list->ffvl_visited_list,
4295 file_path
4296#ifdef FEAT_PATH_EXTRA
4297 , (char_u *)""
4298#endif
4299 ) == FAIL)
4300 {
4301 if (p_verbose >= 5)
4302 {
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004303 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00004304 smsg((char_u *)"Already: %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004305 file_path);
4306 /* don't overwrite this either */
4307 msg_puts((char_u *)"\n");
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004308 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004309 }
4310 continue;
4311 }
4312#endif
4313
4314 /* push dir to examine rest of subdirs later */
4315 ctx->ffs_filearray_cur = i + 1;
4316 ff_push(ctx);
4317
4318 simplify_filename(file_path);
4319 if (mch_dirname(ff_expand_buffer, MAXPATHL)
4320 == OK)
4321 {
4322 p = shorten_fname(file_path,
4323 ff_expand_buffer);
4324 if (p != NULL)
4325 mch_memmove(file_path, p,
4326 STRLEN(p) + 1);
4327 }
4328#ifdef FF_VERBOSE
4329 if (p_verbose >= 5)
4330 {
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004331 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00004332 smsg((char_u *)"HIT: %s", file_path);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004333 /* don't overwrite this either */
4334 msg_puts((char_u *)"\n");
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004335 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004336 }
4337#endif
4338 return file_path;
4339 }
4340
4341#ifdef FEAT_SEARCHPATH
4342 /* Not found or found already, try next suffix. */
4343 if (*suf == NUL)
4344 break;
4345 copy_option_part(&suf, file_path + len,
4346 MAXPATHL - len, ",");
4347#endif
4348 }
4349 }
4350 }
4351#ifdef FEAT_PATH_EXTRA
4352 else
4353 {
4354 /*
4355 * still wildcards left, push the directories for further
4356 * search
4357 */
4358 for (i = ctx->ffs_filearray_cur; i < ctx->ffs_filearray_size;
4359 ++i)
4360 {
4361 if (!mch_isdir(ctx->ffs_filearray[i]))
4362 continue; /* not a directory */
4363
4364 ff_push(ff_create_stack_element(ctx->ffs_filearray[i],
4365 rest_of_wildcards, ctx->ffs_level - 1, 0));
4366 }
4367 }
4368#endif
4369 ctx->ffs_filearray_cur = 0;
4370 ctx->ffs_stage = 1;
4371 }
4372
4373#ifdef FEAT_PATH_EXTRA
4374 /*
4375 * if wildcards contains '**' we have to descent till we reach the
4376 * leaves of the directory tree.
4377 */
4378 if (STRNCMP(ctx->ffs_wc_path, "**", 2) == 0)
4379 {
4380 for (i = ctx->ffs_filearray_cur; i < ctx->ffs_filearray_size; ++i)
4381 {
4382 if (fnamecmp(ctx->ffs_filearray[i], ctx->ffs_fix_path) == 0)
4383 continue; /* don't repush same directory */
4384 if (!mch_isdir(ctx->ffs_filearray[i]))
4385 continue; /* not a directory */
4386 ff_push(ff_create_stack_element(ctx->ffs_filearray[i],
4387 ctx->ffs_wc_path, ctx->ffs_level - 1, 1));
4388 }
4389 }
4390#endif
4391
4392 /* we are done with the current directory */
4393 ff_free_stack_element(ctx);
4394
4395 }
4396
4397#ifdef FEAT_PATH_EXTRA
4398 /* If we reached this, we didn't find anything downwards.
4399 * Let's check if we should do an upward search.
4400 */
4401 if (ff_search_ctx->ffsc_start_dir
4402 && ff_search_ctx->ffsc_stopdirs_v != NULL && !got_int)
4403 {
4404 ff_stack_T *sptr;
4405
4406 /* is the last starting directory in the stop list? */
4407 if (ff_path_in_stoplist(ff_search_ctx->ffsc_start_dir,
4408 (int)(path_end - ff_search_ctx->ffsc_start_dir),
4409 ff_search_ctx->ffsc_stopdirs_v) == TRUE)
4410 break;
4411
4412 /* cut of last dir */
4413 while (path_end > ff_search_ctx->ffsc_start_dir
4414 && *path_end == PATHSEP)
4415 path_end--;
4416 while (path_end > ff_search_ctx->ffsc_start_dir
4417 && *(path_end-1) != PATHSEP)
4418 path_end--;
4419 *path_end = 0;
4420 path_end--;
4421
4422 if (*ff_search_ctx->ffsc_start_dir == 0)
4423 break;
4424
4425 STRCPY(file_path, ff_search_ctx->ffsc_start_dir);
4426 add_pathsep(file_path);
4427 STRCAT(file_path, ff_search_ctx->ffsc_fix_path);
4428
4429 /* create a new stack entry */
4430 sptr = ff_create_stack_element(file_path,
4431 ff_search_ctx->ffsc_wc_path, ff_search_ctx->ffsc_level, 0);
4432 if (sptr == NULL)
4433 break;
4434 ff_push(sptr);
4435 }
4436 else
4437 break;
4438 }
4439#endif
4440
4441 vim_free(file_path);
4442 return NULL;
4443}
4444
4445/*
4446 * Free the list of lists of visited files and directories
4447 * Can handle it if the passed search_context is NULL;
4448 */
4449 void
4450vim_findfile_free_visited(search_ctx)
4451 void *search_ctx;
4452{
4453 if (search_ctx == NULL)
4454 return;
4455
4456 ff_search_ctx = (ff_search_ctx_T *)search_ctx;
4457
4458 vim_findfile_free_visited_list(&ff_search_ctx->ffsc_visited_lists_list);
4459 vim_findfile_free_visited_list(&ff_search_ctx->ffsc_dir_visited_lists_list);
4460}
4461
4462 static void
4463vim_findfile_free_visited_list(list_headp)
4464 ff_visited_list_hdr_T **list_headp;
4465{
4466 ff_visited_list_hdr_T *vp;
4467
4468 while (*list_headp != NULL)
4469 {
4470 vp = (*list_headp)->ffvl_next;
4471 ff_free_visited_list((*list_headp)->ffvl_visited_list);
4472
4473 vim_free((*list_headp)->ffvl_filename);
4474 vim_free(*list_headp);
4475 *list_headp = vp;
4476 }
4477 *list_headp = NULL;
4478}
4479
4480 static void
4481ff_free_visited_list(vl)
4482 ff_visited_T *vl;
4483{
4484 ff_visited_T *vp;
4485
4486 while (vl != NULL)
4487 {
4488 vp = vl->ffv_next;
4489#ifdef FEAT_PATH_EXTRA
4490 vim_free(vl->ffv_wc_path);
4491#endif
4492 vim_free(vl);
4493 vl = vp;
4494 }
4495 vl = NULL;
4496}
4497
4498/*
4499 * Returns the already visited list for the given filename. If none is found it
4500 * allocates a new one.
4501 */
4502 static ff_visited_list_hdr_T*
4503ff_get_visited_list(filename, list_headp)
4504 char_u *filename;
4505 ff_visited_list_hdr_T **list_headp;
4506{
4507 ff_visited_list_hdr_T *retptr = NULL;
4508
4509 /* check if a visited list for the given filename exists */
4510 if (*list_headp != NULL)
4511 {
4512 retptr = *list_headp;
4513 while (retptr != NULL)
4514 {
4515 if (fnamecmp(filename, retptr->ffvl_filename) == 0)
4516 {
4517#ifdef FF_VERBOSE
4518 if (p_verbose >= 5)
4519 {
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004520 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00004521 smsg((char_u *)"ff_get_visited_list: FOUND list for %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004522 filename);
4523 /* don't overwrite this either */
4524 msg_puts((char_u *)"\n");
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004525 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004526 }
4527#endif
4528 return retptr;
4529 }
4530 retptr = retptr->ffvl_next;
4531 }
4532 }
4533
4534#ifdef FF_VERBOSE
4535 if (p_verbose >= 5)
4536 {
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004537 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00004538 smsg((char_u *)"ff_get_visited_list: new list for %s", filename);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004539 /* don't overwrite this either */
4540 msg_puts((char_u *)"\n");
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004541 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004542 }
4543#endif
4544
4545 /*
4546 * if we reach this we didn't find a list and we have to allocate new list
4547 */
4548 retptr = (ff_visited_list_hdr_T*)alloc((unsigned)sizeof(*retptr));
4549 if (retptr == NULL)
4550 return NULL;
4551
4552 retptr->ffvl_visited_list = NULL;
4553 retptr->ffvl_filename = vim_strsave(filename);
4554 if (retptr->ffvl_filename == NULL)
4555 {
4556 vim_free(retptr);
4557 return NULL;
4558 }
4559 retptr->ffvl_next = *list_headp;
4560 *list_headp = retptr;
4561
4562 return retptr;
4563}
4564
4565#ifdef FEAT_PATH_EXTRA
4566/*
4567 * check if two wildcard paths are equal. Returns TRUE or FALSE.
4568 * They are equal if:
4569 * - both paths are NULL
4570 * - they have the same length
4571 * - char by char comparison is OK
4572 * - the only differences are in the counters behind a '**', so
4573 * '**\20' is equal to '**\24'
4574 */
4575 static int
4576ff_wc_equal(s1, s2)
4577 char_u *s1;
4578 char_u *s2;
4579{
4580 int i;
4581
4582 if (s1 == s2)
4583 return TRUE;
4584
4585 if (s1 == NULL || s2 == NULL)
4586 return FALSE;
4587
4588 if (STRLEN(s1) != STRLEN(s2))
4589 return FAIL;
4590
4591 for (i = 0; s1[i] != NUL && s2[i] != NUL; i++)
4592 {
4593 if (s1[i] != s2[i]
4594#ifdef CASE_INSENSITIVE_FILENAME
4595 && TOUPPER_LOC(s1[i]) != TOUPPER_LOC(s2[i])
4596#endif
4597 )
4598 {
4599 if (i >= 2)
4600 if (s1[i-1] == '*' && s1[i-2] == '*')
4601 continue;
4602 else
4603 return FAIL;
4604 else
4605 return FAIL;
4606 }
4607 }
4608 return TRUE;
4609}
4610#endif
4611
4612/*
4613 * maintains the list of already visited files and dirs
4614 * returns FAIL if the given file/dir is already in the list
4615 * returns OK if it is newly added
4616 *
4617 * TODO: What to do on memory allocation problems?
4618 * -> return TRUE - Better the file is found several times instead of
4619 * never.
4620 */
4621 static int
4622ff_check_visited(visited_list, fname
4623#ifdef FEAT_PATH_EXTRA
4624 , wc_path
4625#endif
4626 )
4627 ff_visited_T **visited_list;
4628 char_u *fname;
4629#ifdef FEAT_PATH_EXTRA
4630 char_u *wc_path;
4631#endif
4632{
4633 ff_visited_T *vp;
4634#ifdef UNIX
4635 struct stat st;
4636 int url = FALSE;
4637#endif
4638
4639 /* For an URL we only compare the name, otherwise we compare the
4640 * device/inode (unix) or the full path name (not Unix). */
4641 if (path_with_url(fname))
4642 {
4643 STRNCPY(ff_expand_buffer, fname, MAXPATHL);
4644#ifdef UNIX
4645 url = TRUE;
4646#endif
4647 }
4648 else
4649 {
4650 ff_expand_buffer[0] = NUL;
4651#ifdef UNIX
4652 if (mch_stat((char *)fname, &st) < 0)
4653#else
4654 if (vim_FullName(fname, ff_expand_buffer, MAXPATHL, TRUE) == FAIL)
4655#endif
4656 return FAIL;
4657 }
4658
4659 /* check against list of already visited files */
4660 for (vp = *visited_list; vp != NULL; vp = vp->ffv_next)
4661 {
4662 if (
4663#ifdef UNIX
4664 !url
4665 ? (vp->ffv_dev == st.st_dev
4666 && vp->ffv_ino == st.st_ino)
4667 :
4668#endif
4669 fnamecmp(vp->ffv_fname, ff_expand_buffer) == 0
4670 )
4671 {
4672#ifdef FEAT_PATH_EXTRA
4673 /* are the wildcard parts equal */
4674 if (ff_wc_equal(vp->ffv_wc_path, wc_path) == TRUE)
4675#endif
4676 /* already visited */
4677 return FAIL;
4678 }
4679 }
4680
4681 /*
4682 * New file/dir. Add it to the list of visited files/dirs.
4683 */
4684 vp = (ff_visited_T *)alloc((unsigned)(sizeof(ff_visited_T)
4685 + STRLEN(ff_expand_buffer)));
4686
4687 if (vp != NULL)
4688 {
4689#ifdef UNIX
4690 if (!url)
4691 {
4692 vp->ffv_ino = st.st_ino;
4693 vp->ffv_dev = st.st_dev;
4694 vp->ffv_fname[0] = NUL;
4695 }
4696 else
4697 {
4698 vp->ffv_ino = 0;
4699 vp->ffv_dev = -1;
4700#endif
4701 STRCPY(vp->ffv_fname, ff_expand_buffer);
4702#ifdef UNIX
4703 }
4704#endif
4705#ifdef FEAT_PATH_EXTRA
4706 if (wc_path != NULL)
4707 vp->ffv_wc_path = vim_strsave(wc_path);
4708 else
4709 vp->ffv_wc_path = NULL;
4710#endif
4711
4712 vp->ffv_next = *visited_list;
4713 *visited_list = vp;
4714 }
4715
4716 return OK;
4717}
4718
4719/*
4720 * create stack element from given path pieces
4721 */
4722 static ff_stack_T *
4723ff_create_stack_element(fix_part,
4724#ifdef FEAT_PATH_EXTRA
4725 wc_part,
4726#endif
4727 level, star_star_empty)
4728 char_u *fix_part;
4729#ifdef FEAT_PATH_EXTRA
4730 char_u *wc_part;
4731#endif
4732 int level;
4733 int star_star_empty;
4734{
4735 ff_stack_T *new;
4736
4737 new = (ff_stack_T *)alloc((unsigned)sizeof(ff_stack_T));
4738 if (new == NULL)
4739 return NULL;
4740
4741 new->ffs_prev = NULL;
4742 new->ffs_filearray = NULL;
4743 new->ffs_filearray_size = 0;
4744 new->ffs_filearray_cur = 0;
4745 new->ffs_stage = 0;
4746 new->ffs_level = level;
4747 new->ffs_star_star_empty = star_star_empty;;
4748
4749 /* the following saves NULL pointer checks in vim_findfile */
4750 if (fix_part == NULL)
4751 fix_part = (char_u *)"";
4752 new->ffs_fix_path = vim_strsave(fix_part);
4753
4754#ifdef FEAT_PATH_EXTRA
4755 if (wc_part == NULL)
4756 wc_part = (char_u *)"";
4757 new->ffs_wc_path = vim_strsave(wc_part);
4758#endif
4759
4760 if (new->ffs_fix_path == NULL
4761#ifdef FEAT_PATH_EXTRA
4762 || new->ffs_wc_path == NULL
4763#endif
4764 )
4765 {
4766 ff_free_stack_element(new);
4767 new = NULL;
4768 }
4769
4770 return new;
4771}
4772
4773/*
4774 * push a dir on the directory stack
4775 */
4776 static void
4777ff_push(ctx)
4778 ff_stack_T *ctx;
4779{
4780 /* check for NULL pointer, not to return an error to the user, but
4781 * to prevent a crash
4782 */
4783 if (ctx != NULL)
4784 {
4785 ctx->ffs_prev = ff_search_ctx->ffsc_stack_ptr;
4786 ff_search_ctx->ffsc_stack_ptr = ctx;
4787 }
4788}
4789
4790/*
4791 * pop a dir from the directory stack
4792 * returns NULL if stack is empty
4793 */
4794 static ff_stack_T *
4795ff_pop()
4796{
4797 ff_stack_T *sptr;
4798
4799 sptr = ff_search_ctx->ffsc_stack_ptr;
4800 if (ff_search_ctx->ffsc_stack_ptr != NULL)
4801 ff_search_ctx->ffsc_stack_ptr = ff_search_ctx->ffsc_stack_ptr->ffs_prev;
4802
4803 return sptr;
4804}
4805
4806/*
4807 * free the given stack element
4808 */
4809 static void
4810ff_free_stack_element(ctx)
4811 ff_stack_T *ctx;
4812{
4813 /* vim_free handles possible NULL pointers */
4814 vim_free(ctx->ffs_fix_path);
4815#ifdef FEAT_PATH_EXTRA
4816 vim_free(ctx->ffs_wc_path);
4817#endif
4818
4819 if (ctx->ffs_filearray != NULL)
4820 FreeWild(ctx->ffs_filearray_size, ctx->ffs_filearray);
4821
4822 vim_free(ctx);
4823}
4824
4825/*
4826 * clear the search context
4827 */
4828 static void
4829ff_clear()
4830{
4831 ff_stack_T *sptr;
4832
4833 /* clear up stack */
4834 while ((sptr = ff_pop()) != NULL)
4835 ff_free_stack_element(sptr);
4836
4837 vim_free(ff_search_ctx->ffsc_file_to_search);
4838 vim_free(ff_search_ctx->ffsc_start_dir);
4839 vim_free(ff_search_ctx->ffsc_fix_path);
4840#ifdef FEAT_PATH_EXTRA
4841 vim_free(ff_search_ctx->ffsc_wc_path);
4842#endif
4843
4844#ifdef FEAT_PATH_EXTRA
4845 if (ff_search_ctx->ffsc_stopdirs_v != NULL)
4846 {
4847 int i = 0;
4848
4849 while (ff_search_ctx->ffsc_stopdirs_v[i] != NULL)
4850 {
4851 vim_free(ff_search_ctx->ffsc_stopdirs_v[i]);
4852 i++;
4853 }
4854 vim_free(ff_search_ctx->ffsc_stopdirs_v);
4855 }
4856 ff_search_ctx->ffsc_stopdirs_v = NULL;
4857#endif
4858
4859 /* reset everything */
4860 ff_search_ctx->ffsc_file_to_search = NULL;
4861 ff_search_ctx->ffsc_start_dir = NULL;
4862 ff_search_ctx->ffsc_fix_path = NULL;
4863#ifdef FEAT_PATH_EXTRA
4864 ff_search_ctx->ffsc_wc_path = NULL;
4865 ff_search_ctx->ffsc_level = 0;
4866#endif
4867}
4868
4869#ifdef FEAT_PATH_EXTRA
4870/*
4871 * check if the given path is in the stopdirs
4872 * returns TRUE if yes else FALSE
4873 */
4874 static int
4875ff_path_in_stoplist(path, path_len, stopdirs_v)
4876 char_u *path;
4877 int path_len;
4878 char_u **stopdirs_v;
4879{
4880 int i = 0;
4881
4882 /* eat up trailing path separators, except the first */
4883 while (path_len > 1 && path[path_len - 1] == PATHSEP)
4884 path_len--;
4885
4886 /* if no path consider it as match */
4887 if (path_len == 0)
4888 return TRUE;
4889
4890 for (i = 0; stopdirs_v[i] != NULL; i++)
4891 {
4892 if ((int)STRLEN(stopdirs_v[i]) > path_len)
4893 {
4894 /* match for parent directory. So '/home' also matches
4895 * '/home/rks'. Check for PATHSEP in stopdirs_v[i], else
4896 * '/home/r' would also match '/home/rks'
4897 */
4898 if (fnamencmp(stopdirs_v[i], path, path_len) == 0
4899 && stopdirs_v[i][path_len] == PATHSEP)
4900 return TRUE;
4901 }
4902 else
4903 {
4904 if (fnamecmp(stopdirs_v[i], path) == 0)
4905 return TRUE;
4906 }
4907 }
4908 return FALSE;
4909}
4910#endif
4911
4912#if defined(FEAT_SEARCHPATH) || defined(PROTO)
4913/*
4914 * Find the file name "ptr[len]" in the path.
4915 *
4916 * On the first call set the parameter 'first' to TRUE to initialize
4917 * the search. For repeating calls to FALSE.
4918 *
4919 * Repeating calls will return other files called 'ptr[len]' from the path.
4920 *
4921 * Only on the first call 'ptr' and 'len' are used. For repeating calls they
4922 * don't need valid values.
4923 *
4924 * If nothing found on the first call the option FNAME_MESS will issue the
4925 * message:
4926 * 'Can't find file "<file>" in path'
4927 * On repeating calls:
4928 * 'No more file "<file>" found in path'
4929 *
4930 * options:
4931 * FNAME_MESS give error message when not found
4932 *
4933 * Uses NameBuff[]!
4934 *
4935 * Returns an allocated string for the file name. NULL for error.
4936 *
4937 */
4938 char_u *
4939find_file_in_path(ptr, len, options, first, rel_fname)
4940 char_u *ptr; /* file name */
4941 int len; /* length of file name */
4942 int options;
4943 int first; /* use count'th matching file name */
4944 char_u *rel_fname; /* file name searching relative to */
4945{
4946 return find_file_in_path_option(ptr, len, options, first,
4947 *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path,
4948 FALSE, rel_fname);
4949}
4950
4951/*
4952 * Find the directory name "ptr[len]" in the path.
4953 *
4954 * options:
4955 * FNAME_MESS give error message when not found
4956 *
4957 * Uses NameBuff[]!
4958 *
4959 * Returns an allocated string for the file name. NULL for error.
4960 */
4961 char_u *
4962find_directory_in_path(ptr, len, options, rel_fname)
4963 char_u *ptr; /* file name */
4964 int len; /* length of file name */
4965 int options;
4966 char_u *rel_fname; /* file name searching relative to */
4967{
4968 return find_file_in_path_option(ptr, len, options, TRUE, p_cdpath,
4969 TRUE, rel_fname);
4970}
4971
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00004972 char_u *
Bram Moolenaar071d4272004-06-13 20:20:40 +00004973find_file_in_path_option(ptr, len, options, first, path_option, need_dir, rel_fname)
4974 char_u *ptr; /* file name */
4975 int len; /* length of file name */
4976 int options;
4977 int first; /* use count'th matching file name */
4978 char_u *path_option; /* p_path or p_cdpath */
4979 int need_dir; /* looking for directory name */
4980 char_u *rel_fname; /* file name we are looking relative to. */
4981{
4982 static void *search_ctx = NULL;
4983 static char_u *dir;
4984 static char_u *file_to_find = NULL;
4985 static int did_findfile_init = FALSE;
4986 char_u save_char;
4987 char_u *file_name = NULL;
4988 char_u *buf = NULL;
4989 int rel_to_curdir;
4990#ifdef AMIGA
4991 struct Process *proc = (struct Process *)FindTask(0L);
4992 APTR save_winptr = proc->pr_WindowPtr;
4993
4994 /* Avoid a requester here for a volume that doesn't exist. */
4995 proc->pr_WindowPtr = (APTR)-1L;
4996#endif
4997
4998 if (first == TRUE)
4999 {
5000 /* copy file name into NameBuff, expanding environment variables */
5001 save_char = ptr[len];
5002 ptr[len] = NUL;
5003 expand_env(ptr, NameBuff, MAXPATHL);
5004 ptr[len] = save_char;
5005
5006 vim_free(file_to_find);
5007 file_to_find = vim_strsave(NameBuff);
5008 if (file_to_find == NULL) /* out of memory */
5009 {
5010 file_name = NULL;
5011 goto theend;
5012 }
5013 }
5014
5015 rel_to_curdir = (file_to_find[0] == '.'
5016 && (file_to_find[1] == NUL
5017 || vim_ispathsep(file_to_find[1])
5018 || (file_to_find[1] == '.'
5019 && (file_to_find[2] == NUL
5020 || vim_ispathsep(file_to_find[2])))));
5021 if (vim_isAbsName(file_to_find)
5022 /* "..", "../path", "." and "./path": don't use the path_option */
5023 || rel_to_curdir
5024#if defined(MSWIN) || defined(MSDOS) || defined(OS2)
5025 /* handle "\tmp" as absolute path */
5026 || vim_ispathsep(file_to_find[0])
5027 /* handle "c:name" as absulute path */
5028 || (file_to_find[0] != NUL && file_to_find[1] == ':')
5029#endif
5030#ifdef AMIGA
5031 /* handle ":tmp" as absolute path */
5032 || file_to_find[0] == ':'
5033#endif
5034 )
5035 {
5036 /*
5037 * Absolute path, no need to use "path_option".
5038 * If this is not a first call, return NULL. We already returned a
5039 * filename on the first call.
5040 */
5041 if (first == TRUE)
5042 {
5043 int l;
5044 int run;
5045
5046 if (path_with_url(file_to_find))
5047 {
5048 file_name = vim_strsave(file_to_find);
5049 goto theend;
5050 }
5051
5052 /* When FNAME_REL flag given first use the directory of the file.
5053 * Otherwise or when this fails use the current directory. */
5054 for (run = 1; run <= 2; ++run)
5055 {
5056 l = (int)STRLEN(file_to_find);
5057 if (run == 1
5058 && rel_to_curdir
5059 && (options & FNAME_REL)
5060 && rel_fname != NULL
5061 && STRLEN(rel_fname) + l < MAXPATHL)
5062 {
5063 STRCPY(NameBuff, rel_fname);
5064 STRCPY(gettail(NameBuff), file_to_find);
5065 l = (int)STRLEN(NameBuff);
5066 }
5067 else
5068 {
5069 STRCPY(NameBuff, file_to_find);
5070 run = 2;
5071 }
5072
5073 /* When the file doesn't exist, try adding parts of
5074 * 'suffixesadd'. */
5075 buf = curbuf->b_p_sua;
5076 for (;;)
5077 {
5078 if (
5079#ifdef DJGPP
5080 /* "C:" by itself will fail for mch_getperm(),
5081 * assume it's always valid. */
5082 (need_dir && NameBuff[0] != NUL
5083 && NameBuff[1] == ':'
5084 && NameBuff[2] == NUL) ||
5085#endif
5086 (mch_getperm(NameBuff) >= 0
5087 && (!need_dir || mch_isdir(NameBuff))))
5088 {
5089 file_name = vim_strsave(NameBuff);
5090 goto theend;
5091 }
5092 if (*buf == NUL)
5093 break;
5094 copy_option_part(&buf, NameBuff + l, MAXPATHL - l, ",");
5095 }
5096 }
5097 }
5098 }
5099 else
5100 {
5101 /*
5102 * Loop over all paths in the 'path' or 'cdpath' option.
5103 * When "first" is set, first setup to the start of the option.
5104 * Otherwise continue to find the next match.
5105 */
5106 if (first == TRUE)
5107 {
5108 /* vim_findfile_free_visited can handle a possible NULL pointer */
5109 vim_findfile_free_visited(search_ctx);
5110 dir = path_option;
5111 did_findfile_init = FALSE;
5112 }
5113
5114 for (;;)
5115 {
5116 if (did_findfile_init)
5117 {
5118 ff_search_ctx->ffsc_need_dir = need_dir;
5119 file_name = vim_findfile(search_ctx);
5120 ff_search_ctx->ffsc_need_dir = FALSE;
5121 if (file_name != NULL)
5122 break;
5123
5124 did_findfile_init = FALSE;
5125 }
5126 else
5127 {
5128 char_u *r_ptr;
5129
5130 if (dir == NULL || *dir == NUL)
5131 {
5132 /* We searched all paths of the option, now we can
5133 * free the search context. */
5134 vim_findfile_cleanup(search_ctx);
5135 search_ctx = NULL;
5136 break;
5137 }
5138
5139 if ((buf = alloc((int)(MAXPATHL))) == NULL)
5140 break;
5141
5142 /* copy next path */
5143 buf[0] = 0;
5144 copy_option_part(&dir, buf, MAXPATHL, " ,");
5145
5146#ifdef FEAT_PATH_EXTRA
5147 /* get the stopdir string */
5148 r_ptr = vim_findfile_stopdir(buf);
5149#else
5150 r_ptr = NULL;
5151#endif
5152 search_ctx = vim_findfile_init(buf, file_to_find, r_ptr, 100,
5153 FALSE, TRUE, search_ctx, FALSE, rel_fname);
5154 if (search_ctx != NULL)
5155 did_findfile_init = TRUE;
5156 vim_free(buf);
5157 }
5158 }
5159 }
5160 if (file_name == NULL && (options & FNAME_MESS))
5161 {
5162 if (first == TRUE)
5163 {
5164 if (need_dir)
5165 EMSG2(_("E344: Can't find directory \"%s\" in cdpath"),
5166 file_to_find);
5167 else
5168 EMSG2(_("E345: Can't find file \"%s\" in path"),
5169 file_to_find);
5170 }
5171 else
5172 {
5173 if (need_dir)
5174 EMSG2(_("E346: No more directory \"%s\" found in cdpath"),
5175 file_to_find);
5176 else
5177 EMSG2(_("E347: No more file \"%s\" found in path"),
5178 file_to_find);
5179 }
5180 }
5181
5182theend:
5183#ifdef AMIGA
5184 proc->pr_WindowPtr = save_winptr;
5185#endif
5186 return file_name;
5187}
5188
5189#endif /* FEAT_SEARCHPATH */
5190
5191/*
5192 * Change directory to "new_dir". If FEAT_SEARCHPATH is defined, search
5193 * 'cdpath' for relative directory names, otherwise just mch_chdir().
5194 */
5195 int
5196vim_chdir(new_dir)
5197 char_u *new_dir;
5198{
5199#ifndef FEAT_SEARCHPATH
5200 return mch_chdir((char *)new_dir);
5201#else
5202 char_u *dir_name;
5203 int r;
5204
5205 dir_name = find_directory_in_path(new_dir, (int)STRLEN(new_dir),
5206 FNAME_MESS, curbuf->b_ffname);
5207 if (dir_name == NULL)
5208 return -1;
5209 r = mch_chdir((char *)dir_name);
5210 vim_free(dir_name);
5211 return r;
5212#endif
5213}
5214
5215/*
5216 * Get user name from machine-specific function and cache it.
5217 * Returns the user name in "buf[len]".
5218 * Some systems are quite slow in obtaining the user name (Windows NT).
5219 * Returns OK or FAIL.
5220 */
5221 int
5222get_user_name(buf, len)
5223 char_u *buf;
5224 int len;
5225{
5226 static char_u *name = NULL;
5227
5228 if (name == NULL)
5229 {
5230 if (mch_get_user_name(buf, len) == FAIL)
5231 return FAIL;
5232 name = vim_strsave(buf);
5233 }
5234 else
5235 STRNCPY(buf, name, len);
5236 return OK;
5237}
5238
5239#ifndef HAVE_QSORT
5240/*
5241 * Our own qsort(), for systems that don't have it.
5242 * It's simple and slow. From the K&R C book.
5243 */
5244 void
5245qsort(base, elm_count, elm_size, cmp)
5246 void *base;
5247 size_t elm_count;
5248 size_t elm_size;
5249 int (*cmp) __ARGS((const void *, const void *));
5250{
5251 char_u *buf;
5252 char_u *p1;
5253 char_u *p2;
5254 int i, j;
5255 int gap;
5256
5257 buf = alloc((unsigned)elm_size);
5258 if (buf == NULL)
5259 return;
5260
5261 for (gap = elm_count / 2; gap > 0; gap /= 2)
5262 for (i = gap; i < elm_count; ++i)
5263 for (j = i - gap; j >= 0; j -= gap)
5264 {
5265 /* Compare the elements. */
5266 p1 = (char_u *)base + j * elm_size;
5267 p2 = (char_u *)base + (j + gap) * elm_size;
5268 if ((*cmp)((void *)p1, (void *)p2) <= 0)
5269 break;
5270 /* Exchange the elemets. */
5271 mch_memmove(buf, p1, elm_size);
5272 mch_memmove(p1, p2, elm_size);
5273 mch_memmove(p2, buf, elm_size);
5274 }
5275
5276 vim_free(buf);
5277}
5278#endif
5279
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00005280#if defined(FEAT_EX_EXTRA) || defined(FEAT_CMDL_COMPL) \
5281 || (defined(FEAT_SYN_HL) && defined(FEAT_MBYTE)) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005282/*
5283 * Sort an array of strings.
5284 */
5285static int
5286#ifdef __BORLANDC__
5287_RTLENTRYF
5288#endif
5289sort_compare __ARGS((const void *s1, const void *s2));
5290
5291 static int
5292#ifdef __BORLANDC__
5293_RTLENTRYF
5294#endif
5295sort_compare(s1, s2)
5296 const void *s1;
5297 const void *s2;
5298{
5299 return STRCMP(*(char **)s1, *(char **)s2);
5300}
5301
5302 void
5303sort_strings(files, count)
5304 char_u **files;
5305 int count;
5306{
5307 qsort((void *)files, (size_t)count, sizeof(char_u *), sort_compare);
5308}
5309#endif
5310
5311#if !defined(NO_EXPANDPATH) || defined(PROTO)
5312/*
5313 * Compare path "p[]" to "q[]".
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005314 * If "maxlen" >= 0 compare "p[maxlen]" to "q[maxlen]"
Bram Moolenaar071d4272004-06-13 20:20:40 +00005315 * Return value like strcmp(p, q), but consider path separators.
5316 */
5317 int
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005318pathcmp(p, q, maxlen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005319 const char *p, *q;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005320 int maxlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005321{
5322 int i;
Bram Moolenaar86b68352004-12-27 21:59:20 +00005323 const char *s = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005324
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005325 for (i = 0; maxlen < 0 || i < maxlen; ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005326 {
5327 /* End of "p": check if "q" also ends or just has a slash. */
5328 if (p[i] == NUL)
5329 {
5330 if (q[i] == NUL) /* full match */
5331 return 0;
5332 s = q;
5333 break;
5334 }
5335
5336 /* End of "q": check if "p" just has a slash. */
5337 if (q[i] == NUL)
5338 {
5339 s = p;
5340 break;
5341 }
5342
5343 if (
5344#ifdef CASE_INSENSITIVE_FILENAME
5345 TOUPPER_LOC(p[i]) != TOUPPER_LOC(q[i])
5346#else
5347 p[i] != q[i]
5348#endif
5349#ifdef BACKSLASH_IN_FILENAME
5350 /* consider '/' and '\\' to be equal */
5351 && !((p[i] == '/' && q[i] == '\\')
5352 || (p[i] == '\\' && q[i] == '/'))
5353#endif
5354 )
5355 {
5356 if (vim_ispathsep(p[i]))
5357 return -1;
5358 if (vim_ispathsep(q[i]))
5359 return 1;
5360 return ((char_u *)p)[i] - ((char_u *)q)[i]; /* no match */
5361 }
5362 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00005363 if (s == NULL) /* "i" ran into "maxlen" */
5364 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005365
5366 /* ignore a trailing slash, but not "//" or ":/" */
Bram Moolenaar86b68352004-12-27 21:59:20 +00005367 if (s[i + 1] == NUL
5368 && i > 0
5369 && !after_pathsep((char_u *)s, (char_u *)s + i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005370#ifdef BACKSLASH_IN_FILENAME
Bram Moolenaar86b68352004-12-27 21:59:20 +00005371 && (s[i] == '/' || s[i] == '\\')
Bram Moolenaar071d4272004-06-13 20:20:40 +00005372#else
Bram Moolenaar86b68352004-12-27 21:59:20 +00005373 && s[i] == '/'
Bram Moolenaar071d4272004-06-13 20:20:40 +00005374#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00005375 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00005376 return 0; /* match with trailing slash */
5377 if (s == q)
5378 return -1; /* no match */
5379 return 1;
5380}
5381#endif
5382
5383#if defined(FEAT_PRINTER) || defined(PROTO)
5384/*
5385 * Parse a list of options in the form
5386 * option:value,option:value,option:value
5387 *
5388 * "value" can start with a number which is parsed out, e.g.
5389 * margin:12mm
5390 *
5391 * Returns error message for an illegal option, NULL otherwise.
5392 * Only used for the printer at the moment...
5393 */
5394 char_u *
5395parse_list_options(option_str, table, table_size)
5396 char_u *option_str;
5397 option_table_T *table;
5398 int table_size;
5399{
5400 char_u *stringp;
5401 char_u *colonp;
5402 char_u *commap;
5403 char_u *p;
5404 int idx = 0; /* init for GCC */
5405 int len;
5406
5407 for (idx = 0; idx < table_size; ++idx)
5408 table[idx].present = FALSE;
5409
5410 /*
5411 * Repeat for all comma separated parts.
5412 */
5413 stringp = option_str;
5414 while (*stringp)
5415 {
5416 colonp = vim_strchr(stringp, ':');
5417 if (colonp == NULL)
5418 return (char_u *)N_("E550: Missing colon");
5419 commap = vim_strchr(stringp, ',');
5420 if (commap == NULL)
5421 commap = option_str + STRLEN(option_str);
5422
5423 len = (int)(colonp - stringp);
5424
5425 for (idx = 0; idx < table_size; ++idx)
5426 if (STRNICMP(stringp, table[idx].name, len) == 0)
5427 break;
5428
5429 if (idx == table_size)
5430 return (char_u *)N_("E551: Illegal component");
5431
5432 p = colonp + 1;
5433 table[idx].present = TRUE;
5434
5435 if (table[idx].hasnum)
5436 {
5437 if (!VIM_ISDIGIT(*p))
5438 return (char_u *)N_("E552: digit expected");
5439
5440 table[idx].number = getdigits(&p); /*advances p*/
5441 }
5442
5443 table[idx].string = p;
5444 table[idx].strlen = (int)(commap - p);
5445
5446 stringp = commap;
5447 if (*stringp == ',')
5448 ++stringp;
5449 }
5450
5451 return NULL;
5452}
5453
5454
5455#endif /*FEAT_PRINTER*/
5456
5457/*
5458 * The putenv() implementation below comes from the "screen" program.
5459 * Included with permission from Juergen Weigert.
5460 * See pty.c for the copyright notice.
5461 */
5462
5463/*
5464 * putenv -- put value into environment
5465 *
5466 * Usage: i = putenv (string)
5467 * int i;
5468 * char *string;
5469 *
5470 * where string is of the form <name>=<value>.
5471 * Putenv returns 0 normally, -1 on error (not enough core for malloc).
5472 *
5473 * Putenv may need to add a new name into the environment, or to
5474 * associate a value longer than the current value with a particular
5475 * name. So, to make life simpler, putenv() copies your entire
5476 * environment into the heap (i.e. malloc()) from the stack
5477 * (i.e. where it resides when your process is initiated) the first
5478 * time you call it.
5479 *
5480 * (history removed, not very interesting. See the "screen" sources.)
5481 */
5482
5483#if !defined(HAVE_SETENV) && !defined(HAVE_PUTENV)
5484
5485#define EXTRASIZE 5 /* increment to add to env. size */
5486
5487static int envsize = -1; /* current size of environment */
5488#ifndef MACOS_CLASSIC
5489extern
5490#endif
5491 char **environ; /* the global which is your env. */
5492
5493static int findenv __ARGS((char *name)); /* look for a name in the env. */
5494static int newenv __ARGS((void)); /* copy env. from stack to heap */
5495static int moreenv __ARGS((void)); /* incr. size of env. */
5496
5497 int
5498putenv(string)
5499 const char *string;
5500{
5501 int i;
5502 char *p;
5503
5504 if (envsize < 0)
5505 { /* first time putenv called */
5506 if (newenv() < 0) /* copy env. to heap */
5507 return -1;
5508 }
5509
5510 i = findenv((char *)string); /* look for name in environment */
5511
5512 if (i < 0)
5513 { /* name must be added */
5514 for (i = 0; environ[i]; i++);
5515 if (i >= (envsize - 1))
5516 { /* need new slot */
5517 if (moreenv() < 0)
5518 return -1;
5519 }
5520 p = (char *)alloc((unsigned)(strlen(string) + 1));
5521 if (p == NULL) /* not enough core */
5522 return -1;
5523 environ[i + 1] = 0; /* new end of env. */
5524 }
5525 else
5526 { /* name already in env. */
5527 p = vim_realloc(environ[i], strlen(string) + 1);
5528 if (p == NULL)
5529 return -1;
5530 }
5531 sprintf(p, "%s", string); /* copy into env. */
5532 environ[i] = p;
5533
5534 return 0;
5535}
5536
5537 static int
5538findenv(name)
5539 char *name;
5540{
5541 char *namechar, *envchar;
5542 int i, found;
5543
5544 found = 0;
5545 for (i = 0; environ[i] && !found; i++)
5546 {
5547 envchar = environ[i];
5548 namechar = name;
5549 while (*namechar && *namechar != '=' && (*namechar == *envchar))
5550 {
5551 namechar++;
5552 envchar++;
5553 }
5554 found = ((*namechar == '\0' || *namechar == '=') && *envchar == '=');
5555 }
5556 return found ? i - 1 : -1;
5557}
5558
5559 static int
5560newenv()
5561{
5562 char **env, *elem;
5563 int i, esize;
5564
5565#ifdef MACOS
5566 /* for Mac a new, empty environment is created */
5567 i = 0;
5568#else
5569 for (i = 0; environ[i]; i++)
5570 ;
5571#endif
5572 esize = i + EXTRASIZE + 1;
5573 env = (char **)alloc((unsigned)(esize * sizeof (elem)));
5574 if (env == NULL)
5575 return -1;
5576
5577#ifndef MACOS
5578 for (i = 0; environ[i]; i++)
5579 {
5580 elem = (char *)alloc((unsigned)(strlen(environ[i]) + 1));
5581 if (elem == NULL)
5582 return -1;
5583 env[i] = elem;
5584 strcpy(elem, environ[i]);
5585 }
5586#endif
5587
5588 env[i] = 0;
5589 environ = env;
5590 envsize = esize;
5591 return 0;
5592}
5593
5594 static int
5595moreenv()
5596{
5597 int esize;
5598 char **env;
5599
5600 esize = envsize + EXTRASIZE;
5601 env = (char **)vim_realloc((char *)environ, esize * sizeof (*env));
5602 if (env == 0)
5603 return -1;
5604 environ = env;
5605 envsize = esize;
5606 return 0;
5607}
5608
5609# ifdef USE_VIMPTY_GETENV
5610 char_u *
5611vimpty_getenv(string)
5612 const char_u *string;
5613{
5614 int i;
5615 char_u *p;
5616
5617 if (envsize < 0)
5618 return NULL;
5619
5620 i = findenv((char *)string);
5621
5622 if (i < 0)
5623 return NULL;
5624
5625 p = vim_strchr((char_u *)environ[i], '=');
5626 return (p + 1);
5627}
5628# endif
5629
5630#endif /* !defined(HAVE_SETENV) && !defined(HAVE_PUTENV) */
Bram Moolenaarc4a06d32005-06-07 21:04:49 +00005631
5632#if defined(FEAT_EVAL) || defined(FEAT_SYN_HL) || defined(PROTO)
5633/*
5634 * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
5635 * rights to write into.
5636 */
5637 int
5638filewritable(fname)
5639 char_u *fname;
5640{
5641 int retval = 0;
5642#if defined(UNIX) || defined(VMS)
5643 int perm = 0;
5644#endif
5645
5646#if defined(UNIX) || defined(VMS)
5647 perm = mch_getperm(fname);
5648#endif
5649#ifndef MACOS_CLASSIC /* TODO: get either mch_writable or mch_access */
5650 if (
5651# ifdef WIN3264
5652 mch_writable(fname) &&
5653# else
5654# if defined(UNIX) || defined(VMS)
5655 (perm & 0222) &&
5656# endif
5657# endif
5658 mch_access((char *)fname, W_OK) == 0
5659 )
5660#endif
5661 {
5662 ++retval;
5663 if (mch_isdir(fname))
5664 ++retval;
5665 }
5666 return retval;
5667}
5668#endif