blob: a1e8c1272560f959fe2894cb940fa112544805e6 [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
1085/*
1086 * copy a space a number of times
1087 */
1088 void
1089copy_spaces(ptr, count)
1090 char_u *ptr;
1091 size_t count;
1092{
1093 size_t i = count;
1094 char_u *p = ptr;
1095
1096 while (i--)
1097 *p++ = ' ';
1098}
1099
1100#if defined(FEAT_VISUALEXTRA) || defined(PROTO)
1101/*
1102 * Copy a character a number of times.
1103 * Does not work for multi-byte charactes!
1104 */
1105 void
1106copy_chars(ptr, count, c)
1107 char_u *ptr;
1108 size_t count;
1109 int c;
1110{
1111 size_t i = count;
1112 char_u *p = ptr;
1113
1114 while (i--)
1115 *p++ = c;
1116}
1117#endif
1118
1119/*
1120 * delete spaces at the end of a string
1121 */
1122 void
1123del_trailing_spaces(ptr)
1124 char_u *ptr;
1125{
1126 char_u *q;
1127
1128 q = ptr + STRLEN(ptr);
1129 while (--q > ptr && vim_iswhite(q[0]) && q[-1] != '\\' && q[-1] != Ctrl_V)
1130 *q = NUL;
1131}
1132
1133/*
1134 * This is here because strncpy() does not guarantee successful results when
1135 * the to and from strings overlap. It is only currently called from
1136 * nextwild() which copies part of the command line to another part of the
1137 * command line. This produced garbage when expanding files etc in the middle
1138 * of the command line (on my terminal, anyway) -- webb.
1139 * Note: strncpy() pads the remainder of the buffer with NUL bytes,
1140 * vim_strncpy() doesn't do that.
1141 */
1142 void
1143vim_strncpy(to, from, len)
1144 char_u *to;
1145 char_u *from;
1146 int len;
1147{
1148 int i;
1149
1150 if (to <= from)
1151 {
1152 while (len-- && *from)
1153 *to++ = *from++;
1154 if (len >= 0)
1155 *to = *from; /* Copy NUL */
1156 }
1157 else
1158 {
1159 for (i = 0; i < len; i++)
1160 {
1161 to++;
1162 if (*from++ == NUL)
1163 {
1164 i++;
1165 break;
1166 }
1167 }
1168 for (; i > 0; i--)
1169 *--to = *--from;
1170 }
1171}
1172
1173/*
1174 * Isolate one part of a string option where parts are separated with
1175 * "sep_chars".
1176 * The part is copied into buf[maxlen].
1177 * "*option" is advanced to the next part.
1178 * The length is returned.
1179 */
1180 int
1181copy_option_part(option, buf, maxlen, sep_chars)
1182 char_u **option;
1183 char_u *buf;
1184 int maxlen;
1185 char *sep_chars;
1186{
1187 int len = 0;
1188 char_u *p = *option;
1189
1190 /* skip '.' at start of option part, for 'suffixes' */
1191 if (*p == '.')
1192 buf[len++] = *p++;
1193 while (*p != NUL && vim_strchr((char_u *)sep_chars, *p) == NULL)
1194 {
1195 /*
1196 * Skip backslash before a separator character and space.
1197 */
1198 if (p[0] == '\\' && vim_strchr((char_u *)sep_chars, p[1]) != NULL)
1199 ++p;
1200 if (len < maxlen - 1)
1201 buf[len++] = *p;
1202 ++p;
1203 }
1204 buf[len] = NUL;
1205
1206 if (*p != NUL && *p != ',') /* skip non-standard separator */
1207 ++p;
1208 p = skip_to_option_part(p); /* p points to next file name */
1209
1210 *option = p;
1211 return len;
1212}
1213
1214/*
1215 * replacement for free() that ignores NULL pointers
1216 */
1217 void
1218vim_free(x)
1219 void *x;
1220{
1221 if (x != NULL)
1222 {
1223#ifdef MEM_PROFILE
1224 mem_pre_free(&x);
1225#endif
1226 free(x);
1227 }
1228}
1229
1230#ifndef HAVE_MEMSET
1231 void *
1232vim_memset(ptr, c, size)
1233 void *ptr;
1234 int c;
1235 size_t size;
1236{
1237 char *p = ptr;
1238
1239 while (size-- > 0)
1240 *p++ = c;
1241 return ptr;
1242}
1243#endif
1244
1245#ifdef VIM_MEMCMP
1246/*
1247 * Return zero when "b1" and "b2" are the same for "len" bytes.
1248 * Return non-zero otherwise.
1249 */
1250 int
1251vim_memcmp(b1, b2, len)
1252 void *b1;
1253 void *b2;
1254 size_t len;
1255{
1256 char_u *p1 = (char_u *)b1, *p2 = (char_u *)b2;
1257
1258 for ( ; len > 0; --len)
1259 {
1260 if (*p1 != *p2)
1261 return 1;
1262 ++p1;
1263 ++p2;
1264 }
1265 return 0;
1266}
1267#endif
1268
1269#ifdef VIM_MEMMOVE
1270/*
1271 * Version of memmove() that handles overlapping source and destination.
1272 * For systems that don't have a function that is guaranteed to do that (SYSV).
1273 */
1274 void
1275mch_memmove(dst_arg, src_arg, len)
1276 void *src_arg, *dst_arg;
1277 size_t len;
1278{
1279 /*
1280 * A void doesn't have a size, we use char pointers.
1281 */
1282 char *dst = dst_arg, *src = src_arg;
1283
1284 /* overlap, copy backwards */
1285 if (dst > src && dst < src + len)
1286 {
1287 src += len;
1288 dst += len;
1289 while (len-- > 0)
1290 *--dst = *--src;
1291 }
1292 else /* copy forwards */
1293 while (len-- > 0)
1294 *dst++ = *src++;
1295}
1296#endif
1297
1298#if (!defined(HAVE_STRCASECMP) && !defined(HAVE_STRICMP)) || defined(PROTO)
1299/*
1300 * Compare two strings, ignoring case, using current locale.
1301 * Doesn't work for multi-byte characters.
1302 * return 0 for match, < 0 for smaller, > 0 for bigger
1303 */
1304 int
1305vim_stricmp(s1, s2)
1306 char *s1;
1307 char *s2;
1308{
1309 int i;
1310
1311 for (;;)
1312 {
1313 i = (int)TOLOWER_LOC(*s1) - (int)TOLOWER_LOC(*s2);
1314 if (i != 0)
1315 return i; /* this character different */
1316 if (*s1 == NUL)
1317 break; /* strings match until NUL */
1318 ++s1;
1319 ++s2;
1320 }
1321 return 0; /* strings match */
1322}
1323#endif
1324
1325#if (!defined(HAVE_STRNCASECMP) && !defined(HAVE_STRNICMP)) || defined(PROTO)
1326/*
1327 * Compare two strings, for length "len", ignoring case, using current locale.
1328 * Doesn't work for multi-byte characters.
1329 * return 0 for match, < 0 for smaller, > 0 for bigger
1330 */
1331 int
1332vim_strnicmp(s1, s2, len)
1333 char *s1;
1334 char *s2;
1335 size_t len;
1336{
1337 int i;
1338
1339 while (len > 0)
1340 {
1341 i = (int)TOLOWER_LOC(*s1) - (int)TOLOWER_LOC(*s2);
1342 if (i != 0)
1343 return i; /* this character different */
1344 if (*s1 == NUL)
1345 break; /* strings match until NUL */
1346 ++s1;
1347 ++s2;
1348 --len;
1349 }
1350 return 0; /* strings match */
1351}
1352#endif
1353
1354#if 0 /* currently not used */
1355/*
1356 * Check if string "s2" appears somewhere in "s1" while ignoring case.
1357 * Return NULL if not, a pointer to the first occurrence if it does.
1358 */
1359 char_u *
1360vim_stristr(s1, s2)
1361 char_u *s1;
1362 char_u *s2;
1363{
1364 char_u *p;
1365 int len = STRLEN(s2);
1366 char_u *end = s1 + STRLEN(s1) - len;
1367
1368 for (p = s1; p <= end; ++p)
1369 if (STRNICMP(p, s2, len) == 0)
1370 return p;
1371 return NULL;
1372}
1373#endif
1374
1375/*
1376 * Version of strchr() and strrchr() that handle unsigned char strings
Bram Moolenaar05159a02005-02-26 23:04:13 +00001377 * with characters from 128 to 255 correctly. It also doesn't return a
1378 * pointer to the NUL at the end of the string.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001379 */
1380 char_u *
1381vim_strchr(string, c)
1382 char_u *string;
1383 int c;
1384{
1385 char_u *p;
1386 int b;
1387
1388 p = string;
1389#ifdef FEAT_MBYTE
1390 if (enc_utf8 && c >= 0x80)
1391 {
1392 while (*p != NUL)
1393 {
1394 if (utf_ptr2char(p) == c)
1395 return p;
1396 p += (*mb_ptr2len_check)(p);
1397 }
1398 return NULL;
1399 }
1400 if (enc_dbcs != 0 && c > 255)
1401 {
1402 int n2 = c & 0xff;
1403
1404 c = ((unsigned)c >> 8) & 0xff;
1405 while ((b = *p) != NUL)
1406 {
1407 if (b == c && p[1] == n2)
1408 return p;
1409 p += (*mb_ptr2len_check)(p);
1410 }
1411 return NULL;
1412 }
1413 if (has_mbyte)
1414 {
1415 while ((b = *p) != NUL)
1416 {
1417 if (b == c)
1418 return p;
1419 p += (*mb_ptr2len_check)(p);
1420 }
1421 return NULL;
1422 }
1423#endif
1424 while ((b = *p) != NUL)
1425 {
1426 if (b == c)
1427 return p;
1428 ++p;
1429 }
1430 return NULL;
1431}
1432
1433/*
Bram Moolenaar05159a02005-02-26 23:04:13 +00001434 * Version of strchr() that only works for bytes and handles unsigned char
1435 * strings with characters above 128 correctly. It also doesn't return a
1436 * pointer to the NUL at the end of the string.
1437 */
1438 char_u *
1439vim_strbyte(string, c)
1440 char_u *string;
1441 int c;
1442{
1443 char_u *p = string;
1444
1445 while (*p != NUL)
1446 {
1447 if (*p == c)
1448 return p;
1449 ++p;
1450 }
1451 return NULL;
1452}
1453
1454/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001455 * Search for last occurrence of "c" in "string".
1456 * return NULL if not found.
Bram Moolenaar05159a02005-02-26 23:04:13 +00001457 * Does not handle multi-byte char for "c"!
Bram Moolenaar071d4272004-06-13 20:20:40 +00001458 */
1459 char_u *
1460vim_strrchr(string, c)
1461 char_u *string;
1462 int c;
1463{
1464 char_u *retval = NULL;
Bram Moolenaar05159a02005-02-26 23:04:13 +00001465 char_u *p = string;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001466
Bram Moolenaar05159a02005-02-26 23:04:13 +00001467 while (*p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001468 {
Bram Moolenaar05159a02005-02-26 23:04:13 +00001469 if (*p == c)
1470 retval = p;
1471 mb_ptr_adv(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001472 }
1473 return retval;
1474}
1475
1476/*
1477 * Vim's version of strpbrk(), in case it's missing.
1478 * Don't generate a prototype for this, causes problems when it's not used.
1479 */
1480#ifndef PROTO
1481# ifndef HAVE_STRPBRK
1482# ifdef vim_strpbrk
1483# undef vim_strpbrk
1484# endif
1485 char_u *
1486vim_strpbrk(s, charset)
1487 char_u *s;
1488 char_u *charset;
1489{
1490 while (*s)
1491 {
1492 if (vim_strchr(charset, *s) != NULL)
1493 return s;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001494 mb_ptr_adv(s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001495 }
1496 return NULL;
1497}
1498# endif
1499#endif
1500
1501/*
1502 * Vim has its own isspace() function, because on some machines isspace()
1503 * can't handle characters above 128.
1504 */
1505 int
1506vim_isspace(x)
1507 int x;
1508{
1509 return ((x >= 9 && x <= 13) || x == ' ');
1510}
1511
1512/************************************************************************
Bram Moolenaar383f9bc2005-01-19 22:18:32 +00001513 * Functions for handling growing arrays.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001514 */
1515
1516/*
1517 * Clear an allocated growing array.
1518 */
1519 void
1520ga_clear(gap)
1521 garray_T *gap;
1522{
1523 vim_free(gap->ga_data);
1524 ga_init(gap);
1525}
1526
1527/*
1528 * Clear a growing array that contains a list of strings.
1529 */
1530 void
1531ga_clear_strings(gap)
1532 garray_T *gap;
1533{
1534 int i;
1535
1536 for (i = 0; i < gap->ga_len; ++i)
1537 vim_free(((char_u **)(gap->ga_data))[i]);
1538 ga_clear(gap);
1539}
1540
1541/*
1542 * Initialize a growing array. Don't forget to set ga_itemsize and
1543 * ga_growsize! Or use ga_init2().
1544 */
1545 void
1546ga_init(gap)
1547 garray_T *gap;
1548{
1549 gap->ga_data = NULL;
Bram Moolenaar86b68352004-12-27 21:59:20 +00001550 gap->ga_maxlen = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001551 gap->ga_len = 0;
1552}
1553
1554 void
1555ga_init2(gap, itemsize, growsize)
1556 garray_T *gap;
1557 int itemsize;
1558 int growsize;
1559{
1560 ga_init(gap);
1561 gap->ga_itemsize = itemsize;
1562 gap->ga_growsize = growsize;
1563}
1564
1565/*
1566 * Make room in growing array "gap" for at least "n" items.
1567 * Return FAIL for failure, OK otherwise.
1568 */
1569 int
1570ga_grow(gap, n)
1571 garray_T *gap;
1572 int n;
1573{
1574 size_t len;
1575 char_u *pp;
1576
Bram Moolenaar86b68352004-12-27 21:59:20 +00001577 if (gap->ga_maxlen - gap->ga_len < n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001578 {
1579 if (n < gap->ga_growsize)
1580 n = gap->ga_growsize;
1581 len = gap->ga_itemsize * (gap->ga_len + n);
1582 pp = alloc_clear((unsigned)len);
1583 if (pp == NULL)
1584 return FAIL;
Bram Moolenaar86b68352004-12-27 21:59:20 +00001585 gap->ga_maxlen = gap->ga_len + n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001586 if (gap->ga_data != NULL)
1587 {
1588 mch_memmove(pp, gap->ga_data,
1589 (size_t)(gap->ga_itemsize * gap->ga_len));
1590 vim_free(gap->ga_data);
1591 }
1592 gap->ga_data = pp;
1593 }
1594 return OK;
1595}
1596
1597/*
1598 * Concatenate a string to a growarray which contains characters.
1599 * Note: Does NOT copy the NUL at the end!
1600 */
1601 void
1602ga_concat(gap, s)
1603 garray_T *gap;
1604 char_u *s;
1605{
1606 int len = (int)STRLEN(s);
1607
1608 if (ga_grow(gap, len) == OK)
1609 {
1610 mch_memmove((char *)gap->ga_data + gap->ga_len, s, (size_t)len);
1611 gap->ga_len += len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001612 }
1613}
1614
1615/*
1616 * Append one byte to a growarray which contains bytes.
1617 */
1618 void
1619ga_append(gap, c)
1620 garray_T *gap;
1621 int c;
1622{
1623 if (ga_grow(gap, 1) == OK)
1624 {
1625 *((char *)gap->ga_data + gap->ga_len) = c;
1626 ++gap->ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001627 }
1628}
1629
1630/************************************************************************
1631 * functions that use lookup tables for various things, generally to do with
1632 * special key codes.
1633 */
1634
1635/*
1636 * Some useful tables.
1637 */
1638
1639static struct modmasktable
1640{
1641 short mod_mask; /* Bit-mask for particular key modifier */
1642 short mod_flag; /* Bit(s) for particular key modifier */
1643 char_u name; /* Single letter name of modifier */
1644} mod_mask_table[] =
1645{
1646 {MOD_MASK_ALT, MOD_MASK_ALT, (char_u)'M'},
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001647 {MOD_MASK_META, MOD_MASK_META, (char_u)'T'},
Bram Moolenaar071d4272004-06-13 20:20:40 +00001648 {MOD_MASK_CTRL, MOD_MASK_CTRL, (char_u)'C'},
1649 {MOD_MASK_SHIFT, MOD_MASK_SHIFT, (char_u)'S'},
1650 {MOD_MASK_MULTI_CLICK, MOD_MASK_2CLICK, (char_u)'2'},
1651 {MOD_MASK_MULTI_CLICK, MOD_MASK_3CLICK, (char_u)'3'},
1652 {MOD_MASK_MULTI_CLICK, MOD_MASK_4CLICK, (char_u)'4'},
1653#ifdef MACOS
1654 {MOD_MASK_CMD, MOD_MASK_CMD, (char_u)'D'},
1655#endif
1656 /* 'A' must be the last one */
1657 {MOD_MASK_ALT, MOD_MASK_ALT, (char_u)'A'},
1658 {0, 0, NUL}
1659};
1660
1661/*
1662 * Shifted key terminal codes and their unshifted equivalent.
1663 * Don't add mouse codes here, they are handled seperately!
1664 */
1665#define MOD_KEYS_ENTRY_SIZE 5
1666
1667static char_u modifier_keys_table[] =
1668{
1669/* mod mask with modifier without modifier */
1670 MOD_MASK_SHIFT, '&', '9', '@', '1', /* begin */
1671 MOD_MASK_SHIFT, '&', '0', '@', '2', /* cancel */
1672 MOD_MASK_SHIFT, '*', '1', '@', '4', /* command */
1673 MOD_MASK_SHIFT, '*', '2', '@', '5', /* copy */
1674 MOD_MASK_SHIFT, '*', '3', '@', '6', /* create */
1675 MOD_MASK_SHIFT, '*', '4', 'k', 'D', /* delete char */
1676 MOD_MASK_SHIFT, '*', '5', 'k', 'L', /* delete line */
1677 MOD_MASK_SHIFT, '*', '7', '@', '7', /* end */
1678 MOD_MASK_CTRL, KS_EXTRA, (int)KE_C_END, '@', '7', /* end */
1679 MOD_MASK_SHIFT, '*', '9', '@', '9', /* exit */
1680 MOD_MASK_SHIFT, '*', '0', '@', '0', /* find */
1681 MOD_MASK_SHIFT, '#', '1', '%', '1', /* help */
1682 MOD_MASK_SHIFT, '#', '2', 'k', 'h', /* home */
1683 MOD_MASK_CTRL, KS_EXTRA, (int)KE_C_HOME, 'k', 'h', /* home */
1684 MOD_MASK_SHIFT, '#', '3', 'k', 'I', /* insert */
1685 MOD_MASK_SHIFT, '#', '4', 'k', 'l', /* left arrow */
1686 MOD_MASK_CTRL, KS_EXTRA, (int)KE_C_LEFT, 'k', 'l', /* left arrow */
1687 MOD_MASK_SHIFT, '%', 'a', '%', '3', /* message */
1688 MOD_MASK_SHIFT, '%', 'b', '%', '4', /* move */
1689 MOD_MASK_SHIFT, '%', 'c', '%', '5', /* next */
1690 MOD_MASK_SHIFT, '%', 'd', '%', '7', /* options */
1691 MOD_MASK_SHIFT, '%', 'e', '%', '8', /* previous */
1692 MOD_MASK_SHIFT, '%', 'f', '%', '9', /* print */
1693 MOD_MASK_SHIFT, '%', 'g', '%', '0', /* redo */
1694 MOD_MASK_SHIFT, '%', 'h', '&', '3', /* replace */
1695 MOD_MASK_SHIFT, '%', 'i', 'k', 'r', /* right arr. */
1696 MOD_MASK_CTRL, KS_EXTRA, (int)KE_C_RIGHT, 'k', 'r', /* right arr. */
1697 MOD_MASK_SHIFT, '%', 'j', '&', '5', /* resume */
1698 MOD_MASK_SHIFT, '!', '1', '&', '6', /* save */
1699 MOD_MASK_SHIFT, '!', '2', '&', '7', /* suspend */
1700 MOD_MASK_SHIFT, '!', '3', '&', '8', /* undo */
1701 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_UP, 'k', 'u', /* up arrow */
1702 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_DOWN, 'k', 'd', /* down arrow */
1703
1704 /* vt100 F1 */
1705 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF1, KS_EXTRA, (int)KE_XF1,
1706 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF2, KS_EXTRA, (int)KE_XF2,
1707 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF3, KS_EXTRA, (int)KE_XF3,
1708 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF4, KS_EXTRA, (int)KE_XF4,
1709
1710 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F1, 'k', '1', /* F1 */
1711 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F2, 'k', '2',
1712 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F3, 'k', '3',
1713 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F4, 'k', '4',
1714 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F5, 'k', '5',
1715 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F6, 'k', '6',
1716 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F7, 'k', '7',
1717 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F8, 'k', '8',
1718 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F9, 'k', '9',
1719 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F10, 'k', ';', /* F10 */
1720
1721 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F11, 'F', '1',
1722 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F12, 'F', '2',
1723 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F13, 'F', '3',
1724 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F14, 'F', '4',
1725 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F15, 'F', '5',
1726 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F16, 'F', '6',
1727 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F17, 'F', '7',
1728 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F18, 'F', '8',
1729 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F19, 'F', '9',
1730 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F20, 'F', 'A',
1731
1732 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F21, 'F', 'B',
1733 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F22, 'F', 'C',
1734 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F23, 'F', 'D',
1735 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F24, 'F', 'E',
1736 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F25, 'F', 'F',
1737 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F26, 'F', 'G',
1738 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F27, 'F', 'H',
1739 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F28, 'F', 'I',
1740 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F29, 'F', 'J',
1741 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F30, 'F', 'K',
1742
1743 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F31, 'F', 'L',
1744 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F32, 'F', 'M',
1745 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F33, 'F', 'N',
1746 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F34, 'F', 'O',
1747 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F35, 'F', 'P',
1748 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F36, 'F', 'Q',
1749 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F37, 'F', 'R',
1750
1751 /* TAB pseudo code*/
1752 MOD_MASK_SHIFT, 'k', 'B', KS_EXTRA, (int)KE_TAB,
1753
1754 NUL
1755};
1756
1757static struct key_name_entry
1758{
1759 int key; /* Special key code or ascii value */
1760 char_u *name; /* Name of key */
1761} key_names_table[] =
1762{
1763 {' ', (char_u *)"Space"},
1764 {TAB, (char_u *)"Tab"},
1765 {K_TAB, (char_u *)"Tab"},
1766 {NL, (char_u *)"NL"},
1767 {NL, (char_u *)"NewLine"}, /* Alternative name */
1768 {NL, (char_u *)"LineFeed"}, /* Alternative name */
1769 {NL, (char_u *)"LF"}, /* Alternative name */
1770 {CAR, (char_u *)"CR"},
1771 {CAR, (char_u *)"Return"}, /* Alternative name */
1772 {CAR, (char_u *)"Enter"}, /* Alternative name */
1773 {K_BS, (char_u *)"BS"},
1774 {K_BS, (char_u *)"BackSpace"}, /* Alternative name */
1775 {ESC, (char_u *)"Esc"},
1776 {CSI, (char_u *)"CSI"},
1777 {K_CSI, (char_u *)"xCSI"},
1778 {'|', (char_u *)"Bar"},
1779 {'\\', (char_u *)"Bslash"},
1780 {K_DEL, (char_u *)"Del"},
1781 {K_DEL, (char_u *)"Delete"}, /* Alternative name */
1782 {K_KDEL, (char_u *)"kDel"},
1783 {K_UP, (char_u *)"Up"},
1784 {K_DOWN, (char_u *)"Down"},
1785 {K_LEFT, (char_u *)"Left"},
1786 {K_RIGHT, (char_u *)"Right"},
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00001787 {K_XUP, (char_u *)"xUp"},
1788 {K_XDOWN, (char_u *)"xDown"},
1789 {K_XLEFT, (char_u *)"xLeft"},
1790 {K_XRIGHT, (char_u *)"xRight"},
Bram Moolenaar071d4272004-06-13 20:20:40 +00001791
1792 {K_F1, (char_u *)"F1"},
1793 {K_F2, (char_u *)"F2"},
1794 {K_F3, (char_u *)"F3"},
1795 {K_F4, (char_u *)"F4"},
1796 {K_F5, (char_u *)"F5"},
1797 {K_F6, (char_u *)"F6"},
1798 {K_F7, (char_u *)"F7"},
1799 {K_F8, (char_u *)"F8"},
1800 {K_F9, (char_u *)"F9"},
1801 {K_F10, (char_u *)"F10"},
1802
1803 {K_F11, (char_u *)"F11"},
1804 {K_F12, (char_u *)"F12"},
1805 {K_F13, (char_u *)"F13"},
1806 {K_F14, (char_u *)"F14"},
1807 {K_F15, (char_u *)"F15"},
1808 {K_F16, (char_u *)"F16"},
1809 {K_F17, (char_u *)"F17"},
1810 {K_F18, (char_u *)"F18"},
1811 {K_F19, (char_u *)"F19"},
1812 {K_F20, (char_u *)"F20"},
1813
1814 {K_F21, (char_u *)"F21"},
1815 {K_F22, (char_u *)"F22"},
1816 {K_F23, (char_u *)"F23"},
1817 {K_F24, (char_u *)"F24"},
1818 {K_F25, (char_u *)"F25"},
1819 {K_F26, (char_u *)"F26"},
1820 {K_F27, (char_u *)"F27"},
1821 {K_F28, (char_u *)"F28"},
1822 {K_F29, (char_u *)"F29"},
1823 {K_F30, (char_u *)"F30"},
1824
1825 {K_F31, (char_u *)"F31"},
1826 {K_F32, (char_u *)"F32"},
1827 {K_F33, (char_u *)"F33"},
1828 {K_F34, (char_u *)"F34"},
1829 {K_F35, (char_u *)"F35"},
1830 {K_F36, (char_u *)"F36"},
1831 {K_F37, (char_u *)"F37"},
1832
1833 {K_XF1, (char_u *)"xF1"},
1834 {K_XF2, (char_u *)"xF2"},
1835 {K_XF3, (char_u *)"xF3"},
1836 {K_XF4, (char_u *)"xF4"},
1837
1838 {K_HELP, (char_u *)"Help"},
1839 {K_UNDO, (char_u *)"Undo"},
1840 {K_INS, (char_u *)"Insert"},
1841 {K_INS, (char_u *)"Ins"}, /* Alternative name */
1842 {K_KINS, (char_u *)"kInsert"},
1843 {K_HOME, (char_u *)"Home"},
1844 {K_KHOME, (char_u *)"kHome"},
1845 {K_XHOME, (char_u *)"xHome"},
Bram Moolenaar68b76a62005-03-25 21:53:48 +00001846 {K_ZHOME, (char_u *)"zHome"},
Bram Moolenaar071d4272004-06-13 20:20:40 +00001847 {K_END, (char_u *)"End"},
1848 {K_KEND, (char_u *)"kEnd"},
1849 {K_XEND, (char_u *)"xEnd"},
Bram Moolenaar68b76a62005-03-25 21:53:48 +00001850 {K_ZEND, (char_u *)"zEnd"},
Bram Moolenaar071d4272004-06-13 20:20:40 +00001851 {K_PAGEUP, (char_u *)"PageUp"},
1852 {K_PAGEDOWN, (char_u *)"PageDown"},
1853 {K_KPAGEUP, (char_u *)"kPageUp"},
1854 {K_KPAGEDOWN, (char_u *)"kPageDown"},
1855
1856 {K_KPLUS, (char_u *)"kPlus"},
1857 {K_KMINUS, (char_u *)"kMinus"},
1858 {K_KDIVIDE, (char_u *)"kDivide"},
1859 {K_KMULTIPLY, (char_u *)"kMultiply"},
1860 {K_KENTER, (char_u *)"kEnter"},
1861 {K_KPOINT, (char_u *)"kPoint"},
1862
1863 {K_K0, (char_u *)"k0"},
1864 {K_K1, (char_u *)"k1"},
1865 {K_K2, (char_u *)"k2"},
1866 {K_K3, (char_u *)"k3"},
1867 {K_K4, (char_u *)"k4"},
1868 {K_K5, (char_u *)"k5"},
1869 {K_K6, (char_u *)"k6"},
1870 {K_K7, (char_u *)"k7"},
1871 {K_K8, (char_u *)"k8"},
1872 {K_K9, (char_u *)"k9"},
1873
1874 {'<', (char_u *)"lt"},
1875
1876 {K_MOUSE, (char_u *)"Mouse"},
1877 {K_NETTERM_MOUSE, (char_u *)"NetMouse"},
1878 {K_DEC_MOUSE, (char_u *)"DecMouse"},
1879 {K_JSBTERM_MOUSE, (char_u *)"JsbMouse"},
1880 {K_PTERM_MOUSE, (char_u *)"PtermMouse"},
1881 {K_LEFTMOUSE, (char_u *)"LeftMouse"},
1882 {K_LEFTMOUSE_NM, (char_u *)"LeftMouseNM"},
1883 {K_LEFTDRAG, (char_u *)"LeftDrag"},
1884 {K_LEFTRELEASE, (char_u *)"LeftRelease"},
1885 {K_LEFTRELEASE_NM, (char_u *)"LeftReleaseNM"},
1886 {K_MIDDLEMOUSE, (char_u *)"MiddleMouse"},
1887 {K_MIDDLEDRAG, (char_u *)"MiddleDrag"},
1888 {K_MIDDLERELEASE, (char_u *)"MiddleRelease"},
1889 {K_RIGHTMOUSE, (char_u *)"RightMouse"},
1890 {K_RIGHTDRAG, (char_u *)"RightDrag"},
1891 {K_RIGHTRELEASE, (char_u *)"RightRelease"},
1892 {K_MOUSEDOWN, (char_u *)"MouseDown"},
1893 {K_MOUSEUP, (char_u *)"MouseUp"},
1894 {K_X1MOUSE, (char_u *)"X1Mouse"},
1895 {K_X1DRAG, (char_u *)"X1Drag"},
1896 {K_X1RELEASE, (char_u *)"X1Release"},
1897 {K_X2MOUSE, (char_u *)"X2Mouse"},
1898 {K_X2DRAG, (char_u *)"X2Drag"},
1899 {K_X2RELEASE, (char_u *)"X2Release"},
1900 {K_DROP, (char_u *)"Drop"},
1901 {K_ZERO, (char_u *)"Nul"},
1902#ifdef FEAT_EVAL
1903 {K_SNR, (char_u *)"SNR"},
1904#endif
1905 {K_PLUG, (char_u *)"Plug"},
1906 {0, NULL}
1907};
1908
1909#define KEY_NAMES_TABLE_LEN (sizeof(key_names_table) / sizeof(struct key_name_entry))
1910
1911#ifdef FEAT_MOUSE
1912static struct mousetable
1913{
1914 int pseudo_code; /* Code for pseudo mouse event */
1915 int button; /* Which mouse button is it? */
1916 int is_click; /* Is it a mouse button click event? */
1917 int is_drag; /* Is it a mouse drag event? */
1918} mouse_table[] =
1919{
1920 {(int)KE_LEFTMOUSE, MOUSE_LEFT, TRUE, FALSE},
1921#ifdef FEAT_GUI
1922 {(int)KE_LEFTMOUSE_NM, MOUSE_LEFT, TRUE, FALSE},
1923#endif
1924 {(int)KE_LEFTDRAG, MOUSE_LEFT, FALSE, TRUE},
1925 {(int)KE_LEFTRELEASE, MOUSE_LEFT, FALSE, FALSE},
1926#ifdef FEAT_GUI
1927 {(int)KE_LEFTRELEASE_NM, MOUSE_LEFT, FALSE, FALSE},
1928#endif
1929 {(int)KE_MIDDLEMOUSE, MOUSE_MIDDLE, TRUE, FALSE},
1930 {(int)KE_MIDDLEDRAG, MOUSE_MIDDLE, FALSE, TRUE},
1931 {(int)KE_MIDDLERELEASE, MOUSE_MIDDLE, FALSE, FALSE},
1932 {(int)KE_RIGHTMOUSE, MOUSE_RIGHT, TRUE, FALSE},
1933 {(int)KE_RIGHTDRAG, MOUSE_RIGHT, FALSE, TRUE},
1934 {(int)KE_RIGHTRELEASE, MOUSE_RIGHT, FALSE, FALSE},
1935 {(int)KE_X1MOUSE, MOUSE_X1, TRUE, FALSE},
1936 {(int)KE_X1DRAG, MOUSE_X1, FALSE, TRUE},
1937 {(int)KE_X1RELEASE, MOUSE_X1, FALSE, FALSE},
1938 {(int)KE_X2MOUSE, MOUSE_X2, TRUE, FALSE},
1939 {(int)KE_X2DRAG, MOUSE_X2, FALSE, TRUE},
1940 {(int)KE_X2RELEASE, MOUSE_X2, FALSE, FALSE},
1941 /* DRAG without CLICK */
1942 {(int)KE_IGNORE, MOUSE_RELEASE, FALSE, TRUE},
1943 /* RELEASE without CLICK */
1944 {(int)KE_IGNORE, MOUSE_RELEASE, FALSE, FALSE},
1945 {0, 0, 0, 0},
1946};
1947#endif /* FEAT_MOUSE */
1948
1949/*
1950 * Return the modifier mask bit (MOD_MASK_*) which corresponds to the given
1951 * modifier name ('S' for Shift, 'C' for Ctrl etc).
1952 */
1953 int
1954name_to_mod_mask(c)
1955 int c;
1956{
1957 int i;
1958
1959 c = TOUPPER_ASC(c);
1960 for (i = 0; mod_mask_table[i].mod_mask != 0; i++)
1961 if (c == mod_mask_table[i].name)
1962 return mod_mask_table[i].mod_flag;
1963 return 0;
1964}
1965
Bram Moolenaar071d4272004-06-13 20:20:40 +00001966/*
1967 * Check if if there is a special key code for "key" that includes the
1968 * modifiers specified.
1969 */
1970 int
1971simplify_key(key, modifiers)
1972 int key;
1973 int *modifiers;
1974{
1975 int i;
1976 int key0;
1977 int key1;
1978
1979 if (*modifiers & (MOD_MASK_SHIFT | MOD_MASK_CTRL | MOD_MASK_ALT))
1980 {
1981 /* TAB is a special case */
1982 if (key == TAB && (*modifiers & MOD_MASK_SHIFT))
1983 {
1984 *modifiers &= ~MOD_MASK_SHIFT;
1985 return K_S_TAB;
1986 }
1987 key0 = KEY2TERMCAP0(key);
1988 key1 = KEY2TERMCAP1(key);
1989 for (i = 0; modifier_keys_table[i] != NUL; i += MOD_KEYS_ENTRY_SIZE)
1990 if (key0 == modifier_keys_table[i + 3]
1991 && key1 == modifier_keys_table[i + 4]
1992 && (*modifiers & modifier_keys_table[i]))
1993 {
1994 *modifiers &= ~modifier_keys_table[i];
1995 return TERMCAP2KEY(modifier_keys_table[i + 1],
1996 modifier_keys_table[i + 2]);
1997 }
1998 }
1999 return key;
2000}
2001
2002/*
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002003 * Change <xHome> to <Home>, <xUp> to <Up>, etc.
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002004 */
2005 int
2006handle_x_keys(key)
2007 int key;
2008{
2009 switch (key)
2010 {
2011 case K_XUP: return K_UP;
2012 case K_XDOWN: return K_DOWN;
2013 case K_XLEFT: return K_LEFT;
2014 case K_XRIGHT: return K_RIGHT;
2015 case K_XHOME: return K_HOME;
Bram Moolenaar68b76a62005-03-25 21:53:48 +00002016 case K_ZHOME: return K_HOME;
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002017 case K_XEND: return K_END;
Bram Moolenaar68b76a62005-03-25 21:53:48 +00002018 case K_ZEND: return K_END;
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002019 case K_XF1: return K_F1;
2020 case K_XF2: return K_F2;
2021 case K_XF3: return K_F3;
2022 case K_XF4: return K_F4;
2023 case K_S_XF1: return K_S_F1;
2024 case K_S_XF2: return K_S_F2;
2025 case K_S_XF3: return K_S_F3;
2026 case K_S_XF4: return K_S_F4;
2027 }
2028 return key;
2029}
2030
2031/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00002032 * Return a string which contains the name of the given key when the given
2033 * modifiers are down.
2034 */
2035 char_u *
2036get_special_key_name(c, modifiers)
2037 int c;
2038 int modifiers;
2039{
2040 static char_u string[MAX_KEY_NAME_LEN + 1];
2041
2042 int i, idx;
2043 int table_idx;
2044 char_u *s;
2045
2046 string[0] = '<';
2047 idx = 1;
2048
2049 /* Key that stands for a normal character. */
2050 if (IS_SPECIAL(c) && KEY2TERMCAP0(c) == KS_KEY)
2051 c = KEY2TERMCAP1(c);
2052
2053 /*
2054 * Translate shifted special keys into unshifted keys and set modifier.
2055 * Same for CTRL and ALT modifiers.
2056 */
2057 if (IS_SPECIAL(c))
2058 {
2059 for (i = 0; modifier_keys_table[i] != 0; i += MOD_KEYS_ENTRY_SIZE)
2060 if ( KEY2TERMCAP0(c) == (int)modifier_keys_table[i + 1]
2061 && (int)KEY2TERMCAP1(c) == (int)modifier_keys_table[i + 2])
2062 {
2063 modifiers |= modifier_keys_table[i];
2064 c = TERMCAP2KEY(modifier_keys_table[i + 3],
2065 modifier_keys_table[i + 4]);
2066 break;
2067 }
2068 }
2069
2070 /* try to find the key in the special key table */
2071 table_idx = find_special_key_in_table(c);
2072
2073 /*
2074 * When not a known special key, and not a printable character, try to
2075 * extract modifiers.
2076 */
2077 if (c > 0
2078#ifdef FEAT_MBYTE
2079 && (*mb_char2len)(c) == 1
2080#endif
2081 )
2082 {
2083 if (table_idx < 0
2084 && (!vim_isprintc(c) || (c & 0x7f) == ' ')
2085 && (c & 0x80))
2086 {
2087 c &= 0x7f;
2088 modifiers |= MOD_MASK_ALT;
2089 /* try again, to find the un-alted key in the special key table */
2090 table_idx = find_special_key_in_table(c);
2091 }
2092 if (table_idx < 0 && !vim_isprintc(c) && c < ' ')
2093 {
2094#ifdef EBCDIC
2095 c = CtrlChar(c);
2096#else
2097 c += '@';
2098#endif
2099 modifiers |= MOD_MASK_CTRL;
2100 }
2101 }
2102
2103 /* translate the modifier into a string */
2104 for (i = 0; mod_mask_table[i].name != 'A'; i++)
2105 if ((modifiers & mod_mask_table[i].mod_mask)
2106 == mod_mask_table[i].mod_flag)
2107 {
2108 string[idx++] = mod_mask_table[i].name;
2109 string[idx++] = (char_u)'-';
2110 }
2111
2112 if (table_idx < 0) /* unknown special key, may output t_xx */
2113 {
2114 if (IS_SPECIAL(c))
2115 {
2116 string[idx++] = 't';
2117 string[idx++] = '_';
2118 string[idx++] = KEY2TERMCAP0(c);
2119 string[idx++] = KEY2TERMCAP1(c);
2120 }
2121 /* Not a special key, only modifiers, output directly */
2122 else
2123 {
2124#ifdef FEAT_MBYTE
2125 if (has_mbyte && (*mb_char2len)(c) > 1)
2126 idx += (*mb_char2bytes)(c, string + idx);
2127 else
2128#endif
2129 if (vim_isprintc(c))
2130 string[idx++] = c;
2131 else
2132 {
2133 s = transchar(c);
2134 while (*s)
2135 string[idx++] = *s++;
2136 }
2137 }
2138 }
2139 else /* use name of special key */
2140 {
2141 STRCPY(string + idx, key_names_table[table_idx].name);
2142 idx = (int)STRLEN(string);
2143 }
2144 string[idx++] = '>';
2145 string[idx] = NUL;
2146 return string;
2147}
2148
2149/*
2150 * Try translating a <> name at (*srcp)[] to dst[].
2151 * Return the number of characters added to dst[], zero for no match.
2152 * If there is a match, srcp is advanced to after the <> name.
2153 * dst[] must be big enough to hold the result (up to six characters)!
2154 */
2155 int
2156trans_special(srcp, dst, keycode)
2157 char_u **srcp;
2158 char_u *dst;
2159 int keycode; /* prefer key code, e.g. K_DEL instead of DEL */
2160{
2161 int modifiers = 0;
2162 int key;
2163 int dlen = 0;
2164
2165 key = find_special_key(srcp, &modifiers, keycode);
2166 if (key == 0)
2167 return 0;
2168
2169 /* Put the appropriate modifier in a string */
2170 if (modifiers != 0)
2171 {
2172 dst[dlen++] = K_SPECIAL;
2173 dst[dlen++] = KS_MODIFIER;
2174 dst[dlen++] = modifiers;
2175 }
2176
2177 if (IS_SPECIAL(key))
2178 {
2179 dst[dlen++] = K_SPECIAL;
2180 dst[dlen++] = KEY2TERMCAP0(key);
2181 dst[dlen++] = KEY2TERMCAP1(key);
2182 }
2183#ifdef FEAT_MBYTE
2184 else if (has_mbyte && !keycode)
2185 dlen += (*mb_char2bytes)(key, dst + dlen);
2186#endif
2187 else if (keycode)
2188 dlen = (int)(add_char2buf(key, dst + dlen) - dst);
2189 else
2190 dst[dlen++] = key;
2191
2192 return dlen;
2193}
2194
2195/*
2196 * Try translating a <> name at (*srcp)[], return the key and modifiers.
2197 * srcp is advanced to after the <> name.
2198 * returns 0 if there is no match.
2199 */
2200 int
2201find_special_key(srcp, modp, keycode)
2202 char_u **srcp;
2203 int *modp;
2204 int keycode; /* prefer key code, e.g. K_DEL instead of DEL */
2205{
2206 char_u *last_dash;
2207 char_u *end_of_name;
2208 char_u *src;
2209 char_u *bp;
2210 int modifiers;
2211 int bit;
2212 int key;
2213 long_u n;
2214
2215 src = *srcp;
2216 if (src[0] != '<')
2217 return 0;
2218
2219 /* Find end of modifier list */
2220 last_dash = src;
2221 for (bp = src + 1; *bp == '-' || vim_isIDc(*bp); bp++)
2222 {
2223 if (*bp == '-')
2224 {
2225 last_dash = bp;
2226 if (bp[1] != NUL && bp[2] == '>')
2227 ++bp; /* anything accepted, like <C-?> */
2228 }
2229 if (bp[0] == 't' && bp[1] == '_' && bp[2] && bp[3])
2230 bp += 3; /* skip t_xx, xx may be '-' or '>' */
2231 }
2232
2233 if (*bp == '>') /* found matching '>' */
2234 {
2235 end_of_name = bp + 1;
2236
2237 if (STRNICMP(src + 1, "char-", 5) == 0 && VIM_ISDIGIT(src[6]))
2238 {
2239 /* <Char-123> or <Char-033> or <Char-0x33> */
2240 vim_str2nr(src + 6, NULL, NULL, TRUE, TRUE, NULL, &n);
2241 *modp = 0;
2242 *srcp = end_of_name;
2243 return (int)n;
2244 }
2245
2246 /* Which modifiers are given? */
2247 modifiers = 0x0;
2248 for (bp = src + 1; bp < last_dash; bp++)
2249 {
2250 if (*bp != '-')
2251 {
2252 bit = name_to_mod_mask(*bp);
2253 if (bit == 0x0)
2254 break; /* Illegal modifier name */
2255 modifiers |= bit;
2256 }
2257 }
2258
2259 /*
2260 * Legal modifier name.
2261 */
2262 if (bp >= last_dash)
2263 {
2264 /*
2265 * Modifier with single letter, or special key name.
2266 */
2267 if (modifiers != 0 && last_dash[2] == '>')
2268 key = last_dash[1];
2269 else
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002270 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002271 key = get_special_key_code(last_dash + 1);
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002272 key = handle_x_keys(key);
2273 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002274
2275 /*
2276 * get_special_key_code() may return NUL for invalid
2277 * special key name.
2278 */
2279 if (key != NUL)
2280 {
2281 /*
2282 * Only use a modifier when there is no special key code that
2283 * includes the modifier.
2284 */
2285 key = simplify_key(key, &modifiers);
2286
2287 if (!keycode)
2288 {
2289 /* don't want keycode, use single byte code */
2290 if (key == K_BS)
2291 key = BS;
2292 else if (key == K_DEL || key == K_KDEL)
2293 key = DEL;
2294 }
2295
2296 /*
2297 * Normal Key with modifier: Try to make a single byte code.
2298 */
2299 if (!IS_SPECIAL(key))
2300 key = extract_modifiers(key, &modifiers);
2301
2302 *modp = modifiers;
2303 *srcp = end_of_name;
2304 return key;
2305 }
2306 }
2307 }
2308 return 0;
2309}
2310
2311/*
2312 * Try to include modifiers in the key.
2313 * Changes "Shift-a" to 'A', "Alt-A" to 0xc0, etc.
2314 */
2315 int
2316extract_modifiers(key, modp)
2317 int key;
2318 int *modp;
2319{
2320 int modifiers = *modp;
2321
2322#ifdef MACOS
2323 /* Command-key really special, No fancynest */
2324 if (!(modifiers & MOD_MASK_CMD))
2325#endif
2326 if ((modifiers & MOD_MASK_SHIFT) && ASCII_ISALPHA(key))
2327 {
2328 key = TOUPPER_ASC(key);
2329 modifiers &= ~MOD_MASK_SHIFT;
2330 }
2331 if ((modifiers & MOD_MASK_CTRL)
2332#ifdef EBCDIC
2333 /* * TODO: EBCDIC Better use:
2334 * && (Ctrl_chr(key) || key == '?')
2335 * ??? */
2336 && strchr("?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_", key)
2337 != NULL
2338#else
2339 && ((key >= '?' && key <= '_') || ASCII_ISALPHA(key))
2340#endif
2341 )
2342 {
2343 key = Ctrl_chr(key);
2344 modifiers &= ~MOD_MASK_CTRL;
2345 /* <C-@> is <Nul> */
2346 if (key == 0)
2347 key = K_ZERO;
2348 }
2349#ifdef MACOS
2350 /* Command-key really special, No fancynest */
2351 if (!(modifiers & MOD_MASK_CMD))
2352#endif
2353 if ((modifiers & MOD_MASK_ALT) && key < 0x80
2354#ifdef FEAT_MBYTE
2355 && !enc_dbcs /* avoid creating a lead byte */
2356#endif
2357 )
2358 {
2359 key |= 0x80;
2360 modifiers &= ~MOD_MASK_ALT; /* remove the META modifier */
2361 }
2362
2363 *modp = modifiers;
2364 return key;
2365}
2366
2367/*
2368 * Try to find key "c" in the special key table.
2369 * Return the index when found, -1 when not found.
2370 */
2371 int
2372find_special_key_in_table(c)
2373 int c;
2374{
2375 int i;
2376
2377 for (i = 0; key_names_table[i].name != NULL; i++)
2378 if (c == key_names_table[i].key)
2379 break;
2380 if (key_names_table[i].name == NULL)
2381 i = -1;
2382 return i;
2383}
2384
2385/*
2386 * Find the special key with the given name (the given string does not have to
2387 * end with NUL, the name is assumed to end before the first non-idchar).
2388 * If the name starts with "t_" the next two characters are interpreted as a
2389 * termcap name.
2390 * Return the key code, or 0 if not found.
2391 */
2392 int
2393get_special_key_code(name)
2394 char_u *name;
2395{
2396 char_u *table_name;
2397 char_u string[3];
2398 int i, j;
2399
2400 /*
2401 * If it's <t_xx> we get the code for xx from the termcap
2402 */
2403 if (name[0] == 't' && name[1] == '_' && name[2] != NUL && name[3] != NUL)
2404 {
2405 string[0] = name[2];
2406 string[1] = name[3];
2407 string[2] = NUL;
2408 if (add_termcap_entry(string, FALSE) == OK)
2409 return TERMCAP2KEY(name[2], name[3]);
2410 }
2411 else
2412 for (i = 0; key_names_table[i].name != NULL; i++)
2413 {
2414 table_name = key_names_table[i].name;
2415 for (j = 0; vim_isIDc(name[j]) && table_name[j] != NUL; j++)
2416 if (TOLOWER_ASC(table_name[j]) != TOLOWER_ASC(name[j]))
2417 break;
2418 if (!vim_isIDc(name[j]) && table_name[j] == NUL)
2419 return key_names_table[i].key;
2420 }
2421 return 0;
2422}
2423
2424#ifdef FEAT_CMDL_COMPL
2425 char_u *
2426get_key_name(i)
2427 int i;
2428{
2429 if (i >= KEY_NAMES_TABLE_LEN)
2430 return NULL;
2431 return key_names_table[i].name;
2432}
2433#endif
2434
2435#ifdef FEAT_MOUSE
2436/*
2437 * Look up the given mouse code to return the relevant information in the other
2438 * arguments. Return which button is down or was released.
2439 */
2440 int
2441get_mouse_button(code, is_click, is_drag)
2442 int code;
2443 int *is_click;
2444 int *is_drag;
2445{
2446 int i;
2447
2448 for (i = 0; mouse_table[i].pseudo_code; i++)
2449 if (code == mouse_table[i].pseudo_code)
2450 {
2451 *is_click = mouse_table[i].is_click;
2452 *is_drag = mouse_table[i].is_drag;
2453 return mouse_table[i].button;
2454 }
2455 return 0; /* Shouldn't get here */
2456}
2457
2458/*
2459 * Return the appropriate pseudo mouse event token (KE_LEFTMOUSE etc) based on
2460 * the given information about which mouse button is down, and whether the
2461 * mouse was clicked, dragged or released.
2462 */
2463 int
2464get_pseudo_mouse_code(button, is_click, is_drag)
2465 int button; /* eg MOUSE_LEFT */
2466 int is_click;
2467 int is_drag;
2468{
2469 int i;
2470
2471 for (i = 0; mouse_table[i].pseudo_code; i++)
2472 if (button == mouse_table[i].button
2473 && is_click == mouse_table[i].is_click
2474 && is_drag == mouse_table[i].is_drag)
2475 {
2476#ifdef FEAT_GUI
Bram Moolenaarc91506a2005-04-24 22:04:21 +00002477 /* Trick: a non mappable left click and release has mouse_col -1
2478 * or added MOUSE_COLOFF. Used for 'mousefocus' in
2479 * gui_mouse_moved() */
2480 if (mouse_col < 0 || mouse_col > MOUSE_COLOFF)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002481 {
Bram Moolenaarc91506a2005-04-24 22:04:21 +00002482 if (mouse_col < 0)
2483 mouse_col = 0;
2484 else
2485 mouse_col -= MOUSE_COLOFF;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002486 if (mouse_table[i].pseudo_code == (int)KE_LEFTMOUSE)
2487 return (int)KE_LEFTMOUSE_NM;
2488 if (mouse_table[i].pseudo_code == (int)KE_LEFTRELEASE)
2489 return (int)KE_LEFTRELEASE_NM;
2490 }
2491#endif
2492 return mouse_table[i].pseudo_code;
2493 }
2494 return (int)KE_IGNORE; /* not recongnized, ignore it */
2495}
2496#endif /* FEAT_MOUSE */
2497
2498/*
2499 * Return the current end-of-line type: EOL_DOS, EOL_UNIX or EOL_MAC.
2500 */
2501 int
2502get_fileformat(buf)
2503 buf_T *buf;
2504{
2505 int c = *buf->b_p_ff;
2506
2507 if (buf->b_p_bin || c == 'u')
2508 return EOL_UNIX;
2509 if (c == 'm')
2510 return EOL_MAC;
2511 return EOL_DOS;
2512}
2513
2514/*
2515 * Like get_fileformat(), but override 'fileformat' with "p" for "++opt=val"
2516 * argument.
2517 */
2518 int
2519get_fileformat_force(buf, eap)
2520 buf_T *buf;
2521 exarg_T *eap; /* can be NULL! */
2522{
2523 int c;
2524
2525 if (eap != NULL && eap->force_ff != 0)
2526 c = eap->cmd[eap->force_ff];
2527 else
2528 {
2529 if ((eap != NULL && eap->force_bin != 0)
2530 ? (eap->force_bin == FORCE_BIN) : buf->b_p_bin)
2531 return EOL_UNIX;
2532 c = *buf->b_p_ff;
2533 }
2534 if (c == 'u')
2535 return EOL_UNIX;
2536 if (c == 'm')
2537 return EOL_MAC;
2538 return EOL_DOS;
2539}
2540
2541/*
2542 * Set the current end-of-line type to EOL_DOS, EOL_UNIX or EOL_MAC.
2543 * Sets both 'textmode' and 'fileformat'.
2544 * Note: Does _not_ set global value of 'textmode'!
2545 */
2546 void
2547set_fileformat(t, opt_flags)
2548 int t;
2549 int opt_flags; /* OPT_LOCAL and/or OPT_GLOBAL */
2550{
2551 char *p = NULL;
2552
2553 switch (t)
2554 {
2555 case EOL_DOS:
2556 p = FF_DOS;
2557 curbuf->b_p_tx = TRUE;
2558 break;
2559 case EOL_UNIX:
2560 p = FF_UNIX;
2561 curbuf->b_p_tx = FALSE;
2562 break;
2563 case EOL_MAC:
2564 p = FF_MAC;
2565 curbuf->b_p_tx = FALSE;
2566 break;
2567 }
2568 if (p != NULL)
2569 set_string_option_direct((char_u *)"ff", -1, (char_u *)p,
2570 OPT_FREE | opt_flags);
2571#ifdef FEAT_WINDOWS
2572 check_status(curbuf);
2573#endif
2574#ifdef FEAT_TITLE
2575 need_maketitle = TRUE; /* set window title later */
2576#endif
2577}
2578
2579/*
2580 * Return the default fileformat from 'fileformats'.
2581 */
2582 int
2583default_fileformat()
2584{
2585 switch (*p_ffs)
2586 {
2587 case 'm': return EOL_MAC;
2588 case 'd': return EOL_DOS;
2589 }
2590 return EOL_UNIX;
2591}
2592
2593/*
2594 * Call shell. Calls mch_call_shell, with 'shellxquote' added.
2595 */
2596 int
2597call_shell(cmd, opt)
2598 char_u *cmd;
2599 int opt;
2600{
2601 char_u *ncmd;
2602 int retval;
Bram Moolenaar05159a02005-02-26 23:04:13 +00002603#ifdef FEAT_PROFILE
2604 proftime_T wait_time;
2605#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002606
2607 if (p_verbose > 3)
2608 {
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00002609 verbose_enter();
Bram Moolenaar051b7822005-05-19 21:00:46 +00002610 smsg((char_u *)_("Calling shell to execute: \"%s\""),
Bram Moolenaar071d4272004-06-13 20:20:40 +00002611 cmd == NULL ? p_sh : cmd);
2612 out_char('\n');
2613 cursor_on();
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00002614 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002615 }
2616
Bram Moolenaar05159a02005-02-26 23:04:13 +00002617#ifdef FEAT_PROFILE
2618 if (do_profiling)
2619 prof_child_enter(&wait_time);
2620#endif
2621
Bram Moolenaar071d4272004-06-13 20:20:40 +00002622 if (*p_sh == NUL)
2623 {
2624 EMSG(_(e_shellempty));
2625 retval = -1;
2626 }
2627 else
2628 {
2629#ifdef FEAT_GUI_MSWIN
2630 /* Don't hide the pointer while executing a shell command. */
2631 gui_mch_mousehide(FALSE);
2632#endif
2633#ifdef FEAT_GUI
2634 ++hold_gui_events;
2635#endif
2636 /* The external command may update a tags file, clear cached tags. */
2637 tag_freematch();
2638
2639 if (cmd == NULL || *p_sxq == NUL)
2640 retval = mch_call_shell(cmd, opt);
2641 else
2642 {
2643 ncmd = alloc((unsigned)(STRLEN(cmd) + STRLEN(p_sxq) * 2 + 1));
2644 if (ncmd != NULL)
2645 {
2646 STRCPY(ncmd, p_sxq);
2647 STRCAT(ncmd, cmd);
2648 STRCAT(ncmd, p_sxq);
2649 retval = mch_call_shell(ncmd, opt);
2650 vim_free(ncmd);
2651 }
2652 else
2653 retval = -1;
2654 }
2655#ifdef FEAT_GUI
2656 --hold_gui_events;
2657#endif
2658 /*
2659 * Check the window size, in case it changed while executing the
2660 * external command.
2661 */
2662 shell_resized_check();
2663 }
2664
2665#ifdef FEAT_EVAL
2666 set_vim_var_nr(VV_SHELL_ERROR, (long)retval);
Bram Moolenaar05159a02005-02-26 23:04:13 +00002667# ifdef FEAT_PROFILE
2668 if (do_profiling)
2669 prof_child_exit(&wait_time);
2670# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002671#endif
2672
2673 return retval;
2674}
2675
2676/*
2677 * VISUAL and OP_PENDING State are never set, they are equal to NORMAL State
2678 * with a condition. This function returns the real State.
2679 */
2680 int
2681get_real_state()
2682{
2683 if (State & NORMAL)
2684 {
2685#ifdef FEAT_VISUAL
2686 if (VIsual_active)
2687 return VISUAL;
2688 else
2689#endif
2690 if (finish_op)
2691 return OP_PENDING;
2692 }
2693 return State;
2694}
2695
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002696#if defined(FEAT_MBYTE) || defined(PROTO)
2697/*
2698 * Return TRUE if "p" points to just after a path separator.
2699 * Take care of multi-byte characters.
2700 * "b" must point to the start of the file name
2701 */
2702 int
2703after_pathsep(b, p)
2704 char_u *b;
2705 char_u *p;
2706{
2707 return vim_ispathsep(p[-1])
2708 && (!has_mbyte || (*mb_head_off)(b, p - 1) == 0);
2709}
2710#endif
2711
2712/*
2713 * Return TRUE if file names "f1" and "f2" are in the same directory.
2714 * "f1" may be a short name, "f2" must be a full path.
2715 */
2716 int
2717same_directory(f1, f2)
2718 char_u *f1;
2719 char_u *f2;
2720{
2721 char_u ffname[MAXPATHL];
2722 char_u *t1;
2723 char_u *t2;
2724
2725 /* safety check */
2726 if (f1 == NULL || f2 == NULL)
2727 return FALSE;
2728
2729 (void)vim_FullName(f1, ffname, MAXPATHL, FALSE);
2730 t1 = gettail_sep(ffname);
2731 t2 = gettail_sep(f2);
2732 return (t1 - ffname == t2 - f2
2733 && pathcmp((char *)ffname, (char *)f2, (int)(t1 - ffname)) == 0);
2734}
2735
Bram Moolenaar071d4272004-06-13 20:20:40 +00002736#if defined(FEAT_SESSION) || defined(MSWIN) || defined(FEAT_GUI_MAC) \
Bram Moolenaar843ee412004-06-30 16:16:41 +00002737 || ((defined(FEAT_GUI_GTK) || defined(FEAT_GUI_KDE)) \
2738 && ( defined(FEAT_WINDOWS) || defined(FEAT_DND)) ) \
Bram Moolenaar071d4272004-06-13 20:20:40 +00002739 || defined(FEAT_SUN_WORKSHOP) || defined(FEAT_NETBEANS_INTG) \
2740 || defined(PROTO)
2741/*
2742 * Change to a file's directory.
2743 * Caller must call shorten_fnames()!
2744 * Return OK or FAIL.
2745 */
2746 int
2747vim_chdirfile(fname)
2748 char_u *fname;
2749{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002750 char_u dir[MAXPATHL];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002751
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002752 STRNCPY(dir, fname, MAXPATHL);
2753 dir[MAXPATHL - 1] = NUL;
2754 *gettail_sep(dir) = NUL;
2755 return mch_chdir((char *)dir) == 0 ? OK : FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002756}
2757#endif
2758
2759#if defined(STAT_IGNORES_SLASH) || defined(PROTO)
2760/*
2761 * Check if "name" ends in a slash and is not a directory.
2762 * Used for systems where stat() ignores a trailing slash on a file name.
2763 * The Vim code assumes a trailing slash is only ignored for a directory.
2764 */
2765 int
2766illegal_slash(name)
2767 char *name;
2768{
2769 if (name[0] == NUL)
2770 return FALSE; /* no file name is not illegal */
2771 if (name[strlen(name) - 1] != '/')
2772 return FALSE; /* no trailing slash */
2773 if (mch_isdir((char_u *)name))
2774 return FALSE; /* trailing slash for a directory */
2775 return TRUE;
2776}
2777#endif
2778
2779#if defined(CURSOR_SHAPE) || defined(PROTO)
2780
2781/*
2782 * Handling of cursor and mouse pointer shapes in various modes.
2783 */
2784
2785cursorentry_T shape_table[SHAPE_IDX_COUNT] =
2786{
2787 /* The values will be filled in from the 'guicursor' and 'mouseshape'
2788 * defaults when Vim starts.
2789 * Adjust the SHAPE_IDX_ defines when making changes! */
2790 {0, 0, 0, 700L, 400L, 250L, 0, 0, "n", SHAPE_CURSOR+SHAPE_MOUSE},
2791 {0, 0, 0, 700L, 400L, 250L, 0, 0, "v", SHAPE_CURSOR+SHAPE_MOUSE},
2792 {0, 0, 0, 700L, 400L, 250L, 0, 0, "i", SHAPE_CURSOR+SHAPE_MOUSE},
2793 {0, 0, 0, 700L, 400L, 250L, 0, 0, "r", SHAPE_CURSOR+SHAPE_MOUSE},
2794 {0, 0, 0, 700L, 400L, 250L, 0, 0, "c", SHAPE_CURSOR+SHAPE_MOUSE},
2795 {0, 0, 0, 700L, 400L, 250L, 0, 0, "ci", SHAPE_CURSOR+SHAPE_MOUSE},
2796 {0, 0, 0, 700L, 400L, 250L, 0, 0, "cr", SHAPE_CURSOR+SHAPE_MOUSE},
2797 {0, 0, 0, 700L, 400L, 250L, 0, 0, "o", SHAPE_CURSOR+SHAPE_MOUSE},
2798 {0, 0, 0, 700L, 400L, 250L, 0, 0, "ve", SHAPE_CURSOR+SHAPE_MOUSE},
2799 {0, 0, 0, 0L, 0L, 0L, 0, 0, "e", SHAPE_MOUSE},
2800 {0, 0, 0, 0L, 0L, 0L, 0, 0, "s", SHAPE_MOUSE},
2801 {0, 0, 0, 0L, 0L, 0L, 0, 0, "sd", SHAPE_MOUSE},
2802 {0, 0, 0, 0L, 0L, 0L, 0, 0, "vs", SHAPE_MOUSE},
2803 {0, 0, 0, 0L, 0L, 0L, 0, 0, "vd", SHAPE_MOUSE},
2804 {0, 0, 0, 0L, 0L, 0L, 0, 0, "m", SHAPE_MOUSE},
2805 {0, 0, 0, 0L, 0L, 0L, 0, 0, "ml", SHAPE_MOUSE},
2806 {0, 0, 0, 100L, 100L, 100L, 0, 0, "sm", SHAPE_CURSOR},
2807};
2808
2809#ifdef FEAT_MOUSESHAPE
2810/*
2811 * Table with names for mouse shapes. Keep in sync with all the tables for
2812 * mch_set_mouse_shape()!.
2813 */
2814static char * mshape_names[] =
2815{
2816 "arrow", /* default, must be the first one */
2817 "blank", /* hidden */
2818 "beam",
2819 "updown",
2820 "udsizing",
2821 "leftright",
2822 "lrsizing",
2823 "busy",
2824 "no",
2825 "crosshair",
2826 "hand1",
2827 "hand2",
2828 "pencil",
2829 "question",
2830 "rightup-arrow",
2831 "up-arrow",
2832 NULL
2833};
2834#endif
2835
2836/*
2837 * Parse the 'guicursor' option ("what" is SHAPE_CURSOR) or 'mouseshape'
2838 * ("what" is SHAPE_MOUSE).
2839 * Returns error message for an illegal option, NULL otherwise.
2840 */
2841 char_u *
2842parse_shape_opt(what)
2843 int what;
2844{
2845 char_u *modep;
2846 char_u *colonp;
2847 char_u *commap;
2848 char_u *slashp;
2849 char_u *p, *endp;
2850 int idx = 0; /* init for GCC */
2851 int all_idx;
2852 int len;
2853 int i;
2854 long n;
2855 int found_ve = FALSE; /* found "ve" flag */
2856 int round;
2857
2858 /*
2859 * First round: check for errors; second round: do it for real.
2860 */
2861 for (round = 1; round <= 2; ++round)
2862 {
2863 /*
2864 * Repeat for all comma separated parts.
2865 */
2866#ifdef FEAT_MOUSESHAPE
2867 if (what == SHAPE_MOUSE)
2868 modep = p_mouseshape;
2869 else
2870#endif
2871 modep = p_guicursor;
2872 while (*modep != NUL)
2873 {
2874 colonp = vim_strchr(modep, ':');
2875 if (colonp == NULL)
2876 return (char_u *)N_("E545: Missing colon");
2877 if (colonp == modep)
2878 return (char_u *)N_("E546: Illegal mode");
2879 commap = vim_strchr(modep, ',');
2880
2881 /*
2882 * Repeat for all mode's before the colon.
2883 * For the 'a' mode, we loop to handle all the modes.
2884 */
2885 all_idx = -1;
2886 while (modep < colonp || all_idx >= 0)
2887 {
2888 if (all_idx < 0)
2889 {
2890 /* Find the mode. */
2891 if (modep[1] == '-' || modep[1] == ':')
2892 len = 1;
2893 else
2894 len = 2;
2895 if (len == 1 && TOLOWER_ASC(modep[0]) == 'a')
2896 all_idx = SHAPE_IDX_COUNT - 1;
2897 else
2898 {
2899 for (idx = 0; idx < SHAPE_IDX_COUNT; ++idx)
2900 if (STRNICMP(modep, shape_table[idx].name, len)
2901 == 0)
2902 break;
2903 if (idx == SHAPE_IDX_COUNT
2904 || (shape_table[idx].used_for & what) == 0)
2905 return (char_u *)N_("E546: Illegal mode");
2906 if (len == 2 && modep[0] == 'v' && modep[1] == 'e')
2907 found_ve = TRUE;
2908 }
2909 modep += len + 1;
2910 }
2911
2912 if (all_idx >= 0)
2913 idx = all_idx--;
2914 else if (round == 2)
2915 {
2916#ifdef FEAT_MOUSESHAPE
2917 if (what == SHAPE_MOUSE)
2918 {
2919 /* Set the default, for the missing parts */
2920 shape_table[idx].mshape = 0;
2921 }
2922 else
2923#endif
2924 {
2925 /* Set the defaults, for the missing parts */
2926 shape_table[idx].shape = SHAPE_BLOCK;
2927 shape_table[idx].blinkwait = 700L;
2928 shape_table[idx].blinkon = 400L;
2929 shape_table[idx].blinkoff = 250L;
2930 }
2931 }
2932
2933 /* Parse the part after the colon */
2934 for (p = colonp + 1; *p && *p != ','; )
2935 {
2936#ifdef FEAT_MOUSESHAPE
2937 if (what == SHAPE_MOUSE)
2938 {
2939 for (i = 0; ; ++i)
2940 {
2941 if (mshape_names[i] == NULL)
2942 {
2943 if (!VIM_ISDIGIT(*p))
2944 return (char_u *)N_("E547: Illegal mouseshape");
2945 if (round == 2)
2946 shape_table[idx].mshape =
2947 getdigits(&p) + MSHAPE_NUMBERED;
2948 else
2949 (void)getdigits(&p);
2950 break;
2951 }
2952 len = (int)STRLEN(mshape_names[i]);
2953 if (STRNICMP(p, mshape_names[i], len) == 0)
2954 {
2955 if (round == 2)
2956 shape_table[idx].mshape = i;
2957 p += len;
2958 break;
2959 }
2960 }
2961 }
2962 else /* if (what == SHAPE_MOUSE) */
2963#endif
2964 {
2965 /*
2966 * First handle the ones with a number argument.
2967 */
2968 i = *p;
2969 len = 0;
2970 if (STRNICMP(p, "ver", 3) == 0)
2971 len = 3;
2972 else if (STRNICMP(p, "hor", 3) == 0)
2973 len = 3;
2974 else if (STRNICMP(p, "blinkwait", 9) == 0)
2975 len = 9;
2976 else if (STRNICMP(p, "blinkon", 7) == 0)
2977 len = 7;
2978 else if (STRNICMP(p, "blinkoff", 8) == 0)
2979 len = 8;
2980 if (len != 0)
2981 {
2982 p += len;
2983 if (!VIM_ISDIGIT(*p))
2984 return (char_u *)N_("E548: digit expected");
2985 n = getdigits(&p);
2986 if (len == 3) /* "ver" or "hor" */
2987 {
2988 if (n == 0)
2989 return (char_u *)N_("E549: Illegal percentage");
2990 if (round == 2)
2991 {
2992 if (TOLOWER_ASC(i) == 'v')
2993 shape_table[idx].shape = SHAPE_VER;
2994 else
2995 shape_table[idx].shape = SHAPE_HOR;
2996 shape_table[idx].percentage = n;
2997 }
2998 }
2999 else if (round == 2)
3000 {
3001 if (len == 9)
3002 shape_table[idx].blinkwait = n;
3003 else if (len == 7)
3004 shape_table[idx].blinkon = n;
3005 else
3006 shape_table[idx].blinkoff = n;
3007 }
3008 }
3009 else if (STRNICMP(p, "block", 5) == 0)
3010 {
3011 if (round == 2)
3012 shape_table[idx].shape = SHAPE_BLOCK;
3013 p += 5;
3014 }
3015 else /* must be a highlight group name then */
3016 {
3017 endp = vim_strchr(p, '-');
3018 if (commap == NULL) /* last part */
3019 {
3020 if (endp == NULL)
3021 endp = p + STRLEN(p); /* find end of part */
3022 }
3023 else if (endp > commap || endp == NULL)
3024 endp = commap;
3025 slashp = vim_strchr(p, '/');
3026 if (slashp != NULL && slashp < endp)
3027 {
3028 /* "group/langmap_group" */
3029 i = syn_check_group(p, (int)(slashp - p));
3030 p = slashp + 1;
3031 }
3032 if (round == 2)
3033 {
3034 shape_table[idx].id = syn_check_group(p,
3035 (int)(endp - p));
3036 shape_table[idx].id_lm = shape_table[idx].id;
3037 if (slashp != NULL && slashp < endp)
3038 shape_table[idx].id = i;
3039 }
3040 p = endp;
3041 }
3042 } /* if (what != SHAPE_MOUSE) */
3043
3044 if (*p == '-')
3045 ++p;
3046 }
3047 }
3048 modep = p;
3049 if (*modep == ',')
3050 ++modep;
3051 }
3052 }
3053
3054 /* If the 's' flag is not given, use the 'v' cursor for 's' */
3055 if (!found_ve)
3056 {
3057#ifdef FEAT_MOUSESHAPE
3058 if (what == SHAPE_MOUSE)
3059 {
3060 shape_table[SHAPE_IDX_VE].mshape = shape_table[SHAPE_IDX_V].mshape;
3061 }
3062 else
3063#endif
3064 {
3065 shape_table[SHAPE_IDX_VE].shape = shape_table[SHAPE_IDX_V].shape;
3066 shape_table[SHAPE_IDX_VE].percentage =
3067 shape_table[SHAPE_IDX_V].percentage;
3068 shape_table[SHAPE_IDX_VE].blinkwait =
3069 shape_table[SHAPE_IDX_V].blinkwait;
3070 shape_table[SHAPE_IDX_VE].blinkon =
3071 shape_table[SHAPE_IDX_V].blinkon;
3072 shape_table[SHAPE_IDX_VE].blinkoff =
3073 shape_table[SHAPE_IDX_V].blinkoff;
3074 shape_table[SHAPE_IDX_VE].id = shape_table[SHAPE_IDX_V].id;
3075 shape_table[SHAPE_IDX_VE].id_lm = shape_table[SHAPE_IDX_V].id_lm;
3076 }
3077 }
3078
3079 return NULL;
3080}
3081
3082/*
3083 * Return the index into shape_table[] for the current mode.
3084 * When "mouse" is TRUE, consider indexes valid for the mouse pointer.
3085 */
3086 int
3087get_shape_idx(mouse)
3088 int mouse;
3089{
3090#ifdef FEAT_MOUSESHAPE
3091 if (mouse && (State == HITRETURN || State == ASKMORE))
3092 {
3093# ifdef FEAT_GUI
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00003094 int x, y;
3095 gui_mch_getmouse(&x, &y);
3096 if (Y_2_ROW(y) == Rows - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003097 return SHAPE_IDX_MOREL;
3098# endif
3099 return SHAPE_IDX_MORE;
3100 }
3101 if (mouse && drag_status_line)
3102 return SHAPE_IDX_SDRAG;
3103# ifdef FEAT_VERTSPLIT
3104 if (mouse && drag_sep_line)
3105 return SHAPE_IDX_VDRAG;
3106# endif
3107#endif
3108 if (!mouse && State == SHOWMATCH)
3109 return SHAPE_IDX_SM;
3110#ifdef FEAT_VREPLACE
3111 if (State & VREPLACE_FLAG)
3112 return SHAPE_IDX_R;
3113#endif
3114 if (State & REPLACE_FLAG)
3115 return SHAPE_IDX_R;
3116 if (State & INSERT)
3117 return SHAPE_IDX_I;
3118 if (State & CMDLINE)
3119 {
3120 if (cmdline_at_end())
3121 return SHAPE_IDX_C;
3122 if (cmdline_overstrike())
3123 return SHAPE_IDX_CR;
3124 return SHAPE_IDX_CI;
3125 }
3126 if (finish_op)
3127 return SHAPE_IDX_O;
3128#ifdef FEAT_VISUAL
3129 if (VIsual_active)
3130 {
3131 if (*p_sel == 'e')
3132 return SHAPE_IDX_VE;
3133 else
3134 return SHAPE_IDX_V;
3135 }
3136#endif
3137 return SHAPE_IDX_N;
3138}
3139
3140# if defined(FEAT_MOUSESHAPE) || defined(PROTO)
3141static int old_mouse_shape = 0;
3142
3143/*
3144 * Set the mouse shape:
3145 * If "shape" is -1, use shape depending on the current mode,
3146 * depending on the current state.
3147 * If "shape" is -2, only update the shape when it's CLINE or STATUS (used
3148 * when the mouse moves off the status or command line).
3149 */
3150 void
3151update_mouseshape(shape_idx)
3152 int shape_idx;
3153{
3154 int new_mouse_shape;
3155
3156 /* Only works in GUI mode. */
Bram Moolenaar6bb68362005-03-22 23:03:44 +00003157 if (!gui.in_use || gui.starting)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003158 return;
3159
3160 /* Postpone the updating when more is to come. Speeds up executing of
3161 * mappings. */
3162 if (shape_idx == -1 && char_avail())
3163 {
3164 postponed_mouseshape = TRUE;
3165 return;
3166 }
3167
3168 if (shape_idx == -2
3169 && old_mouse_shape != shape_table[SHAPE_IDX_CLINE].mshape
3170 && old_mouse_shape != shape_table[SHAPE_IDX_STATUS].mshape
3171 && old_mouse_shape != shape_table[SHAPE_IDX_VSEP].mshape)
3172 return;
3173 if (shape_idx < 0)
3174 new_mouse_shape = shape_table[get_shape_idx(TRUE)].mshape;
3175 else
3176 new_mouse_shape = shape_table[shape_idx].mshape;
3177 if (new_mouse_shape != old_mouse_shape)
3178 {
3179 mch_set_mouse_shape(new_mouse_shape);
3180 old_mouse_shape = new_mouse_shape;
3181 }
3182 postponed_mouseshape = FALSE;
3183}
3184# endif
3185
3186#endif /* CURSOR_SHAPE */
3187
3188
3189#ifdef FEAT_CRYPT
3190/*
3191 * Optional encryption suypport.
3192 * Mohsin Ahmed, mosh@sasi.com, 98-09-24
3193 * Based on zip/crypt sources.
3194 *
3195 * NOTE FOR USA: Since 2000 exporting this code from the USA is allowed to
3196 * most countries. There are a few exceptions, but that still should not be a
3197 * problem since this code was originally created in Europe and India.
3198 */
3199
3200/* from zip.h */
3201
3202typedef unsigned short ush; /* unsigned 16-bit value */
3203typedef unsigned long ulg; /* unsigned 32-bit value */
3204
3205static void make_crc_tab __ARGS((void));
3206
3207ulg crc_32_tab[256];
3208
3209/*
3210 * Fill the CRC table.
3211 */
3212 static void
3213make_crc_tab()
3214{
3215 ulg s,t,v;
3216 static int done = FALSE;
3217
3218 if (done)
3219 return;
3220 for (t = 0; t < 256; t++)
3221 {
3222 v = t;
3223 for (s = 0; s < 8; s++)
3224 v = (v >> 1) ^ ((v & 1) * (ulg)0xedb88320L);
3225 crc_32_tab[t] = v;
3226 }
3227 done = TRUE;
3228}
3229
3230#define CRC32(c, b) (crc_32_tab[((int)(c) ^ (b)) & 0xff] ^ ((c) >> 8))
3231
3232
3233static ulg keys[3]; /* keys defining the pseudo-random sequence */
3234
3235/*
3236 * Return the next byte in the pseudo-random sequence
3237 */
3238 int
3239decrypt_byte()
3240{
3241 ush temp;
3242
3243 temp = (ush)keys[2] | 2;
3244 return (int)(((unsigned)(temp * (temp ^ 1)) >> 8) & 0xff);
3245}
3246
3247/*
3248 * Update the encryption keys with the next byte of plain text
3249 */
3250 int
3251update_keys(c)
3252 int c; /* byte of plain text */
3253{
3254 keys[0] = CRC32(keys[0], c);
3255 keys[1] += keys[0] & 0xff;
3256 keys[1] = keys[1] * 134775813L + 1;
3257 keys[2] = CRC32(keys[2], (int)(keys[1] >> 24));
3258 return c;
3259}
3260
3261/*
3262 * Initialize the encryption keys and the random header according to
3263 * the given password.
3264 * If "passwd" is NULL or empty, don't do anything.
3265 */
3266 void
3267crypt_init_keys(passwd)
3268 char_u *passwd; /* password string with which to modify keys */
3269{
3270 if (passwd != NULL && *passwd != NUL)
3271 {
3272 make_crc_tab();
3273 keys[0] = 305419896L;
3274 keys[1] = 591751049L;
3275 keys[2] = 878082192L;
3276 while (*passwd != '\0')
3277 update_keys((int)*passwd++);
3278 }
3279}
3280
3281/*
3282 * Ask the user for a crypt key.
3283 * When "store" is TRUE, the new key in stored in the 'key' option, and the
3284 * 'key' option value is returned: Don't free it.
3285 * When "store" is FALSE, the typed key is returned in allocated memory.
3286 * Returns NULL on failure.
3287 */
3288 char_u *
3289get_crypt_key(store, twice)
3290 int store;
3291 int twice; /* Ask for the key twice. */
3292{
3293 char_u *p1, *p2 = NULL;
3294 int round;
3295
3296 for (round = 0; ; ++round)
3297 {
3298 cmdline_star = TRUE;
3299 cmdline_row = msg_row;
3300 p1 = getcmdline_prompt(NUL, round == 0
3301 ? (char_u *)_("Enter encryption key: ")
3302 : (char_u *)_("Enter same key again: "), 0);
3303 cmdline_star = FALSE;
3304
3305 if (p1 == NULL)
3306 break;
3307
3308 if (round == twice)
3309 {
3310 if (p2 != NULL && STRCMP(p1, p2) != 0)
3311 {
3312 MSG(_("Keys don't match!"));
3313 vim_free(p1);
3314 vim_free(p2);
3315 p2 = NULL;
3316 round = -1; /* do it again */
3317 continue;
3318 }
3319 if (store)
3320 {
3321 set_option_value((char_u *)"key", 0L, p1, OPT_LOCAL);
3322 vim_free(p1);
3323 p1 = curbuf->b_p_key;
3324 }
3325 break;
3326 }
3327 p2 = p1;
3328 }
3329
3330 /* since the user typed this, no need to wait for return */
3331 need_wait_return = FALSE;
3332 msg_didout = FALSE;
3333
3334 vim_free(p2);
3335 return p1;
3336}
3337
3338#endif /* FEAT_CRYPT */
3339
3340/* TODO: make some #ifdef for this */
3341/*--------[ file searching ]-------------------------------------------------*/
3342/*
3343 * File searching functions for 'path', 'tags' and 'cdpath' options.
3344 * External visible functions:
3345 * vim_findfile_init() creates/initialises the search context
3346 * vim_findfile_free_visited() free list of visited files/dirs of search
3347 * context
3348 * vim_findfile() find a file in the search context
3349 * vim_findfile_cleanup() cleanup/free search context created by
3350 * vim_findfile_init()
3351 *
3352 * All static functions and variables start with 'ff_'
3353 *
3354 * In general it works like this:
3355 * First you create yourself a search context by calling vim_findfile_init().
3356 * It is possible to give a search context from a previous call to
3357 * vim_findfile_init(), so it can be reused. After this you call vim_findfile()
3358 * until you are satisfied with the result or it returns NULL. On every call it
3359 * returns the next file which matches the conditions given to
3360 * vim_findfile_init(). If it doesn't find a next file it returns NULL.
3361 *
3362 * It is possible to call vim_findfile_init() again to reinitialise your search
3363 * with some new parameters. Don't forget to pass your old search context to
3364 * it, so it can reuse it and especially reuse the list of already visited
3365 * directories. If you want to delete the list of already visited directories
3366 * simply call vim_findfile_free_visited().
3367 *
3368 * When you are done call vim_findfile_cleanup() to free the search context.
3369 *
3370 * The function vim_findfile_init() has a long comment, which describes the
3371 * needed parameters.
3372 *
3373 *
3374 *
3375 * ATTENTION:
3376 * ==========
3377 * Also we use an allocated search context here, this functions ARE NOT
3378 * thread-safe!!!!!
3379 *
3380 * To minimize parameter passing (or because I'm to lazy), only the
3381 * external visible functions get a search context as a parameter. This is
3382 * then assigned to a static global, which is used throughout the local
3383 * functions.
3384 */
3385
3386/*
3387 * type for the directory search stack
3388 */
3389typedef struct ff_stack
3390{
3391 struct ff_stack *ffs_prev;
3392
3393 /* the fix part (no wildcards) and the part containing the wildcards
3394 * of the search path
3395 */
3396 char_u *ffs_fix_path;
3397#ifdef FEAT_PATH_EXTRA
3398 char_u *ffs_wc_path;
3399#endif
3400
3401 /* files/dirs found in the above directory, matched by the first wildcard
3402 * of wc_part
3403 */
3404 char_u **ffs_filearray;
3405 int ffs_filearray_size;
3406 char_u ffs_filearray_cur; /* needed for partly handled dirs */
3407
3408 /* to store status of partly handled directories
3409 * 0: we work the on this directory for the first time
3410 * 1: this directory was partly searched in an earlier step
3411 */
3412 int ffs_stage;
3413
3414 /* How deep are we in the directory tree?
3415 * Counts backward from value of level parameter to vim_findfile_init
3416 */
3417 int ffs_level;
3418
3419 /* Did we already expand '**' to an empty string? */
3420 int ffs_star_star_empty;
3421} ff_stack_T;
3422
3423/*
3424 * type for already visited directories or files.
3425 */
3426typedef struct ff_visited
3427{
3428 struct ff_visited *ffv_next;
3429
3430#ifdef FEAT_PATH_EXTRA
3431 /* Visited directories are different if the wildcard string are
3432 * different. So we have to save it.
3433 */
3434 char_u *ffv_wc_path;
3435#endif
3436 /* for unix use inode etc for comparison (needed because of links), else
3437 * use filename.
3438 */
3439#ifdef UNIX
3440 int ffv_dev; /* device number (-1 if not set) */
3441 ino_t ffv_ino; /* inode number */
3442#endif
3443 /* The memory for this struct is allocated according to the length of
3444 * ffv_fname.
3445 */
3446 char_u ffv_fname[1]; /* actually longer */
3447} ff_visited_T;
3448
3449/*
3450 * We might have to manage several visited lists during a search.
3451 * This is expecially needed for the tags option. If tags is set to:
3452 * "./++/tags,./++/TAGS,++/tags" (replace + with *)
3453 * So we have to do 3 searches:
3454 * 1) search from the current files directory downward for the file "tags"
3455 * 2) search from the current files directory downward for the file "TAGS"
3456 * 3) search from Vims current directory downwards for the file "tags"
3457 * As you can see, the first and the third search are for the same file, so for
3458 * the third search we can use the visited list of the first search. For the
3459 * second search we must start from a empty visited list.
3460 * The struct ff_visited_list_hdr is used to manage a linked list of already
3461 * visited lists.
3462 */
3463typedef struct ff_visited_list_hdr
3464{
3465 struct ff_visited_list_hdr *ffvl_next;
3466
3467 /* the filename the attached visited list is for */
3468 char_u *ffvl_filename;
3469
3470 ff_visited_T *ffvl_visited_list;
3471
3472} ff_visited_list_hdr_T;
3473
3474
3475/*
3476 * '**' can be expanded to several directory levels.
3477 * Set the default maximium depth.
3478 */
3479#define FF_MAX_STAR_STAR_EXPAND ((char_u)30)
3480/*
3481 * The search context:
3482 * ffsc_stack_ptr: the stack for the dirs to search
3483 * ffsc_visited_list: the currently active visited list
3484 * ffsc_dir_visited_list: the currently active visited list for search dirs
3485 * ffsc_visited_lists_list: the list of all visited lists
3486 * ffsc_dir_visited_lists_list: the list of all visited lists for search dirs
3487 * ffsc_file_to_search: the file to search for
3488 * ffsc_start_dir: the starting directory, if search path was relative
3489 * ffsc_fix_path: the fix part of the given path (without wildcards)
3490 * Needed for upward search.
3491 * ffsc_wc_path: the part of the given path containing wildcards
3492 * ffsc_level: how many levels of dirs to search downwards
3493 * ffsc_stopdirs_v: array of stop directories for upward search
3494 * ffsc_need_dir: TRUE if we search for a directory
3495 */
3496typedef struct ff_search_ctx_T
3497{
3498 ff_stack_T *ffsc_stack_ptr;
3499 ff_visited_list_hdr_T *ffsc_visited_list;
3500 ff_visited_list_hdr_T *ffsc_dir_visited_list;
3501 ff_visited_list_hdr_T *ffsc_visited_lists_list;
3502 ff_visited_list_hdr_T *ffsc_dir_visited_lists_list;
3503 char_u *ffsc_file_to_search;
3504 char_u *ffsc_start_dir;
3505 char_u *ffsc_fix_path;
3506#ifdef FEAT_PATH_EXTRA
3507 char_u *ffsc_wc_path;
3508 int ffsc_level;
3509 char_u **ffsc_stopdirs_v;
3510#endif
3511 int ffsc_need_dir;
3512}ff_search_ctx_T;
3513static ff_search_ctx_T *ff_search_ctx = NULL;
3514
3515/* used for expanding filenames */
3516static char_u *ff_expand_buffer = NULL;
3517
3518/* locally needed functions */
3519#ifdef FEAT_PATH_EXTRA
3520static int ff_check_visited __ARGS((ff_visited_T **, char_u *, char_u *));
3521#else
3522static int ff_check_visited __ARGS((ff_visited_T **, char_u *));
3523#endif
3524static void vim_findfile_free_visited_list __ARGS((ff_visited_list_hdr_T **list_headp));
3525static void ff_free_visited_list __ARGS((ff_visited_T *vl));
3526static ff_visited_list_hdr_T* ff_get_visited_list __ARGS((char_u *, ff_visited_list_hdr_T **list_headp));
3527#ifdef FEAT_PATH_EXTRA
3528static int ff_wc_equal __ARGS((char_u *s1, char_u *s2));
3529#endif
3530
3531static void ff_push __ARGS((ff_stack_T *));
3532static ff_stack_T * ff_pop __ARGS((void));
3533static void ff_clear __ARGS((void));
3534static void ff_free_stack_element __ARGS((ff_stack_T *));
3535#ifdef FEAT_PATH_EXTRA
3536static ff_stack_T *ff_create_stack_element __ARGS((char_u *, char_u *, int, int));
3537#else
3538static ff_stack_T *ff_create_stack_element __ARGS((char_u *, int, int));
3539#endif
3540#ifdef FEAT_PATH_EXTRA
3541static int ff_path_in_stoplist __ARGS((char_u *, int, char_u **));
3542#endif
3543
Bram Moolenaar071d4272004-06-13 20:20:40 +00003544#if 0
3545/*
3546 * if someone likes findfirst/findnext, here are the functions
3547 * NOT TESTED!!
3548 */
3549
3550static void *ff_fn_search_context = NULL;
3551
3552 char_u *
3553vim_findfirst(path, filename, level)
3554 char_u *path;
3555 char_u *filename;
3556 int level;
3557{
3558 ff_fn_search_context =
3559 vim_findfile_init(path, filename, NULL, level, TRUE, FALSE,
3560 ff_fn_search_context, rel_fname);
3561 if (NULL == ff_fn_search_context)
3562 return NULL;
3563 else
3564 return vim_findnext()
3565}
3566
3567 char_u *
3568vim_findnext()
3569{
3570 char_u *ret = vim_findfile(ff_fn_search_context);
3571
3572 if (NULL == ret)
3573 {
3574 vim_findfile_cleanup(ff_fn_search_context);
3575 ff_fn_search_context = NULL;
3576 }
3577 return ret;
3578}
3579#endif
3580
3581/*
3582 * Initialization routine for vim_findfile.
3583 *
3584 * Returns the newly allocated search context or NULL if an error occured.
3585 *
3586 * Don't forget to clean up by calling vim_findfile_cleanup() if you are done
3587 * with the search context.
3588 *
3589 * Find the file 'filename' in the directory 'path'.
3590 * The parameter 'path' may contain wildcards. If so only search 'level'
3591 * directories deep. The parameter 'level' is the absolute maximum and is
3592 * not related to restricts given to the '**' wildcard. If 'level' is 100
3593 * and you use '**200' vim_findfile() will stop after 100 levels.
3594 *
3595 * If 'stopdirs' is not NULL and nothing is found downward, the search is
3596 * restarted on the next higher directory level. This is repeated until the
3597 * start-directory of a search is contained in 'stopdirs'. 'stopdirs' has the
3598 * format ";*<dirname>*\(;<dirname>\)*;\=$".
3599 *
3600 * If the 'path' is relative, the starting dir for the search is either VIM's
3601 * current dir or if the path starts with "./" the current files dir.
3602 * If the 'path' is absolut, the starting dir is that part of the path before
3603 * the first wildcard.
3604 *
3605 * Upward search is only done on the starting dir.
3606 *
3607 * If 'free_visited' is TRUE the list of already visited files/directories is
3608 * cleared. Set this to FALSE if you just want to search from another
3609 * directory, but want to be sure that no directory from a previous search is
3610 * searched again. This is useful if you search for a file at different places.
3611 * The list of visited files/dirs can also be cleared with the function
3612 * vim_findfile_free_visited().
3613 *
3614 * Set the parameter 'need_dir' to TRUE if you want to search for a directory
3615 * instead of a file.
3616 *
3617 * A search context returned by a previous call to vim_findfile_init() can be
3618 * passed in the parameter 'search_ctx'. This context is than reused and
3619 * reinitialized with the new parameters. The list of already viseted
3620 * directories from this context is only deleted if the parameter
3621 * 'free_visited' is true. Be aware that the passed search_context is freed if
3622 * the reinitialization fails.
3623 *
3624 * If you don't have a search context from a previous call 'search_ctx' must be
3625 * NULL.
3626 *
3627 * This function silently ignores a few errors, vim_findfile() will have
3628 * limited functionality then.
3629 */
3630/*ARGSUSED*/
3631 void *
3632vim_findfile_init(path, filename, stopdirs, level, free_visited, need_dir,
3633 search_ctx, tagfile, rel_fname)
3634 char_u *path;
3635 char_u *filename;
3636 char_u *stopdirs;
3637 int level;
3638 int free_visited;
3639 int need_dir;
3640 void *search_ctx;
3641 int tagfile;
3642 char_u *rel_fname; /* file name to use for "." */
3643{
3644#ifdef FEAT_PATH_EXTRA
3645 char_u *wc_part;
3646#endif
3647 ff_stack_T *sptr;
3648
3649 /* If a search context is given by the caller, reuse it, else allocate a
3650 * new one.
3651 */
3652 if (search_ctx != NULL)
3653 ff_search_ctx = search_ctx;
3654 else
3655 {
3656 ff_search_ctx = (ff_search_ctx_T*)alloc(
3657 (unsigned)sizeof(ff_search_ctx_T));
3658 if (ff_search_ctx == NULL)
3659 goto error_return;
3660 memset(ff_search_ctx, 0, sizeof(ff_search_ctx_T));
3661 }
3662
3663 /* clear the search context, but NOT the visited lists */
3664 ff_clear();
3665
3666 /* clear visited list if wanted */
3667 if (free_visited == TRUE)
3668 vim_findfile_free_visited(ff_search_ctx);
3669 else
3670 {
3671 /* Reuse old visited lists. Get the visited list for the given
3672 * filename. If no list for the current filename exists, creates a new
3673 * one.
3674 */
3675 ff_search_ctx->ffsc_visited_list = ff_get_visited_list(filename,
3676 &ff_search_ctx->ffsc_visited_lists_list);
3677 if (ff_search_ctx->ffsc_visited_list == NULL)
3678 goto error_return;
3679 ff_search_ctx->ffsc_dir_visited_list = ff_get_visited_list(filename,
3680 &ff_search_ctx->ffsc_dir_visited_lists_list);
3681 if (ff_search_ctx->ffsc_dir_visited_list == NULL)
3682 goto error_return;
3683 }
3684
3685 if (ff_expand_buffer == NULL)
3686 {
3687 ff_expand_buffer = (char_u*)alloc(MAXPATHL);
3688 if (ff_expand_buffer == NULL)
3689 goto error_return;
3690 }
3691
3692 /* Store information on starting dir now if path is relative.
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00003693 * If path is absolute, we do that later. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003694 if (path[0] == '.'
3695 && (vim_ispathsep(path[1]) || path[1] == NUL)
3696 && (!tagfile || vim_strchr(p_cpo, CPO_DOTTAG) == NULL)
3697 && rel_fname != NULL)
3698 {
3699 int len = (int)(gettail(rel_fname) - rel_fname);
3700
3701 if (!vim_isAbsName(rel_fname) && len + 1 < MAXPATHL)
3702 {
3703 /* Make the start dir an absolute path name. */
3704 STRNCPY(ff_expand_buffer, rel_fname, len);
3705 ff_expand_buffer[len] = NUL;
3706 ff_search_ctx->ffsc_start_dir = FullName_save(ff_expand_buffer,
3707 FALSE);
3708 }
3709 else
3710 ff_search_ctx->ffsc_start_dir = vim_strnsave(rel_fname, len);
3711 if (ff_search_ctx->ffsc_start_dir == NULL)
3712 goto error_return;
3713 if (*++path != NUL)
3714 ++path;
3715 }
3716 else if (*path == NUL || !vim_isAbsName(path))
3717 {
3718#ifdef BACKSLASH_IN_FILENAME
3719 /* "c:dir" needs "c:" to be expanded, otherwise use current dir */
3720 if (*path != NUL && path[1] == ':')
3721 {
3722 char_u drive[3];
3723
3724 drive[0] = path[0];
3725 drive[1] = ':';
3726 drive[2] = NUL;
3727 if (vim_FullName(drive, ff_expand_buffer, MAXPATHL, TRUE) == FAIL)
3728 goto error_return;
3729 path += 2;
3730 }
3731 else
3732#endif
3733 if (mch_dirname(ff_expand_buffer, MAXPATHL) == FAIL)
3734 goto error_return;
3735
3736 ff_search_ctx->ffsc_start_dir = vim_strsave(ff_expand_buffer);
3737 if (ff_search_ctx->ffsc_start_dir == NULL)
3738 goto error_return;
3739
3740#ifdef BACKSLASH_IN_FILENAME
3741 /* A path that starts with "/dir" is relative to the drive, not to the
3742 * directory (but not for "//machine/dir"). Only use the drive name. */
3743 if ((*path == '/' || *path == '\\')
3744 && path[1] != path[0]
3745 && ff_search_ctx->ffsc_start_dir[1] == ':')
3746 ff_search_ctx->ffsc_start_dir[2] = NUL;
3747#endif
3748 }
3749
3750#ifdef FEAT_PATH_EXTRA
3751 /*
3752 * If stopdirs are given, split them into an array of pointers.
3753 * If this fails (mem allocation), there is no upward search at all or a
3754 * stop directory is not recognized -> continue silently.
3755 * If stopdirs just contains a ";" or is empty,
3756 * ff_search_ctx->ffsc_stopdirs_v will only contain a NULL pointer. This
3757 * is handled as unlimited upward search. See function
3758 * ff_path_in_stoplist() for details.
3759 */
3760 if (stopdirs != NULL)
3761 {
3762 char_u *walker = stopdirs;
3763 int dircount;
3764
3765 while (*walker == ';')
3766 walker++;
3767
3768 dircount = 1;
3769 ff_search_ctx->ffsc_stopdirs_v =
3770 (char_u **)alloc((unsigned)sizeof(char_u *));
3771
3772 if (ff_search_ctx->ffsc_stopdirs_v != NULL)
3773 {
3774 do
3775 {
3776 char_u *helper;
3777 void *ptr;
3778
3779 helper = walker;
3780 ptr = vim_realloc(ff_search_ctx->ffsc_stopdirs_v,
3781 (dircount + 1) * sizeof(char_u *));
3782 if (ptr)
3783 ff_search_ctx->ffsc_stopdirs_v = ptr;
3784 else
3785 /* ignore, keep what we have and continue */
3786 break;
3787 walker = vim_strchr(walker, ';');
3788 if (walker)
3789 {
3790 ff_search_ctx->ffsc_stopdirs_v[dircount-1] =
3791 vim_strnsave(helper, (int)(walker - helper));
3792 walker++;
3793 }
3794 else
3795 /* this might be "", which means ascent till top
3796 * of directory tree.
3797 */
3798 ff_search_ctx->ffsc_stopdirs_v[dircount-1] =
3799 vim_strsave(helper);
3800
3801 dircount++;
3802
3803 } while (walker != NULL);
3804 ff_search_ctx->ffsc_stopdirs_v[dircount-1] = NULL;
3805 }
3806 }
3807#endif
3808
3809#ifdef FEAT_PATH_EXTRA
3810 ff_search_ctx->ffsc_level = level;
3811
3812 /* split into:
3813 * -fix path
3814 * -wildcard_stuff (might be NULL)
3815 */
3816 wc_part = vim_strchr(path, '*');
3817 if (wc_part != NULL)
3818 {
3819 int llevel;
3820 int len;
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00003821 char *errpt;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003822
3823 /* save the fix part of the path */
3824 ff_search_ctx->ffsc_fix_path = vim_strnsave(path,
3825 (int)(wc_part - path));
3826
3827 /*
3828 * copy wc_path and add restricts to the '**' wildcard.
3829 * The octett after a '**' is used as a (binary) counter.
3830 * So '**3' is transposed to '**^C' ('^C' is ASCII value 3)
3831 * or '**76' is transposed to '**N'( 'N' is ASCII value 76).
3832 * For EBCDIC you get different character values.
3833 * If no restrict is given after '**' the default is used.
3834 * Due to this technic the path looks awful if you print it as a
3835 * string.
3836 */
3837 len = 0;
3838 while (*wc_part != NUL)
3839 {
3840 if (STRNCMP(wc_part, "**", 2) == 0)
3841 {
3842 ff_expand_buffer[len++] = *wc_part++;
3843 ff_expand_buffer[len++] = *wc_part++;
3844
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00003845 llevel = strtol((char *)wc_part, &errpt, 10);
3846 if ((char_u *)errpt != wc_part && llevel > 0 && llevel < 255)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003847 ff_expand_buffer[len++] = llevel;
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00003848 else if ((char_u *)errpt != wc_part && llevel == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003849 /* restrict is 0 -> remove already added '**' */
3850 len -= 2;
3851 else
3852 ff_expand_buffer[len++] = FF_MAX_STAR_STAR_EXPAND;
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00003853 wc_part = (char_u *)errpt;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003854 if (*wc_part != PATHSEP && *wc_part != NUL)
3855 {
3856 EMSG2(_("E343: Invalid path: '**[number]' must be at the end of the path or be followed by '%s'."), PATHSEPSTR);
3857 goto error_return;
3858 }
3859 }
3860 else
3861 ff_expand_buffer[len++] = *wc_part++;
3862 }
3863 ff_expand_buffer[len] = NUL;
3864 ff_search_ctx->ffsc_wc_path =
3865 vim_strsave(ff_expand_buffer);
3866
3867 if (ff_search_ctx->ffsc_wc_path == NULL)
3868 goto error_return;
3869 }
3870 else
3871#endif
3872 ff_search_ctx->ffsc_fix_path = vim_strsave(path);
3873
3874 if (ff_search_ctx->ffsc_start_dir == NULL)
3875 {
3876 /* store the fix part as startdir.
3877 * This is needed if the parameter path is fully qualified.
3878 */
3879 ff_search_ctx->ffsc_start_dir = vim_strsave(ff_search_ctx->ffsc_fix_path);
3880 if (ff_search_ctx->ffsc_start_dir)
3881 ff_search_ctx->ffsc_fix_path[0] = NUL;
3882 }
3883
3884 /* create an absolute path */
3885 STRCPY(ff_expand_buffer, ff_search_ctx->ffsc_start_dir);
3886 add_pathsep(ff_expand_buffer);
3887 STRCAT(ff_expand_buffer, ff_search_ctx->ffsc_fix_path);
3888 add_pathsep(ff_expand_buffer);
3889
3890 sptr = ff_create_stack_element(ff_expand_buffer,
3891#ifdef FEAT_PATH_EXTRA
3892 ff_search_ctx->ffsc_wc_path,
3893#endif
3894 level, 0);
3895
3896 if (sptr == NULL)
3897 goto error_return;
3898
3899 ff_push(sptr);
3900
3901 ff_search_ctx->ffsc_file_to_search = vim_strsave(filename);
3902 if (ff_search_ctx->ffsc_file_to_search == NULL)
3903 goto error_return;
3904
3905 return ff_search_ctx;
3906
3907error_return:
3908 /*
3909 * We clear the search context now!
3910 * Even when the caller gave us a (perhaps valid) context we free it here,
3911 * as we might have already destroyed it.
3912 */
3913 vim_findfile_cleanup(ff_search_ctx);
3914 return NULL;
3915}
3916
3917#if defined(FEAT_PATH_EXTRA) || defined(PROTO)
3918/*
3919 * Get the stopdir string. Check that ';' is not escaped.
3920 */
3921 char_u *
3922vim_findfile_stopdir(buf)
3923 char_u *buf;
3924{
3925 char_u *r_ptr = buf;
3926
3927 while (*r_ptr != NUL && *r_ptr != ';')
3928 {
3929 if (r_ptr[0] == '\\' && r_ptr[1] == ';')
3930 {
3931 /* overwrite the escape char,
3932 * use STRLEN(r_ptr) to move the trailing '\0'
3933 */
3934 mch_memmove(r_ptr, r_ptr + 1, STRLEN(r_ptr));
3935 r_ptr++;
3936 }
3937 r_ptr++;
3938 }
3939 if (*r_ptr == ';')
3940 {
3941 *r_ptr = 0;
3942 r_ptr++;
3943 }
3944 else if (*r_ptr == NUL)
3945 r_ptr = NULL;
3946 return r_ptr;
3947}
3948#endif
3949
3950/* Clean up the given search context. Can handle a NULL pointer */
3951 void
3952vim_findfile_cleanup(ctx)
3953 void *ctx;
3954{
3955 if (NULL == ctx)
3956 return;
3957
3958 ff_search_ctx = ctx;
3959
3960 vim_findfile_free_visited(ctx);
3961 ff_clear();
3962 vim_free(ctx);
3963 ff_search_ctx = NULL;
3964}
3965
3966/*
3967 * Find a file in a search context.
3968 * The search context was created with vim_findfile_init() above.
3969 * Return a pointer to an allocated file name or NULL if nothing found.
3970 * To get all matching files call this function until you get NULL.
3971 *
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00003972 * If the passed search_context is NULL, NULL is returned.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003973 *
3974 * The search algorithm is depth first. To change this replace the
3975 * stack with a list (don't forget to leave partly searched directories on the
3976 * top of the list).
3977 */
3978 char_u *
3979vim_findfile(search_ctx)
3980 void *search_ctx;
3981{
3982 char_u *file_path;
3983#ifdef FEAT_PATH_EXTRA
3984 char_u *rest_of_wildcards;
3985 char_u *path_end = NULL;
3986#endif
3987 ff_stack_T *ctx;
3988#if defined(FEAT_SEARCHPATH) || defined(FEAT_PATH_EXTRA)
3989 int len;
3990#endif
3991 int i;
3992 char_u *p;
3993#ifdef FEAT_SEARCHPATH
3994 char_u *suf;
3995#endif
3996
3997 if (search_ctx == NULL)
3998 return NULL;
3999
4000 ff_search_ctx = (ff_search_ctx_T*)search_ctx;
4001
4002 /*
4003 * filepath is used as buffer for various actions and as the storage to
4004 * return a found filename.
4005 */
4006 if ((file_path = alloc((int)MAXPATHL)) == NULL)
4007 return NULL;
4008
4009#ifdef FEAT_PATH_EXTRA
4010 /* store the end of the start dir -- needed for upward search */
4011 if (ff_search_ctx->ffsc_start_dir != NULL)
4012 path_end = &ff_search_ctx->ffsc_start_dir[STRLEN(ff_search_ctx->ffsc_start_dir)];
4013#endif
4014
4015#ifdef FEAT_PATH_EXTRA
4016 /* upward search loop */
4017 for (;;)
4018 {
4019#endif
4020 /* downward search loop */
4021 for (;;)
4022 {
4023 /* check if user user wants to stop the search*/
4024 ui_breakcheck();
4025 if (got_int)
4026 break;
4027
4028 /* get directory to work on from stack */
4029 ctx = ff_pop();
4030 if (ctx == NULL)
4031 break;
4032
4033 /*
4034 * TODO: decide if we leave this test in
4035 *
4036 * GOOD: don't search a directory(-tree) twice.
4037 * BAD: - check linked list for every new directory entered.
4038 * - check for double files also done below
4039 *
4040 * Here we check if we already searched this directory.
4041 * We already searched a directory if:
4042 * 1) The directory is the same.
4043 * 2) We would use the same wildcard string.
4044 *
4045 * Good if you have links on same directory via several ways
4046 * or you have selfreferences in directories (e.g. SuSE Linux 6.3:
4047 * /etc/rc.d/init.d is linked to /etc/rc.d -> endless loop)
4048 *
4049 * This check is only needed for directories we work on for the
4050 * first time (hence ctx->ff_filearray == NULL)
4051 */
4052 if (ctx->ffs_filearray == NULL
4053 && ff_check_visited(&ff_search_ctx->ffsc_dir_visited_list
4054 ->ffvl_visited_list,
4055 ctx->ffs_fix_path
4056#ifdef FEAT_PATH_EXTRA
4057 , ctx->ffs_wc_path
4058#endif
4059 ) == FAIL)
4060 {
4061#ifdef FF_VERBOSE
4062 if (p_verbose >= 5)
4063 {
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004064 verbose_enter_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004065 smsg((char_u *)"Already Searched: %s (%s)",
4066 ctx->ffs_fix_path, ctx->ffs_wc_path);
4067 /* don't overwrite this either */
4068 msg_puts((char_u *)"\n");
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004069 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004070 }
4071#endif
4072 ff_free_stack_element(ctx);
4073 continue;
4074 }
4075#ifdef FF_VERBOSE
4076 else if (p_verbose >= 5)
4077 {
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004078 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00004079 smsg((char_u *)"Searching: %s (%s)",
4080 ctx->ffs_fix_path, ctx->ffs_wc_path);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004081 /* don't overwrite this either */
4082 msg_puts((char_u *)"\n");
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004083 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004084 }
4085#endif
4086
4087 /* check depth */
4088 if (ctx->ffs_level <= 0)
4089 {
4090 ff_free_stack_element(ctx);
4091 continue;
4092 }
4093
4094 file_path[0] = NUL;
4095
4096 /*
4097 * If no filearray till now expand wildcards
4098 * The function expand_wildcards() can handle an array of paths
4099 * and all possible expands are returned in one array. We use this
4100 * to handle the expansion of '**' into an empty string.
4101 */
4102 if (ctx->ffs_filearray == NULL)
4103 {
4104 char_u *dirptrs[2];
4105
4106 /* we use filepath to build the path expand_wildcards() should
4107 * expand.
4108 */
4109 dirptrs[0] = file_path;
4110 dirptrs[1] = NULL;
4111
4112 /* if we have a start dir copy it in */
4113 if (!vim_isAbsName(ctx->ffs_fix_path)
4114 && ff_search_ctx->ffsc_start_dir)
4115 {
4116 STRCPY(file_path, ff_search_ctx->ffsc_start_dir);
4117 add_pathsep(file_path);
4118 }
4119
4120 /* append the fix part of the search path */
4121 STRCAT(file_path, ctx->ffs_fix_path);
4122 add_pathsep(file_path);
4123
4124#ifdef FEAT_PATH_EXTRA
4125 rest_of_wildcards = ctx->ffs_wc_path;
4126 if (*rest_of_wildcards != NUL)
4127 {
4128 len = (int)STRLEN(file_path);
4129 if (STRNCMP(rest_of_wildcards, "**", 2) == 0)
4130 {
4131 /* pointer to the restrict byte
4132 * The restrict byte is not a character!
4133 */
4134 p = rest_of_wildcards + 2;
4135
4136 if (*p > 0)
4137 {
4138 (*p)--;
4139 file_path[len++] = '*';
4140 }
4141
4142 if (*p == 0)
4143 {
4144 /* remove '**<numb> from wildcards */
4145 mch_memmove(rest_of_wildcards,
4146 rest_of_wildcards + 3,
4147 STRLEN(rest_of_wildcards + 3) + 1);
4148 }
4149 else
4150 rest_of_wildcards += 3;
4151
4152 if (ctx->ffs_star_star_empty == 0)
4153 {
4154 /* if not done before, expand '**' to empty */
4155 ctx->ffs_star_star_empty = 1;
4156 dirptrs[1] = ctx->ffs_fix_path;
4157 }
4158 }
4159
4160 /*
4161 * Here we copy until the next path separator or the end of
4162 * the path. If we stop at a path separator, there is
4163 * still somthing else left. This is handled below by
4164 * pushing every directory returned from expand_wildcards()
4165 * on the stack again for further search.
4166 */
4167 while (*rest_of_wildcards
4168 && !vim_ispathsep(*rest_of_wildcards))
4169 file_path[len++] = *rest_of_wildcards++;
4170
4171 file_path[len] = NUL;
4172 if (vim_ispathsep(*rest_of_wildcards))
4173 rest_of_wildcards++;
4174 }
4175#endif
4176
4177 /*
4178 * Expand wildcards like "*" and "$VAR".
4179 * If the path is a URL don't try this.
4180 */
4181 if (path_with_url(dirptrs[0]))
4182 {
4183 ctx->ffs_filearray = (char_u **)
4184 alloc((unsigned)sizeof(char *));
4185 if (ctx->ffs_filearray != NULL
4186 && (ctx->ffs_filearray[0]
4187 = vim_strsave(dirptrs[0])) != NULL)
4188 ctx->ffs_filearray_size = 1;
4189 else
4190 ctx->ffs_filearray_size = 0;
4191 }
4192 else
4193 expand_wildcards((dirptrs[1] == NULL) ? 1 : 2, dirptrs,
4194 &ctx->ffs_filearray_size,
4195 &ctx->ffs_filearray,
4196 EW_DIR|EW_ADDSLASH|EW_SILENT);
4197
4198 ctx->ffs_filearray_cur = 0;
4199 ctx->ffs_stage = 0;
4200 }
4201#ifdef FEAT_PATH_EXTRA
4202 else
4203 rest_of_wildcards = &ctx->ffs_wc_path[STRLEN(ctx->ffs_wc_path)];
4204#endif
4205
4206 if (ctx->ffs_stage == 0)
4207 {
4208 /* this is the first time we work on this directory */
4209#ifdef FEAT_PATH_EXTRA
4210 if (*rest_of_wildcards == NUL)
4211#endif
4212 {
4213 /*
4214 * we don't have further wildcards to expand, so we have to
4215 * check for the final file now
4216 */
4217 for (i = ctx->ffs_filearray_cur;
4218 i < ctx->ffs_filearray_size; ++i)
4219 {
4220 if (!path_with_url(ctx->ffs_filearray[i])
4221 && !mch_isdir(ctx->ffs_filearray[i]))
4222 continue; /* not a directory */
4223
4224 /* prepare the filename to be checked for existance
4225 * below */
4226 STRCPY(file_path, ctx->ffs_filearray[i]);
4227 add_pathsep(file_path);
4228 STRCAT(file_path, ff_search_ctx->ffsc_file_to_search);
4229
4230 /*
4231 * Try without extra suffix and then with suffixes
4232 * from 'suffixesadd'.
4233 */
4234#ifdef FEAT_SEARCHPATH
4235 len = (int)STRLEN(file_path);
4236 suf = curbuf->b_p_sua;
4237 for (;;)
4238#endif
4239 {
4240 /* if file exists and we didn't already find it */
4241 if ((path_with_url(file_path)
4242 || (mch_getperm(file_path) >= 0
4243 && (!ff_search_ctx->ffsc_need_dir
4244 || mch_isdir(file_path))))
4245#ifndef FF_VERBOSE
4246 && (ff_check_visited(
4247 &ff_search_ctx->ffsc_visited_list->ffvl_visited_list,
4248 file_path
4249#ifdef FEAT_PATH_EXTRA
4250 , (char_u *)""
4251#endif
4252 ) == OK)
4253#endif
4254 )
4255 {
4256#ifdef FF_VERBOSE
4257 if (ff_check_visited(
4258 &ff_search_ctx->ffsc_visited_list->ffvl_visited_list,
4259 file_path
4260#ifdef FEAT_PATH_EXTRA
4261 , (char_u *)""
4262#endif
4263 ) == FAIL)
4264 {
4265 if (p_verbose >= 5)
4266 {
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004267 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00004268 smsg((char_u *)"Already: %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004269 file_path);
4270 /* don't overwrite this either */
4271 msg_puts((char_u *)"\n");
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004272 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004273 }
4274 continue;
4275 }
4276#endif
4277
4278 /* push dir to examine rest of subdirs later */
4279 ctx->ffs_filearray_cur = i + 1;
4280 ff_push(ctx);
4281
4282 simplify_filename(file_path);
4283 if (mch_dirname(ff_expand_buffer, MAXPATHL)
4284 == OK)
4285 {
4286 p = shorten_fname(file_path,
4287 ff_expand_buffer);
4288 if (p != NULL)
4289 mch_memmove(file_path, p,
4290 STRLEN(p) + 1);
4291 }
4292#ifdef FF_VERBOSE
4293 if (p_verbose >= 5)
4294 {
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004295 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00004296 smsg((char_u *)"HIT: %s", file_path);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004297 /* don't overwrite this either */
4298 msg_puts((char_u *)"\n");
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004299 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004300 }
4301#endif
4302 return file_path;
4303 }
4304
4305#ifdef FEAT_SEARCHPATH
4306 /* Not found or found already, try next suffix. */
4307 if (*suf == NUL)
4308 break;
4309 copy_option_part(&suf, file_path + len,
4310 MAXPATHL - len, ",");
4311#endif
4312 }
4313 }
4314 }
4315#ifdef FEAT_PATH_EXTRA
4316 else
4317 {
4318 /*
4319 * still wildcards left, push the directories for further
4320 * search
4321 */
4322 for (i = ctx->ffs_filearray_cur; i < ctx->ffs_filearray_size;
4323 ++i)
4324 {
4325 if (!mch_isdir(ctx->ffs_filearray[i]))
4326 continue; /* not a directory */
4327
4328 ff_push(ff_create_stack_element(ctx->ffs_filearray[i],
4329 rest_of_wildcards, ctx->ffs_level - 1, 0));
4330 }
4331 }
4332#endif
4333 ctx->ffs_filearray_cur = 0;
4334 ctx->ffs_stage = 1;
4335 }
4336
4337#ifdef FEAT_PATH_EXTRA
4338 /*
4339 * if wildcards contains '**' we have to descent till we reach the
4340 * leaves of the directory tree.
4341 */
4342 if (STRNCMP(ctx->ffs_wc_path, "**", 2) == 0)
4343 {
4344 for (i = ctx->ffs_filearray_cur; i < ctx->ffs_filearray_size; ++i)
4345 {
4346 if (fnamecmp(ctx->ffs_filearray[i], ctx->ffs_fix_path) == 0)
4347 continue; /* don't repush same directory */
4348 if (!mch_isdir(ctx->ffs_filearray[i]))
4349 continue; /* not a directory */
4350 ff_push(ff_create_stack_element(ctx->ffs_filearray[i],
4351 ctx->ffs_wc_path, ctx->ffs_level - 1, 1));
4352 }
4353 }
4354#endif
4355
4356 /* we are done with the current directory */
4357 ff_free_stack_element(ctx);
4358
4359 }
4360
4361#ifdef FEAT_PATH_EXTRA
4362 /* If we reached this, we didn't find anything downwards.
4363 * Let's check if we should do an upward search.
4364 */
4365 if (ff_search_ctx->ffsc_start_dir
4366 && ff_search_ctx->ffsc_stopdirs_v != NULL && !got_int)
4367 {
4368 ff_stack_T *sptr;
4369
4370 /* is the last starting directory in the stop list? */
4371 if (ff_path_in_stoplist(ff_search_ctx->ffsc_start_dir,
4372 (int)(path_end - ff_search_ctx->ffsc_start_dir),
4373 ff_search_ctx->ffsc_stopdirs_v) == TRUE)
4374 break;
4375
4376 /* cut of last dir */
4377 while (path_end > ff_search_ctx->ffsc_start_dir
4378 && *path_end == PATHSEP)
4379 path_end--;
4380 while (path_end > ff_search_ctx->ffsc_start_dir
4381 && *(path_end-1) != PATHSEP)
4382 path_end--;
4383 *path_end = 0;
4384 path_end--;
4385
4386 if (*ff_search_ctx->ffsc_start_dir == 0)
4387 break;
4388
4389 STRCPY(file_path, ff_search_ctx->ffsc_start_dir);
4390 add_pathsep(file_path);
4391 STRCAT(file_path, ff_search_ctx->ffsc_fix_path);
4392
4393 /* create a new stack entry */
4394 sptr = ff_create_stack_element(file_path,
4395 ff_search_ctx->ffsc_wc_path, ff_search_ctx->ffsc_level, 0);
4396 if (sptr == NULL)
4397 break;
4398 ff_push(sptr);
4399 }
4400 else
4401 break;
4402 }
4403#endif
4404
4405 vim_free(file_path);
4406 return NULL;
4407}
4408
4409/*
4410 * Free the list of lists of visited files and directories
4411 * Can handle it if the passed search_context is NULL;
4412 */
4413 void
4414vim_findfile_free_visited(search_ctx)
4415 void *search_ctx;
4416{
4417 if (search_ctx == NULL)
4418 return;
4419
4420 ff_search_ctx = (ff_search_ctx_T *)search_ctx;
4421
4422 vim_findfile_free_visited_list(&ff_search_ctx->ffsc_visited_lists_list);
4423 vim_findfile_free_visited_list(&ff_search_ctx->ffsc_dir_visited_lists_list);
4424}
4425
4426 static void
4427vim_findfile_free_visited_list(list_headp)
4428 ff_visited_list_hdr_T **list_headp;
4429{
4430 ff_visited_list_hdr_T *vp;
4431
4432 while (*list_headp != NULL)
4433 {
4434 vp = (*list_headp)->ffvl_next;
4435 ff_free_visited_list((*list_headp)->ffvl_visited_list);
4436
4437 vim_free((*list_headp)->ffvl_filename);
4438 vim_free(*list_headp);
4439 *list_headp = vp;
4440 }
4441 *list_headp = NULL;
4442}
4443
4444 static void
4445ff_free_visited_list(vl)
4446 ff_visited_T *vl;
4447{
4448 ff_visited_T *vp;
4449
4450 while (vl != NULL)
4451 {
4452 vp = vl->ffv_next;
4453#ifdef FEAT_PATH_EXTRA
4454 vim_free(vl->ffv_wc_path);
4455#endif
4456 vim_free(vl);
4457 vl = vp;
4458 }
4459 vl = NULL;
4460}
4461
4462/*
4463 * Returns the already visited list for the given filename. If none is found it
4464 * allocates a new one.
4465 */
4466 static ff_visited_list_hdr_T*
4467ff_get_visited_list(filename, list_headp)
4468 char_u *filename;
4469 ff_visited_list_hdr_T **list_headp;
4470{
4471 ff_visited_list_hdr_T *retptr = NULL;
4472
4473 /* check if a visited list for the given filename exists */
4474 if (*list_headp != NULL)
4475 {
4476 retptr = *list_headp;
4477 while (retptr != NULL)
4478 {
4479 if (fnamecmp(filename, retptr->ffvl_filename) == 0)
4480 {
4481#ifdef FF_VERBOSE
4482 if (p_verbose >= 5)
4483 {
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004484 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00004485 smsg((char_u *)"ff_get_visited_list: FOUND list for %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004486 filename);
4487 /* don't overwrite this either */
4488 msg_puts((char_u *)"\n");
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004489 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004490 }
4491#endif
4492 return retptr;
4493 }
4494 retptr = retptr->ffvl_next;
4495 }
4496 }
4497
4498#ifdef FF_VERBOSE
4499 if (p_verbose >= 5)
4500 {
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004501 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00004502 smsg((char_u *)"ff_get_visited_list: new list for %s", filename);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004503 /* don't overwrite this either */
4504 msg_puts((char_u *)"\n");
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004505 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004506 }
4507#endif
4508
4509 /*
4510 * if we reach this we didn't find a list and we have to allocate new list
4511 */
4512 retptr = (ff_visited_list_hdr_T*)alloc((unsigned)sizeof(*retptr));
4513 if (retptr == NULL)
4514 return NULL;
4515
4516 retptr->ffvl_visited_list = NULL;
4517 retptr->ffvl_filename = vim_strsave(filename);
4518 if (retptr->ffvl_filename == NULL)
4519 {
4520 vim_free(retptr);
4521 return NULL;
4522 }
4523 retptr->ffvl_next = *list_headp;
4524 *list_headp = retptr;
4525
4526 return retptr;
4527}
4528
4529#ifdef FEAT_PATH_EXTRA
4530/*
4531 * check if two wildcard paths are equal. Returns TRUE or FALSE.
4532 * They are equal if:
4533 * - both paths are NULL
4534 * - they have the same length
4535 * - char by char comparison is OK
4536 * - the only differences are in the counters behind a '**', so
4537 * '**\20' is equal to '**\24'
4538 */
4539 static int
4540ff_wc_equal(s1, s2)
4541 char_u *s1;
4542 char_u *s2;
4543{
4544 int i;
4545
4546 if (s1 == s2)
4547 return TRUE;
4548
4549 if (s1 == NULL || s2 == NULL)
4550 return FALSE;
4551
4552 if (STRLEN(s1) != STRLEN(s2))
4553 return FAIL;
4554
4555 for (i = 0; s1[i] != NUL && s2[i] != NUL; i++)
4556 {
4557 if (s1[i] != s2[i]
4558#ifdef CASE_INSENSITIVE_FILENAME
4559 && TOUPPER_LOC(s1[i]) != TOUPPER_LOC(s2[i])
4560#endif
4561 )
4562 {
4563 if (i >= 2)
4564 if (s1[i-1] == '*' && s1[i-2] == '*')
4565 continue;
4566 else
4567 return FAIL;
4568 else
4569 return FAIL;
4570 }
4571 }
4572 return TRUE;
4573}
4574#endif
4575
4576/*
4577 * maintains the list of already visited files and dirs
4578 * returns FAIL if the given file/dir is already in the list
4579 * returns OK if it is newly added
4580 *
4581 * TODO: What to do on memory allocation problems?
4582 * -> return TRUE - Better the file is found several times instead of
4583 * never.
4584 */
4585 static int
4586ff_check_visited(visited_list, fname
4587#ifdef FEAT_PATH_EXTRA
4588 , wc_path
4589#endif
4590 )
4591 ff_visited_T **visited_list;
4592 char_u *fname;
4593#ifdef FEAT_PATH_EXTRA
4594 char_u *wc_path;
4595#endif
4596{
4597 ff_visited_T *vp;
4598#ifdef UNIX
4599 struct stat st;
4600 int url = FALSE;
4601#endif
4602
4603 /* For an URL we only compare the name, otherwise we compare the
4604 * device/inode (unix) or the full path name (not Unix). */
4605 if (path_with_url(fname))
4606 {
4607 STRNCPY(ff_expand_buffer, fname, MAXPATHL);
4608#ifdef UNIX
4609 url = TRUE;
4610#endif
4611 }
4612 else
4613 {
4614 ff_expand_buffer[0] = NUL;
4615#ifdef UNIX
4616 if (mch_stat((char *)fname, &st) < 0)
4617#else
4618 if (vim_FullName(fname, ff_expand_buffer, MAXPATHL, TRUE) == FAIL)
4619#endif
4620 return FAIL;
4621 }
4622
4623 /* check against list of already visited files */
4624 for (vp = *visited_list; vp != NULL; vp = vp->ffv_next)
4625 {
4626 if (
4627#ifdef UNIX
4628 !url
4629 ? (vp->ffv_dev == st.st_dev
4630 && vp->ffv_ino == st.st_ino)
4631 :
4632#endif
4633 fnamecmp(vp->ffv_fname, ff_expand_buffer) == 0
4634 )
4635 {
4636#ifdef FEAT_PATH_EXTRA
4637 /* are the wildcard parts equal */
4638 if (ff_wc_equal(vp->ffv_wc_path, wc_path) == TRUE)
4639#endif
4640 /* already visited */
4641 return FAIL;
4642 }
4643 }
4644
4645 /*
4646 * New file/dir. Add it to the list of visited files/dirs.
4647 */
4648 vp = (ff_visited_T *)alloc((unsigned)(sizeof(ff_visited_T)
4649 + STRLEN(ff_expand_buffer)));
4650
4651 if (vp != NULL)
4652 {
4653#ifdef UNIX
4654 if (!url)
4655 {
4656 vp->ffv_ino = st.st_ino;
4657 vp->ffv_dev = st.st_dev;
4658 vp->ffv_fname[0] = NUL;
4659 }
4660 else
4661 {
4662 vp->ffv_ino = 0;
4663 vp->ffv_dev = -1;
4664#endif
4665 STRCPY(vp->ffv_fname, ff_expand_buffer);
4666#ifdef UNIX
4667 }
4668#endif
4669#ifdef FEAT_PATH_EXTRA
4670 if (wc_path != NULL)
4671 vp->ffv_wc_path = vim_strsave(wc_path);
4672 else
4673 vp->ffv_wc_path = NULL;
4674#endif
4675
4676 vp->ffv_next = *visited_list;
4677 *visited_list = vp;
4678 }
4679
4680 return OK;
4681}
4682
4683/*
4684 * create stack element from given path pieces
4685 */
4686 static ff_stack_T *
4687ff_create_stack_element(fix_part,
4688#ifdef FEAT_PATH_EXTRA
4689 wc_part,
4690#endif
4691 level, star_star_empty)
4692 char_u *fix_part;
4693#ifdef FEAT_PATH_EXTRA
4694 char_u *wc_part;
4695#endif
4696 int level;
4697 int star_star_empty;
4698{
4699 ff_stack_T *new;
4700
4701 new = (ff_stack_T *)alloc((unsigned)sizeof(ff_stack_T));
4702 if (new == NULL)
4703 return NULL;
4704
4705 new->ffs_prev = NULL;
4706 new->ffs_filearray = NULL;
4707 new->ffs_filearray_size = 0;
4708 new->ffs_filearray_cur = 0;
4709 new->ffs_stage = 0;
4710 new->ffs_level = level;
4711 new->ffs_star_star_empty = star_star_empty;;
4712
4713 /* the following saves NULL pointer checks in vim_findfile */
4714 if (fix_part == NULL)
4715 fix_part = (char_u *)"";
4716 new->ffs_fix_path = vim_strsave(fix_part);
4717
4718#ifdef FEAT_PATH_EXTRA
4719 if (wc_part == NULL)
4720 wc_part = (char_u *)"";
4721 new->ffs_wc_path = vim_strsave(wc_part);
4722#endif
4723
4724 if (new->ffs_fix_path == NULL
4725#ifdef FEAT_PATH_EXTRA
4726 || new->ffs_wc_path == NULL
4727#endif
4728 )
4729 {
4730 ff_free_stack_element(new);
4731 new = NULL;
4732 }
4733
4734 return new;
4735}
4736
4737/*
4738 * push a dir on the directory stack
4739 */
4740 static void
4741ff_push(ctx)
4742 ff_stack_T *ctx;
4743{
4744 /* check for NULL pointer, not to return an error to the user, but
4745 * to prevent a crash
4746 */
4747 if (ctx != NULL)
4748 {
4749 ctx->ffs_prev = ff_search_ctx->ffsc_stack_ptr;
4750 ff_search_ctx->ffsc_stack_ptr = ctx;
4751 }
4752}
4753
4754/*
4755 * pop a dir from the directory stack
4756 * returns NULL if stack is empty
4757 */
4758 static ff_stack_T *
4759ff_pop()
4760{
4761 ff_stack_T *sptr;
4762
4763 sptr = ff_search_ctx->ffsc_stack_ptr;
4764 if (ff_search_ctx->ffsc_stack_ptr != NULL)
4765 ff_search_ctx->ffsc_stack_ptr = ff_search_ctx->ffsc_stack_ptr->ffs_prev;
4766
4767 return sptr;
4768}
4769
4770/*
4771 * free the given stack element
4772 */
4773 static void
4774ff_free_stack_element(ctx)
4775 ff_stack_T *ctx;
4776{
4777 /* vim_free handles possible NULL pointers */
4778 vim_free(ctx->ffs_fix_path);
4779#ifdef FEAT_PATH_EXTRA
4780 vim_free(ctx->ffs_wc_path);
4781#endif
4782
4783 if (ctx->ffs_filearray != NULL)
4784 FreeWild(ctx->ffs_filearray_size, ctx->ffs_filearray);
4785
4786 vim_free(ctx);
4787}
4788
4789/*
4790 * clear the search context
4791 */
4792 static void
4793ff_clear()
4794{
4795 ff_stack_T *sptr;
4796
4797 /* clear up stack */
4798 while ((sptr = ff_pop()) != NULL)
4799 ff_free_stack_element(sptr);
4800
4801 vim_free(ff_search_ctx->ffsc_file_to_search);
4802 vim_free(ff_search_ctx->ffsc_start_dir);
4803 vim_free(ff_search_ctx->ffsc_fix_path);
4804#ifdef FEAT_PATH_EXTRA
4805 vim_free(ff_search_ctx->ffsc_wc_path);
4806#endif
4807
4808#ifdef FEAT_PATH_EXTRA
4809 if (ff_search_ctx->ffsc_stopdirs_v != NULL)
4810 {
4811 int i = 0;
4812
4813 while (ff_search_ctx->ffsc_stopdirs_v[i] != NULL)
4814 {
4815 vim_free(ff_search_ctx->ffsc_stopdirs_v[i]);
4816 i++;
4817 }
4818 vim_free(ff_search_ctx->ffsc_stopdirs_v);
4819 }
4820 ff_search_ctx->ffsc_stopdirs_v = NULL;
4821#endif
4822
4823 /* reset everything */
4824 ff_search_ctx->ffsc_file_to_search = NULL;
4825 ff_search_ctx->ffsc_start_dir = NULL;
4826 ff_search_ctx->ffsc_fix_path = NULL;
4827#ifdef FEAT_PATH_EXTRA
4828 ff_search_ctx->ffsc_wc_path = NULL;
4829 ff_search_ctx->ffsc_level = 0;
4830#endif
4831}
4832
4833#ifdef FEAT_PATH_EXTRA
4834/*
4835 * check if the given path is in the stopdirs
4836 * returns TRUE if yes else FALSE
4837 */
4838 static int
4839ff_path_in_stoplist(path, path_len, stopdirs_v)
4840 char_u *path;
4841 int path_len;
4842 char_u **stopdirs_v;
4843{
4844 int i = 0;
4845
4846 /* eat up trailing path separators, except the first */
4847 while (path_len > 1 && path[path_len - 1] == PATHSEP)
4848 path_len--;
4849
4850 /* if no path consider it as match */
4851 if (path_len == 0)
4852 return TRUE;
4853
4854 for (i = 0; stopdirs_v[i] != NULL; i++)
4855 {
4856 if ((int)STRLEN(stopdirs_v[i]) > path_len)
4857 {
4858 /* match for parent directory. So '/home' also matches
4859 * '/home/rks'. Check for PATHSEP in stopdirs_v[i], else
4860 * '/home/r' would also match '/home/rks'
4861 */
4862 if (fnamencmp(stopdirs_v[i], path, path_len) == 0
4863 && stopdirs_v[i][path_len] == PATHSEP)
4864 return TRUE;
4865 }
4866 else
4867 {
4868 if (fnamecmp(stopdirs_v[i], path) == 0)
4869 return TRUE;
4870 }
4871 }
4872 return FALSE;
4873}
4874#endif
4875
4876#if defined(FEAT_SEARCHPATH) || defined(PROTO)
4877/*
4878 * Find the file name "ptr[len]" in the path.
4879 *
4880 * On the first call set the parameter 'first' to TRUE to initialize
4881 * the search. For repeating calls to FALSE.
4882 *
4883 * Repeating calls will return other files called 'ptr[len]' from the path.
4884 *
4885 * Only on the first call 'ptr' and 'len' are used. For repeating calls they
4886 * don't need valid values.
4887 *
4888 * If nothing found on the first call the option FNAME_MESS will issue the
4889 * message:
4890 * 'Can't find file "<file>" in path'
4891 * On repeating calls:
4892 * 'No more file "<file>" found in path'
4893 *
4894 * options:
4895 * FNAME_MESS give error message when not found
4896 *
4897 * Uses NameBuff[]!
4898 *
4899 * Returns an allocated string for the file name. NULL for error.
4900 *
4901 */
4902 char_u *
4903find_file_in_path(ptr, len, options, first, rel_fname)
4904 char_u *ptr; /* file name */
4905 int len; /* length of file name */
4906 int options;
4907 int first; /* use count'th matching file name */
4908 char_u *rel_fname; /* file name searching relative to */
4909{
4910 return find_file_in_path_option(ptr, len, options, first,
4911 *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path,
4912 FALSE, rel_fname);
4913}
4914
4915/*
4916 * Find the directory name "ptr[len]" in the path.
4917 *
4918 * options:
4919 * FNAME_MESS give error message when not found
4920 *
4921 * Uses NameBuff[]!
4922 *
4923 * Returns an allocated string for the file name. NULL for error.
4924 */
4925 char_u *
4926find_directory_in_path(ptr, len, options, rel_fname)
4927 char_u *ptr; /* file name */
4928 int len; /* length of file name */
4929 int options;
4930 char_u *rel_fname; /* file name searching relative to */
4931{
4932 return find_file_in_path_option(ptr, len, options, TRUE, p_cdpath,
4933 TRUE, rel_fname);
4934}
4935
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00004936 char_u *
Bram Moolenaar071d4272004-06-13 20:20:40 +00004937find_file_in_path_option(ptr, len, options, first, path_option, need_dir, rel_fname)
4938 char_u *ptr; /* file name */
4939 int len; /* length of file name */
4940 int options;
4941 int first; /* use count'th matching file name */
4942 char_u *path_option; /* p_path or p_cdpath */
4943 int need_dir; /* looking for directory name */
4944 char_u *rel_fname; /* file name we are looking relative to. */
4945{
4946 static void *search_ctx = NULL;
4947 static char_u *dir;
4948 static char_u *file_to_find = NULL;
4949 static int did_findfile_init = FALSE;
4950 char_u save_char;
4951 char_u *file_name = NULL;
4952 char_u *buf = NULL;
4953 int rel_to_curdir;
4954#ifdef AMIGA
4955 struct Process *proc = (struct Process *)FindTask(0L);
4956 APTR save_winptr = proc->pr_WindowPtr;
4957
4958 /* Avoid a requester here for a volume that doesn't exist. */
4959 proc->pr_WindowPtr = (APTR)-1L;
4960#endif
4961
4962 if (first == TRUE)
4963 {
4964 /* copy file name into NameBuff, expanding environment variables */
4965 save_char = ptr[len];
4966 ptr[len] = NUL;
4967 expand_env(ptr, NameBuff, MAXPATHL);
4968 ptr[len] = save_char;
4969
4970 vim_free(file_to_find);
4971 file_to_find = vim_strsave(NameBuff);
4972 if (file_to_find == NULL) /* out of memory */
4973 {
4974 file_name = NULL;
4975 goto theend;
4976 }
4977 }
4978
4979 rel_to_curdir = (file_to_find[0] == '.'
4980 && (file_to_find[1] == NUL
4981 || vim_ispathsep(file_to_find[1])
4982 || (file_to_find[1] == '.'
4983 && (file_to_find[2] == NUL
4984 || vim_ispathsep(file_to_find[2])))));
4985 if (vim_isAbsName(file_to_find)
4986 /* "..", "../path", "." and "./path": don't use the path_option */
4987 || rel_to_curdir
4988#if defined(MSWIN) || defined(MSDOS) || defined(OS2)
4989 /* handle "\tmp" as absolute path */
4990 || vim_ispathsep(file_to_find[0])
4991 /* handle "c:name" as absulute path */
4992 || (file_to_find[0] != NUL && file_to_find[1] == ':')
4993#endif
4994#ifdef AMIGA
4995 /* handle ":tmp" as absolute path */
4996 || file_to_find[0] == ':'
4997#endif
4998 )
4999 {
5000 /*
5001 * Absolute path, no need to use "path_option".
5002 * If this is not a first call, return NULL. We already returned a
5003 * filename on the first call.
5004 */
5005 if (first == TRUE)
5006 {
5007 int l;
5008 int run;
5009
5010 if (path_with_url(file_to_find))
5011 {
5012 file_name = vim_strsave(file_to_find);
5013 goto theend;
5014 }
5015
5016 /* When FNAME_REL flag given first use the directory of the file.
5017 * Otherwise or when this fails use the current directory. */
5018 for (run = 1; run <= 2; ++run)
5019 {
5020 l = (int)STRLEN(file_to_find);
5021 if (run == 1
5022 && rel_to_curdir
5023 && (options & FNAME_REL)
5024 && rel_fname != NULL
5025 && STRLEN(rel_fname) + l < MAXPATHL)
5026 {
5027 STRCPY(NameBuff, rel_fname);
5028 STRCPY(gettail(NameBuff), file_to_find);
5029 l = (int)STRLEN(NameBuff);
5030 }
5031 else
5032 {
5033 STRCPY(NameBuff, file_to_find);
5034 run = 2;
5035 }
5036
5037 /* When the file doesn't exist, try adding parts of
5038 * 'suffixesadd'. */
5039 buf = curbuf->b_p_sua;
5040 for (;;)
5041 {
5042 if (
5043#ifdef DJGPP
5044 /* "C:" by itself will fail for mch_getperm(),
5045 * assume it's always valid. */
5046 (need_dir && NameBuff[0] != NUL
5047 && NameBuff[1] == ':'
5048 && NameBuff[2] == NUL) ||
5049#endif
5050 (mch_getperm(NameBuff) >= 0
5051 && (!need_dir || mch_isdir(NameBuff))))
5052 {
5053 file_name = vim_strsave(NameBuff);
5054 goto theend;
5055 }
5056 if (*buf == NUL)
5057 break;
5058 copy_option_part(&buf, NameBuff + l, MAXPATHL - l, ",");
5059 }
5060 }
5061 }
5062 }
5063 else
5064 {
5065 /*
5066 * Loop over all paths in the 'path' or 'cdpath' option.
5067 * When "first" is set, first setup to the start of the option.
5068 * Otherwise continue to find the next match.
5069 */
5070 if (first == TRUE)
5071 {
5072 /* vim_findfile_free_visited can handle a possible NULL pointer */
5073 vim_findfile_free_visited(search_ctx);
5074 dir = path_option;
5075 did_findfile_init = FALSE;
5076 }
5077
5078 for (;;)
5079 {
5080 if (did_findfile_init)
5081 {
5082 ff_search_ctx->ffsc_need_dir = need_dir;
5083 file_name = vim_findfile(search_ctx);
5084 ff_search_ctx->ffsc_need_dir = FALSE;
5085 if (file_name != NULL)
5086 break;
5087
5088 did_findfile_init = FALSE;
5089 }
5090 else
5091 {
5092 char_u *r_ptr;
5093
5094 if (dir == NULL || *dir == NUL)
5095 {
5096 /* We searched all paths of the option, now we can
5097 * free the search context. */
5098 vim_findfile_cleanup(search_ctx);
5099 search_ctx = NULL;
5100 break;
5101 }
5102
5103 if ((buf = alloc((int)(MAXPATHL))) == NULL)
5104 break;
5105
5106 /* copy next path */
5107 buf[0] = 0;
5108 copy_option_part(&dir, buf, MAXPATHL, " ,");
5109
5110#ifdef FEAT_PATH_EXTRA
5111 /* get the stopdir string */
5112 r_ptr = vim_findfile_stopdir(buf);
5113#else
5114 r_ptr = NULL;
5115#endif
5116 search_ctx = vim_findfile_init(buf, file_to_find, r_ptr, 100,
5117 FALSE, TRUE, search_ctx, FALSE, rel_fname);
5118 if (search_ctx != NULL)
5119 did_findfile_init = TRUE;
5120 vim_free(buf);
5121 }
5122 }
5123 }
5124 if (file_name == NULL && (options & FNAME_MESS))
5125 {
5126 if (first == TRUE)
5127 {
5128 if (need_dir)
5129 EMSG2(_("E344: Can't find directory \"%s\" in cdpath"),
5130 file_to_find);
5131 else
5132 EMSG2(_("E345: Can't find file \"%s\" in path"),
5133 file_to_find);
5134 }
5135 else
5136 {
5137 if (need_dir)
5138 EMSG2(_("E346: No more directory \"%s\" found in cdpath"),
5139 file_to_find);
5140 else
5141 EMSG2(_("E347: No more file \"%s\" found in path"),
5142 file_to_find);
5143 }
5144 }
5145
5146theend:
5147#ifdef AMIGA
5148 proc->pr_WindowPtr = save_winptr;
5149#endif
5150 return file_name;
5151}
5152
5153#endif /* FEAT_SEARCHPATH */
5154
5155/*
5156 * Change directory to "new_dir". If FEAT_SEARCHPATH is defined, search
5157 * 'cdpath' for relative directory names, otherwise just mch_chdir().
5158 */
5159 int
5160vim_chdir(new_dir)
5161 char_u *new_dir;
5162{
5163#ifndef FEAT_SEARCHPATH
5164 return mch_chdir((char *)new_dir);
5165#else
5166 char_u *dir_name;
5167 int r;
5168
5169 dir_name = find_directory_in_path(new_dir, (int)STRLEN(new_dir),
5170 FNAME_MESS, curbuf->b_ffname);
5171 if (dir_name == NULL)
5172 return -1;
5173 r = mch_chdir((char *)dir_name);
5174 vim_free(dir_name);
5175 return r;
5176#endif
5177}
5178
5179/*
5180 * Get user name from machine-specific function and cache it.
5181 * Returns the user name in "buf[len]".
5182 * Some systems are quite slow in obtaining the user name (Windows NT).
5183 * Returns OK or FAIL.
5184 */
5185 int
5186get_user_name(buf, len)
5187 char_u *buf;
5188 int len;
5189{
5190 static char_u *name = NULL;
5191
5192 if (name == NULL)
5193 {
5194 if (mch_get_user_name(buf, len) == FAIL)
5195 return FAIL;
5196 name = vim_strsave(buf);
5197 }
5198 else
5199 STRNCPY(buf, name, len);
5200 return OK;
5201}
5202
5203#ifndef HAVE_QSORT
5204/*
5205 * Our own qsort(), for systems that don't have it.
5206 * It's simple and slow. From the K&R C book.
5207 */
5208 void
5209qsort(base, elm_count, elm_size, cmp)
5210 void *base;
5211 size_t elm_count;
5212 size_t elm_size;
5213 int (*cmp) __ARGS((const void *, const void *));
5214{
5215 char_u *buf;
5216 char_u *p1;
5217 char_u *p2;
5218 int i, j;
5219 int gap;
5220
5221 buf = alloc((unsigned)elm_size);
5222 if (buf == NULL)
5223 return;
5224
5225 for (gap = elm_count / 2; gap > 0; gap /= 2)
5226 for (i = gap; i < elm_count; ++i)
5227 for (j = i - gap; j >= 0; j -= gap)
5228 {
5229 /* Compare the elements. */
5230 p1 = (char_u *)base + j * elm_size;
5231 p2 = (char_u *)base + (j + gap) * elm_size;
5232 if ((*cmp)((void *)p1, (void *)p2) <= 0)
5233 break;
5234 /* Exchange the elemets. */
5235 mch_memmove(buf, p1, elm_size);
5236 mch_memmove(p1, p2, elm_size);
5237 mch_memmove(p2, buf, elm_size);
5238 }
5239
5240 vim_free(buf);
5241}
5242#endif
5243
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00005244#if defined(FEAT_EX_EXTRA) || defined(FEAT_CMDL_COMPL) \
5245 || (defined(FEAT_SYN_HL) && defined(FEAT_MBYTE)) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005246/*
5247 * Sort an array of strings.
5248 */
5249static int
5250#ifdef __BORLANDC__
5251_RTLENTRYF
5252#endif
5253sort_compare __ARGS((const void *s1, const void *s2));
5254
5255 static int
5256#ifdef __BORLANDC__
5257_RTLENTRYF
5258#endif
5259sort_compare(s1, s2)
5260 const void *s1;
5261 const void *s2;
5262{
5263 return STRCMP(*(char **)s1, *(char **)s2);
5264}
5265
5266 void
5267sort_strings(files, count)
5268 char_u **files;
5269 int count;
5270{
5271 qsort((void *)files, (size_t)count, sizeof(char_u *), sort_compare);
5272}
5273#endif
5274
5275#if !defined(NO_EXPANDPATH) || defined(PROTO)
5276/*
5277 * Compare path "p[]" to "q[]".
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005278 * If "maxlen" >= 0 compare "p[maxlen]" to "q[maxlen]"
Bram Moolenaar071d4272004-06-13 20:20:40 +00005279 * Return value like strcmp(p, q), but consider path separators.
5280 */
5281 int
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005282pathcmp(p, q, maxlen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005283 const char *p, *q;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005284 int maxlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005285{
5286 int i;
Bram Moolenaar86b68352004-12-27 21:59:20 +00005287 const char *s = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005288
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005289 for (i = 0; maxlen < 0 || i < maxlen; ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005290 {
5291 /* End of "p": check if "q" also ends or just has a slash. */
5292 if (p[i] == NUL)
5293 {
5294 if (q[i] == NUL) /* full match */
5295 return 0;
5296 s = q;
5297 break;
5298 }
5299
5300 /* End of "q": check if "p" just has a slash. */
5301 if (q[i] == NUL)
5302 {
5303 s = p;
5304 break;
5305 }
5306
5307 if (
5308#ifdef CASE_INSENSITIVE_FILENAME
5309 TOUPPER_LOC(p[i]) != TOUPPER_LOC(q[i])
5310#else
5311 p[i] != q[i]
5312#endif
5313#ifdef BACKSLASH_IN_FILENAME
5314 /* consider '/' and '\\' to be equal */
5315 && !((p[i] == '/' && q[i] == '\\')
5316 || (p[i] == '\\' && q[i] == '/'))
5317#endif
5318 )
5319 {
5320 if (vim_ispathsep(p[i]))
5321 return -1;
5322 if (vim_ispathsep(q[i]))
5323 return 1;
5324 return ((char_u *)p)[i] - ((char_u *)q)[i]; /* no match */
5325 }
5326 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00005327 if (s == NULL) /* "i" ran into "maxlen" */
5328 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005329
5330 /* ignore a trailing slash, but not "//" or ":/" */
Bram Moolenaar86b68352004-12-27 21:59:20 +00005331 if (s[i + 1] == NUL
5332 && i > 0
5333 && !after_pathsep((char_u *)s, (char_u *)s + i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005334#ifdef BACKSLASH_IN_FILENAME
Bram Moolenaar86b68352004-12-27 21:59:20 +00005335 && (s[i] == '/' || s[i] == '\\')
Bram Moolenaar071d4272004-06-13 20:20:40 +00005336#else
Bram Moolenaar86b68352004-12-27 21:59:20 +00005337 && s[i] == '/'
Bram Moolenaar071d4272004-06-13 20:20:40 +00005338#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00005339 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00005340 return 0; /* match with trailing slash */
5341 if (s == q)
5342 return -1; /* no match */
5343 return 1;
5344}
5345#endif
5346
5347#if defined(FEAT_PRINTER) || defined(PROTO)
5348/*
5349 * Parse a list of options in the form
5350 * option:value,option:value,option:value
5351 *
5352 * "value" can start with a number which is parsed out, e.g.
5353 * margin:12mm
5354 *
5355 * Returns error message for an illegal option, NULL otherwise.
5356 * Only used for the printer at the moment...
5357 */
5358 char_u *
5359parse_list_options(option_str, table, table_size)
5360 char_u *option_str;
5361 option_table_T *table;
5362 int table_size;
5363{
5364 char_u *stringp;
5365 char_u *colonp;
5366 char_u *commap;
5367 char_u *p;
5368 int idx = 0; /* init for GCC */
5369 int len;
5370
5371 for (idx = 0; idx < table_size; ++idx)
5372 table[idx].present = FALSE;
5373
5374 /*
5375 * Repeat for all comma separated parts.
5376 */
5377 stringp = option_str;
5378 while (*stringp)
5379 {
5380 colonp = vim_strchr(stringp, ':');
5381 if (colonp == NULL)
5382 return (char_u *)N_("E550: Missing colon");
5383 commap = vim_strchr(stringp, ',');
5384 if (commap == NULL)
5385 commap = option_str + STRLEN(option_str);
5386
5387 len = (int)(colonp - stringp);
5388
5389 for (idx = 0; idx < table_size; ++idx)
5390 if (STRNICMP(stringp, table[idx].name, len) == 0)
5391 break;
5392
5393 if (idx == table_size)
5394 return (char_u *)N_("E551: Illegal component");
5395
5396 p = colonp + 1;
5397 table[idx].present = TRUE;
5398
5399 if (table[idx].hasnum)
5400 {
5401 if (!VIM_ISDIGIT(*p))
5402 return (char_u *)N_("E552: digit expected");
5403
5404 table[idx].number = getdigits(&p); /*advances p*/
5405 }
5406
5407 table[idx].string = p;
5408 table[idx].strlen = (int)(commap - p);
5409
5410 stringp = commap;
5411 if (*stringp == ',')
5412 ++stringp;
5413 }
5414
5415 return NULL;
5416}
5417
5418
5419#endif /*FEAT_PRINTER*/
5420
5421/*
5422 * The putenv() implementation below comes from the "screen" program.
5423 * Included with permission from Juergen Weigert.
5424 * See pty.c for the copyright notice.
5425 */
5426
5427/*
5428 * putenv -- put value into environment
5429 *
5430 * Usage: i = putenv (string)
5431 * int i;
5432 * char *string;
5433 *
5434 * where string is of the form <name>=<value>.
5435 * Putenv returns 0 normally, -1 on error (not enough core for malloc).
5436 *
5437 * Putenv may need to add a new name into the environment, or to
5438 * associate a value longer than the current value with a particular
5439 * name. So, to make life simpler, putenv() copies your entire
5440 * environment into the heap (i.e. malloc()) from the stack
5441 * (i.e. where it resides when your process is initiated) the first
5442 * time you call it.
5443 *
5444 * (history removed, not very interesting. See the "screen" sources.)
5445 */
5446
5447#if !defined(HAVE_SETENV) && !defined(HAVE_PUTENV)
5448
5449#define EXTRASIZE 5 /* increment to add to env. size */
5450
5451static int envsize = -1; /* current size of environment */
5452#ifndef MACOS_CLASSIC
5453extern
5454#endif
5455 char **environ; /* the global which is your env. */
5456
5457static int findenv __ARGS((char *name)); /* look for a name in the env. */
5458static int newenv __ARGS((void)); /* copy env. from stack to heap */
5459static int moreenv __ARGS((void)); /* incr. size of env. */
5460
5461 int
5462putenv(string)
5463 const char *string;
5464{
5465 int i;
5466 char *p;
5467
5468 if (envsize < 0)
5469 { /* first time putenv called */
5470 if (newenv() < 0) /* copy env. to heap */
5471 return -1;
5472 }
5473
5474 i = findenv((char *)string); /* look for name in environment */
5475
5476 if (i < 0)
5477 { /* name must be added */
5478 for (i = 0; environ[i]; i++);
5479 if (i >= (envsize - 1))
5480 { /* need new slot */
5481 if (moreenv() < 0)
5482 return -1;
5483 }
5484 p = (char *)alloc((unsigned)(strlen(string) + 1));
5485 if (p == NULL) /* not enough core */
5486 return -1;
5487 environ[i + 1] = 0; /* new end of env. */
5488 }
5489 else
5490 { /* name already in env. */
5491 p = vim_realloc(environ[i], strlen(string) + 1);
5492 if (p == NULL)
5493 return -1;
5494 }
5495 sprintf(p, "%s", string); /* copy into env. */
5496 environ[i] = p;
5497
5498 return 0;
5499}
5500
5501 static int
5502findenv(name)
5503 char *name;
5504{
5505 char *namechar, *envchar;
5506 int i, found;
5507
5508 found = 0;
5509 for (i = 0; environ[i] && !found; i++)
5510 {
5511 envchar = environ[i];
5512 namechar = name;
5513 while (*namechar && *namechar != '=' && (*namechar == *envchar))
5514 {
5515 namechar++;
5516 envchar++;
5517 }
5518 found = ((*namechar == '\0' || *namechar == '=') && *envchar == '=');
5519 }
5520 return found ? i - 1 : -1;
5521}
5522
5523 static int
5524newenv()
5525{
5526 char **env, *elem;
5527 int i, esize;
5528
5529#ifdef MACOS
5530 /* for Mac a new, empty environment is created */
5531 i = 0;
5532#else
5533 for (i = 0; environ[i]; i++)
5534 ;
5535#endif
5536 esize = i + EXTRASIZE + 1;
5537 env = (char **)alloc((unsigned)(esize * sizeof (elem)));
5538 if (env == NULL)
5539 return -1;
5540
5541#ifndef MACOS
5542 for (i = 0; environ[i]; i++)
5543 {
5544 elem = (char *)alloc((unsigned)(strlen(environ[i]) + 1));
5545 if (elem == NULL)
5546 return -1;
5547 env[i] = elem;
5548 strcpy(elem, environ[i]);
5549 }
5550#endif
5551
5552 env[i] = 0;
5553 environ = env;
5554 envsize = esize;
5555 return 0;
5556}
5557
5558 static int
5559moreenv()
5560{
5561 int esize;
5562 char **env;
5563
5564 esize = envsize + EXTRASIZE;
5565 env = (char **)vim_realloc((char *)environ, esize * sizeof (*env));
5566 if (env == 0)
5567 return -1;
5568 environ = env;
5569 envsize = esize;
5570 return 0;
5571}
5572
5573# ifdef USE_VIMPTY_GETENV
5574 char_u *
5575vimpty_getenv(string)
5576 const char_u *string;
5577{
5578 int i;
5579 char_u *p;
5580
5581 if (envsize < 0)
5582 return NULL;
5583
5584 i = findenv((char *)string);
5585
5586 if (i < 0)
5587 return NULL;
5588
5589 p = vim_strchr((char_u *)environ[i], '=');
5590 return (p + 1);
5591}
5592# endif
5593
5594#endif /* !defined(HAVE_SETENV) && !defined(HAVE_PUTENV) */