Strategies for programmatic manipulation of NSTextView maintaining undo

I'd like to build a smart NSTextView, with various "smart" editing features like automatic closing bracket insertion.


What's the correct way to go about modiying an NSTextStorage in response to a user action while maintaining a logical undo stack in the NSUndoManager?


Undo should revert back to the state of the text storage before the user made their change, including any additional "smart" changes that came after it.