summary refs log tree commit diff
path: root/bin/catsh/libedit/search.c
blob: 5226cf5fa6a365a0ce9bea15e45b6922090c3c94 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
/*	$NetBSD: search.c,v 1.47 2016/05/09 21:46:56 christos Exp $	*/

/*-
 * Copyright (c) 1992, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * This code is derived from software contributed to Berkeley by
 * Christos Zoulas of Cornell University.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include "config.h"
#if !defined(lint) && !defined(SCCSID)
#if 0
static char sccsid[] = "@(#)search.c	8.1 (Berkeley) 6/4/93";
#else
__RCSID("$NetBSD: search.c,v 1.47 2016/05/09 21:46:56 christos Exp $");
#endif
#endif /* not lint && not SCCSID */

/*
 * search.c: History and character search functions
 */
#include <stdlib.h>
#include <string.h>
#if defined(REGEX)
#include <regex.h>
#elif defined(REGEXP)
#include <regexp.h>
#endif

#include "el.h"
#include "common.h"
#include "fcns.h"

/*
 * Adjust cursor in vi mode to include the character under it
 */
#define	EL_CURSOR(el) \
    ((el)->el_line.cursor + (((el)->el_map.type == MAP_VI) && \
			    ((el)->el_map.current == (el)->el_map.alt)))

/* search_init():
 *	Initialize the search stuff
 */
libedit_private int
search_init(EditLine *el)
{

	el->el_search.patbuf = el_malloc(EL_BUFSIZ *
	    sizeof(*el->el_search.patbuf));
	if (el->el_search.patbuf == NULL)
		return -1;
	el->el_search.patbuf[0] = L'\0';
	el->el_search.patlen = 0;
	el->el_search.patdir = -1;
	el->el_search.chacha = L'\0';
	el->el_search.chadir = CHAR_FWD;
	el->el_search.chatflg = 0;
	return 0;
}


/* search_end():
 *	Initialize the search stuff
 */
libedit_private void
search_end(EditLine *el)
{

	el_free(el->el_search.patbuf);
	el->el_search.patbuf = NULL;
}


#ifdef REGEXP
/* regerror():
 *	Handle regular expression errors
 */
void
/*ARGSUSED*/
regerror(const char *msg)
{
}
#endif


/* el_match():
 *	Return if string matches pattern
 */
libedit_private int
el_match(const wchar_t *str, const wchar_t *pat)
{
	static ct_buffer_t conv;
#if defined (REGEX)
	regex_t re;
	int rv;
#elif defined (REGEXP)
	regexp *rp;
	int rv;
#else
	extern char	*re_comp(const char *);
	extern int	 re_exec(const char *);
#endif

	if (wcsstr(str, pat) != 0)
		return 1;

#if defined(REGEX)
	if (regcomp(&re, ct_encode_string(pat, &conv), 0) == 0) {
		rv = regexec(&re, ct_encode_string(str, &conv), (size_t)0, NULL,
		    0) == 0;
		regfree(&re);
	} else {
		rv = 0;
	}
	return rv;
#elif defined(REGEXP)
	if ((re = regcomp(ct_encode_string(pat, &conv))) != NULL) {
		rv = regexec(re, ct_encode_string(str, &conv));
		el_free(re);
	} else {
		rv = 0;
	}
	return rv;
#else
	if (re_comp(ct_encode_string(pat, &conv)) != NULL)
		return 0;
	else
		return re_exec(ct_encode_string(str, &conv)) == 1;
#endif
}


/* c_hmatch():
 *	 return True if the pattern matches the prefix
 */
libedit_private int
c_hmatch(EditLine *el, const wchar_t *str)
{
#ifdef SDEBUG
	(void) fprintf(el->el_errfile, "match `%s' with `%s'\n",
	    el->el_search.patbuf, str);
#endif /* SDEBUG */

	return el_match(str, el->el_search.patbuf);
}


/* c_setpat():
 *	Set the history seatch pattern
 */
libedit_private void
c_setpat(EditLine *el)
{
	if (el->el_state.lastcmd != ED_SEARCH_PREV_HISTORY &&
	    el->el_state.lastcmd != ED_SEARCH_NEXT_HISTORY) {
		el->el_search.patlen =
		    (size_t)(EL_CURSOR(el) - el->el_line.buffer);
		if (el->el_search.patlen >= EL_BUFSIZ)
			el->el_search.patlen = EL_BUFSIZ - 1;
		if (el->el_search.patlen != 0) {
			(void) wcsncpy(el->el_search.patbuf, el->el_line.buffer,
			    el->el_search.patlen);
			el->el_search.patbuf[el->el_search.patlen] = '\0';
		} else
			el->el_search.patlen = wcslen(el->el_search.patbuf);
	}
#ifdef SDEBUG
	(void) fprintf(el->el_errfile, "\neventno = %d\n",
	    el->el_history.eventno);
	(void) fprintf(el->el_errfile, "patlen = %d\n", el->el_search.patlen);
	(void) fprintf(el->el_errfile, "patbuf = \"%s\"\n",
	    el->el_search.patbuf);
	(void) fprintf(el->el_errfile, "cursor %d lastchar %d\n",
	    EL_CURSOR(el) - el->el_line.buffer,
	    el->el_line.lastchar - el->el_line.buffer);
#endif
}


/* ce_inc_search():
 *	Emacs incremental search
 */
libedit_private el_action_t
ce_inc_search(EditLine *el, int dir)
{
	static const wchar_t STRfwd[] = L"fwd", STRbck[] = L"bck";
	static wchar_t pchar = L':';  /* ':' = normal, '?' = failed */
	static wchar_t endcmd[2] = {'\0', '\0'};
	wchar_t *ocursor = el->el_line.cursor, oldpchar = pchar, ch;
	const wchar_t *cp;

	el_action_t ret = CC_NORM;

	int ohisteventno = el->el_history.eventno;
	size_t oldpatlen = el->el_search.patlen;
	int newdir = dir;
	int done, redo;

	if (el->el_line.lastchar + sizeof(STRfwd) /
	    sizeof(*el->el_line.lastchar) + 2 +
	    el->el_search.patlen >= el->el_line.limit)
		return CC_ERROR;

	for (;;) {

		if (el->el_search.patlen == 0) {	/* first round */
			pchar = ':';
#ifdef ANCHOR
#define	LEN	2
			el->el_search.patbuf[el->el_search.patlen++] = '.';
			el->el_search.patbuf[el->el_search.patlen++] = '*';
#else
#define	LEN	0
#endif
		}
		done = redo = 0;
		*el->el_line.lastchar++ = '\n';
		for (cp = (newdir == ED_SEARCH_PREV_HISTORY) ? STRbck : STRfwd;
		    *cp; *el->el_line.lastchar++ = *cp++)
			continue;
		*el->el_line.lastchar++ = pchar;
		for (cp = &el->el_search.patbuf[LEN];
		    cp < &el->el_search.patbuf[el->el_search.patlen];
		    *el->el_line.lastchar++ = *cp++)
			continue;
		*el->el_line.lastchar = '\0';
		re_refresh(el);

		if (el_wgetc(el, &ch) != 1)
			return ed_end_of_file(el, 0);

		switch (el->el_map.current[(unsigned char) ch]) {
		case ED_INSERT:
		case ED_DIGIT:
			if (el->el_search.patlen >= EL_BUFSIZ - LEN)
				terminal_beep(el);
			else {
				el->el_search.patbuf[el->el_search.patlen++] =
				    ch;
				*el->el_line.lastchar++ = ch;
				*el->el_line.lastchar = '\0';
				re_refresh(el);
			}
			break;

		case EM_INC_SEARCH_NEXT:
			newdir = ED_SEARCH_NEXT_HISTORY;
			redo++;
			break;

		case EM_INC_SEARCH_PREV:
			newdir = ED_SEARCH_PREV_HISTORY;
			redo++;
			break;

		case EM_DELETE_PREV_CHAR:
		case ED_DELETE_PREV_CHAR:
			if (el->el_search.patlen > LEN)
				done++;
			else
				terminal_beep(el);
			break;

		default:
			switch (ch) {
			case 0007:	/* ^G: Abort */
				ret = CC_ERROR;
				done++;
				break;

			case 0027:	/* ^W: Append word */
			/* No can do if globbing characters in pattern */
				for (cp = &el->el_search.patbuf[LEN];; cp++)
				    if (cp >= &el->el_search.patbuf[
					el->el_search.patlen]) {
					el->el_line.cursor +=
					    el->el_search.patlen - LEN - 1;
					cp = c__next_word(el->el_line.cursor,
					    el->el_line.lastchar, 1,
					    ce__isword);
					while (el->el_line.cursor < cp &&
					    *el->el_line.cursor != '\n') {
						if (el->el_search.patlen >=
						    EL_BUFSIZ - LEN) {
							terminal_beep(el);
							break;
						}
						el->el_search.patbuf[el->el_search.patlen++] =
						    *el->el_line.cursor;
						*el->el_line.lastchar++ =
						    *el->el_line.cursor++;
					}
					el->el_line.cursor = ocursor;
					*el->el_line.lastchar = '\0';
					re_refresh(el);
					break;
				    } else if (isglob(*cp)) {
					    terminal_beep(el);
					    break;
				    }
				break;

			default:	/* Terminate and execute cmd */
				endcmd[0] = ch;
				el_wpush(el, endcmd);
				/* FALLTHROUGH */

			case 0033:	/* ESC: Terminate */
				ret = CC_REFRESH;
				done++;
				break;
			}
			break;
		}

		while (el->el_line.lastchar > el->el_line.buffer &&
		    *el->el_line.lastchar != '\n')
			*el->el_line.lastchar-- = '\0';
		*el->el_line.lastchar = '\0';

		if (!done) {

			/* Can't search if unmatched '[' */
			for (cp = &el->el_search.patbuf[el->el_search.patlen-1],
			    ch = L']';
			    cp >= &el->el_search.patbuf[LEN];
			    cp--)
				if (*cp == '[' || *cp == ']') {
					ch = *cp;
					break;
				}
			if (el->el_search.patlen > LEN && ch != L'[') {
				if (redo && newdir == dir) {
					if (pchar == '?') { /* wrap around */
						el->el_history.eventno =
						    newdir == ED_SEARCH_PREV_HISTORY ? 0 : 0x7fffffff;
						if (hist_get(el) == CC_ERROR)
							/* el->el_history.event
							 * no was fixed by
							 * first call */
							(void) hist_get(el);
						el->el_line.cursor = newdir ==
						    ED_SEARCH_PREV_HISTORY ?
						    el->el_line.lastchar :
						    el->el_line.buffer;
					} else
						el->el_line.cursor +=
						    newdir ==
						    ED_SEARCH_PREV_HISTORY ?
						    -1 : 1;
				}
#ifdef ANCHOR
				el->el_search.patbuf[el->el_search.patlen++] =
				    '.';
				el->el_search.patbuf[el->el_search.patlen++] =
				    '*';
#endif
				el->el_search.patbuf[el->el_search.patlen] =
				    '\0';
				if (el->el_line.cursor < el->el_line.buffer ||
				    el->el_line.cursor > el->el_line.lastchar ||
				    (ret = ce_search_line(el, newdir))
				    == CC_ERROR) {
					/* avoid c_setpat */
					el->el_state.lastcmd =
					    (el_action_t) newdir;
					ret = (el_action_t)
					    (newdir == ED_SEARCH_PREV_HISTORY ?
					    ed_search_prev_history(el, 0) :
					    ed_search_next_history(el, 0));
					if (ret != CC_ERROR) {
						el->el_line.cursor = newdir ==
						    ED_SEARCH_PREV_HISTORY ?
						    el->el_line.lastchar :
						    el->el_line.buffer;
						(void) ce_search_line(el,
						    newdir);
					}
				}
				el->el_search.patlen -= LEN;
				el->el_search.patbuf[el->el_search.patlen] =
				    '\0';
				if (ret == CC_ERROR) {
					terminal_beep(el);
					if (el->el_history.eventno !=
					    ohisteventno) {
						el->el_history.eventno =
						    ohisteventno;
						if (hist_get(el) == CC_ERROR)
							return CC_ERROR;
					}
					el->el_line.cursor = ocursor;
					pchar = '?';
				} else {
					pchar = ':';
				}
			}
			ret = ce_inc_search(el, newdir);

			if (ret == CC_ERROR && pchar == '?' && oldpchar == ':')
				/*
				 * break abort of failed search at last
				 * non-failed
				 */
				ret = CC_NORM;

		}
		if (ret == CC_NORM || (ret == CC_ERROR && oldpatlen == 0)) {
			/* restore on normal return or error exit */
			pchar = oldpchar;
			el->el_search.patlen = oldpatlen;
			if (el->el_history.eventno != ohisteventno) {
				el->el_history.eventno = ohisteventno;
				if (hist_get(el) == CC_ERROR)
					return CC_ERROR;
			}
			el->el_line.cursor = ocursor;
			if (ret == CC_ERROR)
				re_refresh(el);
		}
		if (done || ret != CC_NORM)
			return ret;
	}
}


/* cv_search():
 *	Vi search.
 */
libedit_private el_action_t
cv_search(EditLine *el, int dir)
{
	wchar_t ch;
	wchar_t tmpbuf[EL_BUFSIZ];
	ssize_t tmplen;

#ifdef ANCHOR
	tmpbuf[0] = '.';
	tmpbuf[1] = '*';
#endif
	tmplen = LEN;

	el->el_search.patdir = dir;

	tmplen = c_gets(el, &tmpbuf[LEN],
		dir == ED_SEARCH_PREV_HISTORY ? L"\n/" : L"\n?" );
	if (tmplen == -1)
		return CC_REFRESH;

	tmplen += LEN;
	ch = tmpbuf[tmplen];
	tmpbuf[tmplen] = '\0';

	if (tmplen == LEN) {
		/*
		 * Use the old pattern, but wild-card it.
		 */
		if (el->el_search.patlen == 0) {
			re_refresh(el);
			return CC_ERROR;
		}
#ifdef ANCHOR
		if (el->el_search.patbuf[0] != '.' &&
		    el->el_search.patbuf[0] != '*') {
			(void) wcsncpy(tmpbuf, el->el_search.patbuf,
			    sizeof(tmpbuf) / sizeof(*tmpbuf) - 1);
			el->el_search.patbuf[0] = '.';
			el->el_search.patbuf[1] = '*';
			(void) wcsncpy(&el->el_search.patbuf[2], tmpbuf,
			    EL_BUFSIZ - 3);
			el->el_search.patlen++;
			el->el_search.patbuf[el->el_search.patlen++] = '.';
			el->el_search.patbuf[el->el_search.patlen++] = '*';
			el->el_search.patbuf[el->el_search.patlen] = '\0';
		}
#endif
	} else {
#ifdef ANCHOR
		tmpbuf[tmplen++] = '.';
		tmpbuf[tmplen++] = '*';
#endif
		tmpbuf[tmplen] = '\0';
		(void) wcsncpy(el->el_search.patbuf, tmpbuf, EL_BUFSIZ - 1);
		el->el_search.patlen = (size_t)tmplen;
	}
	el->el_state.lastcmd = (el_action_t) dir;	/* avoid c_setpat */
	el->el_line.cursor = el->el_line.lastchar = el->el_line.buffer;
	if ((dir == ED_SEARCH_PREV_HISTORY ? ed_search_prev_history(el, 0) :
	    ed_search_next_history(el, 0)) == CC_ERROR) {
		re_refresh(el);
		return CC_ERROR;
	}
	if (ch == 0033) {
		re_refresh(el);
		return ed_newline(el, 0);
	}
	return CC_REFRESH;
}


/* ce_search_line():
 *	Look for a pattern inside a line
 */
libedit_private el_action_t
ce_search_line(EditLine *el, int dir)
{
	wchar_t *cp = el->el_line.cursor;
	wchar_t *pattern = el->el_search.patbuf;
	wchar_t oc, *ocp;
#ifdef ANCHOR
	ocp = &pattern[1];
	oc = *ocp;
	*ocp = '^';
#else
	ocp = pattern;
	oc = *ocp;
#endif

	if (dir == ED_SEARCH_PREV_HISTORY) {
		for (; cp >= el->el_line.buffer; cp--) {
			if (el_match(cp, ocp)) {
				*ocp = oc;
				el->el_line.cursor = cp;
				return CC_NORM;
			}
		}
		*ocp = oc;
		return CC_ERROR;
	} else {
		for (; *cp != '\0' && cp < el->el_line.limit; cp++) {
			if (el_match(cp, ocp)) {
				*ocp = oc;
				el->el_line.cursor = cp;
				return CC_NORM;
			}
		}
		*ocp = oc;
		return CC_ERROR;
	}
}


/* cv_repeat_srch():
 *	Vi repeat search
 */
libedit_private el_action_t
cv_repeat_srch(EditLine *el, wint_t c)
{

#ifdef SDEBUG
	(void) fprintf(el->el_errfile, "dir %d patlen %d patbuf %s\n",
	    c, el->el_search.patlen, ct_encode_string(el->el_search.patbuf));
#endif

	el->el_state.lastcmd = (el_action_t) c;	/* Hack to stop c_setpat */
	el->el_line.lastchar = el->el_line.buffer;

	switch (c) {
	case ED_SEARCH_NEXT_HISTORY:
		return ed_search_next_history(el, 0);
	case ED_SEARCH_PREV_HISTORY:
		return ed_search_prev_history(el, 0);
	default:
		return CC_ERROR;
	}
}


/* cv_csearch():
 *	Vi character search
 */
libedit_private el_action_t
cv_csearch(EditLine *el, int direction, wint_t ch, int count, int tflag)
{
	wchar_t *cp;

	if (ch == 0)
		return CC_ERROR;

	if (ch == (wint_t)-1) {
		if (el_wgetc(el, &ch) != 1)
			return ed_end_of_file(el, 0);
	}

	/* Save for ';' and ',' commands */
	el->el_search.chacha = ch;
	el->el_search.chadir = direction;
	el->el_search.chatflg = (char)tflag;

	cp = el->el_line.cursor;
	while (count--) {
		if ((wint_t)*cp == ch)
			cp += direction;
		for (;;cp += direction) {
			if (cp >= el->el_line.lastchar)
				return CC_ERROR;
			if (cp < el->el_line.buffer)
				return CC_ERROR;
			if ((wint_t)*cp == ch)
				break;
		}
	}

	if (tflag)
		cp -= direction;

	el->el_line.cursor = cp;

	if (el->el_chared.c_vcmd.action != NOP) {
		if (direction > 0)
			el->el_line.cursor++;
		cv_delfini(el);
		return CC_REFRESH;
	}
	return CC_CURSOR;
}