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