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