File: widgetPlus.tcl

package info (click to toggle)
tklib 0.7%2B20210111-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 17,676 kB
  • sloc: tcl: 82,240; sh: 5,801; ansic: 792; pascal: 359; makefile: 70; sed: 53; exp: 21
file content (1677 lines) | stat: -rw-r--r-- 57,846 bytes parent folder | download
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
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
# ------------------------------------------------------------------------------
# FILE:
#       widgetPlus-*.dmw, widgetPlus-*.tm
#
# DESCRIPTION:
#       Module to provide enhancements to entry, spinbox, ttk::entry,
#       ttk::spinbox, and ttk::combobox widgets, with Undo/Redo, <<Selection>>,
#       -inactiveselectbackground and improved bindings.
#
# LICENCE:
#       Copyright (C) 2015-2018 Keith Nash.
#       This file is part of Tklib and may be used subject to the terms in
#       file license.terms; please note in particular the terms repeated here:
#
#     IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY
#     FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
#     ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY
#     DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE
#     POSSIBILITY OF SUCH DAMAGE.
#
#     THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
#     INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
#     FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE
#     IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE
#     NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
#     MODIFICATIONS.
#
# ------------------------------------------------------------------------------
# One line exceeds 80 columns, for clarity.
# Conventional use of namespace/package names.
# Defines bindtags EntryPlus, SpinboxPlus, TEntryPlus, TSpinboxPlus,
# TComboboxPlus, and BwEntryPlus.
# Docs are in "man n widgetPlus".

package require Tcl 8.5
package require Tk 8.5
package require snit

namespace eval ::widgetPlus {
    variable BWidgetEnabled 0
    namespace export entryPlus spinboxPlus
    namespace export ttkEntryPlus ttkSpinboxPlus ttkComboboxPlus
}


# ------------------------------------------------------------------------------
#  Commands ::widgetPlus::entryPlus ::widgetPlus::spinboxPlus
#  ::widgetPlus::ttkEntryPlus ::widgetPlus::ttkSpinboxPlus
#  ::widgetPlus::ttkComboboxPlus
# ------------------------------------------------------------------------------
# Commands for objects ::widgetPlus::entryPlus etc.
# These simple wrapper commands allow most of the code to be held in a common
# object, ::widgetPlus::WidgetPlusPrivateCore.
#
# It is a pity not to use snit::widgetadaptor wrappers for
# ::widgetPlus::WidgetPlusPrivateCore, but they do give more obscure error
# messages, chiefly by using "::hull2.e" not ".e" in the message text.  This
# change causes 20 more (harmless) test failures in entryPlus.test.
#
# A downside to these simple wrappers is that, while the Snit typemethod
#    widgetPlus::entryPlus info instances
# works, it is really an alias to 
#    widgetPlus::WidgetPlusPrivateCore info instances
# and so it includes "types" such as widgetPlus::spinboxPlus as well as
# widgetPlus::entryPlus.
# ------------------------------------------------------------------------------

proc ::widgetPlus::entryPlus {args} {
    set sub [lindex $args 0]
    set lenny [llength $args]
    if {($sub eq {create}) && ($lenny > 1)} {
        set win  [lindex $args 1]
        set args [lrange $args 2 end]
    } elseif {[string index $sub 0] eq {.}} {
        set win  $sub
        set args [lrange $args 1 end]
    } elseif {$lenny == 0} {
        set    msg {wrong # args: }
        append msg {should be "entryPlus pathName ?-option value ...?"}
        return -code error $msg
    } else {
        # A typemethod.
        return [::widgetPlus::WidgetPlusPrivateCore {*}$args]
    }
    ::widgetPlus::WidgetPlusPrivateCore create $win entry {*}$args
}

proc ::widgetPlus::spinboxPlus {args} {
    set sub [lindex $args 0]
    set lenny [llength $args]
    if {($sub eq {create}) && ($lenny > 1)} {
        set win  [lindex $args 1]
        set args [lrange $args 2 end]
    } elseif {[string index $sub 0] eq {.}} {
        set win  $sub
        set args [lrange $args 1 end]
    } elseif {$lenny == 0} {
        set    msg {wrong # args: }
        append msg {should be "spinboxPlus pathName ?-option value ...?"}
        return -code error $msg
    } else {
        # A typemethod.
        return [::widgetPlus::WidgetPlusPrivateCore {*}$args]
    }
    ::widgetPlus::WidgetPlusPrivateCore create $win spinbox {*}$args
}

proc ::widgetPlus::ttkEntryPlus {args} {
    set sub [lindex $args 0]
    set lenny [llength $args]
    if {($sub eq {create}) && ($lenny > 1)} {
        set win  [lindex $args 1]
        set args [lrange $args 2 end]
    } elseif {[string index $sub 0] eq {.}} {
        set win  $sub
        set args [lrange $args 1 end]
    } elseif {$lenny == 0} {
        set    msg {wrong # args: }
        append msg {should be "ttkEntryPlus pathName ?-option value ...?"}
        return -code error $msg
    } else {
        # A typemethod.
        return [::widgetPlus::WidgetPlusPrivateCore {*}$args]
    }
    ::widgetPlus::WidgetPlusPrivateCore create $win ttk::entry {*}$args
}

proc ::widgetPlus::ttkSpinboxPlus {args} {
    set sub [lindex $args 0]
    set lenny [llength $args]
    if {($sub eq {create}) && ($lenny > 1)} {
        set win  [lindex $args 1]
        set args [lrange $args 2 end]
    } elseif {[string index $sub 0] eq {.}} {
        set win  $sub
        set args [lrange $args 1 end]
    } elseif {$lenny == 0} {
        set    msg {wrong # args: }
        append msg {should be "ttkSpinboxPlus pathName ?-option value ...?"}
        return -code error $msg
    } else {
        # A typemethod.
        return [::widgetPlus::WidgetPlusPrivateCore {*}$args]
    }
    ::widgetPlus::WidgetPlusPrivateCore create $win ttk::spinbox {*}$args
}

proc ::widgetPlus::ttkComboboxPlus {args} {
    set sub [lindex $args 0]
    set lenny [llength $args]
    if {($sub eq {create}) && ($lenny > 1)} {
        set win  [lindex $args 1]
        set args [lrange $args 2 end]
    } elseif {[string index $sub 0] eq {.}} {
        set win  $sub
        set args [lrange $args 1 end]
    } elseif {$lenny == 0} {
        set    msg {wrong # args: }
        append msg {should be "ttkComboboxPlus pathName ?-option value ...?"}
        return -code error $msg
    } else {
        # A typemethod.
        return [::widgetPlus::WidgetPlusPrivateCore {*}$args]
    }
    ::widgetPlus::WidgetPlusPrivateCore create $win ttk::combobox {*}$args
}


# ------------------------------------------------------------------------------
#  Proc ::widgetPlus::replaceBindtag
# ------------------------------------------------------------------------------
# Command to remove a specific bindtag on a window, and replace it with 0 or
# more others.
# ------------------------------------------------------------------------------

proc ::widgetPlus::replaceBindtag {w OldTag args} {
    set pos [lsearch -exact [bindtags $w] $OldTag]
    if {$pos == -1} {
        return 0
    } else {
        bindtags $w [lreplace [bindtags $w] $pos $pos {*}$args]
        return 1
    }
}


# ------------------------------------------------------------------------------
#  Proc ::widgetPlus::copyBindtag
# ------------------------------------------------------------------------------
# Command to copy all the bindings from one bindtag to another.
# ------------------------------------------------------------------------------

proc ::widgetPlus::copyBindtag {from to} {
    foreach binding [bind $from] {
        bind $to $binding [bind $from $binding]
    }
    return
}


# ------------------------------------------------------------------------------
#  Bindtag EntryPlus (replaces bindtag Entry for widget entry)
# ------------------------------------------------------------------------------
# Cf. bindtag Entry defined in Tk file library/entry.tcl.
#
# Copy the bindings at run time from Entry to EntryPlus.  Replace some bindings
# and add new ones.  Define in this file all the commands used by the
# replacement bindings, so that the bindings are resilient against changes in
# Tk file library/entry.tcl.
# ------------------------------------------------------------------------------

# ------------------------------------------------------------------------------
# (1) Copy all bindings from Entry to EntryPlus
# ------------------------------------------------------------------------------

# Ensure entry.tcl has been sourced.
catch ::tk::EntryPaste

::widgetPlus::copyBindtag Entry EntryPlus


# ------------------------------------------------------------------------------
# (2) Replace two bindings copied from bindtag Entry.
# ------------------------------------------------------------------------------

# Give x11 the same behavior as other windowing systems.

bind EntryPlus <<Paste>> {
    catch {
	if {[tk windowingsystem] ne "x11TheOldFashionedWay"} {
	    catch {
		%W delete sel.first sel.last
	    }
	}
	%W insert insert [::widgetPlus::GetSelection %W CLIPBOARD]
	widgetPlus::EntrySeeInsert %W
    }
}

# Remove this antiquated binding (which inserts text from the PRIMARY
# selection, on windowing systems other than win32).

bind EntryPlus <Insert> {# nothing}


# ------------------------------------------------------------------------------
# (2a) Define the commands used by the bindings (2), so they are resilient
#      against any incompatible revisions to library/entry.tcl.
# ------------------------------------------------------------------------------

# ::widgetPlus::EntrySeeInsert -- copy of ::tk::EntrySeeInsert
# Make sure that the insertion cursor is visible in the entry window.
# If not, adjust the view so that it is.
#
# Arguments:
# w -		The entry window.

proc ::widgetPlus::EntrySeeInsert w {
    set c [$w index insert]
    if {($c < [$w index @0]) || ($c > [$w index @[winfo width $w]])} {
	$w xview $c
    }
}

# ::widgetPlus::GetSelection -- copy of ::tk::GetSelection
#   This tries to obtain the default selection.  On Unix, we first try
#   and get a UTF8_STRING, a type supported by modern Unix apps for
#   passing Unicode data safely.  We fall back on the default STRING
#   type otherwise.  On Windows, only the STRING type is necessary.
# Arguments:
#   w	The widget for which the selection will be retrieved.
#	Important for the -displayof property.
#   sel	The source of the selection (PRIMARY or CLIPBOARD)
# Results:
#   Returns the selection, or an error if none could be found
#
if {[tk windowingsystem] ne "win32"} {
    proc ::widgetPlus::GetSelection {w {sel PRIMARY}} {
	if {[catch {
	    selection get -displayof $w -selection $sel -type UTF8_STRING
	} txt] && [catch {
	    selection get -displayof $w -selection $sel
	} txt]} then {
	    return -code error -errorcode {TK SELECTION NONE} \
		"could not find default selection"
	} else {
	    return $txt
	}
    }
} else {
    proc ::widgetPlus::GetSelection {w {sel PRIMARY}} {
	if {[catch {
	    selection get -displayof $w -selection $sel
	} txt]} then {
	    return -code error -errorcode {TK SELECTION NONE} \
		"could not find default selection"
	} else {
	    return $txt
	}
    }
}

# ------------------------------------------------------------------------------
# (3) Add new bindings that depend on widgetPlus commands.
# ------------------------------------------------------------------------------

bind EntryPlus <<Undo>> {
    if {![catch { %W edit undo }]} {
	# Cancel the selection so that Undo does not mess it up.
	%W selection clear
    }
}

bind EntryPlus <<Redo>> {
    if {![catch { %W edit redo }]} {
	# Cancel the selection so that Redo does not mess it up.
	%W selection clear
    }
}

# These bindings let the widgetPlus have option -inactiveselectbackground as
# well as -selectbackground.

bind EntryPlus <FocusIn> {
    %W SelectColorIn
}

bind EntryPlus <FocusOut> {
    %W SelectColorOut
}


# ------------------------------------------------------------------------------
#  Proc ::widgetPlus::EnableBWidget
# ------------------------------------------------------------------------------
# Command to check that BWidget Entry is available, and then copy and modify its
# bindtag BwEntry to BwEntryPlus.
# ------------------------------------------------------------------------------

proc ::widgetPlus::EnableBWidget {} {
    variable BWidgetEnabled

    if {[catch {package present BWidget}]} {
        # Do not load BWidget here - it is clearer if the caller does this.
        return -code error {package BWidget has not been loaded}
    }

    # Ensure bwidget-${ver}/entry.tcl has been sourced.
    catch ::Entry

    EnablePrivateCommand
    set BWidgetEnabled 1

    return
}


# ------------------------------------------------------------------------------
#  Proc ::widgetPlus::EnableSlab
# ------------------------------------------------------------------------------
# Command to check that Slab::Entry is available, and then copy and modify its
# bindtag BwEntry to BwEntryPlus.
#
# Slab and BWidget use identical bindings.  This may change in future.
# ------------------------------------------------------------------------------

proc ::widgetPlus::EnableSlab {} {
    variable BWidgetEnabled

    if {[catch {package present Slab}]} {
        # Do not load Slab here - it is clearer if this is done by the caller.
        return -code error {package Slab has not been loaded}
    }

    # Ensure module Slab::Entry has been sourced.
    catch ::Slab::Entry

    EnablePrivateCommand
    set BWidgetEnabled 1

    return
}


proc ::widgetPlus::EnablePrivateCommand {} {
#indent-4

# ------------------------------------------------------------------------------
#  Bindtag BwEntryPlus (replaces bindtag BwEntry for BWidget's Entry widget)
# ------------------------------------------------------------------------------
# Cf. bindtag BwEntry defined in BWidget file library/entry.tcl.
#
# Copy the bindings at run time from BwEntry to BwEntryPlus.  Replace some
# bindings and add new ones.  Define in this file all the commands used by the
# replacement bindings, so that the bindings are resilient against changes in
# BWidget file bwidget-${ver}/entry.tcl.
# ------------------------------------------------------------------------------

# ------------------------------------------------------------------------------
# (1) Copy all bindings from BwEntry to BwEntryPlus
# ------------------------------------------------------------------------------

::widgetPlus::copyBindtag BwEntry BwEntryPlus


# ------------------------------------------------------------------------------
# (2) Replace two bindings copied from bindtag BwEntry.
# ------------------------------------------------------------------------------

# Give x11 the same behavior as other windowing systems.

bind BwEntryPlus <<Paste>> {
    catch {
	if {[tk windowingsystem] ne "x11TheOldFashionedWay"} {
	    catch {
		%W delete sel.first sel.last
	    }
	}
	%W insert insert [::widgetPlus::GetSelection %W CLIPBOARD]
	widgetPlus::EntrySeeInsert %W
    }
}

# Remove this antiquated binding (which inserts text from the PRIMARY
# selection, on windowing systems other than win32).

bind BwEntryPlus <Insert> {# nothing}


# ------------------------------------------------------------------------------
# (3) Add new bindings that depend on widgetPlus commands.
# ------------------------------------------------------------------------------

bind BwEntryPlus <<Undo>> {
    if {![catch { %W edit undo }]} {
	# Cancel the selection so that Undo does not mess it up.
	%W selection clear
    }
}

bind BwEntryPlus <<Redo>> {
    if {![catch { %W edit redo }]} {
	# Cancel the selection so that Redo does not mess it up.
	%W selection clear
    }
}

# These bindings let the widgetPlus have option -inactiveselectbackground as
# well as -selectbackground.

bind BwEntryPlus <FocusIn> {
    %W SelectColorIn
}

bind BwEntryPlus <FocusOut> {
    %W SelectColorOut
}

return

#indent_4
}


# ------------------------------------------------------------------------------
#  Bindtag SpinboxPlus (replaces bindtag Spinbox for widget spinbox)
# ------------------------------------------------------------------------------
# Cf. bindtag Spinbox defined in Tk file library/spinbox.tcl.
#
# Copy the bindings at run time from Spinbox to SpinboxPlus.  Replace some
# bindings and add new ones.  Define in this file all the commands used by the
# replacement bindings, so that the bindings are resilient against changes in
# Tk files library/entry.tcl and library/spinbox.tcl.
# ------------------------------------------------------------------------------

# ------------------------------------------------------------------------------
# (1) Copy all bindings from Spinbox to SpinboxPlus
# ------------------------------------------------------------------------------

# Ensure entry.tcl and spinbox.tcl have been sourced.
namespace eval ::tk::spinbox {}
catch ::tk::EntryPaste
catch ::tk::spinbox::Paste

::widgetPlus::copyBindtag Spinbox SpinboxPlus


# ------------------------------------------------------------------------------
# (2) Replace two bindings copied from bindtag TEntry.
# ------------------------------------------------------------------------------

bind SpinboxPlus <Insert> {# nothing}

bind SpinboxPlus <<Paste>> {
    catch {
	if {[tk windowingsystem] ne "x11TheOldFashionedWay"} {
	    catch {
		%W delete sel.first sel.last
	    }
	}
	%W insert insert [::widgetPlus::GetSelection %W CLIPBOARD]
	::widgetPlus::EntrySeeInsert %W
    }
}


# ------------------------------------------------------------------------------
# (2a) Define the commands used by the bindings (2), so they are resilient
#      against any incompatible revisions to library/spinbox.tcl.
# ------------------------------------------------------------------------------

# ::widgetPlus::SpinboxPaste -- copy of ::tk::spinbox::Paste
# This procedure sets the insertion cursor to the current mouse position,
# pastes the selection there, and sets the focus to the window.
#
# Arguments:
# w -		The spinbox window.
# x -		X position of the mouse.

proc ::widgetPlus::SpinboxPaste {w x} {
    $w icursor [::widgetPlus::SpinboxClosestGap $w $x]
    catch {$w insert insert [::widgetPlus::GetSelection $w PRIMARY]}
    if {"disabled" eq [$w cget -state]} {
	focus $w
    }
}


# ::widgetPlus::SpinboxClosestGap -- copy of ::tk::spinbox::ClosestGap
# Given x and y coordinates, this procedure finds the closest boundary
# between characters to the given coordinates and returns the index
# of the character just after the boundary.
#
# Arguments:
# w -		The spinbox window.
# x -		X-coordinate within the window.

proc ::widgetPlus::SpinboxClosestGap {w x} {
    set pos [$w index @$x]
    set bbox [$w bbox $pos]
    if {($x - [lindex $bbox 0]) < ([lindex $bbox 2]/2)} {
	return $pos
    }
    incr pos
}


# ------------------------------------------------------------------------------
# (3) Add new bindings that depend on widgetPlus commands.
# ------------------------------------------------------------------------------

bind SpinboxPlus <<Undo>> {
    if {![catch { %W edit undo }]} {
	# Cancel the selection so that Undo does not mess it up.
	%W selection clear
    }
}

bind SpinboxPlus <<Redo>> {
    if {![catch { %W edit redo }]} {
	# Cancel the selection so that Redo does not mess it up.
	%W selection clear
    }
}

# These bindings let the widgetPlus have option -inactiveselectbackground as
# well as -selectbackground.

bind SpinboxPlus <FocusIn> {
    %W SelectColorIn
}

bind SpinboxPlus <FocusOut> {
    %W SelectColorOut
}


# ------------------------------------------------------------------------------
#  Bindtag TEntryPlus (replaces bindtag TEntry for widget ttk::entry)
# ------------------------------------------------------------------------------
# Cf. bindtag TEntry defined in Tk file library/ttk/entry.tcl.
#
# Copy the bindings at run time from TEntry to TEntryPlus.  Replace some
# bindings and add new ones.  Define in this file all the commands used by the
# replacement bindings, so that the bindings are resilient against changes in
# Tk file library/ttk/entry.tcl.
# ------------------------------------------------------------------------------

# ------------------------------------------------------------------------------
# (1) Copy all bindings from TEntry to TEntryPlus
# ------------------------------------------------------------------------------

# File tk.tcl automatically sources ttk/ttk.tcl which sources all ttk files.

::widgetPlus::copyBindtag TEntry TEntryPlus


# ------------------------------------------------------------------------------
# (2) Replace no bindings copied from bindtag TEntry.
# ------------------------------------------------------------------------------


# ------------------------------------------------------------------------------
# (3) Add new bindings that depend on widgetPlus commands.
# ------------------------------------------------------------------------------

bind TEntryPlus <<Undo>> {
    if {![catch { %W edit undo }]} {
	# Cancel the selection so that Undo does not mess it up.
	%W selection clear
    }
}

bind TEntryPlus <<Redo>> {
    if {![catch { %W edit redo }]} {
	# Cancel the selection so that Redo does not mess it up.
	%W selection clear
    }
}


# ------------------------------------------------------------------------------
#  Bindtag TSpinboxPlus (replaces bindtag TSpinbox for widget ttk::spinbox)
# ------------------------------------------------------------------------------
# Cf. bindtag TSpinbox defined in Tk file library/ttk/spinbox.tcl.
#
# Copy the bindings at run time from TSpinbox to TSpinboxPlus.  Replace some
# bindings and add new ones.  Define in this file all the commands used by the
# replacement bindings, so that the bindings are resilient against changes in
# Tk files library/ttk/entry.tcl and library/ttk/spinbox.tcl.
# ------------------------------------------------------------------------------

# ------------------------------------------------------------------------------
# (1) Copy all bindings from TSpinbox to TSpinboxPlus
# ------------------------------------------------------------------------------
# (TSpinbox is itself copied with revisions from TEntry.)

# File tk.tcl automatically sources ttk/ttk.tcl which sources all ttk files.

::widgetPlus::copyBindtag TSpinbox TSpinboxPlus


# ------------------------------------------------------------------------------
# (2) Replace no bindings copied from bindtag TSpinbox.
# ------------------------------------------------------------------------------


# ------------------------------------------------------------------------------
# (3) Add new bindings that depend on widgetPlus commands.
# ------------------------------------------------------------------------------

bind TSpinboxPlus <<Undo>> {
    if {![catch { %W edit undo }]} {
	# Cancel the selection so that Undo does not mess it up.
	%W selection clear
    }
}

bind TSpinboxPlus <<Redo>> {
    if {![catch { %W edit redo }]} {
	# Cancel the selection so that Redo does not mess it up.
	%W selection clear
    }
}


# ------------------------------------------------------------------------------
#  Bindtag TComboboxPlus (replaces bindtag TCombobox for widget ttk::combobox)
# ------------------------------------------------------------------------------
# Cf. bindtag TCombobox defined in Tk file library/ttk/combobox.tcl.
#
# Copy the bindings at run time from TCombobox to TComboboxPlus.  Replace some
# bindings and add new ones.  Define in this file all the commands used by the
# replacement bindings, so that the bindings are resilient against changes in
# Tk files library/ttk/entry.tcl and library/ttk/combobox.tcl.
# ------------------------------------------------------------------------------

# ------------------------------------------------------------------------------
# (1) Copy all bindings from TCombobox to TComboboxPlus
# ------------------------------------------------------------------------------
# (TCombobox is itself copied with revisions from TEntry.)

# File tk.tcl automatically sources ttk/ttk.tcl which sources all ttk files.

::widgetPlus::copyBindtag TCombobox TComboboxPlus


# ------------------------------------------------------------------------------
# (2) Replace no bindings copied from bindtag TCombobox.
# ------------------------------------------------------------------------------


# ------------------------------------------------------------------------------
# (3) Add new bindings that depend on widgetPlus commands.
# ------------------------------------------------------------------------------

bind TComboboxPlus <<Undo>> {
    if {![catch { %W edit undo }]} {
	# Cancel the selection so that Undo does not mess it up.
	%W selection clear
    }
}

bind TComboboxPlus <<Redo>> {
    if {![catch { %W edit redo }]} {
	# Cancel the selection so that Redo does not mess it up.
	%W selection clear
    }
}


# ------------------------------------------------------------------------------
#  Object widgetPlus::color
# ------------------------------------------------------------------------------
# A Snit validation type for a Tk color.
# Use "-strict 0" for cases where the acceptable value is a color or {}.
# ------------------------------------------------------------------------------

snit::type widgetPlus::color {
    option -strict -type snit::boolean -default 1

    typemethod validate {value} {
        if {[catch {winfo rgb . $value} color]} {
            set msg "unknown color name \"$value\""
            return -code error -errorcode INVALID $msg
        }
        return $value
    }

    constructor {args} {
        $self configurelist $args
        return
    }

    method validate {value} {
        if {($value eq {}) && (!$options(-strict))} {
             return {}
        }

        $type validate $value
    }
}


# ------------------------------------------------------------------------------
#  Object ::widgetPlus::WidgetPlusPrivateCore
# ------------------------------------------------------------------------------
# This object forms the core of ::widgetPlus::entryPlus etc.  Its existence
# avoids the quintuplication of most of its code.
# ------------------------------------------------------------------------------

snit::widgetadaptor ::widgetPlus::WidgetPlusPrivateCore {
#indent-4

variable My -array {
     ,list     {{}}
     ,pointer  0
     ,modified 0
     ,trace    {}
     ,oldValue {}
}

option {-undo undo Undo} \
        -default 1 \
        -type snit::boolean \
        -configuremethod SetOption

option {-maxundo maxUndo MaxUndo} \
        -default 0 \
        -type snit::integer

option {-selectbackground selectBackground Foreground} \
        -default #418bd4 \
        -type widgetPlus::color \
        -configuremethod SetOption

option {-inactiveselectbackground inactiveSelectBackground Foreground} \
        -default #c3c3c3 \
        -type {widgetPlus::color -strict 0} \
        -configuremethod SetOption

option {-textvariable textVariable Variable} \
        -default {} \
        -configuremethod SetOption

delegate option * to hull
delegate method * to hull


typevariable Our -array {
    ,classList       {entry ttk::entry spinbox ttk::spinbox ttk::combobox}
    ,themedClassList {ttk::entry ttk::spinbox ttk::combobox}
    ,c2t             {
                          Entry     entry
                          TEntry    ttk::entry
                          Spinbox   spinbox
                          TSpinbox  ttk::spinbox
                          TCombobox ttk::combobox
                     }
}

variable My -array {
    ,type   {}
}


# ------------------------------------------------------------------------------
#  Constructor
# ------------------------------------------------------------------------------
# The command can be run regardless of whether the entry, spinbox, ttk::entry,
# ttk::spinbox, or ttk::combobox widget has already been created.
#
# Note the first argument "kind", which is the name of the widget to be used as
# the hull.  This argument is provided by the wrapper commands
# ::widgetPlus::entryPlus etc, and is not visible to end users.
# ------------------------------------------------------------------------------

constructor {kind args} {
    if {$kind ni $Our(,classList)} {
        set msg "argument \"kind\" must be one of entry,\
                 spinbox, ttk::entry, ttk::spinbox, or ttk::combobox"
        return -code error $msg
    }
    if {$kind eq {entry}} {
        set ia an
    } else {
        set ia a
    }

    set My(,type) $kind

    # When the hull is fed options one at a time, it raises an error if it gets
    # an incompatible combination (e.g. spinbox -from and -to).  To avoid this,
    # organise the arguments here and pass them to the hull in one command.
    set hullOpts $args
    set selfOpts {}
    foreach key {
        -undo
        -maxundo
        -selectbackground
        -inactiveselectbackground
        -textvariable
    } {
        dict unset hullOpts $key
        if {[dict exists $args $key]} {
            dict set selfOpts $key [dict get $args $key]
        }
    }

    if {[winfo exists $win]} {
        # Use an existing widget as the hull, if it is "suitable", i.e.
        # - It must be an entry, spinbox, ttk::entry, ttk::spinbox, or
        #   ttk::combobox widget
        # - Its "type" must agree with that specified by argument "kind"
        # - It must not already be wrapped by widgetPlus::WidgetPlusPrivateCore

        if {![dict exists $Our(,c2t) [winfo class $win]]} {
            set msg "window $win already exists, but it is not $ia $My(,type)"
            return -code error $msg

        } elseif {[dict get $Our(,c2t) [winfo class $win]] ne $My(,type)} {
            set msg "window $win already exists, but it is not $ia $My(,type)"
            return -code error $msg

        } elseif {![catch {$win EntryPlusCanary}]} {
            set msg "window $win already exists, but it is\
                     already wrapped by widgetPlus"
            return -code error $msg

        } else {
            installhull $win
            if {![$self IsThemed]} {
                $self configure -selectbackground [$hull cget -selectbackground]
            }
            $self configure -textvariable [$hull cget -textvariable]
            $hull configure {*}$hullOpts
        }
    } else {
        # Create a new widget for the hull.
        installhull using $My(,type) {*}$hullOpts
    }

    $self configurelist $selfOpts
    # Options -selectbackground, -inactiveselectbackground have no effect
    # if the widget is themed, and they do not propagate to the hull.

    set tag [winfo class $win]
    ::widgetPlus::replaceBindtag $win $tag ${tag}Plus
    if {($tag eq {Entry}) && ($::widgetPlus::BWidgetEnabled)} {
        ::widgetPlus::replaceBindtag $win BwEntry BwEntryPlus
    }

    if {[focus -displayof $win] eq $win} {
        $self SelectColorIn
    } else {
        $self SelectColorOut
    }

    return SET_BY_SNIT
}


# ------------------------------------------------------------------------------
#  Destructor
# ------------------------------------------------------------------------------

destructor {
    set cb [mymethod TextVarTracer]
    set val $options(-textvariable)
    if {$val ne {}} {
        namespace eval :: [list trace remove variable $val {write unset} $cb]
    }
    return
}


# ------------------------------------------------------------------------------
#  Method EntryPlusCanary
# ------------------------------------------------------------------------------
# The existence of this method indicates that this is a
# widgetPlus::WidgetPlusPrivateCore widget.
# It is called by the constructor to test that a
# widgetPlus::WidgetPlusPrivateCore widget does not use another
# widgetPlus::WidgetPlusPrivateCore as its hull.
# ------------------------------------------------------------------------------

method EntryPlusCanary {} {
    return
}


# ------------------------------------------------------------------------------
#  Method SetOption
# ------------------------------------------------------------------------------
# Snit configuremethod for options -selectbackground -inactiveselectbackground.
# ------------------------------------------------------------------------------

method SetOption {opt val} {
    if {$opt ni {-selectbackground -inactiveselectbackground
                 -textvariable -undo}
    } {
        return -code error {argument "opt" must be -selectbackground,\
                -inactiveselectbackground, -textvariable, or -undo}
    }

    set oldVal $options($opt)
    set options($opt) $val

    if 0 {
    } elseif {    ($opt eq {-selectbackground})
               && ([focus -displayof $win] eq $win)
    } {
        $self SelectColorIn

    } elseif {    ($opt eq {-inactiveselectbackground})
               && ([focus -displayof $win] ne $win)
    } {
        $self SelectColorOut

    } elseif {    ($opt eq {-textvariable}) && ($val ne $oldVal)} {
        set cb [mymethod TextVarTracer]
        if {$oldVal ne {}} {
            namespace eval :: [list trace remove variable $oldVal {write unset} $cb]
        } else {
        }

        set ClearOldVal 1
        if {$val ne {}} {
            namespace eval :: [list trace add variable $val {write unset} $cb]

            # If the variable's val is defined, this will fire the trace and
            # will call Push and set My(,oldValue).
            catch {
                set ValueOfVar [namespace eval :: [list set $val]]
                namespace eval :: [list set $val $ValueOfVar]
                set ClearOldVal 0
            }
        } else {
        }

        # Either -textvariable is {}, or the variable has not been set.
        if {$ClearOldVal} {
            $self Push {}
            set My(,oldValue) {}
        } else {
        }

        $hull configure -textvariable $val

    } elseif {($opt eq {-undo}) && ($val ne $oldVal)} {
        # On a change of value, start the undo/redo stack from scratch.
        $self edit reset

    } else {
    }

    return
}


# ------------------------------------------------------------------------------
#  Method TextVarTracer
# ------------------------------------------------------------------------------
# This command is bound to a trace on the -textvariable, and is called whenever
# that variable is set or unset.
# - When -textvariable is not {}, it is the name of a global variable.  A trace
#   on writing or unsetting that variable will monitor all changes to the text
#   displayed in the widget: both changes made when the script modifiies the
#   value of the global variable; and changes made by the "insert" and "delete"
#   methods (and thus, via bindings, by the GUI user), which Tk also applies to
#   the global variable.  There is no need for separate monitoring of changes
#   made by "insert" or "replace".
# - When -textvariable is {}, there is no "textvariable".  Changes made by
#   "insert" or "delete" are monitored by code in those methods.
# ------------------------------------------------------------------------------

method TextVarTracer {name1 name2 op} {
    if {$op eq "write"} {
        set oldVal $My(,oldValue)
        set newVal [namespace eval :: [list set $options(-textvariable)]]
        set My(,oldValue) $newVal
        if {$newVal ne $oldVal} {
            set My(,modified) 1
            $self Push $newVal
        } else {
        }
    } elseif {$op eq "unset"} {
        # The trace is removed when the variable is unset.
        # Re-add the trace.
        set cb [mymethod TextVarTracer]
        set val $options(-textvariable)
        namespace eval :: [list trace add variable $val {write unset} $cb]
        # The entry widget retains the last value of the unset -textvariable.
        # Leave the Undo/Redo stack and My(,oldValue) unchanged.
    }
    return
}


# ------------------------------------------------------------------------------
#  Method SetTextSilently
# ------------------------------------------------------------------------------
# Command to set widget text without invoking the trace on the -textvariable.
# ------------------------------------------------------------------------------

method SetTextSilently {txt} {
    set cb [mymethod TextVarTracer]
    set val $options(-textvariable)

    if {$val ne {}} {
        namespace eval :: [list trace remove variable $val {write unset} $cb]
    }

    $hull delete 0 end
    $hull insert 0 $txt

    if {$val ne {}} {
        namespace eval :: [list trace add variable $val {write unset} $cb]
    }
    return
}


# ------------------------------------------------------------------------------
#  Method IsThemed
# ------------------------------------------------------------------------------
# Command to return a boolean value, true iff the widget is themed (Ttk).
# ------------------------------------------------------------------------------

method IsThemed {} {
    expr {$My(,type) in $Our(,themedClassList)}
}


# ------------------------------------------------------------------------------
#  Method SelectColorIn
# ------------------------------------------------------------------------------
# Command to set the hull's -selectbackground to the widget's -selectbackground.
#
# The command is called:
# 1. when the widget acquires focus
# 2. when the value of -selectbackground is changed while the widget has focus
# 3. at construction if the widget has focus
# ------------------------------------------------------------------------------

method SelectColorIn {} {
    if {![$self IsThemed]} {
        $hull configure -selectbackground [$self cget -selectbackground]
    }
    return
}


# ------------------------------------------------------------------------------
#  Method SelectColorOut
# ------------------------------------------------------------------------------
# Command to set the hull's -selectbackground to the widget's
# -inactiveselectbackground.
#
# The command is called:
# 1. when the widget loses focus
# 2. when the value of -inactiveselectbackground is changed while the widget
#    does not have focus
# 3. at construction if the widget does not have focus
# ------------------------------------------------------------------------------

method SelectColorOut {} {
    if {![$self IsThemed]} {
        set col [$self cget -inactiveselectbackground]
        if {$col eq {}} {
            set col [$self cget -background]
        }
        $hull configure -selectbackground $col
    }
    return
}


# ------------------------------------------------------------------------------
#  Method FullSelection
# ------------------------------------------------------------------------------
# Command to return the selection in the widget, or {} if none exists.
# ------------------------------------------------------------------------------

method FullSelection {} {
    set content {}
    catch {
        set from [$hull index sel.first]
        set to   [$hull index sel.last]
        set content [string range [$hull get] $from $to]
    }
    return $content
}


# ------------------------------------------------------------------------------
#  Method invoke (spinbox only)
# ------------------------------------------------------------------------------
# Command to wrap the hull method and also:
# 1. copy the widget text, if changed, to the Undo/Redo stack.
# 2. generate a <<Selection>> event if the selection is changed.
# ------------------------------------------------------------------------------

method invoke {element} {
    if {$My(,type) ne {spinbox}} {
        $hull invoke {*}$args
        # The line above will cause an error return.  Just make sure ...
        set msg "bad option \"invoke\""
        return -code error $msg
    }


    set oldSel [$self FullSelection]

    set old [$hull get]
    set result [$hull invoke $element]
    if {![info exists hull]} {
        # The widget has been deleted.
        return $result
    }
    set new [$hull get]

    if {($new ne $old) && ($options(-textvariable) eq {})} {
        set My(,modified) 1
        $self Push $new
    }


    set newSel [$self FullSelection]

    if {$oldSel ne $newSel} {
        event generate $win <<Selection>>
    }

    return $result
}


# ------------------------------------------------------------------------------
#  Method current (ttk::combobox only)
# ------------------------------------------------------------------------------
# Command to wrap the hull method and also:
# 1. copy the widget text, if changed, to the Undo/Redo stack.
# 2. generate a <<Selection>> event if the selection is changed.
# ------------------------------------------------------------------------------

method current {args} {
    if {$My(,type) ne {ttk::combobox}} {
        $hull current {*}$args
        # The line above will cause an error return.  Just make sure ...
        set msg "bad option \"current\""
        return -code error $msg
    } elseif {[llength $args] ni {0 1}} {
        set msg "wrong # args: should be \"$win current ?newIndex?\""
        return -code error $msg
    } elseif {[llength $args] == 0} {
        # Just reads the current value.
        return [$hull current]
    }

    set newValue [lindex $args 0]
    # Now write $newValue to the widget.

    set oldSel [$self FullSelection]

    set old [$hull get]
    set result [$hull current $newValue]

    if {![info exists hull]} {
        # The widget has been deleted.
        return $result
    }
    set new [$hull get]

    if {($new ne $old) && ($options(-textvariable) eq {})} {
        set My(,modified) 1
        $self Push $new
    }

    set newSel [$self FullSelection]

    if {$oldSel ne $newSel} {
        event generate $win <<Selection>>
    }

    return $result


}

# ------------------------------------------------------------------------------
#  Method set (spinbox ttk::spinbox, and ttk::combobox only)
# ------------------------------------------------------------------------------
# Command to wrap the hull method and also:
# 1. copy the widget text, if changed, to the Undo/Redo stack.
# 2. generate a <<Selection>> event if the selection is changed.
# ------------------------------------------------------------------------------

method set {args} {
    if {$My(,type) ni {spinbox ttk::spinbox ttk::combobox}} {
        $hull set {*}$args
        # The line above will cause an error return.  Just make sure ...
        set msg "bad option \"set\""
        return -code error $msg

    } elseif {($My(,type) eq {spinbox}) && ([llength $args] ni {0 1})} {
        set msg "wrong # args: should be \"$win set ?string?\""
        return -code error $msg

    } elseif {    ($My(,type) in {ttk::spinbox ttk::combobox})
               && ([llength $args] != 1)
    } {
        set msg "wrong # args: should be \"$win set value\""
        return -code error $msg

    } elseif {[llength $args] == 0} {
        # Just reads the current value.
        return [$hull set]
    }

    set newValue [lindex $args 0]
    # Now write $newValue to the widget.

    set oldSel [$self FullSelection]

    set old [$hull get]
    set result [$hull set $newValue]

    if {![info exists hull]} {
        # The widget has been deleted.
        return $result
    }
    set new [$hull get]

    if {($new ne $old) && ($options(-textvariable) eq {})} {
        set My(,modified) 1
        $self Push $new
    }

    set newSel [$self FullSelection]

    if {$oldSel ne $newSel} {
        event generate $win <<Selection>>
    }

    return $result
}


# ------------------------------------------------------------------------------
#  Method delete
# ------------------------------------------------------------------------------
# Command to wrap the hull method and also:
# 1. copy the widget text, if changed, to the Undo/Redo stack.
# 2. generate a <<Selection>> event if the selection is changed.
# ------------------------------------------------------------------------------

method delete {args} {
    if {[llength $args] ni {1 2}} {
        set msg "wrong # args: should be \"$win delete firstIndex ?lastIndex?\""
        return -code error $msg
    }

    set oldSel [$self FullSelection]

    set old [$hull get]
    set result [$hull delete {*}$args]
    if {![info exists hull]} {
        # The widget has been deleted.
        return $result
    }
    set new [$hull get]
    if {($new ne $old) && ($options(-textvariable) eq {})} {
        set My(,modified) 1
        $self Push $new
    }

    set newSel [$self FullSelection]

    if {$oldSel ne $newSel} {
        event generate $win <<Selection>>
    }

    return $result
}


# ------------------------------------------------------------------------------
#  Method insert
# ------------------------------------------------------------------------------
# Command to wrap the hull method and also:
# 1. copy the widget text, if changed, to the Undo/Redo stack.
# 2. The object must generate a <<Selection>> event if the selection is changed.
# ------------------------------------------------------------------------------

method insert {index text} {
    set oldSel [$self FullSelection]

    set old [$hull get]
    set result [$hull insert $index $text]
    if {![info exists hull]} {
        # The widget has been deleted.
        return $result
    }
    set new [$hull get]
    if {($new ne $old) && ($options(-textvariable) eq {})} {
        set My(,modified) 1
        $self Push $new
    }

    set newSel [$self FullSelection]

    if {$oldSel ne $newSel} {
        event generate $win <<Selection>>
    }

    return $result
}


# ------------------------------------------------------------------------------
#  Method edit
# ------------------------------------------------------------------------------
# Hierarchical submethods are defined below.  Snit correctly returns an error
# for submethods that do not exist, and for bare "$w edit", but the messages are
# not as helpful as they might be.
# ------------------------------------------------------------------------------

# ------------------------------------------------------------------------------
#  Hierarchical Method edit canredo
# ------------------------------------------------------------------------------
# Command returns true iff a redo operation is available.
# ------------------------------------------------------------------------------

method {edit canredo} {} {
    expr {[$win cget -undo] && ($My(,pointer) < [llength $My(,list)] - 1)}
}


# ------------------------------------------------------------------------------
#  Hierarchical Method edit canundo
# ------------------------------------------------------------------------------
# Command returns true iff an undo operation is available.
# ------------------------------------------------------------------------------

method {edit canundo} {} {
    expr {[$win cget -undo] && ($My(,pointer) > 0)}
}


# ------------------------------------------------------------------------------
#  Hierarchical Method edit redo
# ------------------------------------------------------------------------------
# Command to attempt a "redo" operation.  If the pointer is already at the end
# of the Redo stack, the command raises an error.  Otherwise, it increments the
# stack pointer and changes the widget text to the next value from the Redo
# stack.
# ------------------------------------------------------------------------------

method {edit redo} {} {
    if {![$win cget -undo]} {
        return
    }

    $hull selection clear
    if {[$self edit canredo]} {
        incr My(,pointer)
        $self SetTextSilently [$self GetCurrent]
        set My(,modified) 1
    } else {
        return -code error {nothing to redo}
    }
    return
}


# ------------------------------------------------------------------------------
#  Hierarchical Method edit undo
# ------------------------------------------------------------------------------
# Command to attempt an "undo" operation.  If the pointer is already at the end
# of the Undo stack, the command raises an error.  Otherwise, it decrements the
# stack pointer and changes the widget text to the next value from the Undo
# stack.
# ------------------------------------------------------------------------------

method {edit undo} {} {
    if {![$win cget -undo]} {
        return
    }

    $hull selection clear
    if {[$self edit canundo]} {
        incr My(,pointer) -1
        $self SetTextSilently [$self GetCurrent]
        set My(,modified) 1
    } else {
        return -code error {nothing to undo}
    }
    return
}


# ------------------------------------------------------------------------------
#  Hierarchical Method edit modified
# ------------------------------------------------------------------------------
# Accessor command for the "modified" state of the widget.  "Set" semantics.
# ------------------------------------------------------------------------------

method {edit modified} {args} {
    set lenny [llength $args]
    set newValue [lindex $args 0]

    if {$lenny == 0} {
        return $My(,modified)
    } elseif {$lenny > 1} {
        return -code error "usage: $win edit modified ?value?"
    } elseif {[string is boolean -strict $newValue]} {
        # && ($lenny == 1)
        # Store boolean as 0 or 1.
        set My(,modified) [expr {$newValue && $newValue}]
    } else {
        return -code error "boolean value required"
    }
    # N.B. Multiple Return.
}


# ------------------------------------------------------------------------------
#  Hierarchical Method edit separator
# ------------------------------------------------------------------------------
# Does nothing.  Each insert/delete operation has its own implicit separator.
#
# If separators are implemented in future, this command will insert a separator
# on the Undo/Redo stack.
# ------------------------------------------------------------------------------

method {edit separator} {} {
    return
}


# ------------------------------------------------------------------------------
#  Hierarchical Method edit reset
# ------------------------------------------------------------------------------
# Command to reset the Undo/Redo stack.
# ------------------------------------------------------------------------------

method {edit reset} {} {
    if {![$win cget -undo]} {
        return
    }

    set My(,pointer) 0
    set My(,list) [list [$hull get]]
    return
}


# ------------------------------------------------------------------------------
#  Method Push
# ------------------------------------------------------------------------------
# Command to push a new value onto the Undo stack, and remove the Redo stack.
# ------------------------------------------------------------------------------

method Push {new} {
    incr My(,pointer)
    if {$My(,pointer) < [llength $My(,list)]} {
        set My(,list) [lreplace $My(,list) $My(,pointer) end]
    }
    lappend My(,list) $new

    $self ResizeStack
    return
}


# ------------------------------------------------------------------------------
#  Method ResizeStack
# ------------------------------------------------------------------------------
# Command to limit the Undo/Redo stack to the size specified by option -maxundo.
# Called only from Push.  If called from elsewhere, must generalise to the case
# where My(,pointer) is reduced below 0.
# ------------------------------------------------------------------------------

method ResizeStack {} {
    set maxUndo [expr {max(0,[$win cget -maxundo])}]
    set lastDead [expr {$My(,pointer) - $maxUndo - 1}]
    if {($maxUndo > 0) && ($lastDead > -1)} {
        set My(,list)    [lreplace $My(,list) 0 $lastDead]
        set My(,pointer) [expr {$My(,pointer) - $lastDead - 1}]
    }
    return
}


# ------------------------------------------------------------------------------
#  Method GetCurrent
# ------------------------------------------------------------------------------
# The pointer indicates a position in the Undo/Redo stack.
# This command retrieves the value from that position on the Undo/Redo stack,
# without changing either the stack or the pointer.
# ------------------------------------------------------------------------------

method GetCurrent {} {
    return [lindex $My(,list) $My(,pointer)]
}


# ------------------------------------------------------------------------------
#  Method selection
# ------------------------------------------------------------------------------
# Command to wrap the hull method and generate a <<Selection>> event.
# - This event is needed by the persistent selection module persistentSelection.
# - To use the persistentSelection module, the caller must bind a suitable
#   command to the <<Selection>> event on this widget.
#
# - The event is generated for subcommands that can modify the selection,
#   whether or not they actually do so.
# - The hull return value is stored and returned, because subcommand "present"
#   returns a non-empty value.
# ------------------------------------------------------------------------------

method selection {args} {

    # --------------------------------------------------------------------------
    # 0. Process arguments: check correct number, to give an appropriate error
    #    message.
    # --------------------------------------------------------------------------

    set lenny [llength $args]
    set com   [lindex $args 0]
    if {$lenny == 0} {
        set msg "wrong # args: should be \"$win selection option ?index?\""
        return -code error $msg
    } elseif {    ($My(,type) eq "spinbox")
               && ($com ni {adjust clear element from present range to})
    } {
        set msg "bad selection option \"$com\": must be adjust, clear,\
                 element, from, present, range, or to"
        return -code error $msg
    } elseif {    ($My(,type) eq "entry")
               && ($com ni {adjust clear from present range to})
    } {
        set msg "bad selection option \"$com\": must be adjust, clear, from,\
                 present, range, or to"
        return -code error $msg
    } elseif {    ($My(,type) in {ttk::entry ttk::spinbox ttk::combobox})
               && ($com ni {clear present range})
    } {
        set msg "bad selection option \"$com\": must be clear, present,\
                 or range"
        return -code error $msg
    } elseif {($com in {clear present}) && ($lenny != 1)} {
        set msg "wrong # args: should be \"$win selection $com\""
        return -code error $msg
    } elseif {($com in {adjust from to}) && ($lenny != 2)} {
        set msg "wrong # args: should be \"$win selection $com index\""
        return -code error $msg
    } elseif {($com eq {range}) && ($lenny != 3)} {
        set msg "wrong # args: should be \"$win selection $com start end\""
        return -code error $msg
    } elseif {($com eq {element}) && ($lenny != 1) && ($lenny != 2)} {
        set msg "wrong # args: should be \"$win selection $com ?element?\""
        return -code error $msg
    } else {
        # A valid command com with the correct number of arguments.
    }

    # --------------------------------------------------------------------------
    # 1. Process arguments: convert all indices to in-range integers.
    # --------------------------------------------------------------------------
    # Number of arguments, including subcommand:
    #   element        - 0 or 1 args, not an index
    #   clear present  - 1 args
    #   adjust from to - 2 args
    #   range          - 3 args
    # All arguments except the first (the subcommand) are indices - except for
    # subcommand "element".
    # Sanitise them: make each one a numerical value that is
    # neither < 0 nor > length.
    # --------------------------------------------------------------------------

    set lenny [llength $args]
    set newArgs {}
    set i 0
    foreach arg $args {
        set tmp $arg
        if {($i != 0) && ($com ne "element")} {
            set tmp [$hull index $tmp]
        }
        set arg$i $tmp
        lappend newArgs $tmp
        incr i
    }


    # --------------------------------------------------------------------------
    # 2. Rewrite the command to avoid unhelpful cases.
    # --------------------------------------------------------------------------
    # The command "$hull selection range $i $j" clears the persistent selection
    # if indices $i and $j are the same.  E.g. if click at the end of an entry
    # widget and do a slight drag, the persistent selection is lost.
    # Replace this command with "$hull selection clear" which does not do this.
    # - FIXME understand why this happens - is this a bug in persistentSelection
    #   or this module, or a misunderstanding of the entry widget?
    # - FIXME do a similar thing if needed for subcommands "to" and "adjust",
    #   which can clear the widget.
    # --------------------------------------------------------------------------

    if {($arg0 eq {range}) && ($lenny == 3) && ($arg1 == $arg2)} {
        set newArgs clear
    }


    # --------------------------------------------------------------------------
    # 3. Evaluate the hull command.
    # --------------------------------------------------------------------------

    set res [$hull selection {*}$newArgs]


    # --------------------------------------------------------------------------
    # 4. Generate a <<Selection>> event if appropriate.
    # --------------------------------------------------------------------------

    if {[lindex $args 0] in {adjust clear range to}} {
        event generate $win <<Selection>>
    }

    return $res
}


#indent+4
}

package provide widgetPlus 1.0b2