Text processing with NSLinguisticTagger: implementing Writer Pro's syntax control

Here’s how to implement Writer Pro’s syntax highlighting feature using attributed strings and NSLinguisticTagger.

Project on GitHub.

demo gif

- (void)highlightLinguisticTag:(NSString *)tag {
    self.textView.attributedText = [self attributedStringHighlightedForTag:tag];
}

- (NSAttributedString *)attributedStringHighlightedForTag:(NSString *)tag {
    NSString *string = @"Some string..."
    NSRange stringRange = NSMakeRange(0, string.length);

    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:string attributes:nil];
    [text addAttribute:NSForegroundColorAttributeName value:[UIColor lightGrayColor] range:stringRange];

    NSLinguisticTagger *tagger = [[NSLinguisticTagger alloc] initWithTagSchemes:@[NSLinguisticTagSchemeLexicalClass] options:0];
    tagger.string = string;
    [tagger enumerateTagsInRange:stringRange scheme:NSLinguisticTagSchemeLexicalClass options:0 usingBlock:^(NSString *tokenTag, NSRange tokenRange, NSRange sentenceRange, BOOL *stop) {
        if ([tokenTag isEqualToString:tag]) {
            [text addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:tokenRange];
        }
    }];

    return text;
}

Follow me on Twitter to keep up with what I’ve learned building my personal finance tool, Stash.

Subscribe to my mailing list to learn more about technology and business.

Your email will never be shared with anyone else.

Read more posts …
Written: December 25th, 2013
Categories: NSLinguisticTagger, text-processing