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