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