File: formutab.tcl

package info (click to toggle)
moomps 4.6-2
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 2,444 kB
  • ctags: 2,307
  • sloc: tcl: 34,882; sh: 167; makefile: 91
file content (723 lines) | stat: -rw-r--r-- 35,152 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
# copyright (C) 1997-2005 Jean-Luc Fontaine (mailto:jfontain@free.fr)
# this program is free software: please read the COPYRIGHT file enclosed in this package or use the Help Copyright menu

# $Id: formutab.tcl,v 1.39 2005/02/21 20:49:32 jfontain Exp $


namespace eval formulas {

if {$global::withGUI} {
    set (existingMessage) [mc {identical expression found in existing formula "%s"}]
}

    class table {

if {$global::withGUI} {

        proc table {this parentPath args} composite {[new frame $parentPath] $args} viewer {} {
            composite::complete $this
            constructor $this $composite::($this,-object) $composite::($this,-category)
            # wait till after completion before creating table since some options are not dynamically settable
            set table [new dataTable $widget::($this,path)\
                -data $($this,dataName) -draggable $composite::($this,-draggable) -background $viewer::(background)\
            ]
            pack $widget::($table,path) -fill both -expand 1
            set tablePath $dataTable::($table,tablePath)
            if {!$global::readOnly} {
                set menu [menu $tablePath.menu -tearoff 0]
                set ($this,help) [new menuContextHelp $menu]
                $menu add command -label [mc Edit]... -command "formulasDialog $this \$($this,pointed)"
                menuContextHelp::set $($this,help) 0 [mc {edit formulas in this table}]
                bindtags $tablePath [concat [bindtags $tablePath] PopupMenu$this]
                if {[package vcompare $::tcl_version 8.4] < 0} {
                    bind PopupMenu$this <ButtonPress-3> "
                        if {\[string length \$::tkPriv(popup)\] == 0} {
                            set ($this,pointed) \[formulas::table::pointed $this %x %y\]
                            tk_popup $menu %X %Y
                        }
                    "
                } else {
                    bind PopupMenu$this <ButtonPress-3> "
                        if {\[string length \$::tk::Priv(popup)\] == 0} {
                            set ($this,pointed) \[formulas::table::pointed $this %x %y\]
                            tk_popup $menu %X %Y
                        }
                    "
                }
            }
            set ($this,drop) [new dropSite -path $tablePath -formats {FORMULAS KILL} -command "formulas::table::handleDrop $this"]
            set bindings [new bindings $tablePath end]
            bindings::set $bindings <Enter> "formulas::table::enter $this %x %y"
            bindings::set $bindings <Leave> "formulas::table::leave $this"
            set ($this,bindings) $bindings
            set ($this,tablePath) $tablePath
            set ($this,table) $table
            set configurations $composite::($this,-configurations); set rows $composite::($this,-rows)
            if {[llength $configurations] != [llength $rows]} {
                error "fatal dashboard file error: [llength $configurations] configurations but [llength $rows] rows"
            }
            set formulas [createFormulas $this $configurations $rows]
            if {[llength $formulas] == 0} {
                set label [centerMessage $tablePath\
                    [mc "formulas table:\ndrop or edit formulas"] $viewer::(background) $global::viewerMessageColor\
                ]
                if {!$global::readOnly} {
                    bindtags $label [concat [bindtags $label] PopupMenu$this]
                }
            } else {
                manage $this $formulas
            }
            set ($this,constructed) {}
            set-state $this $composite::($this,-state)            ;# force state initialization now that drag and drop objects exist
        }

} else {                          ;# remove Tk dependant code since this class can be used by monitoring daemon in a Tcl environment

        proc table {this args} switched {$args} viewer {} {
            switched::complete $this
            constructor $this $switched::($this,-object) $switched::($this,-category)
            set formulas [createFormulas $this $switched::($this,-configurations) $switched::($this,-rows)]
            if {[llength $formulas] > 0} {
                manage $this $formulas
            }
        }

}

        proc constructor {this object category} {
            set ($this,nextRow) 0
            set dataName ::formulas::table::$(nextDataIndex)data          ;# unique name based on index (available after completion)
            catch {unset $dataName}
            array set $dataName [list\
                updates 0\
                0,label [mc formula] 0,type ascii\
                1,label [mc value] 1,type real\
                indexColumns 0\
                sort {0 increasing}\
            ]
            set ($this,dataName) $dataName
            set instance [modules::loadFormulasModule $(nextDataIndex) $object $category]
            set ($this,namespace) $modules::instance::($instance,namespace)
            foreach [list ${dataName}(0,message) ${dataName}(1,message)] [$($this,namespace)::messages] {}
            set ($this,instance) $instance
            incr (nextDataIndex)
        }

        proc createFormulas {this configurations rows} {
            set formulas {}
            foreach options $configurations row $rows {                                       ;# create formulas from dashboard file
                set formula [eval new formulas::formula $options]
                set ($this,row,$formula) $row
                if {$row >= $($this,nextRow)} {set ($this,nextRow) [expr {$row + 1}]}             ;# make sure rows are never reused
                lappend formulas $formula
            }
            return $formulas
        }

        proc ~table {this} {
            variable ${this}count

            foreach formula [formulas $this] {delete $formula}
            catch {unset ${this}count}
if {$global::withGUI} {
            catch {delete $($this,tip)}
            delete $($this,drop) $($this,bindings) $($this,table)
            if {[info exists ($this,help)]} {delete $($this,help)}
}
            set dataName $($this,dataName)
            incr ${dataName}(updates)                                          ;# so related viewers can show cells have disappeared
            unset $dataName
            modules::unload $($this,instance)
if {$global::withGUI} {
            if {[string length $composite::($this,-deletecommand)] > 0} {
                uplevel #0 $composite::($this,-deletecommand)                               ;# always invoke command at global level
            }
} else {
            if {[string length $switched::($this,-deletecommand)] > 0} {
                uplevel #0 $switched::($this,-deletecommand)
            }
}
        }

        proc options {this} {                                       ;# data index must be forced so that initialization always occur
            return [list\
                [list -category {} {}]\
                [list -configurations {} {}]\
                [list -dataindex {}]\
                [list -deletecommand {} {}]\
                [list -draggable 0 0]\
                [list -object {} {}]\
                [list -rows {} {}]\
                [list -state normal]\
            ]
        }

        set (nextDataIndex) 0                        ;# used when data array index is not specified as an option when creating table
        proc reset {} {                              ;# reset generated counter (invoker must insure that there are no viewers left)
            set (nextDataIndex) 0
        }
        # data array name index must be specifiable so that data viewers depending on formulas table data array name (through their
        # monitored cells) do not fail accessing that data (required when generating viewers from save file)
        proc set-dataindex {this value} {                                                     ;# always invoked at construction time
if {$global::withGUI} {
            set complete $composite::($this,complete)
} else {
            set complete $switched::($this,complete)
}
            if {$complete} {
                error {option -dataindex cannot be set dynamically}
            }
            if {[string length $value] > 0} {                       ;# specified, else use internally generated next available index
                if {$value < $(nextDataIndex)} {
                    error "specified data index ($value) is lower than internal formulas table index"
                }
                set (nextDataIndex) $value
            }
        }

        proc set-deletecommand {this value} {}

        proc set-draggable {this value} {
if {$global::withGUI} {
            set complete $composite::($this,complete)
} else {
            set complete $switched::($this,complete)
}
            if {$complete} {
                error {option -draggable cannot be set dynamically}
            }
        }

        proc set-configurations {this value} {}                                                               ;# from dashboard file

        proc set-rows {this value} {}                                                                         ;# from dashboard file

        proc set-category {this value} {
if {$global::withGUI} {
            set complete $composite::($this,complete)
} else {
            set complete $switched::($this,complete)
}
            if {$complete} {
                error {option -category cannot be set dynamically}
            }
        }

        proc set-object {this value} {
if {$global::withGUI} {
            set complete $composite::($this,complete)
} else {
            set complete $switched::($this,complete)
}
            if {$complete} {
                error {option -object cannot be set dynamically}
            }
        }

if {$global::withGUI} {

        proc set-state {this value} {
            if {![info exists ($this,constructed)]} return                           ;# delayed until the end of object construction
            switch $value {
                disabled {
                    if {$composite::($this,-draggable)} {
                        set drag $dataTable::($($this,table),drag)
                        dragSite::provide $drag FORMULAS {}
                        dragSite::provide $drag OBJECTS {}
                        dragSite::provide $drag DATACELLS {}
                    }
                    switched::configure $($this,drop) -state disabled
                }
                normal {
                    ### hack: drag  code should be separated from dataTable which should provide a selected member procedure ###
                    if {$composite::($this,-draggable)} {
                        set drag $dataTable::($($this,table),drag)
                        # extend data table drag capabilities ### hack ### eventually allow row selection only instead of cells ###
                        dragSite::provide $drag FORMULAS "formulas::table::dragData $this"
                        dragSite::provide $drag OBJECTS "formulas::table::dragData $this"   ;# to be able to drop formulas in eraser
                        dragSite::provide $drag DATACELLS "formulas::table::dragData $this"    ;# intercept original data cells drag
                    }
                    switched::configure $($this,drop) -state normal
                }
                default {
                    error "bad state value \"$value\": must be normal or disabled"
                }
            }
        }

} else {

        proc set-state {this value} {}

}

        proc cells {this} {
            return {}                                                                           ;# contains formulas, not data cells
        }

        # note: also returns whether any existing formulas names were changed
        proc manage {this formulas {update 0}} {                                      ;# note: formulas to be managed by this object
            variable ${this}count             ;# cells data array usage count per formula (empty array if formula contains no cells)

if {$global::withGUI} {
            if {[llength $formulas] > 0} {
                centerMessage $($this,tablePath) {}                             ;# keep displaying help message only in empty viewer
            }
}
            set dataName $($this,dataName)
            set anyConstant 0
            set anyNameChange 0
            foreach formula $formulas {
                # always make sure formula deletion is detected, as formulas delete command may be reset in dialog box
                switched::configure $formula -deletecommand "formulas::table::deleted $this $formula"
                set name [switched::cget $formula -name]
                if {[info exists ($this,row,$formula)]} {                              ;# created from constructor or edited by user
                    set row $($this,row,$formula)
                    if {[info exists ${dataName}($row,0)] && ![string equal [set ${dataName}($row,0)] $name]} {
                        set anyNameChange 1
                    }
                } else {                                                                  ;# new formula created dynamically by user
                    $($this,namespace)::new [set row [set ($this,row,$formula) $($this,nextRow)]]
                    incr ($this,nextRow)
                }
                set ${dataName}($row,0) $name
                set ${dataName}($row,1) ?
                set cells [switched::cget $formula -cells]
                if {[llength $cells] == 0} {                                                                       ;# no moving data
                    set ${this}count($formula,) 1
                    catch {set ${dataName}($row,1) [formulas::formula::value $formula]}                  ;# update now and once only
                    set anyConstant 1
                } else {
                    array unset ${this}count $formula,*
                    foreach cell $cells {
                        viewer::parse $cell array ignore ignore ignore
                        if {![catch {set asynchronous [modules::asynchronous $array]}] && $asynchronous} {
                            # notes: may not be a module (statistics table); for synchronous modules, update{} is directly invoked
                            viewer::registerTrace $this $array                   ;# otherwise formula not updated when value changes
                        }
                        if {![info exists ${this}count($formula,$array)]} {set ${this}count($formula,$array) 0}
                        incr ${this}count($formula,$array)
                        set arrays($array) {}
                    }
                }
                $($this,namespace)::name $row [set ${dataName}($row,0)]
                $($this,namespace)::value $row [set ${dataName}($row,1)]
                set managed($formula) {}
            }
            if {$update} {                                                                                    ;# remove old formulas
                foreach formula [formulas $this] {
                    if {![info exists managed($formula)]} {
                        delete $formula                                                    ;# note: automatically updates data table
                    }
                }
            }
            if {$anyConstant} {
                $($this,namespace)::update
if {$global::withGUI} {
                dataTable::update $($this,table)                  ;# since there is no associated array that could trigger an update
}
            }
            foreach array [array names arrays] {                   ;# update immediately (as done in viewer layer for other viewers)
                update $this $array
            }
            return $anyNameChange
        }

        proc update {this {array *}} {      ;# update all formulas or formulas with cells of the specified asynchronous module array
            variable ${this}count

            foreach name [array names ${this}count "\[0-9\]*,$array"] {
                set update([lindex [split $name ,] 0]) {} ;# update a formula once only even if containing cells from the same array
            }
            set dataName $($this,dataName)
            set updated 0
            foreach name [array names update] {
                set formula [lindex [split $name ,] 0]
                set value ?; catch {set value [formulas::formula::value $formula]}
                set row $($this,row,$formula)
                $($this,namespace)::value $row [set ${dataName}($row,1) $value]
                set updated 1
            }
            if {$updated} {
                incr ${dataName}(updates)                                                            ;# let data table update itself
                $($this,namespace)::update
            }
        }

        proc deleted {this formula} {
            variable ${this}count

            set cells [switched::cget $formula -cells]
            if {[llength $cells] == 0} {
                if {[incr ${this}count($formula,) -1] == 0} {unset ${this}count($formula,)}
            } else {
                foreach cell [switched::cget $formula -cells] {
                    viewer::parse $cell array ignore ignore ignore
                    if {![catch {set asynchronous [modules::asynchronous $array]}] && $asynchronous}  { ;# note: may not be a module
                        viewer::unregisterTrace $this $array
                    }
                    if {[incr ${this}count($formula,$array) -1] == 0} {unset ${this}count($formula,$array)}
                }
            }
            set row $($this,row,$formula)
            set dataName $($this,dataName)
            unset ${dataName}($row,0) ${dataName}($row,1) ($this,row,$formula)
            $($this,namespace)::delete $row
            $($this,namespace)::update                                              ;# so that viewers immediately display void data
if {$global::withGUI} {
            dataTable::update $($this,table)
}
        }

        proc formulas {this} {
            set list {}
            foreach name [array names {} $this,row,*] {
                lappend list [lindex [split $name ,] end]
            }
            return [lsort -integer $list]
        }

if {$global::withGUI} {

        proc initializationConfiguration {this} {
            scan [namespace tail $($this,dataName)] %u index                                        ;# retrieve index from data name
            set arguments {}
            set rows {}
            foreach formula [formulas $this] {                               ;# note: always return configurations in the same order
                set list {}
                foreach option {cellindexes cells commenttext name text} {
                    lappend list -$option [switched::cget $formula -$option]
                }
                lappend rows $($this,row,$formula)
                lappend arguments $list
            }
            return [list\
                -dataindex $index -rows $rows -object $composite::($this,-object) -category $composite::($this,-category)\
                -configurations $arguments\
            ]
        }

        proc handleDrop {this} {
            if {![catch {set formulas $dragSite::data(FORMULAS)}]} {
                foreach formula $formulas {
                    set identical 0
                    foreach existing [formulas $this] {
                        if {[formulas::formula::equal $existing $formula]} {set identical $existing; break}
                    }
                    if {$identical > 0} {
                        lifoLabel::flash $global::messenger [format $formulas::(existingMessage) [switched::cget $identical -name]]
                        continue
                    }
                    manage $this [new $formula]
                }
            } elseif {[info exists dragSite::data(KILL)]} {
                delete $this                                                                                       ;# self destructs
            }
        }

        proc dragData {this format} {
            set cells [dataTable::dragData $($this,table) DATACELLS]
            switch $format {
                FORMULAS - OBJECTS {
                    foreach cell $cells {
                        regexp {\(([^,]+)} $cell dummy row
                        foreach {name value} [array get {} $this,row,*] {
                            if {$value == $row} {
                                set formulas([lindex [split $name ,] end]) {}
                                break
                            }
                        }
                    }
                    set objects [array names formulas]
                    if {([llength $objects] == 0) && [string equal $format OBJECTS]} {
                        return $this                                                 ;# return formulas table object itself if empty
                    } else {
                        return $objects
                    }
                }
                DATACELLS {                               ;# return data cells from the formulas module, not the internal data array
                    set namespace $($this,namespace)
                    set list {}
                    foreach cell $cells {
                        regexp {\((.+)\)$} $cell dummy coordinates
                        # note: works before columns are identically numbered between the local and formulas module data arrays
                        lappend list ${namespace}::data($coordinates)
                    }
                    return $list
                }
            }
        }

        proc pointed {this x y} {                                                      ;# return formula under specified coordinates
            set row [dataTable::dataRow $($this,table) [$($this,tablePath) index @$x,$y row]]
            if {[string length $row] > 0} {
                foreach {name value} [array get {} $this,row,*] {
                    if {$value == $row} {return [lindex [split $name ,] end]}
                }
            }
            return 0
        }

        proc enter {this x y} {
            raiseExistingFormulasDialog                                 ;# so that user stays aware a formulas table is being edited
            bindings::set $($this,bindings) <Motion> "formulas::table::motion $this %x %y"
            set ($this,cell) [$($this,tablePath) index @$x,$y]
            in $this $($this,cell) $x $y
        }

        proc leave {this} {
            bindings::set $($this,bindings) <Motion> {}
            catch {unset ($this,cell)}                                            ;# should not need to be caught but better be safe
        }

        proc motion {this x y} {
            set cell [$($this,tablePath) index @$x,$y]
            if {![info exists ($this,cell)]} {set ($this,cell) cell}                       ;# should never happen but better be safe
            if {[string equal $cell $($this,cell)]} return                                                              ;# no change
            in $this [set ($this,cell) $cell] $x $y
        }

        proc in {this cell x y} {
            scan $cell %d,%d row column
            if {($row < 0) || ($column != 0)} return                                 ;# ignore title areas and check for name column
            set formula [pointed $this $x $y]
            if {$formula == 0} return
            foreach {left top width height} [$($this,tablePath) bbox $cell] {}
            if {![info exists height]} return                                                 ;# check for invalid box, just in case
            catch {delete $($this,tip)}                                  ;# ephemeral tip has a good chance of being deleted already
            set ($this,tip) [new widgetTip\
                -path $($this,tablePath) -text [switched::cget $formula -commenttext]\
                -rectangle [list $left $top [expr {$left + $width}] [expr {$top + $height}]] -ephemeral 1\
            ]
        }

        proc monitored {this cell} {                                                     ;# implementation of viewer layer interface
            # note: cell is not part of a formula but rather a formula table data cell
            return [dataTable::monitored $($this,table) $cell]
        }

        proc setCellColor {this source color} { ;# source cell always comes from formulas module data: formulas<N>::data(row,column)
            if {![string equal [namespace qualifiers $source] $($this,namespace)]} return                      ;# not for this table
            scan $source {%*[^(](%lu,%u)} row column
            # note: works before columns are identically numbered between the local and formulas module data arrays
            dataTable::setCellColor $($this,table) $row $column $color
        }

        proc title {this} {
            regsub {<0>$} $modules::instance::($($this,instance),identifier) {} title
            return $title                                      ;# with removed trailing namespace index for first instance of module
        }

}

    }


    class formula {

        proc formula {this args} switched {$args} {
            if {![info exists (interpreter)]} {set (interpreter) [interpreter $this]}
            switched::complete $this
        }

        proc formula {this copy} switched {} {                                                                   ;# copy constructor
            if {![info exists (interpreter)]} {set (interpreter) [interpreter $this]}
            switched::complete $this
            copyOptions $this $copy
        }

        proc ~formula {this} {
            variable ${this}cell
            variable ${this}last

            catch {unset ${this}cell}
            catch {unset ${this}last}
            if {[string length $switched::($this,-deletecommand)] > 0} {
                uplevel #0 $switched::($this,-deletecommand)                                ;# always invoke command at global level
            }
        }

        proc interpreter {this} {
            set interpreter [interp create -safe]           ;# safe interpreter with only expr{} command and no variables whatsoever
            foreach variable [$interpreter eval {info globals}] {
                $interpreter eval "unset $variable"
            }
            foreach command [$interpreter eval {info commands}] {
                switch $command {expr - rename continue}
                $interpreter eval "rename $command {}"
            }
            $interpreter eval {rename rename {}}
            interp recursionlimit $interpreter 1
            return $interpreter
        }

        proc copyOptions {to from} {
            switched::configure $to -cellindexes [switched::cget $from -cellindexes] -cells [switched::cget $from -cells]\
                -commenttext [switched::cget $from -commenttext] -name [switched::cget $from -name]\
                -text [switched::cget $from -text] -deletecommand [switched::cget $from -deletecommand]
        }

        proc options {this} {
            return [list\
                [list -cellindexes {} {}]\
                [list -cells {} {}]\
                [list -commenttext {} {}]\
                [list -deletecommand {} {}]\
                [list -name {} {}]\
                [list -text {} {}]\
            ]
        }

        proc set-cellindexes {this value} {
            catch {unset ($this,expression)}                                                        ;# force expression regeneration
        }
        proc set-cells {this value} {
            catch {unset ($this,expression)}
        }
        proc set-text {this value} {
            catch {unset ($this,expression)}
        }

        proc set-commenttext {this value} {}                  ;# note: with a "text" ending so that it is properly in dashboard file

        proc set-deletecommand {this value} {}

        proc set-name {this value} {}

        proc expression {this} {
            variable ${this}cell
            variable ${this}last

            catch {unset ${this}cell}                                                              ;# regenerate included cells list
            catch {unset ${this}last}
            set text $switched::($this,-text)
            set offset(0) 0
            set length 0; set index 0
            foreach line [split $text \n] {
                incr length [string length $line]
                set offset([incr index]) [incr length]                                              ;# also count new line character
            }
            set indexes {}
            foreach value $switched::($this,-cellindexes) {
                foreach {line index} [split $value .] {}
                incr line -1                                                 ;# normalize line numbers (start from 1 in text widget)
                lappend indexes [expr {$offset($line) + $index}]
            }
            set expression {}
            set first 0
            foreach index $indexes cell $switched::($this,-cells) {
                viewer::parse $cell array row column ignore
                set key $array,$row,$column
                set ${this}cell($key) $cell                                                 ;# remember cell inclusion in expression
                set string [string range $text $first [expr {$index - 1}]]
                switch -regexp -- $string {
                    {delta\s*\(\s*$} {
                        regsub {delta\s*\(\s*$} $string {} string                    ;# remove function name and opening parentheses
                        # force integers subtraction:
                        append expression $string \( int(\${$cell}-\${formulas::formula::${this}last($key)})
                        set last($key) {}
                    }
                    {diff\s*\(\s*$} {
                        regsub {diff\s*\(\s*$} $string {} string
                        # force double calculations:
                        append expression $string \( double(\${$cell})-\${formulas::formula::${this}last($key)}
                        set last($key) {}
                    }
                    {last\s*\(\s*$} {
                        regsub {last\s*\(\s*$} $string {} string
                        append expression $string \( \${formulas::formula::${this}last($key)}
                        set last($key) {}
                    }
                    default {
                        append expression $string \${$cell}
                    }
                }
                set first [expr {$index + 1}]                                              ;# account for cell replacement character
            }
            append expression [string range $text $first end]
            set ($this,last) [array names last]                                                       ;# cells that need last values
            return $expression
        }

        proc value {this} {
            variable ${this}cell
            variable ${this}last

            check $this
            if {![info exists ($this,expression)]} {
                set ($this,expression) [expression $this]
            }
            set error 0
            set now [expr {[clock clicks -milliseconds] / 1000.0}]
            set seconds ?; catch {set seconds [expr {$now - $($this,seconds)}]}
            set ($this,seconds) $now
            set pattern {diff\s*\(\s*time\s*\)}                 ;# use expression variable for better performance by pre-compilation
            if {([regsub -all $pattern $($this,expression) $seconds expression] > 0) && [string equal $seconds ?]} {
                set result {diff(time) not yet available}
                set error 1
            } else {
                foreach key $($this,last) {                                   ;# check cells that require last value to be available
                    if {![info exists ${this}last($key)]} {
                        foreach {array row column} [split $key ,] break
                        set result "[lindex [viewer::label $array $row $column] 0] data not yet available"
                        set error 1
                        break
                    }
                }
            }
            if {!$error} {
                set error [catch {$(interpreter) eval expr [list [subst -nobackslashes -nocommands $expression]]} result]
            }
            foreach {key cell} [array get ${this}cell] {
                catch {set ${this}last($key) [set $cell]}
            }
            foreach key [array names ${this}last] {                                             ;# delete no longer used last values
                if {![info exists ${this}cell($key)]} {unset ${this}last($key)}
            }
            if {$error} {
                error $result                                                                                  ;# throw error if any
            } else {
                return $result                                                            ;# implies value is correct if we get here
            }
        }

        proc check {this} {
            foreach function [list delta diff last] {                                          ;# check arguments of added functions
                set text $switched::($this,-text)
                while {[string length $text] > 0} {
                    set expression "$function\\s*\\((\[^\)\]*)\\)"
                    if {![regexp $expression $text ignore argument]} break
                    switch [string trim $argument] {
                        \$ {}
                        time {
                            if {![string equal $function diff]} {
                                error "${function}(time) should be diff(time)"
                            }
                        }
                        default {
                            regsub -all {\$} $argument value argument                            ;### replace with actual values ###
                            if {[string equal $function diff]} {
                                set message "${function}() takes one argument (data cell or \"time\")"
                            } else {
                                set message "${function}() takes one data cell argument"
                            }
                            if {[string length [string trim $argument]] > 0} {append message ", not: $argument"}
                            error $message
                        }
                    }
                    regexp -indices $expression $text indexes
                    set text [string range $text [expr {[lindex $indexes end] + 1}] end]                     ;# check remaining text
                }
            }
        }

        proc equal {formula1 formula2} {
            regsub -all {\s} [expression $formula1] {} expression1                                              ;# ignore whitespace
            regsub -all {\s} [expression $formula2] {} expression2
            return [string equal $expression1 $expression2]                              ;# note: name and comments are not compared
        }

    }


}