reload-self

What is reloading self, is reload-self: edit the program in a text widget and reload.

The core of it is: make a text widget. Fill it with the program text. Alt-F1 saves the text to a new file and runs it with tclkit. Alt-F2 saves the text to the current program file and runs itself.

Boom! You're eating your own tail, using the text widget as an editor, and feeling hitek.

Video walk-through of the entire code starting from tclkit

Starting from a tclkit, end up with a program with a text widget that reloads the program, replacing any need for a text editor: http://www.youtube.com/watch?v=hQcZE2b_pDE

Code used in the screen recording video walkthrough

There are better ways of doing things, keep this code as-is to match the screen recording, so people can follow along.

proc file_save {fn c} {
  set f [open $fn w]
  puts -nonewline $f $c
  close $f
}

proc file_get {fn} {
  set f [open $fn r]
  set c [read $f]
  close $f
  return $c
}

console show

set dir [file dirname [info nameofexe]]
cd $dir

pack [text .tx -bg #cccccc -fg black]

if {$argv eq ""} {set LOADER prog.x} else {set LOADER [lindex $argv 0]}

.tx insert end [file_get $LOADER]


bind all <Alt-F1> run_another
bind all <Alt-F2> reload_self

proc run_another {} {

  set c [.tx get 1.0 end-1c]

  set run_fn run[clock micro].txt

  file_save [file join $::dir $run_fn] $c

  exec [file join $::dir tclkit] $run_fn $run_fn &

}

proc reload_self {} {

  set c [.tx get 1.0 end-1c]
  file_save $::LOADER $c
  exec tclkit $::LOADER $::LOADER &
  exit

}

 discussion about the code used in the screen recording

AMG: I believe [info script] is the command you're looking for.

Ro: Thanks buddy, forgot about that when I was doing the screen recording... !

Cleaned up code which is clearer than the code used in the recording

This code is still very much the same as the code used in the screen recording but I have added in an easier way to find the current script name using info script.

Also because I 'cd' into the directory of the tclkit exe, it is simpler to point to filenames that are used by relative paths. Goofy stuff.

proc file_save {fn c} {
  set f [open $fn w]
  puts -nonewline $f $c
  close $f
}

proc file_get {fn} {
  set f [open $fn r]
  set c [read $f]
  close $f
  return $c
}

console show

set dir [file dirname [info nameofexe]]
cd $dir

pack [text .tx -bg #cccccc -fg black]

set LOADER [file normalize [info script]]

.tx insert end [file_get $LOADER]


bind all <Alt-F1> run_another
bind all <Alt-F2> reload_self

proc run_another {} {
  set c [.tx get 1.0 end-1c]
  set run_fn run[clock micro].txt
  file_save $run_fn $c
  exec tclkit $run_fn &
}

proc reload_self {} {
  set c [.tx get 1.0 end-1c]
  file_save $::LOADER $c
  exec tclkit $::LOADER &
  exit
}