# This is a _simple_ editor that might be nice to use occasinally.
# Usage: edit file; file does not have to exist.

set _edit_id 0

proc edit {file} {
    global _edit_id

    set id [incr _edit_id]
    set w .edit$id

    toplevel $w
    wm title $w Edit
    
    text $w.text -relief sunken -yscrollcommand [list $w.scroll set] \
	    -width 80 -height 30
    scrollbar $w.scroll -relief sunken -command [list $w.text yview]
    label $w.status -textvariable _edit_${id}(file)

    menu $w.menubar
    $w.menubar add cascade -label File -menu $w.menubar.file -underline 0
    $w.menubar add cascade -label Edit -menu $w.menubar.edit -underline 0
    
    menu $w.menubar.file
    $w.menubar.file add command -label Open -command [list _edit_open $id]
    $w.menubar.file add command -label Save -accelerator C-s\
	    -command "_edit_save $id \$_edit_${id}(file)"
    $w.menubar.file add command -label "Save as" -command [list _edit_save $id]
    $w.menubar.file add command -label Close -command [list _edit_close $id]\
	    -accelerator C-q

    bind $w.text <Control-q> [list _edit_close $id]
    bind $w.text <Control-s> "_edit_save $id \$_edit_${id}(file)"

    menu $w.menubar.edit
    $w.menubar.edit add command -label Cut \
	    -command [list event generate $w.text <<Cut>>]
    $w.menubar.edit add command -label Copy \
	    -command [list event generate $w.text <<Copy>>]
    $w.menubar.edit add command -label Paste \
	    -command [list event generate $w.text <<Paste>>]

    $w configure -menu $w.menubar

    grid $w.text  -sticky news
    grid $w.scroll -row 0 -column 1 -sticky ns
    grid $w.status -row 1 -sticky w

    focus $w.text
    _edit_open $id $file

    return
}

proc _edit_close {id {file ""}} {
    upvar #0 _edit_$id edit

    unset edit
    destroy .edit$id
}

proc _edit_save {id {file ""}} {
    upvar #0 _edit_$id edit

    if {![string length $file]} {
	set file [tk_getSaveFile -title "Save file as"]
    }

    if {[string length $file]} {
	set w .edit$id
	
	if {[catch {open $file w+} fd]} {
	    tk_dialog $w.err "Error saving file" $fd error 0 Ok
	    return
	}
	
	foreach {key val index} [$w.text dump -text 0.0 "end - 1 c"] {
	    puts -nonewline $fd $val
	}
	
	flush $fd
	close $fd
	
	set edit(file) $file 
    }

    return
}

proc _edit_open {id {file ""}} {
    upvar #0 _edit_$id edit
    
    if {![string length $file]} {
	set file [tk_getOpenFile -title "Open a file"]
    }

    if {[string length $file]} {
	 set w .edit$id
	
	if {[file exists $file]} {
	    if {[catch {open $file r} fd]} {
		tk_dialog $w.err "Error opening file" $fd error 0 Ok
		return
	    }
	    
	    $w.text delete 0.0 end
	    $w.text insert 0.0 [read $fd]
	    close $fd
	}
	
	set edit(file) $file
    }
    
    return    
}


