Question

I want to create a text view which will support highlighting of basic things, like links and hashtags. The similar features can be found in Twitter.app:

Twitter.app screenshot

It is not necessary to support clicking on those links, just need to highlight all things properly while user is editing contents of text view.

The question is, what is the best way to do that? I don't really want to use heavy-weight syntax highlighting libraries, but I didn't find any simple and small libraries to highlight only a few things.

Should I parse text and highlight it by myself? If I should, what libraries can I use to tokenise text, and what libraries will allow me to make live highlighting?

Was it helpful?

Solution

Yes, if you want that light-weight use your own parsing to find relevant parts and then use the textStorage of NSTextView to change text attributes for the found range.

OTHER TIPS

Have you tried using Regular Expressions to match your text (in background, when text is updated)? After you find matches, it is pretty simple to set required attributes (of a NSAttributedString).

You can have a look at Regular expressions in an Objective-C Cocoa application

Here is a small example: you need to implement this delegate method, textview1 is outlet of TextView:

   - (BOOL)textView:(NSTextView *)textView shouldChangeTextInRange:(NSRange)affectedCharRange replacementString:(NSString *)replacementString
    {
        NSLog(@"string is this");
        NSString *allTheText =[textView1 string];
        NSArray *lines = [allTheText componentsSeparatedByString:@""];
        NSString *str=[[NSString alloc]init];
        NSMutableAttributedString *attr;
        BOOL isNext=YES;
        [textView1 setString:@""];
        for (str in lines)
        {
            attr=[[NSMutableAttributedString alloc]initWithString:str];
            if ([str length] > 0)
            {

                NSRange range=NSMakeRange(0, [str length]);
                [attr addAttribute:NSLinkAttributeName value:[NSColor greenColor] range:range];
                [textView1 .textStorage appendAttributedString:attr];
                isNext=YES;

            }
            else
            {
                NSString *str=@"";
                NSAttributedString *attr=[[NSAttributedString alloc]initWithString:str];
                [textView1 .textStorage appendAttributedString:attr];
                isNext=NO;
            }
        }
   }

this will give you text in blue color with hyperlink;.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top