/********************************************************************
 *                                                                  *
 *      CRISP - Custom Reduced Instruction Set Programmers Editor   *
 *                                                                  *
 *      (C) Paul Fox, 1989                                          *
 *                                                                  *
 *    Please See COPYLEFT notice.                                   *
 *                                                                  *
 ********************************************************************/
# include	"crisp.h"

# define	BRACKETS	"[](){}"
void
find_matching_brace()
{
	string bracket, mbracket, s, s1;
	int	br_level, i, incr, fwd;

	save_position();
	bracket = read(1);
	if (index(bracket, BRACKETS) == 0) {
		if (re_search(SF_UNIX, "[()[\\]{}]") <= 0) {
			beep();
			return;
			}
		bracket = read(1);
		}
	message("Locating matching bracket...");
	i = index(BRACKETS, bracket) - 1;
	fwd = i & 1;
	incr = -1;
	if (fwd)
		incr = 1;
	i = 2*i+1;
	mbracket = substr("[][]()(){}{}", i, 2);
	s = "[" + quote_regexp(mbracket) + "]";
	s1 = substr(mbracket, 1, 1);

	br_level = 1;
	while (br_level > 0) {
		if (fwd) {
			prev_char();
			if (re_search(SF_BACKWARDS, s) <= 0)
				break;
			}
		else {
			next_char();
			if (re_search(NULL, s) <= 0)
				break;
			}
		if (read(1) == s1) 
			br_level -= incr;
		else
			br_level += incr;
		}
	if (br_level) {
		error("Matching %s not found.", mbracket);
		restore_position();
		beep();
		return;
		}
	restore_position(0);
	message("");

}
