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