Question

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:

  1. Do the processing in the background. As the user types, this means text could be unformatted for a few seconds. I don't really like this idea.
  2. Perform highlighting only on the visible section of text. Do more highlighting as the user scrolls. This still has the problem that as the user scrolls, the text would be unformatted but slowly pop into a formatted style.

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.

Was it helpful?
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top