Merge from vendor branch BINUTILS:
[dragonfly.git] / lib / libedit / search.c
1 /*-
2  * Copyright (c) 1992, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Christos Zoulas of Cornell University.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *      This product includes software developed by the University of
19  *      California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  * @(#)search.c 8.1 (Berkeley) 6/4/93
37  * $DragonFly: src/lib/libedit/search.c,v 1.4 2003/11/12 20:21:29 eirikn Exp $
38  */
39
40 /*
41  * search.c: History and character search functions
42  */
43 #include "sys.h"
44 #include <stdlib.h>
45 #if defined(REGEX)
46 #include <regex.h>
47 #elif defined(REGEXP)
48 #include <regexp.h>
49 #endif
50 #include "el.h"
51
52 /*
53  * Adjust cursor in vi mode to include the character under it
54  */
55 #define EL_CURSOR(el) \
56     ((el)->el_line.cursor + (((el)->el_map.type == MAP_VI) && \
57                             ((el)->el_map.current == (el)->el_map.alt)))
58
59 /* search_init():
60  *      Initialize the search stuff
61  */
62 protected int
63 search_init(el)
64     EditLine *el;
65 {
66     el->el_search.patbuf = (char *) el_malloc(EL_BUFSIZ);
67     el->el_search.patlen = 0;
68     el->el_search.patdir = -1;
69     el->el_search.chacha = '\0';
70     el->el_search.chadir = -1;
71     return 0;
72 }
73
74
75 /* search_end():
76  *      Initialize the search stuff
77  */
78 protected void
79 search_end(el)
80     EditLine *el;
81 {
82     el_free((ptr_t) el->el_search.patbuf);
83     el->el_search.patbuf = NULL;
84 }
85
86 #ifdef REGEXP
87 /* regerror():
88  *      Handle regular expression errors
89  */
90 public void
91 /*ARGSUSED*/
92 regerror(msg)
93     const char *msg;
94 {
95 }
96 #endif
97
98 /* el_match():
99  *      Return if string matches pattern
100  */
101 protected int
102 el_match(str, pat)
103     const char *str;
104     const char *pat;
105 {
106 #if defined (REGEX)
107     regex_t re;
108     int rv;
109 #elif defined (REGEXP)
110     regexp *rp;
111     int rv;
112 #else 
113     extern char *re_comp (const char *);
114     extern int re_exec (const char *);
115 #endif
116
117     if (strstr(str, pat) != NULL)
118         return 1;
119
120 #if defined(REGEX)
121     if (regcomp(&re, pat, 0) == 0) {
122         rv = regexec(&re, str, 0, NULL, 0) == 0;
123         regfree(&re);
124     } else {
125         rv = 0;
126     }
127     return rv;
128 #elif defined(REGEXP)
129     if ((re = regcomp(pat)) != NULL) {
130         rv = regexec(re, str);
131         free((ptr_t) re);
132     } else {
133         rv = 0;
134     }
135     return rv;
136 #else
137     if (re_comp(pat) != NULL)
138         return 0;
139     else
140     return re_exec(str) == 1;
141 #endif
142 }
143
144
145 /* c_hmatch():
146  *       return True if the pattern matches the prefix
147  */
148 protected int
149 c_hmatch(el, str)
150     EditLine *el;
151     const char *str;
152 {
153 #ifdef SDEBUG
154     (void) fprintf(el->el_errfile, "match `%s' with `%s'\n",
155                    el->el_search.patbuf, str);
156 #endif /* SDEBUG */
157
158     return el_match(str, el->el_search.patbuf);
159 }
160
161
162 /* c_setpat():
163  *      Set the history seatch pattern
164  */
165 protected void
166 c_setpat(el)
167     EditLine *el;
168 {
169     if (el->el_state.lastcmd != ED_SEARCH_PREV_HISTORY &&
170         el->el_state.lastcmd != ED_SEARCH_NEXT_HISTORY) {
171         el->el_search.patlen = EL_CURSOR(el) - el->el_line.buffer;
172         if (el->el_search.patlen >= EL_BUFSIZ)
173             el->el_search.patlen = EL_BUFSIZ -1;
174         if (el->el_search.patlen >= 0)  {
175             (void) strncpy(el->el_search.patbuf, el->el_line.buffer,
176                            el->el_search.patlen);
177             el->el_search.patbuf[el->el_search.patlen] = '\0';
178         }
179         else
180             el->el_search.patlen = strlen(el->el_search.patbuf);
181     }
182 #ifdef SDEBUG
183     (void) fprintf(el->el_errfile, "\neventno = %d\n", el->el_history.eventno);
184     (void) fprintf(el->el_errfile, "patlen = %d\n", el->el_search.patlen);
185     (void) fprintf(el->el_errfile, "patbuf = \"%s\"\n", el->el_search.patbuf);
186     (void) fprintf(el->el_errfile, "cursor %d lastchar %d\n",
187                    EL_CURSOR(el) - el->el_line.buffer,
188                    el->el_line.lastchar - el->el_line.buffer);
189 #endif
190 }
191
192
193 /* ce_inc_search():
194  *      Emacs incremental search
195  */
196 protected el_action_t
197 ce_inc_search(el, dir)
198     EditLine *el;
199     int dir;
200 {
201     static char STRfwd[] = { 'f', 'w', 'd', '\0' },
202                 STRbck[] = { 'b', 'c', 'k', '\0' };
203     static char pchar = ':';    /* ':' = normal, '?' = failed */
204     static char endcmd[2] = { '\0', '\0' };
205     char ch, *cp, *ocursor = el->el_line.cursor, oldpchar = pchar;
206
207     el_action_t ret = CC_NORM;
208
209     int ohisteventno = el->el_history.eventno,
210         oldpatlen = el->el_search.patlen,
211         newdir = dir,
212         done, redo;
213
214     if (el->el_line.lastchar + sizeof(STRfwd) / sizeof(char) + 2 +
215         el->el_search.patlen >= el->el_line.limit)
216         return CC_ERROR;
217
218     for (;;) {
219
220         if (el->el_search.patlen == 0) {        /* first round */
221             pchar = ':';
222 #ifdef ANCHOR
223             el->el_search.patbuf[el->el_search.patlen++] = '.';
224             el->el_search.patbuf[el->el_search.patlen++] = '*';
225 #endif
226         }
227         done = redo = 0;
228         *el->el_line.lastchar++ = '\n';
229         for (cp = newdir == ED_SEARCH_PREV_HISTORY ? STRbck : STRfwd;
230              *cp; *el->el_line.lastchar++ = *cp++)
231              continue;
232         *el->el_line.lastchar++ = pchar;
233         for (cp = &el->el_search.patbuf[1];
234               cp < &el->el_search.patbuf[el->el_search.patlen];
235               *el->el_line.lastchar++ = *cp++)
236             continue;
237         *el->el_line.lastchar = '\0';
238         re_refresh(el);
239
240         if (el_getc(el, &ch) != 1)
241             return ed_end_of_file(el, 0);
242
243         switch (el->el_map.current[(unsigned char) ch]) {
244         case ED_INSERT:
245         case ED_DIGIT:
246             if (el->el_search.patlen > EL_BUFSIZ - 3)
247                 term_beep(el);
248             else {
249                 el->el_search.patbuf[el->el_search.patlen++] = ch;
250                 *el->el_line.lastchar++ = ch;
251                 *el->el_line.lastchar = '\0';
252                 re_refresh(el);
253             }
254             break;
255
256         case EM_INC_SEARCH_NEXT:
257             newdir = ED_SEARCH_NEXT_HISTORY;
258             redo++;
259             break;
260
261         case EM_INC_SEARCH_PREV:
262             newdir = ED_SEARCH_PREV_HISTORY;
263             redo++;
264             break;
265
266         case ED_DELETE_PREV_CHAR:
267             if (el->el_search.patlen > 1)
268                 done++;
269             else
270                 term_beep(el);
271             break;
272
273         default:
274             switch (ch) {
275             case 0007:          /* ^G: Abort */
276                 ret = CC_ERROR;
277                 done++;
278                 break;
279
280             case 0027:          /* ^W: Append word */
281                 /* No can do if globbing characters in pattern */
282                 for (cp = &el->el_search.patbuf[1]; ; cp++)
283                     if (cp >= &el->el_search.patbuf[el->el_search.patlen]) {
284                         el->el_line.cursor += el->el_search.patlen - 1;
285                         cp = c__next_word(el->el_line.cursor,
286                                           el->el_line.lastchar, 1, ce__isword);
287                         while (el->el_line.cursor < cp &&
288                                *el->el_line.cursor != '\n') {
289                             if (el->el_search.patlen > EL_BUFSIZ - 3) {
290                                 term_beep(el);
291                                 break;
292                             }
293                             el->el_search.patbuf[el->el_search.patlen++] =
294                                 *el->el_line.cursor;
295                             *el->el_line.lastchar++ = *el->el_line.cursor++;
296                         }
297                         el->el_line.cursor = ocursor;
298                         *el->el_line.lastchar = '\0';
299                         re_refresh(el);
300                         break;
301                     } else if (isglob(*cp)) {
302                         term_beep(el);
303                         break;
304                     }
305                 break;
306
307             default:            /* Terminate and execute cmd */
308                 endcmd[0] = ch;
309                 el_push(el, endcmd);
310                 /*FALLTHROUGH*/
311
312             case 0033:          /* ESC: Terminate */
313                 ret = CC_REFRESH;
314                 done++;
315                 break;
316             }
317             break;
318         }
319
320         while (el->el_line.lastchar > el->el_line.buffer &&
321                *el->el_line.lastchar != '\n')
322             *el->el_line.lastchar-- = '\0';
323         *el->el_line.lastchar = '\0';
324
325         if (!done) {
326
327             /* Can't search if unmatched '[' */
328             for (cp = &el->el_search.patbuf[el->el_search.patlen-1], ch = ']';
329                  cp > el->el_search.patbuf; cp--)
330                 if (*cp == '[' || *cp == ']') {
331                     ch = *cp;
332                     break;
333                 }
334
335             if (el->el_search.patlen > 1 && ch != '[') {
336                 if (redo && newdir == dir) {
337                     if (pchar == '?') { /* wrap around */
338                         el->el_history.eventno =
339                             newdir == ED_SEARCH_PREV_HISTORY ? 0 : 0x7fffffff;
340                         if (hist_get(el) == CC_ERROR)
341                             /* el->el_history.eventno was fixed by first call */
342                             (void) hist_get(el);
343                         el->el_line.cursor = newdir == ED_SEARCH_PREV_HISTORY ?
344                             el->el_line.lastchar : el->el_line.buffer;
345                     } else
346                         el->el_line.cursor +=
347                                 newdir == ED_SEARCH_PREV_HISTORY ? -1 : 1;
348                 }
349 #ifdef ANCHOR
350                 el->el_search.patbuf[el->el_search.patlen++] = '.';
351                 el->el_search.patbuf[el->el_search.patlen++] = '*';
352 #endif
353                 el->el_search.patbuf[el->el_search.patlen] = '\0';
354                 if (el->el_line.cursor < el->el_line.buffer ||
355                     el->el_line.cursor > el->el_line.lastchar ||
356                     (ret = ce_search_line(el, &el->el_search.patbuf[1],
357                                           newdir)) == CC_ERROR) {
358                     /* avoid c_setpat */
359                     el->el_state.lastcmd = (el_action_t) newdir;
360                     ret = newdir == ED_SEARCH_PREV_HISTORY ?
361                         ed_search_prev_history(el, 0) :
362                         ed_search_next_history(el, 0);
363                     if (ret != CC_ERROR) {
364                         el->el_line.cursor = newdir == ED_SEARCH_PREV_HISTORY ?
365                             el->el_line.lastchar : el->el_line.buffer;
366                         (void) ce_search_line(el, &el->el_search.patbuf[1],
367                                               newdir);
368                     }
369                 }
370                 el->el_search.patbuf[--el->el_search.patlen] = '\0';
371                 if (ret == CC_ERROR) {
372                     term_beep(el);
373                     if (el->el_history.eventno != ohisteventno) {
374                         el->el_history.eventno = ohisteventno;
375                         if (hist_get(el) == CC_ERROR)
376                             return CC_ERROR;
377                     }
378                     el->el_line.cursor = ocursor;
379                     pchar = '?';
380                 } else {
381                     pchar = ':';
382                 }
383             }
384
385             ret = ce_inc_search(el, newdir);
386
387             if (ret == CC_ERROR && pchar == '?' && oldpchar == ':')
388                 /* break abort of failed search at last non-failed */
389                 ret = CC_NORM;
390
391         }
392
393         if (ret == CC_NORM || (ret == CC_ERROR && oldpatlen == 0)) {
394             /* restore on normal return or error exit */
395             pchar = oldpchar;
396             el->el_search.patlen = oldpatlen;
397             if (el->el_history.eventno != ohisteventno) {
398                 el->el_history.eventno = ohisteventno;
399                 if (hist_get(el) == CC_ERROR)
400                     return CC_ERROR;
401             }
402             el->el_line.cursor = ocursor;
403             if (ret == CC_ERROR)
404                 re_refresh(el);
405         }
406         if (done || ret != CC_NORM)
407             return ret;
408     }
409 }
410
411
412 /* cv_search():
413  *      Vi search.
414  */
415 protected el_action_t
416 cv_search(el, dir)
417     EditLine *el;
418     int dir;
419 {
420     char ch;
421     char tmpbuf[EL_BUFSIZ];
422     int tmplen;
423
424     tmplen = 0;
425 #ifdef ANCHOR
426     tmpbuf[tmplen++] = '.';
427     tmpbuf[tmplen++] = '*';
428 #endif
429
430     el->el_line.buffer[0] = '\0';
431     el->el_line.lastchar = el->el_line.buffer;
432     el->el_line.cursor = el->el_line.buffer;
433     el->el_search.patdir = dir;
434
435     c_insert(el, 2);    /* prompt + '\n' */
436     *el->el_line.cursor++ = '\n';
437     *el->el_line.cursor++ = dir == ED_SEARCH_PREV_HISTORY ? '/' : '?';
438     re_refresh(el);
439
440 #ifdef ANCHOR
441 # define LEN 2
442 #else
443 # define LEN 0
444 #endif
445
446     tmplen = c_gets(el, &tmpbuf[LEN]) + LEN;
447     ch = tmpbuf[tmplen];
448     tmpbuf[tmplen] = '\0';
449
450     if (tmplen == LEN) {
451         /*
452          * Use the old pattern, but wild-card it.
453          */
454         if (el->el_search.patlen == 0) {
455             el->el_line.buffer[0] = '\0';
456             el->el_line.lastchar = el->el_line.buffer;
457             el->el_line.cursor = el->el_line.buffer;
458             re_refresh(el);
459             return CC_ERROR;
460         }
461 #ifdef ANCHOR
462         if (el->el_search.patbuf[0] != '.' && el->el_search.patbuf[0] != '*') {
463             (void)strncpy(tmpbuf, el->el_search.patbuf, sizeof(tmpbuf) - 1);
464             el->el_search.patbuf[0] = '.';
465             el->el_search.patbuf[1] = '*';
466             (void)strncpy(&el->el_search.patbuf[2], tmpbuf, EL_BUFSIZ - 3);
467             el->el_search.patlen++;
468             el->el_search.patbuf[el->el_search.patlen++] = '.';
469             el->el_search.patbuf[el->el_search.patlen++] = '*';
470             el->el_search.patbuf[el->el_search.patlen] = '\0';
471         }
472 #endif
473     }
474     else {
475 #ifdef ANCHOR
476         tmpbuf[tmplen++] = '.';
477         tmpbuf[tmplen++] = '*';
478 #endif
479         tmpbuf[tmplen] = '\0';
480         (void)strncpy(el->el_search.patbuf, tmpbuf, EL_BUFSIZ - 1);
481         el->el_search.patlen = tmplen;
482     }
483     el->el_state.lastcmd = (el_action_t) dir; /* avoid c_setpat */
484     el->el_line.cursor = el->el_line.lastchar = el->el_line.buffer;
485     if ((dir == ED_SEARCH_PREV_HISTORY ? ed_search_prev_history(el, 0) :
486                                 ed_search_next_history(el, 0)) == CC_ERROR) {
487         re_refresh(el);
488         return CC_ERROR;
489     }
490     else {
491         if (ch == 0033) {
492             re_refresh(el);
493             *el->el_line.lastchar++ = '\n';
494             *el->el_line.lastchar = '\0';
495             re_goto_bottom(el);
496             return CC_NEWLINE;
497         }
498         else
499             return CC_REFRESH;
500     }
501 }
502
503
504 /* ce_search_line():
505  *      Look for a pattern inside a line
506  */
507 protected el_action_t
508 ce_search_line(el, pattern, dir)
509     EditLine *el;
510     char *pattern;
511     int dir;
512 {
513     char *cp;
514
515     if (dir == ED_SEARCH_PREV_HISTORY) {
516         for (cp = el->el_line.cursor; cp >= el->el_line.buffer; cp--)
517             if (el_match(cp, pattern)) {
518                 el->el_line.cursor = cp;
519                 return CC_NORM;
520             }
521         return CC_ERROR;
522     } else {
523         for (cp = el->el_line.cursor; *cp != '\0' &&
524              cp < el->el_line.limit; cp++)
525             if (el_match(cp, pattern)) {
526                 el->el_line.cursor = cp;
527                 return CC_NORM;
528             }
529         return CC_ERROR;
530     }
531 }
532
533
534 /* cv_repeat_srch():
535  *      Vi repeat search
536  */
537 protected el_action_t
538 cv_repeat_srch(el, c)
539     EditLine *el;
540     int c;
541 {
542 #ifdef SDEBUG
543     (void) fprintf(el->el_errfile, "dir %d patlen %d patbuf %s\n",
544                    c, el->el_search.patlen, el->el_search.patbuf);
545 #endif
546
547     el->el_state.lastcmd = (el_action_t) c;  /* Hack to stop c_setpat */
548     el->el_line.lastchar = el->el_line.buffer;
549
550     switch (c) {
551     case ED_SEARCH_NEXT_HISTORY:
552         return ed_search_next_history(el, 0);
553     case ED_SEARCH_PREV_HISTORY:
554         return ed_search_prev_history(el, 0);
555     default:
556         return CC_ERROR;
557     }
558 }
559
560
561 /* cv_csearch_back():
562  *      Vi character search reverse
563  */
564 protected el_action_t
565 cv_csearch_back(el, ch, count, tflag)
566     EditLine *el;
567     int ch, count, tflag;
568 {
569     char *cp;
570
571     cp = el->el_line.cursor;
572     while (count--) {
573         if (*cp == ch)
574             cp--;
575         while (cp > el->el_line.buffer && *cp != ch)
576             cp--;
577     }
578
579     if (cp < el->el_line.buffer || (cp == el->el_line.buffer && *cp != ch))
580         return CC_ERROR;
581
582     if (*cp == ch && tflag)
583         cp++;
584
585     el->el_line.cursor = cp;
586
587     if (el->el_chared.c_vcmd.action & DELETE) {
588         el->el_line.cursor++;
589         cv_delfini(el);
590         return CC_REFRESH;
591     }
592
593     re_refresh_cursor(el);
594     return CC_NORM;
595 }
596
597
598 /* cv_csearch_fwd():
599  *      Vi character search forward
600  */
601 protected el_action_t
602 cv_csearch_fwd(el, ch, count, tflag)
603     EditLine *el;
604     int ch, count, tflag;
605 {
606     char *cp;
607
608     cp = el->el_line.cursor;
609     while (count--) {
610         if(*cp == ch)
611             cp++;
612         while (cp < el->el_line.lastchar && *cp != ch)
613             cp++;
614     }
615
616     if (cp >= el->el_line.lastchar)
617         return CC_ERROR;
618
619     if (*cp == ch && tflag)
620         cp--;
621
622     el->el_line.cursor = cp;
623
624     if (el->el_chared.c_vcmd.action & DELETE) {
625         el->el_line.cursor++;
626         cv_delfini(el);
627         return CC_REFRESH;
628     }
629     re_refresh_cursor(el);
630     return CC_NORM;
631 }