#!/home/bwelch/bin/wish -f
# Tkexample chapter
# Updated to work with browse1.tcl
# Simple evaluator.  This uses the following
# Tk widgets:
#	.eval - the frame around the text log
# Procedures:
#	_Eval - the main eval procedure
# Variables:
#	_prompt - the command line prompt
#	_t - holds the ID of the text widget

if {$argc > 0} {
	# Check in with the browser
	send [lindex $argv 0] [list set browse(evalInterp) [tk appname]]
}
set _debug 0

# A frame, scrollbar, and text
frame .eval
set _t [text .eval.t -width 80 -height 20 -yscrollcommand {.eval.s set}]
scrollbar .eval.s -command {.eval.t yview}
pack .eval.s -side left -fill y
pack .eval.t -side right -fill both -expand true
pack .eval -fill both -expand true

# Insert the prompt and initialize the limit mark
.eval.t insert insert "Tcl eval log\n"
set _prompt "tcl> "
.eval.t insert insert $_prompt
.eval.t mark set limit insert
.eval.t mark gravity limit left
focus .eval.t

# Keybindings that limit input and eval things
bind .eval.t <Return> { _Eval .eval.t ; break }
bind .eval.t <Any-Key> {
	if [%W compare insert < limit] {
		%W mark set insert end
	}
}
bindtags .eval.t {.eval.t Text all}

proc _Eval { t } {
	global _prompt _debug
	set command [$t get limit end]
	if [info complete $command] {
		set err [catch {uplevel #0 $command} result]
		if {$_debug} {
		    puts stdout "$err: $result\n"
		}
		$t insert insert \n$result\n
		$t insert insert $_prompt
		$t see insert
		$t mark set limit insert
		return
	}
}

proc _EvalServe { command } {
	global _prompt _debug
	set t .eval.t
	$t insert insert $command\n

	set err [catch {uplevel #0 $command} result]
	if {$_debug} {
	    puts stdout "$err: $result\n"
	}
	$t insert insert \n$result\n
	$t insert insert $_prompt
	$t see insert
	$t mark set limit insert
}

proc _Cleanup {} {
    foreach w [winfo children .] {
	if {$w != ".eval"} {
	    destroy $w
	}
    }
}
