Overloading a widget command

Ludwig Callewaert wrote in comp.lang.tcl, regarding a change-sensitive text widget:

All changes to the text widget are either done with the insert or delete text widget command. Overload these (by using Wcb for instance).

By overloading I mean that you provide a new implementation for those commands. In your case, the overloaded commands could first call the original insert or delete command and could then set a flag (a global variable for instance) indicating that the content of the text widget has changed. By putting a trace on that flag (with the trace command), you can make something happen everytime the widget content changes.

There are actually several ways to do this. One possibility is the following:

 # Create the text widget
 pack [text .t]

 # The flag
 global flag

 set flag 0

 # Put a trace on the flag to execute your proc
 trace add variable flag write changed

 # rename the widget procedure
 rename .t orig_t
 # the new widget procedure
 proc .t {args} {
   global flag
   set returnVal [eval [concat orig_t $args]]
   set command [lindex $args 0]
   if {[string equal $command "insert"] || [string equal $command "delete"]} {
      set flag 1
   return $returnVal

 # Whatever you need to do when something changes
 proc changed {args} {
   puts "something changed"

Wcb, the widget callback package which can be found at http://www.nemethi.de/ is a more general way to do this.