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