Debian Codegraph @

reapp.c

raw
1 /**************************************************************************
2 * This program is Copyright (C) 1986-2002 by Jonathan Payne. JOVE is *
3 * provided by Jonathan and Jovehacks without charge and without *
4 * warranty. You may copy, modify, and/or distribute JOVE, provided that *
5 * this notice is included in all the source files and documentation. *
6 **************************************************************************/
7
8 /* regular expression applications: search, replace, and tags */
9
10 #include "jove.h"
11 #include "fp.h"
12 #include "re.h"
13 #include "jctype.h"
14 #include "chars.h"
15 #include "disp.h"
16 #include "ask.h"
17 #include "extend.h" /* for chr_to_* */
18 #include "fmt.h"
19 #include "marks.h"
20 #include "reapp.h"
21 #include "wind.h"
22
23 #ifdef MAC
24 # include "mac.h"
25 #else
26 # include <sys/stat.h>
27 #endif
28
29 private void
30 IncSearch(int);
31
32 private int
33 isearch(int, Bufpos *);
34
35 private char
36 searchstr[128]; /* global search string */
37
38 jbool
39 UseRE = NO; /* VAR: use regular expressions in search */
40
41 private void
42 setsearch(const char *str)
43 {
44 jamstr(searchstr, str);
45 }
46
47 private char *
48 getsearch(void)
49 {
50 return searchstr;
51 }
52
53 private void
54 search(int dir, jbool re, jbool setdefault)
55 {
56 Bufpos *newdot;
57 const char *s = ask(searchstr, ProcFmt);
58
59 if (setdefault)
60 setsearch(s);
61 okay_wrap = YES;
62 newdot = dosearch(s, dir, re);
63 okay_wrap = NO;
64 if (newdot == NULL) {
65 if (WrapScan) {
66 complain("No \"%s\" in buffer.", s);
67 /* NOTREACHED */
68 } else {
69 complain("No \"%s\" found to %s.", s,
70 (dir == FORWARD) ? "bottom" : "top");
71 /* NOTREACHED */
72 }
73 }
74 PushPntp(newdot->p_line);
75 SetDot(newdot);
76 }
77
78 void
79 ForSearch(void)
80 {
81 search(FORWARD, UseRE, YES);
82 }
83
84 void
85 RevSearch(void)
86 {
87 search(BACKWARD, UseRE, YES);
88 }
89
90 void
91 FSrchND(void)
92 {
93 search(FORWARD, UseRE, NO);
94 }
95
96 void
97 RSrchND(void)
98 {
99 search(BACKWARD, UseRE, NO);
100 }
101
102 private int
103 substitute(struct RE_block *re_blk, jbool query,
104 LinePtr l1, int char1,
105 LinePtr l2, int char2)
106 {
107 LinePtr lp;
108 int numdone = 0,
109 UNDO_nd = 0,
110 offset = char1;
111 jbool stop = NO;
112 daddr UNDO_da = NULL_DADDR;
113 LinePtr UNDO_lp = NULL;
114
115 lsave();
116
117 for (lp = l1; lp != l2->l_next; lp = lp->l_next) {
118 int crater = -1; /* end of last substitution on this line */
119 jbool LineDone = NO; /* already replaced last empty string on line? */
120
121 while (!LineDone
122 && re_lindex(lp, offset, FORWARD, re_blk, NO, crater)
123 && (lp != l2 || REeom <= char2))
124 {
125 DotTo(lp, REeom);
126 offset = curchar;
127 if (query) {
128 ZXchar c;
129
130 message("Replace (Type '?' for help)? ");
131 reswitch:
132 redisplay();
133 c = kbd_getch();
134 if (c == AbortChar)
135 return numdone;
136
137 switch (CharUpcase(c)) {
138 case '.':
139 stop = YES;
140 /*FALLTHROUGH*/
141 case ' ':
142 case 'Y':
143 break;
144
145 case BS:
146 case DEL:
147 case 'N':
148 if (REbom == REeom) {
149 offset += 1;
150 if (linebuf[REeom] == '\0')
151 LineDone = YES;
152 }
153 continue;
154
155 case CTL('W'):
156 re_dosub(re_blk, linebuf, YES);
157 if (lp == l2)
158 char2 += REdelta;
159 modify();
160 numdone += 1;
161 curchar = REbom;
162 makedirty(curline);
163 /*FALLTHROUGH*/
164 case CTL('R'):
165 case 'R':
166 RErecur();
167 UNDO_lp = NULL; /* can't reliably undo this */
168 offset = curchar;
169 lp = curline;
170 continue;
171
172 case CTL('U'):
173 case 'U':
174 if (UNDO_lp == NULL) {
175 rbell();
176 goto reswitch;
177 }
178 lp = UNDO_lp;
179 lp->l_dline = UNDO_da;
180 if (UNDO_lp == curline)
181 getDOT(); /* downdate line cache */
182 makedirty(lp);
183 offset = 0;
184 numdone = UNDO_nd;
185 UNDO_lp = NULL;
186 continue;
187
188 case 'P':
189 case '!':
190 query = NO;
191 break;
192
193 case CR:
194 case LF:
195 case 'Q':
196 return numdone;
197
198 case CTL('L'):
199 RedrawDisplay();
200 goto reswitch;
201
202 default:
203 rbell();
204 message("Space or Y, Period, Delete or N, ^R or R, ^W, ^U or U, P or !, Return.");
205 goto reswitch;
206 }
207 }
208 if (UNDO_lp != curline) {
209 UNDO_da = curline->l_dline;
210 UNDO_lp = curline;
211 UNDO_nd = numdone;
212 }
213 if (REbom == REeom && linebuf[REeom] == '\0')
214 LineDone = YES;
215 re_dosub(re_blk, linebuf, NO);
216 if (lp == l2)
217 char2 += REdelta;
218 numdone += 1;
219 modify();
220 crater = offset = curchar = REeom;
221 makedirty(curline);
222 if (query) {
223 message(mesgbuf); /* no blinking */
224 redisplay(); /* show the change */
225 }
226 if (stop)
227 return numdone;
228 }
229 offset = 0;
230 }
231 return numdone;
232 }
233
234 /* prompt for search and replacement strings and do the substitution */
235 private void
236 replace(jbool query, jbool inreg)
237 {
238 LinePtr l1 = curline,
239 l2 = curbuf->b_last;
240 int char1 = curchar,
241 char2 = length(curbuf->b_last),
242 numdone;
243 struct RE_block re_blk;
244
245 if (inreg) {
246 Mark *m = CurMark();
247
248 l2 = m->m_line;
249 char2 = m->m_char;
250 (void) fixorder(&l1, &char1, &l2, &char2);
251 }
252
253 /* get search string */
254 jamstr(rep_search,
255 ask(rep_search[0] ? rep_search : (char *)NULL, ProcFmt));
256 REcompile(rep_search, UseRE, &re_blk);
257
258 /* Now the replacement string. Do_ask() so the user can play with
259 * the default (previous) replacement string by typing ^R in ask(),
260 * OR, can just hit Return to replace with nothing.
261 */
262 {
263 const char *rp = do_ask("\r\n",
264 NULL_ASK_EXT, rep_str, ": %f %s with ", rep_search);
265
266 jamstr(rep_str, rp == NULL? NullStr : rp);
267 }
268
269 if ((numdone = substitute(&re_blk, query, l1, char1, l2, char2)) != 0
270 && !inreg) {
271 do_set_mark(l1, char1);
272 add_mess(" "); /* just making things pretty */
273 } else {
274 message(NullStr);
275 }
276 add_mess("(%d substitution%n)", numdone, numdone);
277 }
278
279 void
280 RegReplace(void)
281 {
282 replace(NO, YES);
283 }
284
285 void
286 QRepSearch(void)
287 {
288 replace(YES, NO);
289 }
290
291 void
292 RepSearch(void)
293 {
294 replace(NO, NO);
295 }
296
297 /* Lookup a tag in tag file FILE. FILE is assumed to be sorted
298 * alphabetically. The FASTTAGS code, which is implemented with
299 * a binary search, depends on this assumption. If it's not true
300 * it is possible to comment out the fast tag code (which is clearly
301 * labeled), delete the marked test in the sequential loop, and
302 * everything else will just work.
303 */
304 private jbool
305 lookup_tag(jbool *ispat, char *searchbuf, size_t sbsize,
306 char *filebuf, char *tag, char *file)
307 {
308 size_t taglen = strlen(tag);
309 char line[JBUFSIZ],
310 pattern[200];
311 File *fp;
312 struct stat
313 stbuf;
314 jbool success = NO;
315
316 fp = open_file(file, iobuff, F_READ, NO);
317 if (fp == NULL) {
318 message(IOerr("open", file));
319 return NO;
320 }
321 /* Build a pattern to parse the tag line.
322 *
323 * - the tag name is at the start of the line.
324 * Since our name may only be a prefix, ignore
325 * the rest of the tab-terminated field.
326 * ^%s[^\t]*\t
327 *
328 * - a file name, terminated by a tab.
329 * Use parens to capture the field as \1:
330 * \\([^\t]*\\)\t
331 *
332 * - EITHER: a pattern to match for the
333 * start of the object within the source file.
334 * Capture the delimiter as \2 and the pattern as \3.
335 * \\([?/]\\)\\(.*\\)\\2
336 * OR: a line number.
337 * Capture the lack-of-delimiter in \2 and the number in \3.
338 * \\(\\)\\([0-9]*\\)
339 *
340 * - possible gunge in the form of an ex(1) comment:
341 * \\{;".*\\|\\}
342 *
343 * - the end
344 * $
345 *
346 * Some tag lines collected in the wild:
347 * AddError proc.c /^AddError(laste, errline, buf, line, charpos)$/
348 * AddError proc.c /^AddError(laste, errline, buf, line, charpos)$/;" f
349 * AT_BOL re.c 49;" d file:
350 */
351 swritef(pattern, sizeof(pattern),
352 /*tag name
353 *======== file name
354 * ============ pattern
355 * ===================== line number
356 * ================= gunge
357 * =============
358 */
359 "^%s[^\t]*\t\\([^\t]*\\)\t\\{\\([?/]\\)\\(.*\\)\\2\\|\\(\\)\\([0-9]*\\)\\}\\{;\".*\\|\\}$",
360 tag);
361
362 /* ********BEGIN FAST TAG CODE******** */
363
364 /* Mac doesn't have fstat */
365 #ifdef MAC
366 if (stat(file, &stbuf) >= 0)
367 #else
368 if (fstat(fp->f_fd, &stbuf) >= 0)
369 #endif
370 {
371 /* Invariant: if there is a line matching the tag, it
372 * begins somewhere after position lower, and begins
373 * at or before upper. There is one possible
374 * exception: if lower is 0, the line with the tag
375 * might be the very first line.
376 *
377 * When this loop is done, we seek to lower, advance
378 * past the next newline (unless lower is 0), and fall
379 * into the sequential search.
380 */
381 off_t lower = 0,
382 upper = stbuf.st_size;
383
384 for (;;) {
385 off_t mid;
386 int chars_eq;
387
388 if (upper - lower < JBUFSIZ)
389 break; /* small range: search sequentially */
390
391 mid = (lower + upper) / 2;
392 f_seek(fp, mid); /* mid will not be 0 */
393 f_toNL(fp);
394 if (f_gets(fp, line, sizeof line))
395 break; /* unexpected: bail out */
396
397 chars_eq = numcomp(line, tag);
398 if ((size_t)chars_eq == taglen && jiswhite(line[chars_eq])) {
399 /* we hit the exact line: get out */
400 lower = mid;
401 break;
402 }
403 if (line[chars_eq] < tag[chars_eq])
404 lower = mid; /* line is BEFORE tag */
405 else
406 upper = mid; /* line is AFTER tag */
407 }
408 /* sequentially search from lower */
409 f_seek(fp, lower);
410 if (lower > 0)
411 f_toNL(fp);
412 }
413
414 /* END FAST TAG CODE */
415
416 while (!f_gets(fp, line, sizeof line)) {
417 int cmp = line[0] - *tag;
418
419 if (cmp == 0) {
420 cmp = strncmp(line, tag, taglen);
421 if (cmp == 0) {
422 /* we've found the match */
423 if (!LookingAt(pattern, line, 0)) {
424 complain("tag line confuses me: %s", line);
425 /* NOTREACHED */
426
427 } else {
428 char patdelim[2];
429
430 putmatch(1, filebuf, (size_t)FILESIZE);
431 putmatch(2, patdelim, sizeof(patdelim));
432 putmatch(3, searchbuf, sbsize);
433 *ispat = patdelim[0] != '\0';
434 success = YES;
435 }
436 break;
437 }
438 }
439 if (cmp > 0)
440 break; /* failure: gone too far. PRESUMES ALPHABETIC ORDER */
441 }
442 close_file(fp);
443
444 if (!success)
445 s_mess("Can't find tag \"%s\".", tag);
446 return success;
447 }
448
449 char TagFile[FILESIZE] = "tags"; /* VAR: default tag file */
450
451 void
452 find_tag(char *tag, jbool localp)
453 {
454 char filebuf[FILESIZE],
455 sstr[200], /* 100 wasn't big enough */
456 tfbuf[FILESIZE];
457 Bufpos *bp;
458 Buffer *b;
459 jbool ispat;
460
461 if (lookup_tag(&ispat, sstr, sizeof(sstr), filebuf, tag,
462 localp? TagFile : ask_file("With tag file ", TagFile, tfbuf)))
463 {
464 set_mark();
465 b = do_find(curwind, filebuf, YES, NO);
466 if (curbuf != b)
467 SetABuf(curbuf);
468 SetBuf(b);
469 if (ispat) {
470 if ((bp = dosearch(sstr, BACKWARD, NO)) == NULL
471 && (bp = dosearch(sstr, FORWARD, NO)) == NULL)
472 message("Well, I found the file, but the tag is missing.");
473 else
474 SetDot(bp);
475 } else {
476 long lnum = 0; /* keep gcc -W quiet */
477
478 if (chr_to_long(sstr, 10, YES, &lnum) != YES || lnum < 1) {
479 swritef(mesgbuf, sizeof mesgbuf, "Invalid line number: %s", sstr);
480 message(mesgbuf);
481 } else {
482 LinePtr tagline = next_line(curbuf->b_first, lnum - 1);
483
484 PushPntp(tagline);
485 SetLine(tagline);
486 }
487 }
488 }
489 }
490
491 void
492 FindTag(void)
493 {
494 jbool localp = !is_an_arg();
495 char tag[128];
496
497 jamstr(tag, ask((char *)NULL, ProcFmt));
498 find_tag(tag, localp);
499 }
500
501 /* Find Tag at Dot. */
502
503 void
504 FDotTag(void)
505 {
506 int c1 = curchar,
507 c2 = c1;
508 char tagname[50];
509
510 if (!jisident(linebuf[curchar])) {
511 complain("Not a tag!");
512 /* NOTREACHED */
513 }
514 while (c1 > 0 && jisident(linebuf[c1 - 1]))
515 c1 -= 1;
516 while (jisident(linebuf[c2]))
517 c2 += 1;
518 if ((c2 - c1) >= (int)sizeof(tagname)) {
519 complain("tag too long");
520 /* NOTREACHED */
521 }
522 null_ncpy(tagname, linebuf + c1, (size_t) (c2 - c1));
523 find_tag(tagname, !is_an_arg());
524 }
525
526 /* I-search returns a code saying what to do:
527 * I_STOP: We found the match, so unwind the stack and leave
528 * where it is.
529 * I_DELETE: Rubout the last command.
530 * I_BACKUP: Back up to where the isearch was last NOT failing.
531 * I_TOSTART: Abort the search, going back where isearch started
532 *
533 * When a character is typed it is appended to the search string, and
534 * then, isearch is called recursively. When ^S or ^R is typed, isearch
535 * is again called recursively.
536 */
537 #define I_STOP 1
538 #define I_DELETE 2
539 #define I_BACKUP 3
540 #define I_TOSTART 4
541
542 private char
543 ISbuf[128],
544 *incp = NULL;
545
546 ZXchar SExitChar = CR; /* VAR: type this to stop i-search */
547
548 private Bufpos *
549 doisearch(int dir, ZXchar c, jbool failing)
550 {
551 static Bufpos buf;
552 Bufpos *bp;
553
554 if (c != CTL('S') && c != CTL('R')) {
555 if (failing)
556 return NULL;
557
558 DOTsave(&buf);
559 if (dir == FORWARD) {
560 if (ZXC(linebuf[curchar]) == c
561 || (CaseIgnore && cind_eq(linebuf[curchar], c))) {
562 buf.p_char = curchar + 1;
563 return &buf;
564 }
565 } else {
566 if (look_at(ISbuf))
567 return &buf;
568 }
569 }
570 okay_wrap = YES;
571 if ((bp = dosearch(ISbuf, dir, NO)) == NULL)
572 rbell(); /* ring the first time there's no match */
573 okay_wrap = NO;
574 return bp;
575 }
576
577 void
578 IncFSearch(void)
579 {
580 IncSearch(FORWARD);
581 }
582
583 void
584 IncRSearch(void)
585 {
586 IncSearch(BACKWARD);
587 }
588
589 private void
590 IncSearch(int dir)
591 {
592 Bufpos save_env;
593
594 DOTsave(&save_env);
595 ISbuf[0] = '\0';
596 incp = ISbuf;
597 if (isearch(dir, &save_env) == I_TOSTART)
598 SetDot(&save_env);
599 else {
600 if (LineDist(curline, save_env.p_line) >= MarkThresh)
601 do_set_mark(save_env.p_line, save_env.p_char);
602 }
603 setsearch(ISbuf);
604 }
605
606 /* Nicely recursive. */
607
608 private int
609 isearch(int dir, Bufpos *bp)
610 {
611 Bufpos pushbp;
612 ZXchar c;
613 int ndir;
614 jbool failing;
615 char *orig_incp;
616
617 if (bp != NULL) { /* Move to the new position. */
618 pushbp.p_line = bp->p_line;
619 pushbp.p_char = bp->p_char;
620 SetDot(bp);
621 failing = NO;
622 } else {
623 DOTsave(&pushbp);
624 failing = YES;
625 }
626 orig_incp = incp;
627 ndir = dir; /* Same direction as when we got here, unless
628 we change it with ^S or ^R. */
629 for (;;) {
630 SetDot(&pushbp);
631 message(NullStr);
632 if (failing)
633 add_mess("Failing ");
634 if (dir == BACKWARD)
635 add_mess("reverse-");
636 add_mess("I-search: %s", ISbuf);
637 DrawMesg(NO);
638 add_mess(NullStr); /* tell me this is disgusting ... */
639 c = getch();
640 if (c == SExitChar)
641 return I_STOP;
642
643 if (c == AbortChar) {
644 /* If we're failing, we backup until we're no longer
645 * failing or we've reached the beginning; else, we
646 * just abort the search and go back to the start.
647 */
648 return failing? I_BACKUP : I_TOSTART;
649 }
650 switch (c) {
651 case DEL:
652 case BS:
653 return I_DELETE;
654
655 case CTL('\\'):
656 c = CTL('S');
657 /*FALLTHROUGH*/
658 case CTL('S'):
659 case CTL('R'):
660 /* If this is the first time through and we have a
661 * search string left over from last time, and Inputp
662 * is not in use [kludge!], use that one now.
663 */
664 if (Inputp == NULL && incp == ISbuf) {
665 Inputp = getsearch();
666 continue;
667 }
668 ndir = (c == CTL('S')) ? FORWARD : BACKWARD;
669 /* If we're failing and we're not changing our
670 * direction, don't recur since there's no way
671 * the search can work.
672 */
673 if (failing && ndir == dir) {
674 rbell();
675 continue;
676 }
677 break;
678
679 case '\\':
680 if (incp > &ISbuf[(sizeof ISbuf) - 1]) {
681 rbell();
682 continue;
683 }
684 *incp++ = '\\';
685 add_mess("\\");
686 /*FALLTHROUGH*/
687 case CTL('Q'):
688 case CTL('^'):
689 add_mess(NullStr);
690 c = getch();
691 goto literal;
692
693 default:
694 /* check for "funny" characters */
695 if (!jisprint(c) || IsPrefixChar(c)) {
696 Ungetc(c);
697 return I_STOP;
698 }
699 /*FALLTHROUGH*/
700 case '\t':
701 literal:
702 if (incp > &ISbuf[(sizeof ISbuf) - 1]) {
703 rbell();
704 continue;
705 }
706 *incp++ = c;
707 *incp = '\0';
708 break;
709 }
710 add_mess("%s", orig_incp);
711 add_mess(" ..."); /* so we know what's going on */
712 DrawMesg(NO); /* do it now */
713 switch (isearch(ndir, doisearch(ndir, c, failing))) {
714 case I_TOSTART:
715 return I_TOSTART;
716
717 case I_STOP:
718 return I_STOP;
719
720 case I_BACKUP:
721 /* If we're not failing, we just continue to to the
722 * for loop; otherwise we keep returning to the
723 * previous levels until we find one that isn't
724 * failing OR we reach the beginning.
725 */
726 if (failing)
727 return I_BACKUP;
728
729 /*FALLTHROUGH*/
730 case I_DELETE:
731 incp = orig_incp;
732 *incp = '\0';
733 continue;
734 }
735 }
736 }