Updated 2014-05-24 17:07:34 by pooryorick

if 0 {Richard Suchenwirth 2004-12-12 - Not as exciting as Baywatch, but still I had some fun... Some editors (e.g. PFE, MS Visual Studio) pop up an alert dialog when a file was changed on disk while being edited - that might lead to edit conflicts. Emacs shows a more subtle warning at the first attempt to change a file that has changed on disk.

In this fun project I try to emulate this feature. It is oversimplified because it does not update the mtime (file modification time) to check, once you saved it from the editor itself. So make sure to call text'watch'file again after saving.

Using the global variable ::_twf it is at least possible to avoid false alarms - for a more serious implementation one might use a namespaced array of watchers, indexed by file name, in case you want multiple edit windows. }
 proc text'watch'file {w file {mtime -}} {
    set checkinterval 1000 ;# modify as needed
    if {$mtime eq "-"} {
        if [info exists ::_twf] {after cancel $::_twf}
        set file [file join [pwd] $file]
        text'watch'file $w $file [file mtime $file]
    } else {
        set newtime [file mtime $file]
        if {$newtime != $mtime} {
            set answer [tk_messageBox -type yesno -message \
                "The file\n$file\nhas changed on disk. Reload it?"]
            if {$answer eq "yes"} {text'read'file $w $file}
            text'watch'file $w $file
        } else {set ::_twf [after $checkinterval [info level 0]]}
 proc text'read'file {w file} {
    set f [open $file]
    $w delete 1.0 end
    $w insert end [read $f]
    close $f
#-- Testing:
 pack [text .t -wrap word] -fill both -expand 1
 set file textwatch.tcl
 text'read'file  .t $file
 text'watch'file .t $file

if 0 {The dialog should come up when you change the file externally, say by touch-ing it in pure Tcl, which might be done with
 file mtime $filename [clock seconds]

or editing it with another editor.

See also [1] for watching directory-changes in a similar way....