history object

wdb In certain cases I need earlier versions of widget content, similar to command history. Specially in search-replace-spell dialog of my not-yet published tknotepad.tcl which I developped toward the Eierlegende Wollmilchsau. Not rocket science, but not really fun. Remember I'm able to do errors even on simple things. So I wrote my own history object using obj. (My private slogan: never again thinking yourself!)

Create new history object:

 set h [obj::new history]


 $h add $content

appends $content to history. If Option -unique is set to true, then doublettes are removed;

 $h back

decreases index, returns previous content,

 $h forward

same, but direction forward,

 $h atEnd

returns true if index at end,

 $h atStart

returns true if index at start.

# file: history-0.1.tm

package require obj
package provide history 0.1

obj::class history

obj::configure history -unique false

obj::validatemethod history -unique bool {
  if {![string is boolean -strict $bool]} then {
    return -code error\
      [list $self expects for -unique a boolean value\
        but returned non-boolean value $bool]

obj::inscope history namespace import ::tcl::mathop::*

obj::constructor history {} {
  my list {}
  my index -1

obj::method history add str {
  my list [lrange [my list] 0 [my index]]
  if {[$self cget -unique]} then {
    set found [lsearch [my list] $str]
    my list [lreplace [my list] $found $found]
  my list [::list {*}[my list] $str]
  my index [- [llength [my list]] 1]
  set str

obj::method history back {} {
  if {[my index] >= 0} then {
    my index [- [my index] 1]
    ::lindex [my list] [my index]

obj::method history forward {} {
  if {[my index]+1 < [llength [my list]]} then {
    my index [+ [my index] 1]
    ::lindex [my list] [my index]

obj::method history get {} {
  ::lindex [my list] [my index]

obj::method history atEnd {} {
  expr {[my index]+1 == [llength [my list]] ? yes : no}

obj::method history atStart {} {
  expr {[my index] <= 0 ? yes : no}

If you prefer another OO system, it is a breeze to transform it. Have fun.