[ Team LiB ] Previous Section Next Section

The Undo Mechanism

Beginning in Tk 8.4, the text widget supports an unlimited undo and redo mechanism. You enable the undo mechanism by setting the text widget's undo attribute to True. The undo attribute has a default value of False for backward compatibility.

When enabled, each insert and delete action, whether performed by the user or programmatically, is recorded on an undo stack. You can programmatically undo an edit with the edit undo operation. The undone changes are then moved to the redo stack, so that an undone edit can be redone again with the with the edit redo operation. The redo stack is cleared whenever new edit actions are recorded on the undo stack. (Both the edit undo and edit redo operations generate error conditions if the undo or redo stack is empty, respectively.) The text widget also has default undo and redo bindings; by default, undo is <Control-z> and redo is <Control-y> on Windows, <Control-Z> on all other platforms. (See "Text Bindings" on page 551.)

Each edit undo operation undoes the last action, which is defined as all of the insert and delete commands that are recorded on the undo stack in between two separators. When the autoSeparators attribute is True (the default), a separator is automatically placed on the stack whenever:

  • the mode changes from insertion to deletion, or vice versa

  • the user moves the insert mark using the keyboard or the mouse

  • the user presses the <Return> key

If you set the autoSeparators attribute to False, you are responsible for programmatically placing separators on the stack with the edit separator operation. By turning the autoseparators off and inserting them at the desired points, you can define compound actions, such as search and replace. The default paste binding is an example of such an action, such that overwriting selected text by pasting from the clipboard is considered an atomic action.

As of Tk 8.4, only insert and delete operations are handled by the undo mechanism. In particular, tag operations, such as applying a tag to text, are not actions captured by the undo mechanism, even if the tag was applied as part of an insert operation. As an example, consider the following insertion:

$t insert end "Let's insert some " {} \
    "special" blue " text." {}

If this operation were undone and then redone, the text would be re-inserted, but without applying the blue tag on the word "special".

    [ Team LiB ] Previous Section Next Section