I've got an attributed string bound to a NSTextView. I'm using a method that is called (using KVO) every time the string is edited to add background color attributes to string based on a regEx match. I do this by creating a new mutable attributed string with -initWithAttributedString:
then -beginEditing
, -addAttribute:
, -endEditing
. Once I've added all the background color attributes I want, I call the string's setter [self setTextViewString:mutableAttributedString]
The issue is, that if there actually are any attributes added to the string, it kills undo and moves the cursor to the end of the string.
How can I maintain undo? I've maintained cursor position by calling the textView's selectedRanges and setSelectedRanges: methods on either side of the setter, but this still seems a bit hackish.
I wasn't able to bind the textview directly to the mutableattributedstring, but it seems like there should be a more direct way to modify the bound string so it doesn't mess up editing.
PS, the addition of attributes happens after the KVO method finishes by calling -performSelectorOnMainThread:
It was the only way I could get the added attributes to display.