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