Project 5 of 15, for Paul
Undo/Redo Text Editor
An undo/redo text editor for the code Paul writes on the Workshop chalkboard: a stack of edits to undo, a stack of undos to redo, and a queue of commands run in the order they were typed.
Sign up free to open itLog in
Act 4 needs a free account, so your work is saved as you go. Act 1 is open to everyone.
The brief
- PaulYou know the chalkboard in the Workshop? I write the day's plan on it, rub it out and write it again.
- PaulI'd like to try it out first, with a button that takes back the last bit.
- PaulAnd another one that puts it back, for when I change my mind about changing my mind.
- NeilThat's a stack of what you did and a stack of what you took back, two piles used from the top.
In editor.py, an Editor holds one line of text, text, which starts empty. Its __init__(limit=20) is written: undo_stack is a deque(maxlen=limit), so only the latest limit edits are kept, and redo_stack is a list.
type(words)adds the words to the end of the text.delete(count)deletes the lastcountcharacters, or all of them if there are fewer.- Each
typeordeletethat changes the text is an edit: it goes on the undo stack as a pair,("type", words)or("delete", removed), whereremovedis the characters really deleted, and it empties the redo stack. Typing nothing, or deleting nothing, isn't an edit. undo()takes back the latest edit still standing and puts it on the redo stack.redo()does the latest undone edit again and puts it back on the undo stack. Each returnsTrue, orFalse, changing nothing, if there's nothing to do.run(editor, line)carries out a line of commands, split on;, in the order they were typed, using adequeas the queue. It returns a list of what to print:showgivesBoard:and the text; anundoorredowith nothing to do givesNothing to undo.orNothing to redo.;deletewith no whole number after it givesDelete how many?; any other word gives the line of commands,COMMANDS; a blank command gives nothing.
The loop at the bottom asks Edit? until it's told quit.
Commands: type <words>, delete <how many>, undo, redo, show, quit. Several at once: put ; between them. Edit? type Stacks at 10 Edit? type , queues 2 Edit? show Board: Stacks at 10, queues 2 Edit? delete 10; show Board: Stacks at 10 Edit? undo; show Board: Stacks at 10, queues 2 Edit? redo; redo; show Nothing to redo. Board: Stacks at 10 Edit? quit
What you learn
What's in it
- A pile used from the top
- The top of the pile
- Brackets on a stack
- Undo and redo
- Two stacks
- First come, first served
- To the back of the queue
- A list built for both ends
- The queue at the printer
- How Paul would do it
- Fix Riya's version
- Make the text editor
- Ship it