home *** CD-ROM | disk | FTP | other *** search
/ Power Programming / powerprogramming1994.iso / progtool / editor / j414src.arc / RE1.C < prev    next >
C/C++ Source or Header  |  1989-10-10  |  14KB  |  614 lines

  1. /***************************************************************************
  2.  * This program is Copyright (C) 1986, 1987, 1988 by Jonathan Payne.  JOVE *
  3.  * is provided to you without charge, and with no warranty.  You may give  *
  4.  * away copies of JOVE, including sources, provided that this notice is    *
  5.  * included in all the files.                                              *
  6.  ***************************************************************************/
  7.  
  8. #include "jove.h"
  9. #include "fp.h"
  10. #include "re.h"
  11. #include "ctype.h"
  12. #include "chars.h"
  13. #include "disp.h"
  14.  
  15. #ifdef MAC
  16. # include "mac.h"
  17. #else
  18. # include <sys/stat.h>
  19. #endif
  20.  
  21. private Bufpos *doisearch proto((int, int, int));
  22.  
  23. private void
  24.     IncSearch proto((int)),
  25.     replace proto((int, int));
  26. private int
  27.     isearch proto((int, Bufpos *)),
  28.     lookup proto((char *, char *, char *, char *)),
  29.     substitute proto((struct RE_block *, int, Line *, int, Line *, int));
  30.  
  31. private int
  32. substitute(re_blk, query, l1, char1, l2, char2)
  33. struct RE_block    *re_blk;
  34. Line    *l1,
  35.     *l2;
  36. int    query,
  37.     char1,
  38.     char2;
  39. {
  40.     Line    *lp;
  41.     int    numdone = 0,
  42.         UNDO_nd = 0,
  43.         offset = char1,
  44.         stop = NO;
  45.     daddr    UNDO_da = 0;
  46.     Line    *UNDO_lp = NULL;
  47.  
  48.     lsave();
  49.     REdirection = FORWARD;
  50.  
  51.     for (lp = l1; lp != l2->l_next; lp = lp->l_next) {
  52.         int    crater = -1;    /* end of last substitution on this line */
  53.         int    LineDone = NO;    /* already replaced last empty string on line? */
  54.  
  55.         while (!LineDone
  56.         && re_lindex(lp, offset, re_blk, NO, crater)
  57.         && (lp != l2 || REeom <= char2))
  58.         {
  59.             DotTo(lp, REeom);
  60.             offset = curchar;
  61.             if (query) {
  62.                 int    c;
  63.  
  64.                 message("Replace (Type '?' for help)? ");
  65. reswitch:
  66.                 redisplay();
  67.                 c = jgetchar();
  68.                 if (c == AbortChar)
  69.                     return numdone;
  70.  
  71.                 switch (CharUpcase(c)) {
  72.                 case '.':
  73.                     stop = YES;
  74.                     /*FALLTHROUGH*/
  75.                 case ' ':
  76.                 case 'Y':
  77.                     break;
  78.  
  79.                 case BS:
  80.                 case RUBOUT:
  81.                 case 'N':
  82.                     if (REbom == REeom) {
  83.                         offset += 1;
  84.                         if (linebuf[REeom] == '\0')
  85.                             LineDone = YES;
  86.                     }
  87.                     continue;
  88.  
  89.                 case CTL('W'):
  90.                     re_dosub(re_blk, linebuf, YES);
  91.                     if (lp == l2)
  92.                         char2 += REdelta;
  93.                     modify();
  94.                     numdone += 1;
  95.                     curchar = REbom;
  96.                     makedirty(curline);
  97.                     UNDO_da = curline->l_dline;
  98.                     UNDO_lp = curline;
  99.                     /*FALLTHROUGH*/
  100.                 case CTL('R'):
  101.                 case 'R':
  102.                     RErecur();
  103.                     UNDO_lp = NULL;    /* can't reliably undo this */
  104.                     offset = curchar;
  105.                     lp = curline;
  106.                     continue;
  107.  
  108.                 case CTL('U'):
  109.                 case 'U':
  110.                     if (UNDO_lp == NULL) {
  111.                         rbell();
  112.                         goto reswitch;
  113.                     }
  114.                     if (UNDO_lp == NULL)
  115.                         getline(UNDO_da, linebuf);    /* someone ought to */
  116.                     lp = UNDO_lp;
  117.                     lp->l_dline = UNDO_da;
  118.                     makedirty(lp);
  119.                     offset = 0;
  120.                     numdone = UNDO_nd;
  121.                     UNDO_lp = NULL;
  122.                     continue;
  123.  
  124.                 case 'P':
  125.                 case '!':
  126.                     query = 0;
  127.                     break;
  128.  
  129.                 case CR:
  130.                 case LF:
  131.                 case 'Q':
  132.                     return numdone;
  133.  
  134.                 case CTL('L'):
  135.                     RedrawDisplay();
  136.                     goto reswitch;
  137.  
  138.                 default:
  139.                     rbell();
  140. message("Space or Y, Period, Rubout or N, C-R or R, C-W, C-U or U, P or !, Return.");
  141.                     goto reswitch;
  142.                 }
  143.             }
  144.             if (UNDO_lp != curline) {
  145.                 UNDO_da = curline->l_dline;
  146.                 UNDO_lp = curline;
  147.                 UNDO_nd = numdone;
  148.             }
  149.             if (REbom == REeom && linebuf[REeom] == '\0')
  150.                 LineDone = YES;
  151.             re_dosub(re_blk, linebuf, NO);
  152.             if (lp == l2)
  153.                 char2 += REdelta;
  154.             numdone += 1;
  155.             modify();
  156.             crater = offset = curchar = REeom;
  157.             makedirty(curline);
  158.             if (query) {
  159.                 message(mesgbuf);    /* no blinking */
  160.                 redisplay();        /* show the change */
  161.             }
  162.             if (stop)
  163.                 return numdone;
  164.         }
  165.         offset = 0;
  166.     }
  167.     return numdone;
  168. }
  169.  
  170. /* prompt for search and replacement strings and do the substitution */
  171. private void
  172. replace(query, inreg)
  173. int    query,
  174.     inreg;
  175. {
  176.     Mark    *m;
  177.     char    *rep_ptr;
  178.     Line    *l1 = curline,
  179.         *l2 = curbuf->b_last;
  180.     int    char1 = curchar,
  181.         char2 = length(curbuf->b_last),
  182.         numdone;
  183.     struct RE_block    re_blk;
  184.  
  185.     if (inreg) {
  186.         m = CurMark();
  187.         l2 = m->m_line;
  188.         char2 = m->m_char;
  189.         (void) fixorder(&l1, &char1, &l2, &char2);
  190.     }
  191.  
  192.     /* get search string */
  193.     strcpy(rep_search, ask(rep_search[0] ? rep_search : (char *) 0, ProcFmt));
  194.     REcompile(rep_search, UseRE, &re_blk);
  195.     /* Now the replacement string.  Do_ask() so the user can play with
  196.        the default (previous) replacement string by typing C-R in ask(),
  197.        OR, he can just hit Return to replace with nothing. */
  198.     rep_ptr = do_ask("\r\n", (int (*) proto((int))) 0, rep_str,
  199.         ": %f %s with ", rep_search);
  200.     if (rep_ptr == 0)
  201.         rep_ptr = NullStr;
  202.     strcpy(rep_str, rep_ptr);
  203.  
  204.     if (((numdone = substitute(&re_blk, query, l1, char1, l2, char2)) != 0) &&
  205.         (inreg == NO)) {
  206.         do_set_mark(l1, char1);
  207.         add_mess(" ");        /* just making things pretty */
  208.     } else
  209.         message("");
  210.     add_mess("(%d substitution%n)", numdone, numdone);
  211. }
  212.  
  213. void
  214. RegReplace()
  215. {
  216.     replace(0, YES);
  217. }
  218.  
  219. void
  220. QRepSearch()
  221. {
  222.     replace(1, NO);
  223. }
  224.  
  225. void
  226. RepSearch()
  227. {
  228.     replace(0, NO);
  229. }
  230.  
  231. /* Lookup a tag in tag file FILE.  FILE is assumed to be sorted
  232.    alphabetically.  The FASTTAGS code, which is implemented with
  233.    a binary search, depends on this assumption.  If it's not true
  234.    it is possible to comment out the fast tag code (which is clearly
  235.    labeled), delete the marked test in the sequential loop, and
  236.    everything else will just work. */
  237.  
  238. private int
  239. lookup(searchbuf, filebuf, tag, file)
  240. char    *searchbuf,
  241.     *filebuf,
  242.     *tag,
  243.     *file;
  244. {
  245.     register size_t    taglen = strlen(tag);
  246.     char    line[JBUFSIZ],
  247.         pattern[128];
  248.     register File    *fp;
  249.     struct stat    stbuf;
  250.     int    success = NO;
  251.  
  252.     fp = open_file(file, iobuff, F_READ, NO, YES);
  253.     if (fp == NIL)
  254.         return NO;
  255.     swritef(pattern, "^%s[^\t]*\t*\\([^\t]*\\)\t*\\([?/]\\)\\(.*\\)\\2$", tag);
  256.  
  257.     /* ********BEGIN FAST TAG CODE******** */
  258.  
  259.     if (stat(file, &stbuf) >= 0) {
  260.         /* Invariant: if there is a line matching the tag, it
  261.          * begins somewhere after position lower, and begins
  262.          * at or before upper.  There is one possible
  263.          * exception: if lower is 0, the line with the tag
  264.          * might be the very first line.
  265.          *
  266.          * When this loop is done, we seek to lower, advance
  267.          * past the next newline (unless lower is 0), and fall
  268.          * into the sequential search.
  269.          */
  270.         register off_t    lower = 0;
  271.         register off_t    upper = stbuf.st_size;
  272.  
  273.         for (;;) {
  274.             off_t    mid;
  275.             int    chars_eq;
  276.  
  277.             if (upper - lower < JBUFSIZ)
  278.                 break;    /* small range: search sequentially */
  279.             mid = (lower + upper) / 2;
  280.             f_seek(fp, mid);    /* mid will not be 0 */
  281.             f_toNL(fp);
  282.             if (f_gets(fp, line, sizeof line) == EOF)
  283.                 break;        /* unexpected: bail out */
  284.             chars_eq = numcomp(line, tag);
  285.             if (chars_eq == taglen && iswhite(line[chars_eq])) {
  286.                 /* we hit the exact line: get out */
  287.                 lower = mid;
  288.                 break;
  289.             }
  290.             if (line[chars_eq] < tag[chars_eq])
  291.                 lower = mid;    /* line is BEFORE tag */
  292.             else
  293.                 upper = mid;    /* line is AFTER tag */
  294.         }
  295.         /* sequentially search from lower */
  296.         f_seek(fp, lower);
  297.         if (lower > 0)
  298.             f_toNL(fp);
  299.     }
  300.  
  301.     /* END FAST TAG CODE */
  302.  
  303.     while (f_gets(fp, line, sizeof line) != EOF) {
  304.         int    cmp = line[0] - *tag;
  305.  
  306.         if (cmp == 0) {
  307.             cmp = strncmp(line, tag, taglen);
  308.             if (cmp == 0) {
  309.                 /* we've found the match */
  310.                 if (!LookingAt(pattern, line, 0)) {
  311.                     complain("I thought I saw it!");
  312.                 } else {
  313.                     putmatch(1, filebuf, (size_t)FILESIZE);
  314.                     putmatch(3, searchbuf, (size_t)100);
  315.                     success = YES;
  316.                 }
  317.                 break;
  318.             }
  319.         }
  320.         if (cmp > 0)
  321.             break;    /* failure: gone too far.  PRESUMES ALPHABETIC ORDER */
  322.     }
  323.     close_file(fp);
  324.  
  325.     if (success == NO)
  326.         s_mess("Can't find tag \"%s\".", tag);
  327.     return success;
  328. }
  329.  
  330. #if !(defined(MSDOS) || defined(MAC))
  331. char    TagFile[FILESIZE] = "./tags";
  332. #else /* MSDOS */
  333. char    TagFile[FILESIZE] = "tags";
  334. #endif /* MSDOS */
  335.  
  336. void
  337. find_tag(tag, localp)
  338. char    *tag;
  339. int    localp;
  340. {
  341.     char    filebuf[FILESIZE],
  342.         sstr[100],
  343.         tfbuf[FILESIZE];
  344.     register Bufpos    *bp;
  345.     register Buffer    *b;
  346.     char    *tagfname;
  347.  
  348.     if (!localp) {
  349.         char    prompt[128];
  350.  
  351.         swritef(prompt, "With tag file (%s default): ", TagFile);
  352.         tagfname = ask_file(prompt, TagFile, tfbuf);
  353.     } else
  354.         tagfname = TagFile;
  355.     if (lookup(sstr, filebuf, tag, tagfname) == 0)
  356.         return;
  357.     set_mark();
  358.     b = do_find(curwind, filebuf, 0);
  359.     if (curbuf != b)
  360.         SetABuf(curbuf);
  361.     SetBuf(b);
  362.     if ((bp = dosearch(sstr, BACKWARD, 0)) == 0 &&
  363.         ((bp = dosearch(sstr, FORWARD, 0)) == 0))
  364.         message("Well, I found the file, but the tag is missing.");
  365.     else
  366.         SetDot(bp);
  367. }
  368.  
  369. void
  370. FindTag()
  371. {
  372.     int    localp = !is_an_arg();
  373.     char    tag[128];
  374.  
  375.     strcpy(tag, ask((char *) 0, ProcFmt));
  376.     find_tag(tag, localp);
  377. }
  378.  
  379. /* Find Tag at Dot. */
  380.  
  381. void
  382. FDotTag()
  383. {
  384.     int    c1 = curchar,
  385.         c2 = c1;
  386.     char    tagname[50];
  387.  
  388.     if (!ismword(linebuf[curchar]))
  389.         complain("Not a tag!");
  390.     while (c1 > 0 && ismword(linebuf[c1 - 1]))
  391.         c1 -= 1;
  392.     while (ismword(linebuf[c2]))
  393.         c2 += 1;
  394.  
  395.     null_ncpy(tagname, linebuf + c1, (size_t) (c2 - c1));
  396.     find_tag(tagname, !is_an_arg());
  397. }
  398.  
  399. /* I-search returns a code saying what to do:
  400.    STOP:    We found the match, so unwind the stack and leave
  401.         where it is.
  402.    DELETE:    Rubout the last command.
  403.    BACKUP:    Back up to where the isearch was last NOT failing.
  404.  
  405.    When a character is typed it is appended to the search string, and
  406.    then, isearch is called recursively.  When C-S or C-R is typed, isearch
  407.    is again called recursively. */
  408.  
  409. #define STOP    1
  410. #define DELETE    2
  411. #define BACKUP    3
  412. #define TOSTART    4
  413.  
  414. static char    ISbuf[128],
  415.         *incp = 0;
  416. int    SExitChar = CR;
  417.  
  418. #define cmp_char(a, b)    ((a) == (b) || (CaseIgnore && (CharUpcase(a) == CharUpcase(b))))
  419.  
  420. static Bufpos *
  421. doisearch(dir, c, failing)
  422. register int    c,
  423.         dir,
  424.         failing;
  425. {
  426.     static Bufpos    buf;
  427.     Bufpos    *bp;
  428.  
  429.     if (c == CTL('S') || c == CTL('R'))
  430.         goto dosrch;
  431.  
  432.     if (failing)
  433.         return 0;
  434.     DOTsave(&buf);
  435.     if (dir == FORWARD) {
  436.         if (cmp_char(linebuf[curchar], c)) {
  437.             buf.p_char = curchar + 1;
  438.             return &buf;
  439.         }
  440.     } else {
  441.         if (look_at(ISbuf))
  442.             return &buf;
  443.     }
  444. dosrch:    okay_wrap = YES;
  445.     if ((bp = dosearch(ISbuf, dir, 0)) == 0)
  446.         rbell();    /* ring the first time there's no match */
  447.     okay_wrap = NO;
  448.     return bp;
  449. }
  450.  
  451. void
  452. IncFSearch()
  453. {
  454.     IncSearch(FORWARD);
  455. }
  456.  
  457. void
  458. IncRSearch()
  459. {
  460.     IncSearch(BACKWARD);
  461. }
  462.  
  463. private void
  464. IncSearch(dir)
  465. int    dir;
  466. {
  467.     Bufpos    save_env;
  468.  
  469.     DOTsave(&save_env);
  470.     ISbuf[0] = 0;
  471.     incp = ISbuf;
  472.     if (isearch(dir, &save_env) == TOSTART)
  473.         SetDot(&save_env);
  474.     else {
  475.         if (LineDist(curline, save_env.p_line) >= MarkThresh)
  476.             do_set_mark(save_env.p_line, save_env.p_char);
  477.     }
  478.     setsearch(ISbuf);
  479. }
  480.  
  481. /* Nicely recursive. */
  482.  
  483. private int
  484. isearch(dir, bp)
  485. int    dir;
  486. Bufpos    *bp;
  487. {
  488.     Bufpos    pushbp;
  489.     int    c,
  490.         ndir,
  491.         failing;
  492.     char    *orig_incp;
  493.  
  494.     if (bp != 0) {        /* Move to the new position. */
  495.         pushbp.p_line = bp->p_line;
  496.         pushbp.p_char = bp->p_char;
  497.         SetDot(bp);
  498.         failing = 0;
  499.     } else {
  500.         DOTsave(&pushbp);
  501.         failing = 1;
  502.     }
  503.     orig_incp = incp;
  504.     ndir = dir;        /* Same direction as when we got here, unless
  505.                    we change it with C-S or C-R. */
  506.     for (;;) {
  507.         SetDot(&pushbp);
  508.         message(NullStr);
  509.         if (failing)
  510.             add_mess("Failing ");
  511.         if (dir == BACKWARD)
  512.             add_mess("reverse-");
  513.         add_mess("I-search: %s", ISbuf);
  514.         DrawMesg(NO);
  515.         add_mess(NullStr);    /* tell me this is disgusting ... */
  516.         c = getch();
  517.         if (c == SExitChar)
  518.             return STOP;
  519.         if (c == AbortChar) {
  520.             /* If we're failing, we backup until we're no longer
  521.                failing or we've reached the beginning; else, we
  522.                just about the search and go back to the start. */
  523.             if (failing)
  524.                 return BACKUP;
  525.             return TOSTART;
  526.         }
  527.         switch (c) {
  528.         case RUBOUT:
  529.         case BS:
  530.             return DELETE;
  531.  
  532.         case CTL('\\'):
  533.             c = CTL('S');
  534.             /*FALLTHROUGH*/
  535.         case CTL('S'):
  536.         case CTL('R'):
  537.             /* If this is the first time through and we have a
  538.                search string left over from last time, use that
  539.                one now. */
  540.             if (incp == ISbuf) {
  541.                 strcpy(ISbuf, getsearch());
  542.                 incp = &ISbuf[strlen(ISbuf)];
  543.             }
  544.             ndir = (c == CTL('S')) ? FORWARD : BACKWARD;
  545.             /* If we're failing and we're not changing our
  546.                direction, don't recur since there's no way
  547.                the search can work. */
  548.             if (failing && ndir == dir) {
  549.                 rbell();
  550.                 continue;
  551.             }
  552.             break;
  553.  
  554.         case '\\':
  555.             if (incp > &ISbuf[(sizeof ISbuf) - 1]) {
  556.                 rbell();
  557.                 continue;
  558.             }
  559.             *incp++ = '\\';
  560.             add_mess("\\");
  561.             /*FALLTHROUGH*/
  562.         case CTL('Q'):
  563.         case CTL('^'):
  564.             add_mess("");
  565.             c = getch() | 0400;
  566.             /*FALLTHROUGH*/
  567.         default:
  568.             if (c & 0400)
  569.                 c &= CHARMASK;
  570.             else {
  571. #ifdef IBMPC
  572.                 if (c == RUBOUT || c == 0xff ||
  573.                     (c < ' ' && c != '\t')
  574. #else
  575.                 if (c > RUBOUT || (c < ' ' && c != '\t')
  576. #endif
  577.                     || PrefChar(c)) {
  578.                     Ungetc(c);
  579.                     return STOP;
  580.                 }
  581.             }
  582.             if (incp > &ISbuf[(sizeof ISbuf) - 1]) {
  583.                 rbell();
  584.                 continue;
  585.             }
  586.             *incp++ = c;
  587.             *incp = 0;
  588.             break;
  589.         }
  590.         add_mess("%s", orig_incp);
  591.         add_mess(" ...");    /* so we know what's going on */
  592.         DrawMesg(NO);        /* do it now */
  593.         switch (isearch(ndir, doisearch(ndir, c, failing))) {
  594.         case TOSTART:
  595.             return TOSTART;
  596.  
  597.         case STOP:
  598.             return STOP;
  599.  
  600.         case BACKUP:
  601.             /* If we're not failing, we just continue to to the
  602.                for loop; otherwise we keep returning to the
  603.                previous levels until we find one that isn't
  604.                failing OR we reach the beginning. */
  605.             if (failing)
  606.                 return BACKUP;
  607.             /*FALLTHROUGH*/
  608.         case DELETE:
  609.             incp = orig_incp;
  610.             *incp = 0;
  611.             continue;
  612.         }
  613.     }
  614. }