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