How to get the range of characters that are visible from within -textStorageDidProcessEditing:?

1.7k views Asked by At

For my syntax highlighting implementation, I observe changes to an NSTextView using -[<NSTextStorageDelegate> textStorageDidProcessEditing:].

- (void)textStorageDidProcessEditing:(NSNotification *)notification {
  if (!self.languageGrammar) return;
  NSTextStorage *textStorage = self.textView.textStorage;
  NSRange glyphRange = [self.textView.layoutManager glyphRangeForBoundingRect:self.scrollView.documentVisibleRect
                                                              inTextContainer:self.textView.textContainer];
  NSRange editedRange = [self.textView.layoutManager characterRangeForGlyphRange:glyphRange actualGlyphRange:NULL];

  [textStorage removeAttribute:NSForegroundColorAttributeName range:editedRange];
  // crash is the line above ^^^^
  // color text ...
}

I want to get the range of visible characters. The above code works until I hit backspace, which makes it crash:

*** -[NSConcreteTextStorage attributesAtIndex:effectiveRange:]: Range or index out of bounds

How would I get the range of visible characters so I can color them?

1

There are 1 answers

0
Joris On BEST ANSWER

Check if the range is beyond the bounds of the entire string, and if it is set the range to fit the bounds of the string:

NSRange range = NSRangeFromString(string);