Want to change files as well as viewing them
So modify the file viewer of [%x viewer %] to allow editing
And since people make mistakes when editing, implement undo
Window can draw lines and report its size
Buffer stores lines of text, keeps track of a
viewport, and transforms buffer coordinates to screen
coordinates
Cursor knows its position in the buffer and can move
up, down, left, and right
App makes a window, a buffer, and a cursor, then
maps keys to actions
[% figure slug=“undo-classes” img=“classes.svg” alt=“Classes in file viewer” caption=“Relationships between classes in file viewer” %]
Create a [%g headless “headless” %] screen for testing
Store current state of display in rectangular grid
Take a list of keystrokes (for simulation)
App to have a method
that gets keystrokes[%inc headless.py mark=screen %]
HeadlessWindow to take a size and
pass it to the screen[%inc headless.py mark=window %]
[%inc headless.py mark=app %]
[%inc test_headless.py mark=example %]
CONTROL_X (exit)[%inc insert_delete.py mark=buffer %]
Delete character under the cursor, not to the left
A little defensive programming as well
[%inc insert_delete.py mark=app %]
[%inc insert_delete.py mark=action %]
[%inc insert_delete.py mark=dispatch %]
_get_key to return family (generic) and key
(specific)[%inc test_insert_delete.py mark=fixture %]
[%inc test_insert_delete.py mark=example %]
[%inc test_insert_delete.py mark=empty %]
In order to undo things we have to:
keep track of actions and reverse them, or
keep track of state and restore it
Recording actions requires less space but can be trickier to implement
Have actions append entries to a log
[%inc history.py mark=app %]
What about undoing cursor movement?
And do we write an interpreter for these log records?
Use the [%g command_pattern “Command” %] design pattern
Each action (verb) is an object (noun) with methods to go forward and backward
Every action is derived from an abstract base class
[%inc action.py mark=Action %]
[%inc action.py mark=Insert %]
[%inc action.py mark=Delete %]
[%inc action.py mark=Move %]
Cursor methods to move in a particular direction
(by name) and move to a particular location[%inc action.py mark=interact %]
Create the action object
Call its .do method
Modify all action methods to take a key to simplify the code a little
[%inc action.py mark=actions %]
And it almost works!
Our first implementation of Undo creates an infinite
loop because it puts itself on the undo stack and then does the action
on the top of the stack
Modify Action to have a .save method
that returns True
Override in Undo
[%inc undoable.py mark=Undo %]
.save is
True
Action.post_action to add the action to
the undo stack[% figure slug=“undo-concept-map” img=“concept_map.svg” alt=“Concept map of undo” caption=“Concept map.” %]