Question

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?

Was it helpful?

Solution

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top