/* This macro performs an EMACS-like incremental search */

init()
{
  assign_key("i_search", 19);   /* <CTRL> S invokes the search */
}


i_search()
{
  int c;
  int len;
  string pattern;

  c = 0;             /* initialize everything */
  pattern = "";
  save_position();

  while (c != '\E')                       /* <ESC> gets us out */
  {
    message(strcat("Incr Search -- ", pattern));

    if ((c = get_tty_char()) == '\b')     /* backspace */
    {
      if ((len = strlen(pattern)) > 1)    /* erase the last char */
        pattern = substr(pattern, 1, len - 1);
      else
        pattern = "";
      restore_position();                 /* go to where we started from */
    }

    else if (c == 7)                      /* <CTRL> G means abort */
    {
      for (len = strlen(pattern);  len > 0;  len = len - 1)
        restore_position();               /* restore to start position */
      break;
    }

    else if (c == '\n' || c == '\E')      /* done!!! - stay where we are */
      break;

    else                                  /* a regular search character */
    {
      /* Notice the use of chr() below. If we didn't use it, then c would */
      /* be converted to a numeric string before it was concatenated. */
      pattern = strcat(pattern, chr(c));  /* tack it onto the end of pattern */

      message(strcat("Incr Search -- ", pattern));
      save_position();

      if (fsearch(pattern) <= 0)          /* search for the pattern */
      {                                   /* it failed! */
        if ((len = strlen(pattern)) > 1)  /* erase this character */
          pattern = substr(pattern, 1, len - 1);
        else
          pattern = "";
        restore_position();
      }
    }
  }

  clear_positions();                       /* reset the position stack */
}
