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