xref: /netbsd/lib/libedit/search.c (revision 6550d01e)
1 /*	$NetBSD: search.c,v 1.24 2010/04/15 00:57:33 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. 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.24 2010/04/15 00:57:33 christos 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 = el_malloc(EL_BUFSIZ *
70 	    sizeof(*el->el_search.patbuf));
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 #ifdef WIDECHAR
113 	static ct_buffer_t conv;
114 #endif
115 #if defined (REGEX)
116 	regex_t re;
117 	int rv;
118 #elif defined (REGEXP)
119 	regexp *rp;
120 	int rv;
121 #else
122 	extern char	*re_comp(const char *);
123 	extern int	 re_exec(const char *);
124 #endif
125 
126 	if (Strstr(str, pat) != 0)
127 		return (1);
128 
129 #if defined(REGEX)
130 	if (regcomp(&re, ct_encode_string(pat, &conv), 0) == 0) {
131 		rv = regexec(&re, ct_encode_string(str, &conv), 0, NULL, 0) == 0;
132 		regfree(&re);
133 	} else {
134 		rv = 0;
135 	}
136 	return (rv);
137 #elif defined(REGEXP)
138 	if ((re = regcomp(ct_encode_string(pat, &conv))) != NULL) {
139 		rv = regexec(re, ct_encode_string(str, &conv));
140 		free((ptr_t) re);
141 	} else {
142 		rv = 0;
143 	}
144 	return (rv);
145 #else
146 	if (re_comp(ct_encode_string(pat, &conv)) != NULL)
147 		return (0);
148 	else
149 		return (re_exec(ct_encode_string(str, &conv)) == 1);
150 #endif
151 }
152 
153 
154 /* c_hmatch():
155  *	 return True if the pattern matches the prefix
156  */
157 protected int
158 c_hmatch(EditLine *el, const Char *str)
159 {
160 #ifdef SDEBUG
161 	(void) fprintf(el->el_errfile, "match `%s' with `%s'\n",
162 	    el->el_search.patbuf, str);
163 #endif /* SDEBUG */
164 
165 	return (el_match(str, el->el_search.patbuf));
166 }
167 
168 
169 /* c_setpat():
170  *	Set the history seatch pattern
171  */
172 protected void
173 c_setpat(EditLine *el)
174 {
175 	if (el->el_state.lastcmd != ED_SEARCH_PREV_HISTORY &&
176 	    el->el_state.lastcmd != ED_SEARCH_NEXT_HISTORY) {
177 		el->el_search.patlen = EL_CURSOR(el) - el->el_line.buffer;
178 		if (el->el_search.patlen >= EL_BUFSIZ)
179 			el->el_search.patlen = EL_BUFSIZ - 1;
180 		if (el->el_search.patlen != 0) {
181 			(void) Strncpy(el->el_search.patbuf, el->el_line.buffer,
182 			    el->el_search.patlen);
183 			el->el_search.patbuf[el->el_search.patlen] = '\0';
184 		} else
185 			el->el_search.patlen = Strlen(el->el_search.patbuf);
186 	}
187 #ifdef SDEBUG
188 	(void) fprintf(el->el_errfile, "\neventno = %d\n",
189 	    el->el_history.eventno);
190 	(void) fprintf(el->el_errfile, "patlen = %d\n", el->el_search.patlen);
191 	(void) fprintf(el->el_errfile, "patbuf = \"%s\"\n",
192 	    el->el_search.patbuf);
193 	(void) fprintf(el->el_errfile, "cursor %d lastchar %d\n",
194 	    EL_CURSOR(el) - el->el_line.buffer,
195 	    el->el_line.lastchar - el->el_line.buffer);
196 #endif
197 }
198 
199 
200 /* ce_inc_search():
201  *	Emacs incremental search
202  */
203 protected el_action_t
204 ce_inc_search(EditLine *el, int dir)
205 {
206 	static const Char STRfwd[] = {'f', 'w', 'd', '\0'},
207 	     STRbck[] = {'b', 'c', 'k', '\0'};
208 	static Char pchar = ':';/* ':' = normal, '?' = failed */
209 	static Char endcmd[2] = {'\0', '\0'};
210 	Char ch, *ocursor = el->el_line.cursor, oldpchar = pchar;
211 	const Char *cp;
212 
213 	el_action_t ret = CC_NORM;
214 
215 	int ohisteventno = el->el_history.eventno;
216 	size_t oldpatlen = el->el_search.patlen;
217 	int newdir = dir;
218 	int done, redo;
219 
220 	if (el->el_line.lastchar + sizeof(STRfwd) /
221 	    sizeof(*el->el_line.lastchar) + 2 +
222 	    el->el_search.patlen >= el->el_line.limit)
223 		return (CC_ERROR);
224 
225 	for (;;) {
226 
227 		if (el->el_search.patlen == 0) {	/* first round */
228 			pchar = ':';
229 #ifdef ANCHOR
230 #define	LEN	2
231 			el->el_search.patbuf[el->el_search.patlen++] = '.';
232 			el->el_search.patbuf[el->el_search.patlen++] = '*';
233 #else
234 #define	LEN	0
235 #endif
236 		}
237 		done = redo = 0;
238 		*el->el_line.lastchar++ = '\n';
239 		for (cp = (newdir == ED_SEARCH_PREV_HISTORY) ? STRbck : STRfwd;
240 		    *cp; *el->el_line.lastchar++ = *cp++)
241 			continue;
242 		*el->el_line.lastchar++ = pchar;
243 		for (cp = &el->el_search.patbuf[LEN];
244 		    cp < &el->el_search.patbuf[el->el_search.patlen];
245 		    *el->el_line.lastchar++ = *cp++)
246 			continue;
247 		*el->el_line.lastchar = '\0';
248 		re_refresh(el);
249 
250 		if (FUN(el,getc)(el, &ch) != 1)
251 			return (ed_end_of_file(el, 0));
252 
253 		switch (el->el_map.current[(unsigned char) ch]) {
254 		case ED_INSERT:
255 		case ED_DIGIT:
256 			if (el->el_search.patlen >= EL_BUFSIZ - LEN)
257 				term_beep(el);
258 			else {
259 				el->el_search.patbuf[el->el_search.patlen++] =
260 				    ch;
261 				*el->el_line.lastchar++ = ch;
262 				*el->el_line.lastchar = '\0';
263 				re_refresh(el);
264 			}
265 			break;
266 
267 		case EM_INC_SEARCH_NEXT:
268 			newdir = ED_SEARCH_NEXT_HISTORY;
269 			redo++;
270 			break;
271 
272 		case EM_INC_SEARCH_PREV:
273 			newdir = ED_SEARCH_PREV_HISTORY;
274 			redo++;
275 			break;
276 
277 		case EM_DELETE_PREV_CHAR:
278 		case ED_DELETE_PREV_CHAR:
279 			if (el->el_search.patlen > LEN)
280 				done++;
281 			else
282 				term_beep(el);
283 			break;
284 
285 		default:
286 			switch (ch) {
287 			case 0007:	/* ^G: Abort */
288 				ret = CC_ERROR;
289 				done++;
290 				break;
291 
292 			case 0027:	/* ^W: Append word */
293 			/* No can do if globbing characters in pattern */
294 				for (cp = &el->el_search.patbuf[LEN];; cp++)
295 				    if (cp >= &el->el_search.patbuf[
296 					el->el_search.patlen]) {
297 					el->el_line.cursor +=
298 					    el->el_search.patlen - LEN - 1;
299 					cp = c__next_word(el->el_line.cursor,
300 					    el->el_line.lastchar, 1,
301 					    ce__isword);
302 					while (el->el_line.cursor < cp &&
303 					    *el->el_line.cursor != '\n') {
304 						if (el->el_search.patlen >=
305 						    EL_BUFSIZ - LEN) {
306 							term_beep(el);
307 							break;
308 						}
309 						el->el_search.patbuf[el->el_search.patlen++] =
310 						    *el->el_line.cursor;
311 						*el->el_line.lastchar++ =
312 						    *el->el_line.cursor++;
313 					}
314 					el->el_line.cursor = ocursor;
315 					*el->el_line.lastchar = '\0';
316 					re_refresh(el);
317 					break;
318 				    } else if (isglob(*cp)) {
319 					    term_beep(el);
320 					    break;
321 				    }
322 				break;
323 
324 			default:	/* Terminate and execute cmd */
325 				endcmd[0] = ch;
326 				FUN(el,push)(el, endcmd);
327 				/* FALLTHROUGH */
328 
329 			case 0033:	/* ESC: Terminate */
330 				ret = CC_REFRESH;
331 				done++;
332 				break;
333 			}
334 			break;
335 		}
336 
337 		while (el->el_line.lastchar > el->el_line.buffer &&
338 		    *el->el_line.lastchar != '\n')
339 			*el->el_line.lastchar-- = '\0';
340 		*el->el_line.lastchar = '\0';
341 
342 		if (!done) {
343 
344 			/* Can't search if unmatched '[' */
345 			for (cp = &el->el_search.patbuf[el->el_search.patlen-1],
346 			    ch = ']';
347 			    cp >= &el->el_search.patbuf[LEN];
348 			    cp--)
349 				if (*cp == '[' || *cp == ']') {
350 					ch = *cp;
351 					break;
352 				}
353 			if (el->el_search.patlen > LEN && ch != '[') {
354 				if (redo && newdir == dir) {
355 					if (pchar == '?') { /* wrap around */
356 						el->el_history.eventno =
357 						    newdir == ED_SEARCH_PREV_HISTORY ? 0 : 0x7fffffff;
358 						if (hist_get(el) == CC_ERROR)
359 							/* el->el_history.event
360 							 * no was fixed by
361 							 * first call */
362 							(void) hist_get(el);
363 						el->el_line.cursor = newdir ==
364 						    ED_SEARCH_PREV_HISTORY ?
365 						    el->el_line.lastchar :
366 						    el->el_line.buffer;
367 					} else
368 						el->el_line.cursor +=
369 						    newdir ==
370 						    ED_SEARCH_PREV_HISTORY ?
371 						    -1 : 1;
372 				}
373 #ifdef ANCHOR
374 				el->el_search.patbuf[el->el_search.patlen++] =
375 				    '.';
376 				el->el_search.patbuf[el->el_search.patlen++] =
377 				    '*';
378 #endif
379 				el->el_search.patbuf[el->el_search.patlen] =
380 				    '\0';
381 				if (el->el_line.cursor < el->el_line.buffer ||
382 				    el->el_line.cursor > el->el_line.lastchar ||
383 				    (ret = ce_search_line(el, newdir))
384 				    == CC_ERROR) {
385 					/* avoid c_setpat */
386 					el->el_state.lastcmd =
387 					    (el_action_t) newdir;
388 					ret = newdir == ED_SEARCH_PREV_HISTORY ?
389 					    ed_search_prev_history(el, 0) :
390 					    ed_search_next_history(el, 0);
391 					if (ret != CC_ERROR) {
392 						el->el_line.cursor = newdir ==
393 						    ED_SEARCH_PREV_HISTORY ?
394 						    el->el_line.lastchar :
395 						    el->el_line.buffer;
396 						(void) ce_search_line(el,
397 						    newdir);
398 					}
399 				}
400 				el->el_search.patlen -= LEN;
401 				el->el_search.patbuf[el->el_search.patlen] =
402 				    '\0';
403 				if (ret == CC_ERROR) {
404 					term_beep(el);
405 					if (el->el_history.eventno !=
406 					    ohisteventno) {
407 						el->el_history.eventno =
408 						    ohisteventno;
409 						if (hist_get(el) == CC_ERROR)
410 							return (CC_ERROR);
411 					}
412 					el->el_line.cursor = ocursor;
413 					pchar = '?';
414 				} else {
415 					pchar = ':';
416 				}
417 			}
418 			ret = ce_inc_search(el, newdir);
419 
420 			if (ret == CC_ERROR && pchar == '?' && oldpchar == ':')
421 				/*
422 				 * break abort of failed search at last
423 				 * non-failed
424 				 */
425 				ret = CC_NORM;
426 
427 		}
428 		if (ret == CC_NORM || (ret == CC_ERROR && oldpatlen == 0)) {
429 			/* restore on normal return or error exit */
430 			pchar = oldpchar;
431 			el->el_search.patlen = oldpatlen;
432 			if (el->el_history.eventno != ohisteventno) {
433 				el->el_history.eventno = ohisteventno;
434 				if (hist_get(el) == CC_ERROR)
435 					return (CC_ERROR);
436 			}
437 			el->el_line.cursor = ocursor;
438 			if (ret == CC_ERROR)
439 				re_refresh(el);
440 		}
441 		if (done || ret != CC_NORM)
442 			return (ret);
443 	}
444 }
445 
446 
447 /* cv_search():
448  *	Vi search.
449  */
450 protected el_action_t
451 cv_search(EditLine *el, int dir)
452 {
453 	Char ch;
454 	Char tmpbuf[EL_BUFSIZ];
455 	int tmplen;
456 
457 #ifdef ANCHOR
458 	tmpbuf[0] = '.';
459 	tmpbuf[1] = '*';
460 #endif
461 	tmplen = LEN;
462 
463 	el->el_search.patdir = dir;
464 
465 	tmplen = c_gets(el, &tmpbuf[LEN],
466 		dir == ED_SEARCH_PREV_HISTORY ? STR("\n/") : STR("\n?") );
467 	if (tmplen == -1)
468 		return CC_REFRESH;
469 
470 	tmplen += LEN;
471 	ch = tmpbuf[tmplen];
472 	tmpbuf[tmplen] = '\0';
473 
474 	if (tmplen == LEN) {
475 		/*
476 		 * Use the old pattern, but wild-card it.
477 		 */
478 		if (el->el_search.patlen == 0) {
479 			re_refresh(el);
480 			return (CC_ERROR);
481 		}
482 #ifdef ANCHOR
483 		if (el->el_search.patbuf[0] != '.' &&
484 		    el->el_search.patbuf[0] != '*') {
485 			(void) Strncpy(tmpbuf, el->el_search.patbuf,
486 			    sizeof(tmpbuf) / sizeof(*tmpbuf) - 1);
487 			el->el_search.patbuf[0] = '.';
488 			el->el_search.patbuf[1] = '*';
489 			(void) Strncpy(&el->el_search.patbuf[2], tmpbuf,
490 			    EL_BUFSIZ - 3);
491 			el->el_search.patlen++;
492 			el->el_search.patbuf[el->el_search.patlen++] = '.';
493 			el->el_search.patbuf[el->el_search.patlen++] = '*';
494 			el->el_search.patbuf[el->el_search.patlen] = '\0';
495 		}
496 #endif
497 	} else {
498 #ifdef ANCHOR
499 		tmpbuf[tmplen++] = '.';
500 		tmpbuf[tmplen++] = '*';
501 #endif
502 		tmpbuf[tmplen] = '\0';
503 		(void) Strncpy(el->el_search.patbuf, tmpbuf, EL_BUFSIZ - 1);
504 		el->el_search.patlen = tmplen;
505 	}
506 	el->el_state.lastcmd = (el_action_t) dir;	/* avoid c_setpat */
507 	el->el_line.cursor = el->el_line.lastchar = el->el_line.buffer;
508 	if ((dir == ED_SEARCH_PREV_HISTORY ? ed_search_prev_history(el, 0) :
509 	    ed_search_next_history(el, 0)) == CC_ERROR) {
510 		re_refresh(el);
511 		return (CC_ERROR);
512 	}
513 	if (ch == 0033) {
514 		re_refresh(el);
515 		return ed_newline(el, 0);
516 	}
517 	return (CC_REFRESH);
518 }
519 
520 
521 /* ce_search_line():
522  *	Look for a pattern inside a line
523  */
524 protected el_action_t
525 ce_search_line(EditLine *el, int dir)
526 {
527 	Char *cp = el->el_line.cursor;
528 	Char *pattern = el->el_search.patbuf;
529 	Char oc, *ocp;
530 #ifdef ANCHOR
531 	ocp = &pattern[1];
532 	oc = *ocp;
533 	*ocp = '^';
534 #else
535 	ocp = pattern;
536 	oc = *ocp;
537 #endif
538 
539 	if (dir == ED_SEARCH_PREV_HISTORY) {
540 		for (; cp >= el->el_line.buffer; cp--) {
541 			if (el_match(cp, ocp)) {
542 				*ocp = oc;
543 				el->el_line.cursor = cp;
544 				return (CC_NORM);
545 			}
546 		}
547 		*ocp = oc;
548 		return (CC_ERROR);
549 	} else {
550 		for (; *cp != '\0' && cp < el->el_line.limit; cp++) {
551 			if (el_match(cp, ocp)) {
552 				*ocp = oc;
553 				el->el_line.cursor = cp;
554 				return (CC_NORM);
555 			}
556 		}
557 		*ocp = oc;
558 		return (CC_ERROR);
559 	}
560 }
561 
562 
563 /* cv_repeat_srch():
564  *	Vi repeat search
565  */
566 protected el_action_t
567 cv_repeat_srch(EditLine *el, Int c)
568 {
569 
570 #ifdef SDEBUG
571 	(void) fprintf(el->el_errfile, "dir %d patlen %d patbuf %s\n",
572 	    c, el->el_search.patlen, ct_encode_string(el->el_search.patbuf));
573 #endif
574 
575 	el->el_state.lastcmd = (el_action_t) c;	/* Hack to stop c_setpat */
576 	el->el_line.lastchar = el->el_line.buffer;
577 
578 	switch (c) {
579 	case ED_SEARCH_NEXT_HISTORY:
580 		return (ed_search_next_history(el, 0));
581 	case ED_SEARCH_PREV_HISTORY:
582 		return (ed_search_prev_history(el, 0));
583 	default:
584 		return (CC_ERROR);
585 	}
586 }
587 
588 
589 /* cv_csearch():
590  *	Vi character search
591  */
592 protected el_action_t
593 cv_csearch(EditLine *el, int direction, Int ch, int count, int tflag)
594 {
595 	Char *cp;
596 
597 	if (ch == 0)
598 		return CC_ERROR;
599 
600 	if (ch == -1) {
601 		Char c;
602 		if (FUN(el,getc)(el, &c) != 1)
603 			return ed_end_of_file(el, 0);
604 		ch = c;
605 	}
606 
607 	/* Save for ';' and ',' commands */
608 	el->el_search.chacha = ch;
609 	el->el_search.chadir = direction;
610 	el->el_search.chatflg = tflag;
611 
612 	cp = el->el_line.cursor;
613 	while (count--) {
614 		if (*cp == ch)
615 			cp += direction;
616 		for (;;cp += direction) {
617 			if (cp >= el->el_line.lastchar)
618 				return CC_ERROR;
619 			if (cp < el->el_line.buffer)
620 				return CC_ERROR;
621 			if (*cp == ch)
622 				break;
623 		}
624 	}
625 
626 	if (tflag)
627 		cp -= direction;
628 
629 	el->el_line.cursor = cp;
630 
631 	if (el->el_chared.c_vcmd.action != NOP) {
632 		if (direction > 0)
633 			el->el_line.cursor++;
634 		cv_delfini(el);
635 		return CC_REFRESH;
636 	}
637 	return CC_CURSOR;
638 }
639