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