# IDE.tcl --
#
#	Miscellaneous routines
#
# Copyright (c) 1996 - 1997, William Byrne
#
# See the file "license.txt" for information on usage and redistribution
# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
#



package provide IDE 1.0

# Create a namespace IDE
namespace eval IDE {
	namespace export unique insertAt ideError
}



# Generate a unique command identifier
proc IDE::unique { {ns ::} } {
	set prefix __
	set i 0 
	while { 1 } {
		incr i
		set u $prefix$i
		if { [info commands $ns$u] == {} } {
			return $ns$u
		}
	}
}

proc IDE::ideError { msg } {
	catch {
		puts stderr $msg
		IDE FocusPad
	}
}

# Insert text at line indexed beginning one. If line is zero,defaults to current line.
proc IDE::insertAt { buf {line 0} } {
	if [catch {
		set M [unique]
		IDE tools module $M
		if [catch {
			set E [unique]
			$M Editor $E
			if [catch {
				set V [unique]
				$E View $V
				if [catch {
					if { $line <= 0 } {
						set line [$V line]
						set stet 1
					} else {
						set stet 0
					}
					set pos [$E CalcPos $line 0];
					set W [unique]
					$E Writer $W
					if [catch {
						if { ![$W CopyTo $pos] || ![$W Insert $buf]} {
							ideError "Unable to insert $buf"
						}
					} errmsg] {
						ideError [format "Reader Error: %s" $errmsg]
					}
					$W Free;
					if { !$stet } {
						$V -v line $line
						$V line $line
						IDE ProcessMessages; #update window
					}
				} errmsg] {
					ideError $errmsg				
				}
				$V Free				
			} errmsg] {
				ideError $errmsg
			}				
			$E Free
		} errmsg] {
			ideError $errmsg
		}
		$M Free
	} errmsg] {
		ideError $errmsg
	}
}


