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