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