xref: /openbsd-src/lib/libedit/search.c (revision 5b133f3f277e80f096764111e64f3a1284acb179)
1 /*	$OpenBSD: search.c,v 1.28 2023/03/08 04:43:05 guenther Exp $	*/
2 /*	$NetBSD: search.c,v 1.45 2016/04/18 17:01:19 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 
38 /*
39  * search.c: History and character search functions
40  */
41 #include <stdlib.h>
42 #include <string.h>
43 #if defined(REGEX)
44 #include <regex.h>
45 #elif defined(REGEXP)
46 #include <regexp.h>
47 #endif
48 
49 #include "el.h"
50 #include "common.h"
51 #include "fcns.h"
52 
53 /*
54  * Adjust cursor in vi mode to include the character under it
55  */
56 #define	EL_CURSOR(el) \
57     ((el)->el_line.cursor + (((el)->el_map.type == MAP_VI) && \
58 			    ((el)->el_map.current == (el)->el_map.alt)))
59 
60 /* search_init():
61  *	Initialize the search stuff
62  */
63 protected int
search_init(EditLine * el)64 search_init(EditLine *el)
65 {
66 
67 	el->el_search.patbuf = reallocarray(NULL, EL_BUFSIZ,
68 	    sizeof(*el->el_search.patbuf));
69 	if (el->el_search.patbuf == NULL)
70 		return -1;
71 	*el->el_search.patbuf = L'\0';
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
search_end(EditLine * el)85 search_end(EditLine *el)
86 {
87 
88 	free(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 void
regerror(const char * msg)98 regerror(const char *msg)
99 {
100 }
101 #endif
102 
103 
104 /* el_match():
105  *	Return if string matches pattern
106  */
107 protected int
el_match(const wchar_t * str,const wchar_t * pat)108 el_match(const wchar_t *str, const wchar_t *pat)
109 {
110 	static ct_buffer_t conv;
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 (wcsstr(str, pat) != 0)
123 		return 1;
124 
125 #if defined(REGEX)
126 	if (regcomp(&re, ct_encode_string(pat, &conv), 0) == 0) {
127 		rv = regexec(&re, ct_encode_string(str, &conv), 0, NULL, 0) == 0;
128 		regfree(&re);
129 	} else {
130 		rv = 0;
131 	}
132 	return rv;
133 #elif defined(REGEXP)
134 	if ((re = regcomp(ct_encode_string(pat, &conv))) != NULL) {
135 		rv = regexec(re, ct_encode_string(str, &conv));
136 		free(re);
137 	} else {
138 		rv = 0;
139 	}
140 	return rv;
141 #else
142 	if (re_comp(ct_encode_string(pat, &conv)) != NULL)
143 		return 0;
144 	else
145 		return re_exec(ct_encode_string(str, &conv)) == 1;
146 #endif
147 }
148 
149 
150 /* c_hmatch():
151  *	 return True if the pattern matches the prefix
152  */
153 protected int
c_hmatch(EditLine * el,const wchar_t * str)154 c_hmatch(EditLine *el, const wchar_t *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
c_setpat(EditLine * el)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) wcsncpy(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 = wcslen(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
ce_inc_search(EditLine * el,int dir)200 ce_inc_search(EditLine *el, int dir)
201 {
202 	static const wchar_t STRfwd[] = L"fwd", STRbck[] = L"bck";
203 	static wchar_t pchar = L':';  /* ':' = normal, '?' = failed */
204 	static wchar_t endcmd[2] = {'\0', '\0'};
205 	wchar_t *ocursor = el->el_line.cursor, oldpchar = pchar, ch;
206 	const wchar_t *cp;
207 
208 	el_action_t ret = CC_NORM;
209 
210 	int ohisteventno = el->el_history.eventno;
211 	size_t oldpatlen = el->el_search.patlen;
212 	int newdir = dir;
213 	int done, redo;
214 
215 	if (el->el_line.lastchar + sizeof(STRfwd) /
216 	    sizeof(*el->el_line.lastchar) + 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 #define	LEN	2
226 			el->el_search.patbuf[el->el_search.patlen++] = '.';
227 			el->el_search.patbuf[el->el_search.patlen++] = '*';
228 #else
229 #define	LEN	0
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[LEN];
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_wgetc(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 - LEN)
252 				terminal_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 EM_DELETE_PREV_CHAR:
273 		case ED_DELETE_PREV_CHAR:
274 			if (el->el_search.patlen > LEN)
275 				done++;
276 			else
277 				terminal_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 							terminal_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 					    terminal_beep(el);
315 					    break;
316 				    }
317 				break;
318 
319 			default:	/* Terminate and execute cmd */
320 				endcmd[0] = ch;
321 				el_wpush(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 = L']';
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 != L'[') {
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 					terminal_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
cv_search(EditLine * el,int dir)446 cv_search(EditLine *el, int dir)
447 {
448 	wchar_t ch;
449 	wchar_t 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 ? L"\n/" : L"\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) wcsncpy(tmpbuf, el->el_search.patbuf,
481 			    sizeof(tmpbuf) / sizeof(*tmpbuf) - 1);
482 			el->el_search.patbuf[0] = '.';
483 			el->el_search.patbuf[1] = '*';
484 			(void) wcsncpy(&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) wcsncpy(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
ce_search_line(EditLine * el,int dir)520 ce_search_line(EditLine *el, int dir)
521 {
522 	wchar_t *cp = el->el_line.cursor;
523 	wchar_t *pattern = el->el_search.patbuf;
524 	wchar_t 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
cv_repeat_srch(EditLine * el,wint_t c)562 cv_repeat_srch(EditLine *el, wint_t 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, ct_encode_string(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
cv_csearch(EditLine * el,int direction,wint_t ch,int count,int tflag)588 cv_csearch(EditLine *el, int direction, wint_t ch, int count, int tflag)
589 {
590 	wchar_t *cp;
591 
592 	if (ch == 0)
593 		return CC_ERROR;
594 
595 	if (ch == (wint_t)-1) {
596 		if (el_wgetc(el, &ch) != 1)
597 			return ed_end_of_file(el, 0);
598 	}
599 
600 	/* Save for ';' and ',' commands */
601 	el->el_search.chacha = ch;
602 	el->el_search.chadir = direction;
603 	el->el_search.chatflg = tflag;
604 
605 	cp = el->el_line.cursor;
606 	while (count--) {
607 		if ((wint_t)*cp == ch)
608 			cp += direction;
609 		for (;;cp += direction) {
610 			if (cp >= el->el_line.lastchar)
611 				return CC_ERROR;
612 			if (cp < el->el_line.buffer)
613 				return CC_ERROR;
614 			if ((wint_t)*cp == ch)
615 				break;
616 		}
617 	}
618 
619 	if (tflag)
620 		cp -= direction;
621 
622 	el->el_line.cursor = cp;
623 
624 	if (el->el_chared.c_vcmd.action != NOP) {
625 		if (direction > 0)
626 			el->el_line.cursor++;
627 		cv_delfini(el);
628 		return CC_REFRESH;
629 	}
630 	return CC_CURSOR;
631 }
632