Paul's Python CoursePPC

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.

About an hour and a half, in 14 steps.

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.

  1. type(words) adds the words to the end of the text.
  2. delete(count) deletes the last count characters, or all of them if there are fewer.
  3. Each type or delete that changes the text is an edit: it goes on the undo stack as a pair, ("type", words) or ("delete", removed), where removed is the characters really deleted, and it empties the redo stack. Typing nothing, or deleting nothing, isn't an edit.
  4. 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 returns True, or False, changing nothing, if there's nothing to do.
  5. run(editor, line) carries out a line of commands, split on ;, in the order they were typed, using a deque as the queue. It returns a list of what to print: show gives Board: and the text; an undo or redo with nothing to do gives Nothing to undo. or Nothing to redo.; delete with no whole number after it gives Delete 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.

What it prints
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

  1. A pile used from the top
  2. The top of the pile
  3. Brackets on a stack
  4. Undo and redo
  5. Two stacks
  6. First come, first served
  7. To the back of the queue
  8. A list built for both ends
  9. The queue at the printer
  10. How Paul would do it
  11. Fix Riya's version
  12. Make the text editor
  13. Ship it