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