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