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