snitfaq(n)

🌸 NAME 🌸

snitfaq — Snit Frequently Asked Questions. That's the whole vibe: it's the FAQ page from the snit manual set (section n, bestie, we're in Tcl-land).


💖 DESCRIPTION 💖

🦋 OVERVIEW 🦋

✨ WHAT IS THIS DOCUMENT? ✨

Okay so real talk: this is an atypical FAQ list, because honestly? barely any of these questions are actually frequently asked. 😭 It's more like — these are the questions I think a newcomer to Snit should be asking. Main character questions only.

And important: this file is not a complete reference to Snit. Nope. That info lives in the snit man page. This one's the vibes-and-orientation doc. 🫶

🧚 WHAT IS SNIT? 🧚

Snit is a framework for defining abstract data types and megawidgets in pure Tcl. 💅

The name "Snit" stands for "Snit's Not Incr Tcl" — which is a whole statement, because it means Snit takes a different approach to defining objects than Incr Tcl does, and Incr Tcl is the best known object framework for Tcl. And fr fr, if I'd realized Snit would get this popular, I'd probably have picked literally anything else for the name. 🙈

The primary purpose of Snit is to be object glue — helping you compose diverse objects from diverse sources into types and megawidgets with clean, convenient interfaces, so you can more easily build your application. That's it. That's the job.

Snit isn't about theoretical purity or minimalist design. It's about being able to do powerful things easily and consistently without having to think about them — so you can concentrate on building your application. Periodt.

Snit isn't about implementing thousands of nearly identical carefully-specified lightweight thingamajigs — not as individual Snit objects, anyway. Traditional Tcl methods will be much faster, and not much more complicated. But Snit is about implementing a clean interface to manage a collection of thousands of nearly identical carefully-specified lightweight thingamajigs (e.g., think of the text widget and text tags, or the canvas widget and canvas objects 👑). Snit lets you hide the details of just how those thingamajigs are stored — so that you can ignore it, and concentrate on building your application. Iconic behaviour, honestly.

Snit isn't a way of life, a silver bullet, or the Fountain of Youth. 💀 It's just a way of managing complexity — and of managing some of the complexity of managing complexity — so that you can concentrate on building your application. Recursion but make it ✨productive✨.

🌈 WHAT VERSION OF TCL DOES SNIT REQUIRE? 🌈

  • Snit 1.3 requires Tcl 8.3 or later
  • Snit 2.2 requires Tcl 8.5 or later

See SNIT VERSIONS for the differences between Snit 1.3 and Snit 2.2. 👀

🎀 WHERE CAN I DOWNLOAD SNIT? 🎀

Snit is part of Tcllib, the standard Tcl library, so bestie you might literally already have it. 😌 It's also available at the Snit Home Page:

http://www.wjduquette.com/snit

💜 WHAT ARE SNIT'S GOALS? 💜

  • A Snit object should be at least as efficient as a hand-coded Tcl object (see http://www.wjduquette.com/tcl/objects.html).
  • The fact that Snit was used in an object's implementation should be transparent (and irrelevant) to clients of that object.
  • Snit should be able to encapsulate objects from other sources, particularly Tk widgets.
  • Snit megawidgets should be (to the extent possible) indistinguishable in interface from Tk widgets.
  • Snit should be Tclish — that is, rather than trying to emulate C++, Smalltalk, or anything else, it should try to emulate Tcl itself. 🐚
  • It should have a simple, easy-to-use, easy-to-remember syntax.

🔥 HOW IS SNIT DIFFERENT FROM OTHER OO FRAMEWORKS? 🔥

Snit is unique among Tcl object systems in that it is based not on inheritance but on delegation. And that's the tea. ☕

Object systems based on inheritance only allow you to inherit from classes defined using the same system, and honestly? that's a shame. In Tcl, an object is anything that acts like an object; it shouldn't matter how the object was implemented. I designed Snit to help me build applications out of the materials at hand — so Snit is designed to be able to incorporate and build on any object, whether it's:

  • a hand-coded object
  • a Tk widget
  • an Incr Tcl object
  • a BWidget
  • or almost anything else

Note that you can achieve the effect of inheritance using COMPONENTS and DELEGATION — and you can inherit from anything that looks like a Tcl object. Slay. 💅

⭐ WHAT CAN I DO WITH SNIT? ⭐

Using Snit, a programmer can:

  • Create abstract data types and Tk megawidgets.
  • Define instance variables, type variables, and Tk-style options.
  • Define constructors, destructors, instance methods, type methods, procs.
  • Assemble a type out of component types. Instance methods and options can be delegated to the component types automatically.

more parts coming, bestie, don't go anywhere 🫶

💖 SNIT VERSIONS 💖

okay bestie, before we go ANY further, we gotta have The Talk about versions, because there are literally two of them living in the same distribution and you need to pick one. no cap. 🫶

✨ WHICH VERSION OF SNIT SHOULD I USE? ✨

So the current Snit distribution ships with two versions: Snit 1.3 and Snit 2.2. Why both, you ask? Because Snit 2.2 takes full advantage of a bunch of new features in Tcl 8.5 to make run-time efficiency chef's kiss better. and as a lil side-effect of all that glow-up? the ugliness of Snit's error messages and stack traces got reduced considerably. we love a redemption arc. 😭✨

The cost of using Snit 2.2, of course, is that you must target Tcl 8.5. that's the tradeoff, bestie, there's always a tradeoff.

Snit 1.3, on the other hand, lacks Snit 2.2's optimizations, but it only requires Tcl 8.3 and later. low maintenance queen. 👑

In short, fr fr:

  • If you're targetting Tcl 8.3 or 8.4 you should use Snit 1.3.
  • If you can afford to target Tcl 8.5, you should definitely use Snit 2.2.
  • If you will be targetting both, you can use Snit 1.3 exclusively, or (if your code is unaffected by the minor incompatibilities between the two versions) you can use Snit 1.3 for Tcl 8.4 and Snit 2.2 for Tcl 8.5.

🌸 HOW DO I SELECT THE VERSION OF SNIT I WANT TO USE? 🌸

To always use Snit 1.3 (or a later version of Snit 1.x), invoke Snit like this:

package require snit 1.3

To always use Snit 2.2 (or a later version of Snit 2.x), say this instead:

package require snit 2.2
⚠️ heads up bestie: if you request Snit 2.2 explicitly, your application will halt with Tcl 8.4, since Snit 2.2 is unavailable for Tcl 8.4. it's giving "not compatible, no exceptions." 💀

If you wish your application to always use the latest available version of Snit, don't specify a version number at all:

package require snit

Tcl will find and load the latest version that's available relative to the version of Tcl being used. but bestie, in this case, be careful to avoid using any incompatible features. 👀


🦋 HOW ARE SNIT 1.3 AND SNIT 2.2 INCOMPATIBLE? 🦋

To the extent possible, Snit 2.2 is intended to be a drop-in replacement for Snit 1.3. adorable, right? Unfortunately, some incompatibilities were inevitable, because Snit 2.2 uses Tcl 8.5's new namespace ensemble mechanism to implement subcommand dispatch. This approach is much faster than the mechanism used in Snit 1.3, and also results in much better error messages; however, it also places new constraints on the implementation. new era, new rules. 💅

There are four specific incompatibilities between Snit 1.3 and Snit 2.2. let's get into it, one by one.

  • Implicit naming of objects — Snit 1.3 supports implicit naming of objects. Suppose you define a new snit::type called dog. You can create instances of dog in three ways:
dog spot               ;# Explicit naming
set obj1 [dog %AUTO%]  ;# Automatic naming
set obj2 [dog]         ;# Implicit naming

In Snit 2.2, type commands are defined using the namespace ensemble mechanism; and namespace ensemble doesn't allow an ensemble command to be called without a subcommand. In short, using namespace ensemble there's no way to support implicit naming. 😔

All is not lost, however. If the type has no type methods, then the type command is a simple command rather than an ensemble, and namespace ensemble is not used. In this case, implicit naming is still possible. ok so there's hope.

In short, you can have implicit naming if you're willing to do without type methods (including the standard type methods, like $type info). To do so, use the -hastypemethods pragma:

pragma -hastypemethods 0
  • Hierarchical methods and type methods are implemented differently — in Snit 2.2 they're just built different. 🫠

A hierarchical method is an instance method which has subcommands; these subcommands are themselves methods. The Tk text widget's tag command and its subcommands are examples of hierarchical methods. You can implement such subcommands in Snit simply by including multiple words in the method names:

method {tag configure} {tag args} { ... }

method {tag cget} {tag option} {...}

Here we've implicitly defined a tag method which has two subcommands, configure and cget.

In Snit 1.3, hierarchical methods could be called in two ways:

$obj tag cget -myoption      ;# The good way
$obj {tag cget} -myoption    ;# The weird way

In the second call, we see that a hierarchical method or type method is simply one whose name contains multiple words.

In Snit 2.2 this is no longer the case, and the "weird" way of calling hierarchical methods and type methods no longer works. sorry to that method. 😭

  • The third incompatibility derives from the second — in Snit 1.3, hierarchical methods were also simply methods whose name contains multiple words. As a result, $obj info methods returned the full names of all hierarchical methods. In the example above, the list returned by $obj info methods would include tag configure and tag cget but not tag, since tag is defined only implicitly.

In Snit 2.2, hierarchical methods and type methods are no longer simply ones whose name contains multiple words; in the above example, the list returned by $obj info methods would include tag but not tag configure or tag cget. flipped the script fr. 🔄

  • The fourth incompatibility is due to a new feature — Snit 2.2 uses the new namespace path command so that a type's code can call any command defined in the type's parent namespace without qualification or importation. For example, suppose you have a package called mypackage which defines a number of commands including a type, ::mypackage::mytype. Thanks to namespace path, the type's code can call any of the other commands defined in ::mypackage::.

This is extremely convenient. However, it also means that commands defined in the parent namespace, ::mypackage::, can block the type's access to identically named commands in the global namespace. This can lead to bugs. 😬 For example, Tcllib includes a type called ::tie::std::file. This type's code calls the standard file command. When run with Snit 2.2, the code broke-- the type's command, ::tie::std::file, is itself a command in the type's parent namespace, and so instead of calling the standard file command, the type found itself calling itself. it's giving mirror selfie but make it a bug. 💀


🌈 ARE THERE OTHER DIFFERENCES BETWEEN SNIT 1.X AND SNIT 2.2? 🌈

Yes. ✨

  • Method dispatch is considerably faster. zoom zoom. 🔥
  • Many error messages and stack traces are cleaner.
  • The -simpledispatch pragma is obsolete, and ignored if present. In Snit 1.x, -simpledispatch substitutes a faster mechanism for method dispatch, at the cost of losing certain features. Snit 2.2 method dispatch is faster still in all cases, so -simpledispatch is no longer needed. retired, iconic, we thank her for her service. 🎀
  • In Snit 2.2, a type's code (methods, type methods, etc.) can call commands from the type's parent namespace without qualifying or importing them, i.e., type ::parentns::mytype's code can call ::parentns::someproc as just someproc.

This is extremely useful when a type is defined as part of a larger package, and shares a parent namespace with the rest of the package; it means that the type can call other commands defined by the package without any extra work. obsessed. 🫶

This feature depends on the new Tcl 8.5 namespace path command, which is why it hasn't been implemented for V1.x. V1.x code can achieve something similar by placing

namespace import [namespace parent]::*

in a type constructor. This is less useful, however, as it picks up only those commands which have already been exported by the parent namespace at the time the type is defined. better than nothing tho. 💜

✨ OBJECTS ✨

🐶 WHAT IS AN OBJECT? 🐶

okay bestie, so a full deep-dive on object-oriented programming is way beyond what this FAQ is doing, obviously. but like, in simple terms? an object is an instance of an abstract data type — basically a coherent lil bundle of code and data that just vibes together. there are SO many ways to represent objects in Tcl/Tk and the most iconic examples are honestly the Tk widgets.

a Tk widget is an object — it's represented by a Tcl command. the object's methods are subcommands of that Tcl command. the object's properties are options you access using the configure and cget methods. and Snit? Snit uses the exact same conventions as Tk widgets do. no cap. 💅

🧠 WHAT IS AN ABSTRACT DATA TYPE? 🧠

in computer science terms, an abstract data type is a complex data structure plus a set of operations — think a stack, a queue, a binary tree, etc — which is to say, in modern terms, an object. in systems that include some form of inheritance, the word class usually gets used instead of abstract data type, but since Snit doesn't implement inheritance the way it's ordinarily understood, the older term just seems more appropriate. sometimes this whole thing is called object-based programming as opposed to object-oriented programming. and lowkey? you can easily create the effect of inheritance using COMPONENTS and DELEGATION. slay.

in Snit, as in Tk, a type is a command that creates instances — objects — which belong to the type. most types define some number of options which can be set at creation time, and usually can be changed later.

furthermore, an instance is also a Tcl command — a command that gives access to the operations which are defined for that abstract data type. conventionally, the operations are defined as subcommands of the instance command. for example, to insert text into a Tk text widget, you use the text widget's insert subcommand:

# Create a text widget and insert some text in it.
text .mytext -width 80 -height 24
.mytext insert end "Howdy!"

in this example, text is the type command and .mytext is the instance command.

in Snit, object subcommands are generally called INSTANCE METHODS. 🫶

🎀 WHAT KINDS OF ABSTRACT DATA TYPES DOES SNIT PROVIDE? 🎀

Snit lets you define three kinds of abstract data type, bestie:

  • snit::type
  • snit::widget
  • snit::widgetadaptor

🐕 WHAT IS A SNIT::TYPE? 🐕

a snit::type is a non-GUI abstract data type, e.g., a stack or a queue. snit::types are defined using the snit::type command. for example, if you were designing a kennel management system for a dog breeder, you'd need a dog type.

% snit::type dog {
    # ...
}
::dog
%

this definition defines a new command (::dog, in this case) that can be used to define dog objects.

an instance of a snit::type can have INSTANCE METHODS, INSTANCE VARIABLES, OPTIONS, and COMPONENTS. the type itself can have TYPE METHODS, TYPE VARIABLES, TYPE COMPONENTS, and PROCS. it's giving so much range. 👑

🦋 WHAT IS A SNIT::WIDGET?, THE SHORT STORY 🦋

a snit::widget is a Tk megawidget built using Snit; it is very similar to a snit::type. see WIDGETS.

🌸 WHAT IS A SNIT::WIDGETADAPTOR?, THE SHORT STORY 🌸

a snit::widgetadaptor uses Snit to wrap an existing widget type (e.g., a Tk label), modifying its interface to a lesser or greater extent. it is very similar to a snit::widget. see WIDGET ADAPTORS.

💖 HOW DO I CREATE AN INSTANCE OF A SNIT::TYPE? 💖

you create an instance of a snit::type by passing the new instance's name to the type's create method. in the following example, we create a dog object called spot.

% snit::type dog {
    # ....
}
::dog
% dog create spot
::spot
%

in general, the create method name can be omitted so long as the instance name doesn't conflict with any defined TYPE METHODS. (see TYPE COMPONENTS for the special case in which this doesn't work.) so the following example is identical to the previous example:

% snit::type dog {
    # ....
}
::dog
% dog spot
::spot
%

this document generally uses the shorter form.

if the dog type defines OPTIONS, these can usually be given defaults at creation time:

% snit::type dog {
    option -breed mongrel
    option -color brown

    method bark {} { return "$self barks." }
}
::dog
% dog create spot -breed dalmation -color spotted
::spot
% spot cget -breed
dalmation
% spot cget -color
spotted
%

once created, the instance name now names a new Tcl command that is used to manipulate the object. for example, the following code makes the dog bark:

% spot bark
::spot barks.
%

periodt. 🐾

🎀 HOW DO I REFER TO AN OBJECT INDIRECTLY? 🎀

some programmers prefer to save the object name in a variable, and reference it that way. for example,

% snit::type dog { ... }
::dog
% set d [dog spot -breed dalmation -color spotted]
::spot
% $d cget -breed
dalmation
% $d bark
::spot barks.
%

if you prefer this style, you might prefer to have Snit generate the instance's name automatically. iykyk.

✨ HOW CAN I GENERATE THE OBJECT NAME AUTOMATICALLY? ✨

if you'd like Snit to generate an object name for you, use the %AUTO% keyword as the requested name:

% snit::type dog { ... }
::dog
% set d [dog %AUTO%]
::dog2
% $d bark
::dog2 barks.
%

the %AUTO% keyword can be embedded in a longer string too:

% set d [dog obj_%AUTO%]
::obj_dog4
% $d bark
::obj_dog4 barks.
%

so versatile. obsessed. 💅

💀 CAN TYPES BE RENAMED? 💀

Tcl's rename command renames other commands. it's a common technique in Tcl to modify an existing command by renaming it and defining a new command with the original name; the new command usually calls the renamed command.

snit::type commands, however, should never be renamed; to do so breaks the connection between the type and its objects.

bestie do NOT do it. i'm serious. the whole type just loses its connection to its babies and it's a mess. 😭

🌈 CAN OBJECTS BE RENAMED? 🌈

Tcl's rename command renames other commands. it's a common technique in Tcl to modify an existing command by renaming it and defining a new command with the original name; the new command usually calls the renamed command.

all Snit objects (including widgets and widgetadaptors) can be renamed, though this flexibility has some consequences:

  • in an instance method, the implicit argument self will always contain the object's current name, so instance methods can always call other instance methods using $self.
  • if the object is renamed, however, then $self's value will change. therefore, don't use $self for anything that will break if $self changes. for example, don't pass a callback command to another object like this:
.btn configure -command [list $self ButtonPress]

you'll get an error if .btn calls your command after your object is renamed.

  • instead, your object should define its callback command like this:
.btn configure -command [mymethod ButtonPress]

the mymethod command returns code that will call the desired method safely; the caller of the callback can add additional arguments to the end of the command as usual.

  • every object has a private namespace; the name of this namespace is available in method bodies, etc., as the value of the implicit argument selfns. this value is constant for the life of the object. use $selfns instead of $self if you need a unique token to identify the object.
  • when a snit::widget's instance command is renamed, its Tk window name remains the same — and is still extremely important. consequently, the Tk window name is available in method bodies as the value of the implicit argument win. this value is constant for the life of the object. when creating child windows, it's best to use $win.child rather than $self.child as the name of the child window.

like, the attention to detail here? iconic. 🎀

🦋 HOW DO I DESTROY A SNIT OBJECT? 🦋

any Snit object of any type can be destroyed by renaming it to the empty string using the Tcl rename command.

Snit megawidgets (i.e., instances of snit::widget and snit::widgetadaptor) can be destroyed like any other widget: by using the Tk destroy command on the widget or on one of its ancestors in the window hierarchy.

every instance of a snit::type has a destroy method:

% snit::type dog { ... }
::dog
% dog spot
::spot
% spot bark
::spot barks.
% spot destroy
% spot barks
invalid command name "spot"
%

finally, every Snit type has a type method called destroy; calling it destroys the type and all of its instances:

% snit::type dog { ... }
::dog
% dog spot
::spot
% spot bark
::spot barks.
% dog destroy
% spot bark
invalid command name "spot"
% dog fido
invalid command name "dog"
%

gone. reduced to atoms. 💀✨


✨ INSTANCE METHODS ✨


🌸 WHAT IS AN INSTANCE METHOD?

okay so an instance method is a proc that's tied to one specific object, and you call it as a subcommand of that object's command. It gets free, all-access, VIP-backstage entry to every single one of the object's type variables, instance variables, and so on. no keycard needed bestie 💅


🌸 HOW DO I DEFINE AN INSTANCE METHOD?

you define instance methods inside the type definition, using the method statement. picture this code, which is like, the dog equivalent of a computer simulation:

% snit::type dog {
    method bark {} {
        return "$self barks."
    }

    method chase {thing} {
        return "$self chases $thing."
    }
}
::dog
%

so this dog can bark, and it can chase things. iconic behavior honestly 🐕

the method statement looks exactly like a normal Tcl proc, except it lives inside a snit::type definition. and notice — every single instance method gets an implicit argument called self, and that argument holds the object's name. (there's more on implicit method arguments coming up, don't worry.)


🌸 HOW DOES A CLIENT CALL AN INSTANCE METHOD?

the method name literally becomes a subcommand of the object. so let's take our simulated dog for a little walk:

% dog spot
::spot
% spot bark
::spot barks.
% spot chase cat
::spot chases cat.
%

ate. no crumbs. 💖


🌸 HOW DOES AN INSTANCE METHOD CALL ANOTHER INSTANCE METHOD?

if method A needs to call method B on the same object, it does it exactly the way a client would: it calls method B as a subcommand of the object itself, using the object name that's sitting right there in the implicit self argument.

so say our dogs never chase anything without barking at it first (rude but consistent):

% snit::type dog {
    method bark {} {
        return "$self barks."
    }

    method chase {thing} {
        return "$self chases $thing.  [$self bark]"
    }
}
::dog
% dog spot
::spot
% spot bark
::spot barks.
% spot chase cat
::spot chases cat.  ::spot barks.
%

see how [$self bark] just… works? that's the whole trick 🫶


🌸 ARE THERE ANY LIMITATIONS ON INSTANCE METHOD NAMES?

not really, bestie — as long as you dodge the standard instance method names: configure, configurelist, cget, destroy, and info. those are taken, don't touch. 🙈

also, if you make a method name out of multiple words, you're defining hierarchical methods. yes, that's a thing, keep reading.


🌸 WHAT IS A HIERARCHICAL METHOD?

an object's methods are subcommands of the object's instance command. hierarchical methods let an object's methods have their own subcommands — and those can have subcommands, and those can have subcommands, forever, like a little command tree 🌳

this is how a ton of the Tk widgets are built. for example, the subcommands of the Tk text widget's tag method are hierarchical methods. so you already know this pattern, you just didn't know it had a name.


🌸 HOW DO I DEFINE A HIERARCHICAL METHOD?

just define methods whose names are multiple words. those words build the hierarchy implicitly, no extra setup. so this code here defines a tag method with the subcommands cget and configure:

snit::widget mytext {
    method {tag configure} {tag args} { ... }

    method {tag cget} {tag option} {...}
}

and here's the important bit — there is no explicit definition of the tag method anywhere. it's implicit in the definitions of tag configure and tag cget. if you tried to also define tag explicitly in this example, you'd get an error. so don't do that. 💀


🌸 HOW DO I CALL HIERARCHICAL METHODS?

subcommands of subcommands, babes:

% mytext .text
.text
% .text tag configure redtext -foreground red -background black
% .text tag cget redtext -foreground
red
%

🌸 HOW DO I MAKE AN INSTANCE METHOD PRIVATE?

defining private methods is super useful — those are instance methods that are only meant to be called by other methods of the same object.

now, real talk: Snit doesn't implement any access control on instance methods, so literally every method is de facto public. no locks, no bouncers. 🚪

but conventionally? the names of public methods start with a lower-case letter, and the names of private methods start with an upper-case letter. that's the vibe check.

so let's say our simulated dogs only bark in response to other stimuli and never bark just for fun. then the bark method becomes Bark to flag it as private:

% snit::type dog {
    # Private by convention: begins with uppercase letter.
    method Bark {} {
        return "$self barks."
    }

    method chase {thing} {
        return "$self chases $thing. [$self Bark]"
    }
}
::dog
% dog fido
::fido
% fido chase cat
::fido chases cat. ::fido barks.
%

the capital letter is doing all the heavy lifting and honestly? it's serving. 👑


🌸 ARE THERE ANY LIMITATIONS ON INSTANCE METHOD ARGUMENTS?

method argument lists are defined just like normal Tcl proc argument lists. in particular, they can include arguments with default values, and the args argument. so all your usual Tcl tricks apply.

but — every method also gets a handful of implicit arguments that Snit hands over, on top of whatever you explicitly defined. and here's the gotcha: the names of those implicit arguments may not be used to name your explicit arguments. so don't try it. 😤


🌸 WHAT IMPLICIT ARGUMENTS ARE PASSED TO EACH INSTANCE METHOD?

the arguments implicitly passed to every method are type, selfns, win, and self. those four, every time, no exceptions.


🌸 WHAT IS $type?

the implicit argument type contains the fully qualified name of the object's type:

% snit::type thing {
    method mytype {} {
        return $type
    }
}
::thing
% thing something
::something
% something mytype
::thing
%

🌸 WHAT IS $self?

the implicit argument self contains the object's fully qualified name.

and here's the tea ☕ — if the object's command gets renamed, then $self will change to match in subsequent calls. so your code should not assume that $self is constant, unless you know for an absolute fact that the object will never be renamed. periodt.

% snit::type thing {
    method myself {} {
        return $self
    }
}
::thing
% thing mutt
::mutt
% mutt myself
::mutt
% rename mutt jeff
% jeff myself
::jeff
%

see? mutt became jeff and $self kept up. glow-up fr fr ✨


🌸 WHAT IS $selfns?

every Snit object has a private namespace where it stores its INSTANCE VARIABLES and OPTIONS. the implicit argument selfns contains the name of that namespace. its value never changes, and it stays constant for the entire life of the object, even if the object's name changes:

% snit::type thing {
    method myNameSpace {} {
        return $selfns
    }
}
::thing
% thing jeff
::jeff
% jeff myNameSpace
::thing::Snit_inst3
% rename jeff mutt
% mutt myNameSpace
::thing::Snit_inst3
%

so that example just showed you exactly how Snit names an instance's private namespace. however — do not write code that depends on that specific naming convention, because it might change in future releases. admire it, don't rely on it. 💅


🌸 WHAT IS $win?

the implicit argument win is defined for all Snit methods, even though it really only makes sense for the methods of WIDGETS and WIDGET ADAPTORS.

$win is simply the original name of the object, whether it's been renamed or not. and for widgets and widgetadaptors, it is therefore also the name of a Tk window.

when a snit::widgetadaptor is used to modify the interface of a widget or megawidget, it has to rename the widget's original command and swap in its own. so if you use win whenever you need the Tk window name, it means a snit::widget or snit::widgetadaptor can get adapted by a snit::widgetadaptor. see WIDGETS for more info. 🪟


🌸 HOW DO I PASS AN INSTANCE METHOD AS A CALLBACK?

depends on the context, bestie. sit with me.

say in my application I have a dog object named fido, and I want fido to bark when a Tk button called .bark is pressed. in that case, you create the callback command the usual way, using list:

button .bark -text "Bark!" -command [list fido bark]

very typical Tcl style — we use a callback to hook two independent components together. love that for us.

but now suppose the dog object has a graphical interface and owns the button itself. then the dog has to pass one of its own instance methods to the button it owns. the obvious thing to do is this:

% snit::widget dog {
    constructor {args} {
        #...
        button $win.barkbtn -text "Bark!" -command [list $self bark]
        #...
    }
}
::dog
%

(note that in this example our dog becomes a snit::widget, because it has GUI behavior. see WIDGETS for more.) so if we create a dog called .spot, it will create a Tk button called .spot.barkbtn, and when you press it, the button will call $self bark.

now — this will work… provided that .spot is never renamed to something else. but surely renaming widgets is abnormal?? and yeah, it is — unless .spot is the hull component of a snit::widgetadaptor. because if it is, then it will be renamed, and .spot will become the name of the snit::widgetadaptor object. then when the button is pressed, the command $self bark gets handled by the snit::widgetadaptor, which might or might not do the right thing. 😬

there's a safer way to do it, and it looks like this:

% snit::widget dog {
    constructor {args} {
        #...
        button $win.barkbtn -text "Bark!" -command [mymethod bark]
        #...
    }
}
::dog
%

the command mymethod takes any number of arguments, and you can use it just like list to build up a callback command. the only difference is that mymethod returns a form of the command that won't change even if the instance's name changes. safe. stable. iconic. 🔥

on the other hand, you might prefer to let a widgetadaptor override a method, so that your renamed widget calls the widgetadaptor's method instead of its own. in that case, using [list $self bark] will do what you want… but this is a technique that should only be used in carefully controlled circumstances. so like, know what you're doing, okay? 🚨


🌸 HOW DO I DELEGATE INSTANCE METHODS TO A COMPONENT?

see DELEGATION. iykyk 💖


✨ INSTANCE VARIABLES ✨

💭 WHAT IS AN INSTANCE VARIABLE? 💭

okay bestie, an instance variable is literally a private little variable that belongs to one specific Snit object. no sharing, no borrowing, just its own personal data. and it can be either a scalar or an array, so you've got options 💅


🎀 HOW IS A SCALAR INSTANCE VARIABLE DEFINED? 🎀

Scalar instance variables get defined right inside the type definition using the variable statement. You can just name it and move on, or you can give it a starting value like the main character it is:

snit::type mytype {
    # Define variable "greeting" and initialize it with "Howdy!"
    variable greeting "Howdy!"
}

🦋 HOW IS AN ARRAY INSTANCE VARIABLE DEFINED? 🦋

Array instance variables are also defined in the type definition using the variable command. And yes, you can initialize them at the same time by specifying the -array option:

snit::type mytype {
    # Define array variable "greetings"
    variable greetings -array {
        formal "Good Evening"
        casual "Howdy!"
    }
}

🌸 WHAT HAPPENS IF I DON'T INITIALIZE AN INSTANCE VARIABLE? 🌸

so real talk: variables do not really exist until they are given values. if you don't initialize a variable when you define it, then you have to be sure to assign a value to it before you reference it. that could be in the constructor, or in some method, whatever works. but you gotta do it, or it's giving undefined behavior vibes 😭


💅 ARE THERE ANY LIMITATIONS ON INSTANCE VARIABLE NAMES? 💅

just a few, bestie. no biggie.

  • First, every Snit object has a built-in instance variable called options, which should never be redefined.
  • Second, all names beginning with Snit_ are reserved for use by Snit internal code.
  • Third, instance variable names containing the namespace delimiter (::) are likely to cause great confusion.
⚠️ so maybe don't touch options, don't use Snit_, and don't get cute with :: unless you enjoy chaos. periodt.

👑 DO I NEED TO DECLARE MY INSTANCE VARIABLES IN MY METHODS? 👑

No. Once you've defined an instance variable in the type definition, it can be used in any instance code — instance methods, the constructor, and the destructor — without declaration. This differs from normal Tcl practice, in which all non-local variables in a proc need to be declared.

There is a speed penalty to having all instance variables implicitly available in all instance code. Even though your code need not declare the variables explicitly, Snit must still declare them, and that takes time. If you have ten instance variables, a method that uses none of them must still pay the declaration penalty for all ten. In most cases, the additional runtime cost is negligible. If extreme cases, you might wish to avoid it; there are two methods for doing so.

The first is to define a single instance variable, an array, and store all of your instance data in the array. This way, you're only paying the declaration penalty for one variable — and you probably need the variable most of the time anyway. This method breaks down if your instance variables include multiple arrays; in Tcl 8.5, however, the dict command might come to your rescue.

The second method is to declare your instance variables explicitly in your instance code, while not including them in the type definition:

snit::type dog {
    constructor {} {
        variable mood

        set mood happy
    }

    method setmood {newMood} {
        variable mood

        set mood $newMood
    }

    method getmood {} {
        variable mood

        return $mood
    }
}

This allows you to ensure that only the required variables are included in each method, at the cost of longer code and run-time errors when you forget to declare a variable you need.

😭 yes, the tradeoff is real: shorter type definitions vs. longer method code, and the risk of runtime sadness. choose your fighter.

🌈 HOW DO I PASS AN INSTANCE VARIABLE'S NAME TO ANOTHER OBJECT? 🌈

In Tk, it's common to pass a widget a variable name; for example, Tk label widgets have a -textvariable option which names the variable which will contain the widget's text. This allows the program to update the label's value just by assigning a new value to the variable.

If you naively pass the instance variable name to the label widget, you'll be confused by the result; Tk will assume that the name names a global variable. Instead, you need to provide a fully-qualified variable name. From within an instance method or a constructor, you can fully qualify the variable's name using the myvar command:

snit::widget mywidget {
    variable labeltext ""

    constructor {args} {
        # ...

        label $win.label -textvariable [myvar labeltext]

        # ...
    }
}

💖 HOW DO I MAKE AN INSTANCE VARIABLE PUBLIC? 💖

Practically speaking, you don't. Instead, you'll implement public variables as OPTIONS. Alternatively, you can write INSTANCE METHODS to set and get the variable's value.

✨ so if you were hoping for a public variable button, bestie, it's not here. options and methods are the moment. iykyk.

✨ OPTIONS ✨

WHAT IS AN OPTION? 💖

ok so bestie, a type's options are basically the equivalent of what other object-oriented languages would call public member variables or properties. they're data values that the clients of an object can retrieve, and (usually) set. iconic, right?

Snit's implementation of options follows the Tk model fairly exactly, except that snit::type objects usually don't interact with THE TK OPTION DATABASE. but snit::widget and snit::widgetadaptor objects? oh they always do. no exceptions. 💅


HOW DO I DEFINE AN OPTION? 🎀

Options get defined in the type definition using the option statement. consider this type, for an app that manages a list of dogs for a pet store 🐶:

snit::type dog {
    option -breed -default mongrel
    option -color -default brown
    option -akc   -default 0
    option -shots -default 0
}

so according to this, a dog has four notable properties: a breed, a color, a flag saying whether it's pedigreed with the American Kennel Club, and another flag saying whether it's had its shots. the default dog, evidently, is a brown mutt. as it should be tbh 🦋

there are a bunch of options you can specify when defining an option. if -default is the only one, you can literally just omit the word -default like this:

snit::type dog {
    option -breed mongrel
    option -color brown
    option -akc   0
    option -shots 0
}

and if no -default value is specified, the option's default value will be the empty string (but see THE TK OPTION DATABASE).

the Snit man page calls options like these "locally defined" options. iykyk 💅


HOW CAN A CLIENT SET OPTIONS AT OBJECT CREATION? ⭐

the normal convention is that the client can pass any number of options and their values after the object's name at object creation. for example, the ::dog command we just defined can now be used to create individual dogs. any or all of the options may be set at creation time:

% dog spot -breed beagle -color "mottled" -akc 1 -shots 1
::spot
% dog fido -shots 1
::fido
%

so ::spot is a pedigreed beagle; ::fido is a typical mutt, but his owners evidently take care of him, because he's had his shots. good boy. 🐕

note: if the type defines a constructor, it can specify a different object-creation syntax. see CONSTRUCTORS for more info. don't @ me.

HOW CAN A CLIENT RETRIEVE AN OPTION'S VALUE? 🔍

you retrieve option values using the cget method. it's giving effortless:

% spot cget -color
mottled
% fido cget -breed
mongrel
%

HOW CAN A CLIENT SET OPTIONS AFTER OBJECT CREATION? 💅

any number of options may be set at one time using the configure instance method. suppose closer inspection shows that ::fido is not a brown mongrel, but rather a rare Arctic Boar Hound of a lovely dun color. plot twist fr fr:

% fido configure -color dun -breed "Arctic Boar Hound"
% fido cget -color
dun
% fido cget -breed
Arctic Boar Hound

alternatively, the configurelist method takes a list of options and values. occasionally this is more convenient:

% set features [list -color dun -breed "Arctic Boar Hound"]
-color dun -breed {Arctic Boar Hound}
% fido configurelist $features
% fido cget -color
dun
% fido cget -breed
Arctic Boar Hound
%

in Tcl 8.5, the * keyword can be used with configure in this case:

% set features [list -color dun -breed "Arctic Boar Hound"]
-color dun -breed {Arctic Boar Hound}
% fido configure {*}$features
% fido cget -color
dun
% fido cget -breed
Arctic Boar Hound
%

the results are the same. slay. 💅


HOW SHOULD AN INSTANCE METHOD ACCESS AN OPTION VALUE? 🧚

there are two ways an instance method can set and retrieve an option's value. one is to use the configure and cget methods, as shown below:

% snit::type dog {
    option -weight 10

    method gainWeight {} {
        set wt [$self cget -weight]
        incr wt
        $self configure -weight $wt
    }
}
::dog
% dog fido
::fido
% fido cget -weight
10
% fido gainWeight
% fido cget -weight
11
%

alternatively, Snit provides a built-in array instance variable called options. the indices are the option names; the values are the option values. the method gainWeight can thus be rewritten like this:

    method gainWeight {} {
        incr options(-weight)
    }

see how much less typing that is? obsessed. using the options variable involves considerably less typing and is the usual way to do it. but — if you use -configuremethod or -cgetmethod (described in the following answers), you might wish to use the configure and cget methods anyway, just so that any special processing you've implemented is sure to get done. also, if the option is delegated to a component then configure and cget are the only way to access it without accessing the component directly. see DELEGATION for more info.


HOW CAN I MAKE AN OPTION READ-ONLY? 🔒

define the option with -readonly yes. periodt.

suppose you've got an option that determines how instances of your type are constructed; it must be set at creation time, after which it's constant. for example, a dog never changes its breed; it might or might not have had its shots, and if not can have them at a later time. -breed should be read-only, but -shots should not be:

% snit::type dog {
    option -breed -default mongrel -readonly yes
    option -shots -default no
}
::dog
% dog fido -breed retriever
::fido
% fido configure -shots yes
% fido configure -breed terrier
option -breed can only be set at instance creation
%

the error message is right there. you've been warned bestie. 😭


HOW CAN I CATCH ACCESSES TO AN OPTION'S VALUE? 👀

define a -cgetmethod for the option. simple as that.


WHAT IS A -CGETMETHOD? 💖

a -cgetmethod is a method that's called whenever the related option's value is queried via the cget instance method. the handler can compute the option's value, retrieve it from a database, or do anything else you'd like it to do. main character energy tbh. ✨

here's what the default behavior would look like if written using a -cgetmethod:

snit::type dog {
    option -color -default brown -cgetmethod GetOption

    method GetOption {option} {
        return $options($option)
    }
}

any instance method can be used, provided that it takes one argument: the name of the option whose value is to be retrieved.


HOW CAN I CATCH CHANGES TO AN OPTION'S VALUE? 🔄

define a -configuremethod for the option. yeah you saw this coming.


WHAT IS A -CONFIGUREMETHOD? 🌈

a -configuremethod is a method that's called whenever the related option is given a new value via the configure or configurelist instance methods. the method can pass the value on to some other object, store it in a database, or do anything else you'd like it to do.

here's what the default configuration behavior would look like if written using a -configuremethod:

snit::type dog {
    option -color -default brown -configuremethod SetOption

    method SetOption {option value} {
        set options($option) $value
    }
}

any instance method can be used, provided that it takes two arguments: the name of the option and the new value.

note bestie: if your method doesn't store the value in the options array, the options array won't get updated. no cap. 💀

HOW CAN I VALIDATE AN OPTION'S VALUE? ✅

define a -validatemethod. that's the whole answer.


WHAT IS A -VALIDATEMETHOD? 🎀

a -validatemethod is a method that's called whenever the related option is given a new value via the configure or configurelist instance methods. it's the method's job to determine whether the new value is valid, and throw an error if it isn't. the -validatemethod, if any, is called before the value is stored in the options array; in particular, it's called before the -configuremethod, if any.

for example, suppose an option always takes a Boolean value. you can ensure the value is in fact a valid Boolean like this:

% snit::type dog {
    option -shots -default no -validatemethod BooleanOption

    method BooleanOption {option value} {
        if {![string is boolean -strict $value]} {
            error "expected a boolean value, got \"$value\""
        }
    }
}
::dog
% dog fido
% fido configure -shots yes
% fido configure -shots NotABooleanValue
expected a boolean value, got "NotABooleanValue"
%

caught in 4k. 📸 note that the same -validatemethod can be used to validate any number of boolean options. reuse queen 💅

any method can be a -validatemethod provided that it takes two arguments: the option name and the new option value.

✨ TYPE VARIABLES ✨

💖 WHAT IS A TYPE VARIABLE? 💖

okay so bestie, a type variable is a private variable that belongs to the Snit type itself, not to any one particular instance of it. like, it's the type's variable, the whole squad shares it. 🫶

if you've done C++ or Java, this is literally the same idea as a static member variable. same vibe, different font.

and guess what — type variables can be scalars or arrays. versatile icon behaviour, honestly. 💅


💖 HOW IS A SCALAR TYPE VARIABLE DEFINED? 💖

scalar type variables get defined right in the type definition using the typevariable statement. you can either just name it, or you can go ahead and initialize it with a value:

snit::type mytype {
    # Define variable "greeting" and initialize it with "Howdy!"
    typevariable greeting "Howdy!"
}

and now? every single object of type mytype has access to one shared variable called greeting. one variable, all the instances, no cap. 🌸


💖 HOW IS AN ARRAY-VALUED TYPE VARIABLE DEFINED? 💖

array-valued type variables also get defined with the typevariable command — and to initialize them, you just toss in the -array option:

snit::type mytype {
    # Define typearray variable "greetings"
    typevariable greetings -array {
        formal "Good Evening"
        casual "Howdy!"
    }
}

it's giving organized. it's giving structured data. we love to see it. 🎀


💖 WHAT HAPPENS IF I DON'T INITIALIZE A TYPE VARIABLE? 💖

real talk: variables don't actually exist until they're given values. so if you don't initialize a variable when you define it, you have to assign a value to it before you ever reference it — in the type constructor, for example.

bestie please don't skip this step, referencing an uninitialized variable is not the slay you think it is 😭

💖 ARE THERE ANY LIMITATIONS ON TYPE VARIABLE NAMES? 💖

type variable names have the exact same restrictions as the names of INSTANCE VARIABLES do. same rules, same energy, no exceptions. ✨


💖 DO I NEED TO DECLARE MY TYPE VARIABLES IN MY METHODS? 💖

nope!! 🙅 once you've defined a type variable in the type definition, it can be used in INSTANCE METHODS or TYPE METHODS with no declaration needed. and yes, that's different from normal Tcl practice, where every non-local variable in a proc has to be declared. snit said "we're not doing that here" and honestly? respect.

type variables are subject to the same speed/readability tradeoffs as instance variables — go peek at Do I need to declare my instance variables in my methods? for the whole tea. ☕


💖 HOW DO I PASS A TYPE VARIABLE'S NAME TO ANOTHER OBJECT? 💖

okay so in Tk, it's super common to hand a widget a variable name. for example, Tk label widgets have a -textvariable option that names the variable which will hold the widget's text. that way your program can update the label's value just by assigning a new value to that variable. convenient!! 🔥

BUT. if you naively pass a type variable name to the label widget, you're gonna be so confused by the result, because Tk will assume that name is naming a global variable. 😭

instead, you need to hand over a fully-qualified variable name. and from inside an instance method or a constructor, you can fully qualify a type variable's name using the mytypevar command:

snit::widget mywidget {
    typevariable labeltext ""

    constructor {args} {
        # ...

        label $win.label -textvariable [mytypevar labeltext]

        # ...
    }
}

see how clean that is? mytypevar is the moment. 👑


💖 HOW DO I MAKE A TYPE VARIABLE PUBLIC? 💖

two ways, bestie. take your pick. 🍓

the preferred way is to write a pair of TYPE METHODS to set and query the type variable's value. classy, controlled, chef's kiss.

type variables are stored in the type's namespace, which has the same name as the type itself. so the other way is to just publicize the type variable's name in your documentation, letting clients access it directly. for example:

snit::type mytype {
    typevariable myvariable
}

set ::mytype::myvariable "New Value"

direct access, no middleman. highkey iconic of you. 💅


✨ TYPE METHODS ✨

💖 WHAT IS A TYPE METHOD? 💖

a type method is a procedure associated with the type itself rather than with any specific instance of the type — and you call it as a subcommand of the type command. type-level behaviour, type-level power. 🌈


💖 HOW DO I DEFINE A TYPE METHOD? 💖

type methods get defined in the type definition using the typemethod statement:

snit::type dog {
    # List of pedigreed dogs
    typevariable pedigreed

    typemethod pedigreedDogs {} {
        return $pedigreed
    }
}

so say the dog type keeps a list of the names of the dogs that have pedigrees — the pedigreedDogs type method returns that list. simple, clean, gorgeous. 🐶

the typemethod statement looks just like a normal Tcl proc, except it lives inside a snit::type definition. and heads up: every type method gets an implicit argument called type, which contains the fully-qualified type name. 👑


💖 HOW DOES A CLIENT CALL A TYPE METHOD? 💖

the type method name literally becomes a subcommand of the type's command. so if the constructor adds each pedigreed dog to the pedigreedDogs list:

snit::type dog {
    option -pedigreed 0

    # List of pedigreed dogs
    typevariable pedigreed

    typemethod pedigreedDogs {} {
        return $pedigreed
    }

    # ...
}

dog spot -pedigreed 1
dog fido

foreach dog [dog pedigreedDogs] { ... }

look at that dog pedigreedDogs just working. main character behaviour fr fr. 🐕✨


💖 ARE THERE ANY LIMITATIONS ON TYPE METHOD NAMES? 💖

not really! as long as you avoid the standard type method names: create, destroy, and info. those three are taken, bestie, pick something else. 🙈


💖 HOW DO I MAKE A TYPE METHOD PRIVATE? 💖

sometimes you want private type methods — like, type methods that are only meant to be called by other type or instance methods of the same object. inner-circle only. 💅

Snit doesn't implement any access control on type methods. by convention though: names of public methods begin with a lower-case letter, and names of private methods begin with an upper-case letter. vibe-based security, we love it.

alternatively, a Snit proc can be used as a private type method — go see PROCS. 🎀


💖 ARE THERE ANY LIMITATIONS ON TYPE METHOD ARGUMENTS? 💖

method argument lists are defined just like normal Tcl proc argument lists! in particular, they can include arguments with default values and the args argument. flexible queen. ✨

however — every type method is called with an implicit argument called type that contains the name of the type command. and on top of that, type methods should by convention avoid using the names of the arguments implicitly defined for INSTANCE METHODS. don't clash, bestie. 🌸


💖 HOW DOES AN INSTANCE OR TYPE METHOD CALL A TYPE METHOD? 💖

if an instance or type method needs to call a type method, it should use $type to do it:

snit::type dog {

    typemethod pedigreedDogs {} { ... }

    typemethod printPedigrees {} {
        foreach obj [$type pedigreedDogs] { ... }
    }
}

$type is the plug. always route through it. 🔌


💖 HOW DO I PASS A TYPE METHOD AS A CALLBACK? 💖

it's common in Tcl to pass a snippet of code to another object so it can call it later. and because types cannot be renamed, you can just use the type name — or, if the callback is registered from within a type method, use type. no fancy footwork required. 🦋

for example, suppose we want to print a list of pedigreed dogs when a Tk button gets pushed:

button .btn -text "Pedigrees" -command [list dog printPedigrees]
pack .btn

alternatively, from a method or type method you can use the mytypemethod command — just like you'd use mymethod to define a callback command for INSTANCE METHODS. same energy, different scope. 💖


💖 CAN TYPE METHODS BE HIERARCHICAL? 💖

yes!! you can define hierarchical type methods in just the same way you can define hierarchical instance methods. go check INSTANCE METHODS for the whole story. nesting rights, unlocked. 🌈


✨ PROCS ✨

💖 WHAT IS A PROC? 💖

a Snit proc is really just a Tcl proc defined inside the type's namespace. that's it, that's the whole thing. 😌

you can use procs for private code that isn't related to any particular instance — like, the little helpers that just exist in the background doing their thing. 🎀


💖 HOW DO I DEFINE A PROC? 💖

procs get defined by including a proc statement in the type definition:

snit::type mytype {
    # Pops and returns the first item from the list stored in the
    # listvar, updating the listvar
   proc pop {listvar} { ... }

   # ...
}

private, tidy, exactly where it should be. chef's kiss. 🍓


💖 ARE THERE ANY LIMITATIONS ON PROC NAMES? 💖

any name works, as long as it does not begin with Snit_ — names starting with Snit_ are reserved for Snit's own use. hands off those, bestie. 🙈

but also, the wise programmer will avoid proc names like set, list, if, etc., because those would shadow standard Tcl command names. don't do that to yourself. 💀

proc names, being private, should begin with a capital letter according to convention — however, since there are typically no public procs in the type's namespace, it doesn't matter much either way. do what feels right, honestly. ✨


💖 HOW DOES A METHOD CALL A PROC? 💖

just like it calls any Tcl command. for example:

snit::type mytype {
    # Pops and returns the first item from the list stored in the
    # listvar, updating the listvar
    proc pop {listvar} { ... }

    variable requestQueue {}

    # Get one request from the queue and process it.
    method processRequest {} {
        set req [pop requestQueue]
    }
}

no special syntax, no secret handshake. just call it. 🫶


💖 HOW CAN I PASS A PROC TO ANOTHER OBJECT AS A CALLBACK? 💖

the myproc command returns a callback command for the proc — exactly the same way mymethod does it for a method. callback, but make it proc. 💅


✨ TYPE CONSTRUCTORS ✨

💖 WHAT IS A TYPE CONSTRUCTOR? 💖

a type constructor is a body of code that initializes the type as a whole — kind of like a C++ static initializer. 🧚

here's the tea: the body of a type constructor is executed once when the type is defined, and never again. one shot. one moment. ⭐

and a type can have at most one type constructor. not two. not three. one. periodt. 👑


💖 HOW DO I DEFINE A TYPE CONSTRUCTOR? 💖

you define a type constructor by using the typeconstructor statement in the type definition. so say the type uses an array-valued type variable as a look-up table, and the values in that array have to be computed at start-up:

% snit::type mytype {
    typevariable lookupTable

    typeconstructor {
        array set lookupTable {key value...}
    }
}

look-up table, populated at definition time, ready to go. setup done before anyone even asks. that's foresight, bestie. 🔮✨

🎀 CONSTRUCTORS 🎀

✨ WHAT IS A CONSTRUCTOR? ✨

Okay bestie, in object-oriented programming, an object's constructor is literally the main character of creation time — it's the thing responsible for initializing the object completely. It receives the list of options you passed to the snit::type command's create method, and after that? It can do whatever it wants. That might include computing instance variable values, reading data from files, creating other objects, updating type and instance variables, and so forth. Sky's the limit fr fr.

The constructor's return value is ignored (unless it's an error, of course 💀).


💅 HOW DO I DEFINE A CONSTRUCTOR? 💅

You define a constructor with the constructor statement in the type definition. Periodt.

Say we wanna keep a list of all pedigreed dogs (obsessed). The list can live in a type variable and get retrieved by a type method. Whenever a dog is created, it can add itself to the list — provided that it's registered with the American Kennel Club, obviously. No AKC, no list, iykyk.

% snit::type dog {
    option -akc 0

    typevariable akcList {}

    constructor {args} {
        $self configurelist $args

        if {$options(-akc)} {
            lappend akcList $self
        }
    }

    typemethod akclist {} {
        return $akcList
    }
}
::dog
% dog spot -akc 1
::spot
% dog fido
::fido
% dog akclist
::spot
%

See how spot made the list and fido simply did not? That's the vibe check right there. 🐕✨


🌸 WHAT DOES THE DEFAULT CONSTRUCTOR DO? 🌸

If you don't provide a constructor explicitly, you get the default constructor, which is identical to the explicitly-defined constructor shown here:

snit::type dog {
    constructor {args} {
        $self configurelist $args
    }
}

When the constructor is called, args will be set to the list of arguments that follow the object's name. The constructor is allowed to interpret this list any way it chooses — the normal convention is to assume it's a list of option names and values, as shown in the example above. And if you simply want to save the option values, use the configurelist method, as shown. Easy. Slay. 💖


🦋 CAN I CHOOSE A DIFFERENT SET OF ARGUMENTS FOR THE CONSTRUCTOR? 🦋

Yes, you absolutely can. For example, suppose we wanted to be sure that the breed was explicitly stated for every dog at creation time, and couldn't be changed thereafter. One way to do that is as follows:

% snit::type dog {
    variable breed

    option -color brown
    option -akc 0

    constructor {theBreed args} {
        set breed $theBreed
        $self configurelist $args
    }

    method breed {} { return $breed }
}
::dog
% dog spot dalmatian -color spotted -akc 1
::spot
% spot breed
dalmatian

The drawback is that this syntax is non-standard, and may limit the compatibility of your new type with other people's code. For example, Snit assumes that it can create COMPONENTS using the standard creation syntax. So like… cute idea, but know what you're getting into, bestie. 🙈


⭐ ARE THERE ANY LIMITATIONS ON CONSTRUCTOR ARGUMENTS? ⭐

Constructor argument lists are subject to the same limitations as those on instance method argument lists. It has the same implicit arguments, and can contain default values and the args argument. Same rules, different day. 💅


🔥 IS THERE ANYTHING SPECIAL ABOUT WRITING THE CONSTRUCTOR? 🔥

Yes. Writing the constructor can be tricky if you're delegating options to components, and there are specific issues relating to snit::widgets and snit::widgetadaptors. Go read DELEGATION, WIDGETS, WIDGET ADAPTORS, and THE TK OPTION DATABASE. That's your homework, no skipping. 📚


💀 DESTRUCTORS 💀

🌈 WHAT IS A DESTRUCTOR? 🌈

A destructor is a special kind of method that's called when an object is destroyed. It's responsible for doing any necessary clean-up when the object goes away: destroying COMPONENTS, closing files, and so forth. It's giving "you had a great run, now let's clean up your room." 🧹


🎀 HOW DO I DEFINE A DESTRUCTOR? 🎀

Destructors are defined by using the destructor statement in the type definition.

Suppose we're maintaining a list of pedigreed dogs; then we'll want to remove dogs from it when they are destroyed. Bye-bye, spot 😭

snit::type dog {
    option -akc 0

    typevariable akcList {}

    constructor {args} {
        $self configurelist $args

        if {$options(-akc)} {
            lappend akcList $self
        }
    }

    destructor {
        set ndx [lsearch $akcList $self]

        if {$ndx != -1} {
            set akcList [lreplace $akcList $ndx $ndx]
        }
    }

    typemethod akclist {} {
        return $akcList
    }
}

🫶 ARE THERE ANY LIMITATIONS ON DESTRUCTOR ARGUMENTS? 🫶

Yes; a destructor has no explicit arguments. None. Zero. Zip. That's just how it is. ✨


🍓 WHAT IMPLICIT ARGUMENTS ARE PASSED TO THE DESTRUCTOR? 🍓

The destructor gets the same implicit arguments that are passed to INSTANCE METHODS: type, selfns, win, and self. Same crew, showing up to the farewell party. 💜


🧚 MUST COMPONENTS BE DESTROYED EXPLICITLY? 🧚

Yes and no. It's giving "it depends," sorry bestie.

Any Tk widgets created by a snit::widget or snit::widgetadaptor will be destroyed automatically by Tk when the megawidget is destroyed, in keeping with normal Tk behavior (destroying a parent widget destroys the whole tree). Tk really said "I got this." 👑

Components of normal snit::types, on the other hand, are never destroyed automatically, nor are non-widget components of Snit megawidgets. So if your object creates them in its constructor, then it should generally destroy them in its destructor. You made the mess, you clean it up. 💅


💖 IS THERE ANY SPECIAL ABOUT WRITING A DESTRUCTOR? 💖

Yes. And this part is important, so lock in.

If an object's constructor throws an error, the object's destructor will be called to clean up; this means that the object might not be completely constructed when the destructor is called. This can cause the destructor to throw its own error; the result is usually misleading, confusing, and unhelpful. Consequently, it's important to write your destructor so that it's fail-safe. No cap.

For example, a dog might create a tail component; the component will need to be destroyed. But suppose there's an error while processing the creation options — the destructor will be called, and there will be no tail to destroy. The simplest solution is generally to catch and ignore any errors while destroying components.

snit::type dog {
    component tail

    constructor {args} {
        $self configurelist $args

        set tail [tail %AUTO%]
    }

    destructor {
        catch {$tail destroy}
    }
}

catch and move on — that's the energy. 🙌

🧩 COMPONENTS 🧩

💫 WHAT IS A COMPONENT?

Okay so picture this: an object is out here living its life and it creates a whole squad of other objects to manage. A Snit megawidget, for instance, will usually spin up a bunch of Tk widgets. Those objects are literally part of the main object — it's composed of them — so we call them components of the object. It's giving main character with a supporting cast. 💅

But bestie, Snit also has a way more precise meaning for COMPONENT. The components of a Snit object are specifically those objects that methods or options can be delegated to. (Go check DELEGATION if you wanna know more about how delegation works.) ✨

💫 HOW DO I DECLARE A COMPONENT?

First step: figure out what role this component plays inside your object, and give that role a name. Then you declare the component with its role name and the component statement. The component statement declares an instance variable, and that variable is where the component's command name gets stored once the component is created. 🌸

So like, say your dog object creates a tail object (the better to wag with, obviously):

snit::type dog {
    component mytail

    constructor {args} {
        # Create and save the component's command
        set mytail [tail %AUTO% -partof $self]
        $self configurelist $args
    }

    method wag {} {
        $mytail wag
    }
}

See how it doesn't matter what the tail object's real name is? The dog object just refers to it by its component name. Iconic. 👑

That example shows one way to delegate the wag method to the mytail component — but head over to DELEGATION for an easier way, because there totally is one. 🦋

💫 HOW IS A COMPONENT NAMED?

A component has two names, not one. Not me giving you a two-for-one deal. 🎀

The first name is the name of the component variable — it represents the role the component object plays inside your Snit object. That's the component name proper, and it's the name you use to refer to the component in Snit code.

The second name is the name of the actual component object that your Snit object's constructor creates. That one is always a Tcl command name, and we call it the component's object name.

In the example from the last question, the component name is mytail, and the mytail component's object name was chosen automatically by Snit, since %AUTO% was used when the component object got created. Snit really said "I got you." ✨

💫 ARE THERE ANY LIMITATIONS ON COMPONENT NAMES?

Yep, unfortunately. 😭

snit::widget and snit::widgetadaptor objects have a special component called the hull component. So the name hull should be used for literally nothing else. Don't try it.

Otherwise, since component names are in fact instance variable names, they have to follow the rules laid out in INSTANCE VARIABLES.

💫 WHAT IS AN OWNED COMPONENT?

An owned component is a component whose object command's lifetime is controlled by the snit::type or snit::widget. So basically, you're its parent. 🫶

Like we said up top, a component is an object our object can delegate methods or options to. Under that definition, our object will usually create its component objects — but not necessarily. Check this out: a dog object has a tail component, but the tail knows it's part of the dog:

snit::type dog {
    component mytail

    constructor {args} {
        set mytail [tail %AUTO% -partof $self]
        $self configurelist $args
    }

    destructor {
        catch {$mytail destroy}
    }

    delegate method wagtail to mytail as wag

    method bark {} {
        return "$self barked."
    }
}

snit::type tail {
    component mydog
    option -partof -readonly yes

    constructor {args} {
        $self configurelist $args
        set mydog $options(-partof)
    }

    method wag {} {
        return "Wag, wag."
    }

    method pull {} {
        $mydog bark
    }
}

So if you ask a dog to wag its tail, it tells its tail to wag. And if you pull the dog's tail, the tail tells the dog to bark. Mutual. 💖 In this scenario, the tail is a component of the dog, and the dog is a component of the tail — but the dog owns the tail, not the other way around. The dog is the one holding the leash, lowkey. 🐕

💫 WHAT DOES THE install COMMAND DO?

The install command creates an owned component using a specified command, and assigns the result to the component's instance variable. Like so:

snit::type dog {
    component mytail

    constructor {args} {
        # set mytail [tail %AUTO% -partof $self]
        install mytail using tail %AUTO% -partof $self
        $self configurelist $args
    }
}

In a snit::type's code, that install command is exactly equivalent to the set mytail command that's commented out. ✨

But in a snit::widget's or snit::widgetadaptor's code, install also queries THE TK OPTION DATABASE and initializes the new component's options accordingly. So for consistency, it's a good idea to get in the habit of using install for all owned components. Trust. 💅

💫 MUST OWNED COMPONENTS BE CREATED IN THE CONSTRUCTOR?

Nope, not necessarily! In fact, there's literally no reason an object can't destroy and recreate a component multiple times over its own lifetime. It's giving character development arc. 🌈

💫 ARE THERE ANY LIMITATIONS ON COMPONENT OBJECT NAMES?

Yes. 🙈

Component objects that are Tk widgets or megawidgets must have valid Tk window names.

Component objects that are not widgets or megawidgets must have fully-qualified command names, i.e., names that include the full namespace of the command. And good news — Snit always creates objects with fully qualified names anyway. 💫

Next up: the object names of components owned by your object must be unique. For widget components this is a non-issue, since widget names are always unique. But consider this code:

snit::type tail { ... }

snit::type dog {
    delegate method wag to mytail

    constructor {} {
        install mytail using tail mytail
    }
}

This code uses the component name, mytail, as the component object name. That is not good, and here's why: Snit instance code executes in the Snit type's namespace. So in this case, the mytail component gets created in the ::dog:: namespace, and will therefore have the name ::dog::mytail.

Now imagine you create two dogs. Both dogs will attempt to create a tail called ::dog::mytail. The first one succeeds. The second one fails, because Snit won't let you create an object if its name is already a command. 💀

Here are two ways to dodge that whole situation:

First — if the component type is a snit::type, you can specify %AUTO% as its name and you're guaranteed to get a unique one. This is the safest thing to do:

install mytail using tail %AUTO%

If the component type isn't a snit::type, you can create the component in the object's instance namespace:

install mytail using tail ${selfns}::mytail

Just make sure you pick a unique name within the instance namespace. 👑

💫 MUST I DESTROY THE COMPONENTS I OWN?

That depends, bestie. 😭

When a parent widget is destroyed, all child widgets are destroyed automatically. So if your object is a snit::widget or snit::widgetadaptor, you don't need to destroy any components that are widgets, because they'll generally be children or descendants of your megawidget. They go down together, slay. 🔥

If your object is an instance of snit::type, though? None of its owned components get destroyed automatically. And the same goes for non-widget components of a snit::widget — those don't get auto-destroyed either. All such owned components must be destroyed explicitly, or they won't be destroyed at all. Periodt. 💅

💫 CAN I EXPOSE A COMPONENT'S OBJECT COMMAND AS PART OF MY INTERFACE?

Yes! And there are two ways to do it. 🌸

The most appropriate way is usually to use DELEGATION. Delegation lets you pass the options and methods you specify along to particular components. That effectively hides the components from the users of your type and ensures good encapsulation. Very demure, very mindful.

However — there are times when it's appropriate, not to mention simpler, to just make the entire component part of your type's public interface. Main character component. ✨

💫 HOW DO I EXPOSE A COMPONENT'S OBJECT COMMAND?

When you declare the component, specify the component statement's -public option. The value of that option is the name of a method which will be delegated to your component's object command. 🎀

So for example, supposed you've written a combobox megawidget that owns a listbox widget, and you want to make the listbox's entire interface public. You can do it like this:

snit::widget combobox {
     component listbox -public listbox

     constructor {args} {
         install listbox using listbox $win.listbox ....
     }
}

combobox .mycombo
.mycombo listbox configure -width 30

Your comobox widget, .mycombo, now has a listbox method which has all of the same subcommands as the listbox widget itself. So the code above sets the listbox component's width to 30. Obsessed. 💜

Usually you'll let the method name be the same as the component name — however, you can name it anything you like. Your call, babe. 🦋

✨ TYPE COMPONENTS ✨

WHAT IS A TYPE COMPONENT? 💭

A type component is a component that belongs to the type itself instead of to one particular instance of the type. The relationship between components and type components is exactly the same as the relationship between INSTANCE VARIABLES and TYPE VARIABLES. And both INSTANCE METHODS and TYPE METHODS can be delegated to type components, bestie. 💅

So once you've got COMPONENTS and DELEGATION down? Type components are just more of the same. No new lore, promise. 🫶


HOW DO I DECLARE A TYPE COMPONENT? 🎀

You declare a type component with the typecomponent statement. It takes the same options that the component statement does — that's -inherit and -public — and it defines a type variable to hold the type component's object command.

Say your model has so many dogs but only one veterinarian. The vet is giving major singleton energy, so you'd make it a type component:

snit::type veterinarian { ... }

snit::type dog {
    typecomponent vet

    # ...
}

HOW DO I INSTALL A TYPE COMPONENT? 🛠️

Just use set to assign the component's object command to the type component. That's it, that's the whole thing. ✨

Why no install? Because types — even snit::widget types — are not widgets, and they don't have options anyway, so all the extra fancy features of install are simply not needed here. Not applicable. Unbothered. 💀

You'll usually install type components inside the type constructor, like so:

snit::type veterinarian { ... }

snit::type dog {
    typecomponent vet

    typeconstructor {
        set vet [veterinarian %AUTO%]
    }
}

ARE THERE ANY LIMITATIONS ON TYPE COMPONENT NAMES? 🚧

Yes bestie, unfortunately. Same limitations as on INSTANCE VARIABLES, TYPE VARIABLES, and normal COMPONENTS. No special exemptions, no loopholes. 😭


💖 DELEGATION 💖

WHAT IS DELEGATION? 📬

Okay so, delegation is basically when you get handed a task and you pass it straight to one of your assistants. (You do have assistants, right? obviously you do 💅)

Snit objects can do the exact same thing. Here's one way the dog object can delegate its wag method and its -taillength option to its tail component:

snit::type dog {
    variable mytail

    option -taillength -configuremethod SetTailOption -cgetmethod GetTailOption

    method SetTailOption {option value} {
         $mytail configure $option $value
    }

    method GetTailOption {option} {
         $mytail cget $option
    }

    method wag {} {
        $mytail wag
    }

    constructor {args} {
        install mytail using tail %AUTO% -partof $self
        $self configurelist $args
    }

}

Now, ngl, this is the hard way to do it — but it demonstrates what delegation is all about, which is the whole point. 👑 The following answers show you the easy way.

Heads up: the constructor calls configurelist after it creates its tail. That order matters, bestie. If it didn't — and -taillength showed up in the list of args — you'd get an error. 💀

HOW CAN I DELEGATE A METHOD TO A COMPONENT OBJECT? 🦋

Delegation happens so often that Snit made it easy. Any method can be delegated to any component or type component with a single delegate statement in the type definition. (Peep COMPONENTS and TYPE COMPONENTS for more on component names. iykyk ✨)

Here's a much better way to delegate the dog object's wag method:

% snit::type dog {
    delegate method wag to mytail

    constructor {} {
        install mytail using tail %AUTO%
    }
}
::dog
% snit::type tail {
    method wag {} { return "Wag, wag, wag."}
}
::tail
% dog spot
::spot
% spot wag
Wag, wag, wag.

This code has the exact same effect as the code in the previous question: when a dog's wag method is called, the call and its arguments get passed along automatically to the tail object. Slay. 🐕

Two things, bestie: first, when a component is mentioned in a delegate statement, the component's instance variable is defined implicitly. But it's still good practice to declare it explicitly with the component statement. Second: you can define a method name using the method statement, or you can define it using delegate — you can't do both. Pick a lane. 🚫

CAN I DELEGATE TO A METHOD WITH A DIFFERENT NAME? 🏷️

Say you want to delegate the dog's wagtail method to the tail's wag method. Which, honestly, makes sense — you wag the tail, not the dog. Anyway, it's easily done:

snit::type dog {
    delegate method wagtail to mytail as wag

    constructor {args} {
        install mytail using tail %AUTO% -partof $self
        $self configurelist $args
    }
}

CAN I DELEGATE TO A METHOD WITH ADDITIONAL ARGUMENTS? ➕

Okay imagine the tail's wag method takes an argument: the number of times the tail should be wagged. And you want to delegate the dog's wagtail method to the tail's wag, but specify that the tail gets wagged exactly three times. This is easily done too, bestie:

snit::type dog {
    delegate method wagtail to mytail as {wag 3}
    # ...
}

snit::type tail {
    method wag {count} {
        return [string repeat "Wag " $count]
    }
    # ...
}

CAN I DELEGATE A METHOD TO SOMETHING OTHER THAN AN OBJECT? 🤔

So, normal method delegation assumes you're delegating a method (a subcommand of an object command) to a method of another object (a subcommand of a different object command). But — plot twist — not all Tcl objects follow Tk conventions, and not everything you'd like to delegate to is necessarily an object.

So Snit makes it easy to delegate a method to pretty much anything you like, using the delegate statement's using clause. 💫

Suppose your dog simulation stores dogs in a database, each dog as a single record. The database API you're using has a bunch of commands to manage records, and each one takes the record ID (a string you choose) as its first argument. For example, saverec saves a record. If you let the record ID be the name of the dog object, you can delegate the dog's save method to the saverec command like this:

snit::type dog {
    delegate method save using {saverec %s}
}

The %s gets replaced with the instance name when the save method is called, and any additional arguments are appended to the resulting command. Periodt. 💅

The using clause understands a bunch of other %-conversions too. Besides the instance name, you can substitute:

  • %m — the method name
  • %t — the type name
  • %n — the instance namespace
  • %w — the Tk window name
  • %c — the component's object command, but only if a component or typecomponent name was given in the delegate statement

HOW CAN I DELEGATE A METHOD TO A TYPE COMPONENT OBJECT? 👑

Literally exactly how you'd delegate to a component object. The delegate method statement accepts both component and type component names in its to clause. Same energy, no extra steps. 🫶


HOW CAN I DELEGATE A TYPE METHOD TO A TYPE COMPONENT OBJECT? 🌈

Use the delegate typemethod statement. It works like delegate method, with these differences:

  1. It defines a type method instead of an instance method.
  2. The using clause ignores the %s, %n, and %w %-conversions.

And naturally, you can't delegate a type method to an instance component... Snit wouldn't know which instance should receive it. No cap. 😭


HOW CAN I DELEGATE AN OPTION TO A COMPONENT OBJECT? ⚙️

The first question in this section (see DELEGATION) shows one way to delegate an option to a component — but this pattern comes up so often that Snit just went ahead and made it easy.

For example: every tail object has a -length option, and we want to let the creator of a dog object set the tail's length. So we do this:

% snit::type dog {
    delegate option -length to mytail

    constructor {args} {
        install mytail using tail %AUTO% -partof $self
        $self configurelist $args
    }
}
::dog
% snit::type tail {
    option -partof
    option -length 5
}
::tail
% dog spot -length 7
::spot
% spot cget -length
7

This gives you nearly the same result as the -configuremethod and -cgetmethod from the first question in this section: whenever a dog object's -length option gets set or retrieved, the underlying tail object's option gets set or retrieved in turn. Iconic. ✨

Same rule as methods, bestie: you can define an option name with the option statement, or you can define it using delegate — you can't do both. 🚫

CAN I DELEGATE TO AN OPTION WITH A DIFFERENT NAME? 🎀

In the previous answer we delegated the dog's -length option down to its tail. Which is, of course, wrong. 😭 The dog has a length, the tail has a length, and those are two different lengths. The dog is not just a tail, bestie.

What we actually want is to give the dog a -taillength option, but delegate it to the tail's -length option:

snit::type dog {
    delegate option -taillength to mytail as -length

    constructor {args} {
        set mytail [tail %AUTO% -partof $self]
        $self configurelist $args
    }
}

HOW CAN I DELEGATE ANY UNRECOGNIZED METHOD OR OPTION TO A COMPONENT OBJECT? 💀

Okay this one's a big mood. It can happen that a Snit object gets most of its behavior from one of its components. This is super common with snit::widgetadaptors, for example, where you want to slightly modify the behavior of an existing widget.

But let's carry on with our dog example. Suppose we have a snit::type called animal that implements a whole variety of animal behaviors — moving, eating, sleeping, and so forth. We want our dog objects to inherit those same behaviors while also adding dog-like behaviors of their own.

Here's how we give a dog its own methods and options while delegating all other methods and options to its animal component:

snit::type dog {
    delegate option * to animal
    delegate method * to animal

    option -akc 0

    constructor {args} {
        install animal using animal %AUTO% -name $self
        $self configurelist $args
    }

    method wag {} {
        return "$self wags its tail"
    }
}

That's it. That's the whole thing. A dog is now an animal that has a -akc option and can wag its tail. Main character energy. 🐶👑

And note: we do not need to specify the full list of method names or option names that animal will receive. It gets anything dog doesn't recognize — and if it doesn't recognize it either, it'll simply throw an error, just as it should. The vibes are immaculate and the error handling is honest. 🫶

You can also yeet all the unknown type methods at a type component with delegate typemethod *. Slay.

HOW CAN I DELEGATE ALL BUT CERTAIN METHODS OR OPTIONS TO A COMPONENT? 💅

So in the last answer we were like "every dog is an animal" and just delegated literally everything unknown to the animal component. But bestie… what if the animal type has some methods or options we genuinely do NOT want? Suppressing a couple? Totally doable.

One option (derogatory): explicitly delegate every single option and method by hand and give up the convenience of delegate method * and delegate option *. Exhausting. But if you're only trying to suppress a few options or methods, there's a way easier route:

snit::type dog {
    delegate option * to animal except -numlegs
    delegate method * to animal except {fly climb}

    # ...

    constructor {args} {
        install animal using animal %AUTO% -name $self -numlegs 4
        $self configurelist $args
    }

    # ...
}

Dogs have four legs, so we state that explicitly when we create the animal component, and we explicitly exclude -numlegs from the set of delegated options. And similarly, dogs can neither fly nor climb, so we exclude those animal methods like shown. Periodt. 🐕

CAN A HIERARCHICAL METHOD BE DELEGATED? 🌸

Yes bestie! Just specify multiple words in the delegated method's name:

snit::type tail {
    method wag {} {return "Wag, wag"}
    method droop {} {return "Droop, droop"}
}

snit::type dog {
    delegate method {tail wag} to mytail
    delegate method {tail droop} to mytail

    # ...

    constructor {args} {
        install mytail using tail %AUTO%
        $self configurelist $args
    }

    # ...
}

Unrecognized hierarchical methods can be delegated too, no cap. The following code delegates all subcommands of the tail method to the mytail component:

snit::type dog {
    delegate method {tail *} to mytail

    # ...
}

🎀 WIDGETS 🎀

WHAT IS A SNIT::WIDGET? ✨

A snit::widget is the Snit version of what Tcl programmers usually call a megawidget: a widget-like object usually consisting of one or more Tk widgets, all contained within a Tk frame. It's giving nesting doll energy 🪆

A snit::widget is also a special kind of snit::type. Just about everything in this whole FAQ list that relates to snit::types also applies to snit::widgets. So if you read the type parts, you're already 90% of the way there. 💖

HOW DO I DEFINE A SNIT::WIDGET? 🦋

snit::widgets are defined using the snit::widget command, just like snit::types are defined by the snit::type command. Same vibe, different command name.

The body of the definition can contain all of the same kinds of statements, plus a couple of others which will be mentioned below. 👑

HOW DO SNIT::WIDGETS DIFFER FROM SNIT::TYPES? 🔥

  • The name of an instance of a snit::type can be any valid Tcl command name, in any namespace. The name of an instance of a snit::widget must be a valid Tk widget name, and its parent widget must already exist.
  • An instance of a snit::type can be destroyed by calling its destroy method. Instances of a snit::widget have no destroy method; use the Tk destroy command instead. Not me reaching for a method that doesn't exist 😭
  • Every instance of a snit::widget has one predefined component called its hull component. The hull is usually a Tk frame or toplevel widget; any other widgets created as part of the snit::widget will usually be contained within the hull.
  • snit::widgets can have their options receive default values from THE TK OPTION DATABASE.

WHAT IS A HULL COMPONENT? 🫶

Snit can't create a Tk widget object; only Tk can do that. So every instance of a snit::widget must be wrapped around a genuine Tk widget — and that Tk widget is called the hull component. Snit effectively piggybacks the behavior you define (methods, options, and so forth) on top of the hull component so that the whole thing behaves like a standard Tk widget. Little guy carrying the whole personality 💅

For snit::widgets the hull component must be a Tk widget that defines the -class option.

snit::widgetadaptors differ from snit::widgets chiefly in that any kind of widget can be used as the hull component; see WIDGET ADAPTORS.

HOW CAN I SET THE HULL TYPE FOR A SNIT::WIDGET? 🌈

A snit::widget's hull component will usually be a Tk frame widget; however, it may be any Tk widget that defines the -class option. You can explicitly choose the hull type you prefer by including the hulltype command in the widget definition:

snit::widget mytoplevel {
    hulltype toplevel

    # ...
}

If no hulltype command appears, the hull will be a frame.

By default, Snit recognizes the following hull types: the Tk widgets frame, labelframe, toplevel, and the Tile widgets ttk::frame, ttk::labelframe, and ttk::toplevel. To enable the use of some other kind of widget as the hull type, you can lappend the widget command to the variable snit::hulltypes (always provided the widget defines the -class option). For example, suppose Tk gets a new widget type called a prettyframe:

lappend snit::hulltypes prettyframe

snit::widget mywidget {
    hulltype prettyframe

    # ...
}

HOW SHOULD I NAME WIDGETS WHICH ARE COMPONENTS OF A SNIT::WIDGET? 🎀

Every widget, whether a genuine Tk widget or a Snit megawidget, has to have a valid Tk window name. When a snit::widget is first created, its instance name, self, is a Tk window name; however, if the snit::widget is used as the hull component by a snit::widgetadaptor its instance name will be changed to something else. For this reason, every snit::widget method, constructor, destructor, and so forth is passed another implicit argument, win, which is the window name of the megawidget. Any children should be named using win as the root. Use win, bestie, not self — this is the whole point. 💜

Thus, suppose you're writing a toolbar widget, a frame consisting of a number of buttons placed side-by-side. It might look something like this:

snit::widget toolbar {
    delegate option * to hull

    constructor {args} {
        button $win.open -text Open -command [mymethod open]
        button $win.save -text Save -command [mymethod save]

        # ....

        $self configurelist $args

    }
}

See also the question on renaming objects, toward the top of this file.


🦋 WIDGET ADAPTORS 🦋

WHAT IS A SNIT::WIDGETADAPTOR? 💖

A snit::widgetadaptor is a kind of snit::widget. Whereas a snit::widget's hull is automatically created and is always a Tk frame, a snit::widgetadaptor can be based on any Tk widget — or on any Snit megawidget, or even (with luck) on megawidgets defined using some other package.

It's called a widget adaptor because it allows you to take an existing widget and customize its behavior. Glow up, but for widgets ✨

HOW DO I DEFINE A SNIT::WIDGETADAPTOR? 🔥

Use the snit::widgetadaptor command. The definition for a snit::widgetadaptor looks just like that for a snit::type or snit::widget, except that the constructor must create and install the hull component.

For example, the following code creates a read-only text widget by the simple device of turning its insert and delete methods into no-ops. Then, we define new methods, ins and del, which get delegated to the hull component as insert and delete. Thus, we've adapted the text widget and given it new behavior while still leaving it fundamentally a text widget.

::snit::widgetadaptor rotext {

    constructor {args} {
        # Create the text widget; turn off its insert cursor
        installhull using text -insertwidth 0

        # Apply any options passed at creation time.
        $self configurelist $args
    }

    # Disable the text widget's insert and delete methods, to
    # make this readonly.
    method insert {args} {}
    method delete {args} {}

    # Enable ins and del as synonyms, so the program can insert and
    # delete.
    delegate method ins to hull as insert
    delegate method del to hull as delete

    # Pass all other methods and options to the real text widget, so
    # that the remaining behavior is as expected.
    delegate method * to hull
    delegate option * to hull
}

The most important part is in the constructor. Whereas snit::widget creates the hull for you, snit::widgetadaptor cannot — it doesn't know what kind of widget you want. So the first thing the constructor does is create the hull component (a Tk text widget in this case), and then installs it using the installhull command.

⚠️ Note: There is no instance command until you create one by installing a hull component. Any attempt to pass methods to $self prior to calling installhull will fail. Don't do it, bestie, it's not the move. 💀

CAN I ADAPT A WIDGET CREATED ELSEWHERE IN THE PROGRAM? 🙈

Yes.

At times, it can be convenient to adapt a pre-existing widget instead of creating your own. For example, the Bwidget PagesManager widget manages a set of frame widgets, only one of which is visible at a time. The application chooses which frame is visible. All of the These frames are created by the PagesManager itself, using its add method. It's convenient to adapt these frames to do what we'd like them to do.

In a case like this, the Tk widget will already exist when the snit::widgetadaptor is created. Snit provides an alternate form of the installhull command for this purpose:

snit::widgetadaptor pageadaptor {
    constructor {args} {
        # The widget already exists; just install it.
        installhull $win

        # ...
    }
}

CAN I ADAPT ANOTHER MEGAWIDGET? 🌸

Maybe. If the other megawidget is a snit::widget or snit::widgetadaptor, then yes. If it isn't then, again, maybe. You'll have to try it and see. You're most likely to have trouble with widget destruction — you have to make sure that your megawidget code receives the <Destroy> event before the megawidget you're adapting does. Timing is everything, iykyk 🧚


👑 THE TK OPTION DATABASE 👑

WHAT IS THE TK OPTION DATABASE? ⭐

The Tk option database is a database of default option values maintained by Tk itself; every Tk application has one. The concept of the option database derives from something called the X Windows resource database; however, the option database is available in every Tk implementation, including those which do not use the X Windows system (e.g., Microsoft Windows). Iconic behavior honestly. 🫶

Okay bestie, full disclosure: the whole Tk option database thing is way bigger than this one page. If you want the deep lore, go read Practical Programming in Tcl and Tk by Welch, Jones, and Hobbs, or Effective Tcl/Tk Programming by Harrison and McClennan. Both have genuinely good intros to it. 📚✨

Snit is built so that, like, most of the time it just Does The Right Thing with the option database — provided the widget dev also does the right thing by Snit. The rest of this section goes deep, but here's the TL;DR checklist for reference:

  • If the widget's default widget class isn't what you want, set it explicitly with the widgetclass statement in the widget definition.
  • When defining or delegating options, spell out the resource and class names explicitly whenever it matters.
  • Use the installhull using command to create and install the hull for snit::widgetadaptors.
  • Use the install command to create and install all components that are widgets.
  • Use the install command for components that aren't widgets too, if you want them to receive option values from the option database. 👑

How Tk widgets interact with the option database? Complex. How Snit interacts with it? even more so, bestie — it really repays attention to detail. 🧠💅


🦋 DO SNIT::TYPES USE THE TK OPTION DATABASE? 🦋

Nope, they don't. Querying the option database needs a Tk window name, and snit::types don't have one. Simple as. 💀

But — if you create an instance of a snit::type as a component of a snit::widget or snit::widgetadaptor, and any options are delegated to that component, and you use install to create and install it, then the megawidget will query the option database on the snit::type's behalf. That might be exactly what you want or it might not, so like… be careful. 🙈


🎀 WHAT IS MY SNIT::WIDGET'S WIDGET CLASS? 🎀

Every Tk widget has a "widget class": a name used when adding option settings to the database. For Tk widgets, the widget class is the same as the widget command name with an initial capital. For example, the widget class of the Tk button widget is Button.

Same energy for snit::widget: the widget class defaults to the unqualified type name with the first letter capitalized. For example, the widget class of

snit::widget ::mylibrary::scrolledText { ... }

is ScrolledText. 💖

You can also set it explicitly with the widgetclass statement inside the snit::widget definition:

snit::widget ::mylibrary::scrolledText {
    widgetclass Text

    # ...
}

That definition is saying a scrolledText megawidget has the same widget class as an ordinary text widget. Whether that's a good idea? Depends on how the rest of the megawidget is defined and how its options are delegated. No cap.


🌸 WHAT IS MY SNIT::WIDGETADAPTOR'S WIDGET CLASS? 🌸

It's just the widget class of its hull widget — Snit has zero control over this.

Heads up: the widget class can only be changed for frame and toplevel widgets. That's literally why those are the valid hull types for snit::widgets.

Also, try to use snit::widgetadaptors only for making small tweaks to another widget's behavior. If you're doing that, it usually won't make sense to change the widget's widget class anyway. 🤷‍♀️


✨ WHAT ARE OPTION RESOURCE AND CLASS NAMES? ✨

Every Tk widget option has three names: the option name, the resource name, and the class name. The option name starts with a hyphen and is all lowercase — you use it when creating widgets, and with the configure and cget commands.

The resource and class names are what get used to initialize option default values by querying the option database. The resource name is usually just the option name minus the hyphen, but it may contain uppercase letters at word boundaries. The class name is usually just the resource name with an initial capital — but not always. For example, here are the option, resource, and class names for several Tk text widget options:

-background         background         Background
-borderwidth        borderWidth        BorderWidth
-insertborderwidth  insertBorderWidth  BorderWidth
-padx               padX               Pad

As you can literally see, sometimes you can infer the resource and class names from the option name… and sometimes you absolutely cannot. 🫠


💜 WHAT ARE THE RESOURCE AND CLASS NAMES FOR MY MEGAWIDGET'S OPTIONS? 💜

For options implicitly delegated to a component using delegate option *, the resource and class names are exactly the ones the component defines. The configure method hands these back, along with the option's default and current values:

% snit::widget mytext {
    delegate option * to text

    constructor {args} {
        install text using text .text
        # ...
    }

    # ...
}
::mytext
% mytext .text
.text
% .text configure -padx
-padx padX Pad 1 1
%

For all other options — whether locally defined or explicitly delegated — the resource and class names can be defined explicitly, or you can just let them fall back to their default values.

By default, the resource name is just the option name minus the hyphen, and the class name is just the option name with an initial capital letter. Say we explicitly delegate -padx:

% snit::widget mytext {
    option -myvalue 5

    delegate option -padx to text
    delegate option * to text

    constructor {args} {
        install text using text .text
        # ...
    }

    # ...
}
::mytext
% mytext .text
.text
% .text configure -myvalue
-myvalue myvalue Myvalue 5 5
% .text configure -padx
-padx padx Padx 1 1
%

See how the resource and class names came out of the default rules? Often those rules are enough, but for -padx we'd most likely rather have the option's resource and class names match the built-in Tk widgets. That's easy to do:

% snit::widget mytext {
    delegate option {-padx padX Pad} to text

    # ...
}
::mytext
% mytext .text
.text
% .text configure -padx
-padx padX Pad 1 1
%

Slay. 💅


🍓 HOW DOES SNIT INITIALIZE MY MEGAWIDGET'S LOCALLY-DEFINED OPTIONS? 🍓

The option database gets queried for each of the megawidget's locally-defined options, using the option's resource and class name. If the result isn't "", it replaces the default value given in the widget definition. Either way, the caller can override the default. For example:

option add *Mywidget.texture pebbled

snit::widget mywidget {
    option -texture smooth
    # ...
}

mywidget .mywidget -texture greasy

Here, -texture would normally default to "smooth", but because of the entry added to the option database it defaults to "pebbled". However — the caller explicitly overrode the default, so the new widget ends up "greasy". Iconic.


🧚 HOW DOES SNIT INITIALIZE DELEGATED OPTIONS? 🧚

Depends, bestie: are the options delegated to the hull, or to some other component? 👀


🌈 HOW DOES SNIT INITIALIZE OPTIONS DELEGATED TO THE HULL? 🌈

A snit::widget's hull is a widget, and once its class is set it's expected to query the option database for itself. The only exception is options delegated to it under a different name. Consider this:

option add *Mywidget.borderWidth 5
option add *Mywidget.relief sunken
option add *Mywidget.hullbackground red
option add *Mywidget.background green

snit::widget mywidget {
    delegate option -borderwidth to hull
    delegate option -hullbackground to hull as -background
    delegate option * to hull
    # ...
}

mywidget .mywidget

set A [.mywidget cget -relief]
set B [.mywidget cget -hullbackground]
set C [.mywidget cget -background]
set D [.mywidget cget -borderwidth]

So the question is: what even are the values of A, B, C, and D? 👑

A is "sunken". The hull is a Tk frame that's been given the widget class Mywidget; it'll automatically query the option database and pick up this value. Since -relief is implicitly delegated to the hull, Snit takes no action.

B is "red". The hull will automatically pick up "green" for its -background option, just like it picked up the -relief value. But Snit knows -hullbackground is mapped to the hull's -background option — hence it queries the option database for -hullbackground, gets "red", and updates the hull accordingly.

C is also "red", because -background is implicitly delegated to the hull, so retrieving it is the same as retrieving -hullbackground. Note that this case is unusual — -background probably should've been excluded using the delegate statement's except clause, or (more likely) delegated to some other component.

D is "5", but not for the reason you think. Notice that as defined above, the resource name for -borderwidth defaults to borderwidth, whereas the option database entry is borderWidth, matching the standard Tk naming for this option. As with -relief, the hull picks up its own -borderwidth option before Snit does anything. Because the option is delegated under its own name, Snit assumes the correct thing happened and doesn't worry about it any further. To avoid confusion, -borderwidth should've been delegated like this:

    delegate option {-borderwidth borderWidth BorderWidth} to hull

For snit::widgetadaptors, the situation is a little different. Widget adaptors keep the widget class of their hull, and the hull is not created automatically by Snit. Instead, the snit::widgetadaptor has to call installhull in its constructor. The normal way looks like this:

snit::widgetadaptor mywidget {
    # ...
    constructor {args} {
        # ...
        installhull using text -foreground white
        # ...
    }
    # ...
}

In this case, the installhull command will create the hull using a command like this:

    set hull [text $win -foreground white]

The hull is a text widget, so its widget class is Text. And just like with snit::widget hulls, Snit assumes it'll pick up all of its normal option values automatically, no help needed from Snit. Options delegated from a different name get initialized from the option database the exact same way as described above. ✨

Back in earlier versions of Snit, snit::widgetadaptors were expected to call installhull like this:

installhull [text $win -foreground white]

This form still works — but Snit will not query the option database the way described above. 🙈

HOW DOES SNIT INITIALIZE OPTIONS DELEGATED TO OTHER COMPONENTS?

For hull components, Snit assumes Tk is gonna do most of the work all by itself. Non-hull components are a lil more complicated, bestie, because they get matched against the option database twice. 💅

A component widget remains a widget still, so it's initialized from the option database in the usual way. A text widget stays a text widget whether it's a component of a megawidget or not, and it'll be created as such. No cap.

But then, the option database gets queried for all options delegated to the component, and the component is initialized accordingly — provided that the install command is used to create it.

Before option database support got added to Snit, the usual way to create a component was to just... create it in the constructor and assign its command name to the component variable:

snit::widget mywidget {
    delegate option -background to myComp

    constructor {args} {
        set myComp [text $win.text -foreground black]
    }
}

The drawback of this method is that Snit has no opportunity to initialize the component properly. So, the following approach is what we use now:

snit::widget mywidget {
    delegate option -background to myComp

    constructor {args} {
        install myComp using text $win.text -foreground black
    }
}

The install command does the following:

  • Builds a list of the options explicitly included in the install command — in this case, -foreground.
  • Queries the option database for all options delegated explicitly to the named component.
  • Creates the component using the specified command, after inserting into it a list of options and values read from the option database. So the explicitly included options (like -foreground) will override anything read from the option database.
  • If the widget definition implicitly delegated options to the component using delegate option *, then Snit calls the newly created component's configure method to receive a list of all of the component's options. From this Snit builds a list of options implicitly delegated to the component which were not explicitly included in the install command. For all such options, Snit queries the option database and configures the component accordingly.

You don't really need to know all of this, honestly. 🫶 Just use install to install your components, and Snit will try to do the right thing.

WHAT HAPPENS IF I INSTALL A NON-WIDGET AS A COMPONENT OF WIDGET?

A snit::type never queries the option database. However, a snit::widget can have non-widget components. And if options are delegated to those components, and if the install command is used to install those components, then they'll be initialized from the option database just as widget components are. ✨

But when used within a megawidget, install assumes that the created component uses a reasonably standard widget-like creation syntax. If it doesn't... don't use install. Periodt.


🌈 ENSEMBLE COMMANDS 🌈

WHAT IS AN ENSEMBLE COMMAND?

An ensemble command is a command with subcommands. Snit objects are all ensemble commands; however, the term more usually refers to commands like the standard Tcl commands string, file, and clock. In a sense, these are singleton objects — there's only one instance of them. 👑

HOW CAN I CREATE AN ENSEMBLE COMMAND USING SNIT?

There are two ways — as a snit::type, or as an instance of a snit::type.

HOW CAN I CREATE AN ENSEMBLE COMMAND USING AN INSTANCE OF A SNIT::TYPE?

Define a type whose INSTANCE METHODS are the subcommands of your ensemble command. Then, create an instance of the type with the desired name. 🎀

For example, the following code uses DELEGATION to create a work-alike for the standard string command:

snit::type ::mynamespace::mystringtype {
    delegate method * to stringhandler

    constructor {} {
        set stringhandler string
    }
}

::mynamespace::mystringtype mystring

We create the type in a namespace, so that the type command is hidden; then we create a single instance with the desired name — mystring, in this case.

This method has two drawbacks. First, it leaves the type command floating about. More seriously, your shiny new ensemble command will have info and destroy subcommands that you probably have no use for. But read on. 🦋

HOW CAN I CREATE AN ENSEMBLE COMMAND USING A SNIT::TYPE?

Define a type whose TYPE METHODS are the subcommands of your ensemble command.

For example, the following code uses DELEGATION to create a work-alike for the standard string command:

snit::type mystring {
    delegate typemethod * to stringhandler

    typeconstructor {
        set stringhandler string
    }
}

Now the type command itself is your ensemble command. 💅

This method has only one drawback, and though it's major, it's also surmountable. Your new ensemble command will have create, info and destroy subcommands you don't want. And worse yet, since the create method can be implicit, users of your command will accidentally be creating instances of your mystring type if they should mispell one of the subcommands. The command will succeed — the first time — but won't do what's wanted. This is very bad. 😭

The work around is to set some PRAGMAS, as shown here:

snit::type mystring {
    pragma -hastypeinfo    no
    pragma -hastypedestroy no
    pragma -hasinstances   no

    delegate typemethod * to stringhandler

    typeconstructor {
        set stringhandler string
    }
}

Here we've used the pragma statement to tell Snit that we don't want the info typemethod or the destroy typemethod, and that our type has no instances; this eliminates the create typemethod and all related code. As a result, our ensemble command will be well-behaved, with no unexpected subcommands. ✨


🧚 PRAGMAS 🧚

WHAT IS A PRAGMA?

A pragma is an option you can set in your type definitions that affects how the type is defined and how it works once it is defined. Lowkey powerful.

HOW DO I SET A PRAGMA?

Use the pragma statement. Each pragma is an option with a value; each time you use the pragma statement you can set one or more of them.

HOW CAN I GET RID OF THE info TYPE METHOD?

Set the -hastypeinfo pragma to no:

snit::type dog {
    pragma -hastypeinfo no
    # ...
}

Snit will refrain from defining the info type method.

HOW CAN I GET RID OF THE destroy TYPE METHOD?

Set the -hastypedestroy pragma to no:

snit::type dog {
    pragma -hastypedestroy no
    # ...
}

Snit will refrain from defining the destroy type method.

HOW CAN I GET RID OF THE create TYPE METHOD?

Set the -hasinstances pragma to no:

snit::type dog {
    pragma -hasinstances no
    # ...
}

Snit will refrain from defining the create type method; if you call the type command with an unknown method name, you'll get an error instead of a new instance of the type.

This is useful if you wish to use a snit::type to define an ensemble command rather than a type with instances.

Pragmas -hastypemethods and -hasinstances cannot both be false (or there'd be nothing left). 💀

HOW CAN I GET RID OF TYPE METHODS ALTOGETHER?

Normal Tk widget type commands don't have subcommands; all they do is create widgets — in Snit terms, the type command calls the create type method directly. To get the same behavior from Snit, set the -hastypemethods pragma to no:

snit::type dog {
    pragma -hastypemethods no
    #...
}

# Creates ::spot
dog spot

# Tries to create an instance called ::create
dog create spot
Pragmas -hastypemethods and -hasinstances cannot both be false (or there'd be nothing left). 💀

WHY CAN'T I CREATE AN OBJECT THAT REPLACES AN OLD OBJECT WITH THE SAME NAME?

Up until Snit 0.95, you could use any name for an instance of a snit::type, even if the name was already in use by some other object or command. You could do the following, for example:

snit::type dog { ... }

dog proc

You now have a new dog named "proc", which is probably not something that you really wanted to do. 🙈 As a result, Snit now throws an error if your chosen instance name names an existing command. To restore the old behavior, set the -canreplace pragma to yes:

snit::type dog {
    pragma -canreplace yes
    # ...
}

HOW CAN I MAKE MY SIMPLE TYPE RUN FASTER?

In Snit 1.x, you can set the -simpledispatch pragma to yes.

Snit 1.x method dispatch is both flexible and fast, but the flexibility comes with a price. If your type doesn't require the flexibility, the -simpledispatch pragma allows you to substitute a simpler dispatch mechanism that runs quite a bit faster. The limitations are these:

  • Methods cannot be delegated.
  • uplevel and upvar do not work as expected: the caller's scope is two levels up rather than one.
  • The option-handling methods (cget, configure, and configurelist) are very slightly slower.

In Snit 2.2, the -simpledispatch macro is obsolete, and ignored; all Snit 2.2 method dispatch is faster than Snit 1.x's -simpledispatch. 💅

🧚 MACROS 🧚

💫 WHAT IS A MACRO? 💫

Okay bestie, listen. A Snit macro is literally nothing more than a Tcl proc that's defined in the Tcl interpreter you're using to compile Snit type definitions. That's it. That's the whole thing. No cap.


🌸 WHAT ARE MACROS GOOD FOR? 🌸

Two things, and they're both iconic:

  • Defining new type definition syntax — like, inventing your own little keywords for type bodies
  • Supporting conditional compilation

🦋 HOW DO I DO CONDITIONAL COMPILATION? 🦋

Okay so picture this: you want your type to use a fast C extension if it's available, and if it's not, you fall back to a slower Tcl implementation. So you need one set of methods in the first case and a whole different set in the second. But wait — how is your type definition even supposed to know whether the fast C extension exists?? 😭

It's easily done, babe. Outside of any type definition, define a macro that returns 1 if the extension is available and 0 otherwise:

if {$gotFastExtension} {
    snit::macro fastcode {} {return 1}
} else {
    snit::macro fastcode {} {return 0}
}

Then you just use your macro in your type definition:

snit::type dog {

    if {[fastcode]} {
        # Fast methods
        method bark {} {...}
        method wagtail {} {...}
    } else {
        # Slow methods
        method bark {} {...}
        method wagtail {} {...}
    }
}

See? Chef's kiss. 👑


🎀 HOW DO I DEFINE NEW TYPE DEFINITION SYNTAX? 🎀

Use a macro, obviously. 💅

So like, say your snit::widget's -background option should be propagated to a bunch of component widgets. You could implement that like this:

snit::widget mywidget {
    option -background -default white -configuremethod PropagateBackground

    method PropagateBackground {option value} {
        $comp1 configure $option $value
        $comp2 configure $option $value
        $comp3 configure $option $value
    }
}

For one option? Fine. Adorable, even. But the moment you've got a bunch of options it becomes tedious and error prone, and nobody has time for that. So package it as a macro:

snit::macro propagate {option "to" components} {
    option $option -configuremethod Propagate$option

    set body "\n"

    foreach comp $components {
        append body "\$$comp configure $option \$value\n"
    }

    method Propagate$option {option value} $body
}

Then you can use it like this:

snit::widget mywidget {
    option -background default -white
    option -foreground default -black

    propagate -background to {comp1 comp2 comp3}
    propagate -foreground to {comp1 comp2 comp3}
}

Look how clean. Slay. ✨


💜 ARE THERE ARE RESTRICTIONS ON MACRO NAMES? 💜

Yes bestie, there are. You can't redefine any standard Tcl commands or Snit type definition statements. You can use any other command name, including the name of a previously defined macro. 🫶

Now, if you're using Snit macros in your application, go ahead and name them in the global namespace, like in the examples above. But if you're using them to define types or widgets for other people to use, you should define your macros in the same namespace as your types or widgets. That way they won't conflict with other people's macros. Considerate queen behavior. 👑

So if my fancy snit::widget is called ::mylib::mywidget, for example, then I should define my propagate macro as ::mylib::propagate:

snit::macro mylib::propagate {option "to" components} { ... }

snit::widget ::mylib::mywidget {
    option -background default -white
    option -foreground default -black

    mylib::propagate -background to {comp1 comp2 comp3}
    mylib::propagate -foreground to {comp1 comp2 comp3}
}

💀 BUGS, IDEAS, FEEDBACK 💀

Okay so real talk: this document, and the package it describes, will undoubtedly contain bugs and other problems. It's giving "we know." 😭 Please report such in the category snit of the Tcllib Trackers at http://core.tcl.tk/tcllib/reportlist. And please also report any ideas for enhancements you may have for either the package and/or the documentation — they want to hear it, fr fr.

When proposing code changes, please provide unified diffs, i.e. the output of diff -u.

Note further that attachments are strongly preferred over inlined patches. Attachments can be made by going to the Edit form of the ticket immediately after its creation, and then using the left-most button in the secondary navigation bar. Don't skip this step bestie, it matters. 💅

🔥 KEYWORDS 🔥

BWidget, C++, Incr Tcl, adaptors, class, mega widget, object, object oriented, widget, widget adaptors


🌈 CATEGORY 🌈

Programming tools


Copyright (c) 2003-2006, by William H. Duquette


And that's the whole page, bestie!! 🎉 You just read snitfaq(n), from tcllib 2.2, and honestly? Iconic behavior. The date line at the bottom is just the usual manpage footer business (source + version + date), but you already got the good stuff: tcllib, version 2.2, page snitfaq(n). Go forth and build something cute. 💖✨🎀🦋🌸🫶

📦 where this page comes from