/*
** 	BRIEF -- Basic Reconfigurable Interactive Editing Facility
**
** 	Written by Dave Nanian and Michael Strickman.
*/

/*
**		savehist.cb:
**
**		This file saves the current history information to the state file
**	on exit.  To use it, put the string "-msavehist" (no quotes) after the
**	"-mrestore" or "-mpwb" in your BFLAGS.  For example:
**
**		set bflags=-mrestore -msavehist
**
**			- or -
**
**		set bflags=-mpwb -mscrapper
*/

extern	_save_state (),
			_restore ();

extern int _history_buf;

replacement _save_state ()
{
	if (_history_buf)
	{
		int	curr_buf = set_buffer (_history_buf),
				end_line,
				end_col;

		save_position ();
		top_of_buffer ();
		drop_anchor ();

		if (end_of_buffer ())
			inq_position (end_line, end_col);

		raise_anchor ();
		restore_position ();
		set_buffer (curr_buf);

		if (end_line)
		{
			string ext;

			inq_names (NULL, ext);

			if (ext == "sts")
			{
				save_position ();
				top_of_buffer ();

				if (search_fwd ("<[\t ]@\\[brief-history\\]", 1, 1))
				{
					drop_anchor ();
					search_fwd ("<[\t ]@\\[end-brief-history\\]*\\c>", 1, 1);
					delete_block ();
				}
				restore_position ();

				set_buffer (_history_buf);
				top_of_buffer ();
				translate ("<", ";", 1, 1);
				end_col++;						// Compensate for extra character
				set_buffer (curr_buf);
			}

			insert ("[brief-history]\n");
			transfer (_history_buf, 1, 1, end_line, end_col);
			insert ("[end-brief-history]\n");
		}
	}
	returns (_save_state ());
}


replacement _restore ()
{
	_restore ();
	top_of_buffer ();

	if (search_fwd ("<\\[brief-history\\]>"))
	{
		down ();
		drop_anchor (4);

		search_fwd ("<\\[end-brief-history\\]>");

		if (inq_mark_size ())
		{
			int	start_line,
					start_col,
					end_line,
					end_col,
					curr_buf;
			string	ext;

			prev_char (2);
			inq_position (end_line, end_col);
			swap_anchor ();
			inq_position (start_line, start_col);

			inq_names (NULL, ext);

			curr_buf = set_buffer (_history_buf);
			transfer (curr_buf, start_line, start_col, end_line, end_col);

			if (ext == "sts")
			{
				top_of_buffer ();
				translate ("<;", "", 1, 1);
			}

			set_buffer (curr_buf);
		}
		raise_anchor ();
	}
}
