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