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