I'm working on adding some syntax highlighting to an app. In a testing class, I currently have an NSTextView
with the textDidChange
notification. Similar to this:
-(void)textDidChange:(NSNotification *)notification
{
[self highlightText];
}
What highlight text does, it grab the string from the NSTextView
parse it and create a NSMutableAttributedString
and finally displays the string. The code is something similar to this: (I use ParseKit to do my parsing. The below sample just highlights code comments).
- (void) highlightText
{
NSMutableAttributedString * resultString = [[NSMutableAttributedString alloc] initWithString: inputTextView.string];
PKTokenizer *t = [PKTokenizer tokenizerWithString: inputTextView.string];
[t setTokenizerState: t.quoteState from: '[' to: ']'];
// We want comments
t.commentState.reportsCommentTokens = YES;
[t enumerateTokensUsingBlock: ^(PKToken * token, BOOL * stop)
{
// Comments take presidense.
if(token.isComment)
{
[resultString addAttribute: NSForegroundColorAttributeName
value: [self commentColor]
range: NSMakeRange(token.offset, token.stringValue.length)];
}
}];
// Monospace
[resultString addAttribute: NSFontAttributeName
value: [NSFont userFixedPitchFontOfSize:0.0]
range: NSMakeRange(0, inputTextView.string.length)];
[[inputTextView textStorage] setAttributedString: resultString];
}
Now this works fine if I am working with a small amount of text, but I would like to improve its performance when working with larger amounts of text. I had two thoughts on the subject:
Does anyone have any suggestions around this area? Am I missing an alternative way to do this, or should this work fine? Does anyone possibly know of any sample code doing something similar/better? I'm currently thinking of going for option #2.
I found a few resources that helped me out:
(Updated: broken cocoadev link)