/* This is the global substitute command - it simulates the global subst */
/* command found in the New York Word word processor (also sold by MAGMA */
/* SYSTEMS). */
/* You first prepare an external file (called "subs" here) that contains */
/* lines of the form :   pattern=sub text */
/* The last line of the file should be a blank line. Then you hit the */
/* <CTRL> G key, and the substitutions are performed. */
/* Written by Marc Adler  8/86 */

init()
{
  assign_key("global_sub", 7);    /* <CTRL> G */
}


global_sub()
{
  string search_pat, sub_text, foo;
  int    old_buf, sub_buf, i;

  save_position();

  /* Read in the substitutions */
  old_buf = currbuf();
  sub_buf = setcurrbuf(create_buffer("subs"));

  while ((i = index(currline(), "=")) > 0)      /* still a pattern? */
  {
    /* Isolate both the pattern and the substitution text  */
    search_pat = substr(currline(), 1, i - 1);
    sub_text = substr(currline(), i + 1, strlen(currline()));

/*   Uncomment the following line if you want to check the patterns */
/*   foo = get_tty_str("srch <%s>, sub <%s>", search_pat, sub_text);*/

    /* Go to the original buffer, and perform a forward substitution without */
    /* user approval. To get approval, change the 3rd param of fsubst to 1.  */
    setcurrbuf(old_buf);
    gobof();
    fsubst(search_pat, sub_text, 0);

    /* Go to the substitution buffer and move down to the next pattern. */
    setcurrbuf(sub_buf);
    if (!down())  break;
  }

  /* Get rid of the substitution buffer and re-enable the original buffer */
  delete_buffer(sub_buf);
  setcurrbuf(old_buf);
  restore_position();
  foo = get_tty_str("Finished with substitutions");
}
