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