2

I'm making a Brainfuck (programming language) IDE, and I'm stuck with the syntax coloring.

I want to predefine a NSDictionary with substrings, and loop through them and return an array with (or loop through) the ranges of the substrings in a given string.

Example:

NSMutableDictionary* keywords = [[NSMutableDictionary alloc] init];

[keywords setObject:[self colorForSymbol:0] forKey:@"<"];

[keywords setObject:[self colorForSymbol:0] forKey:@">"];

[keywords setObject:[self colorForSymbol:1] forKey:@"+"];

[keywords setObject:[self colorForSymbol:1] forKey:@"-"];

And then for each symbol, I would color all the matching NSRanges using the NSTextStorage of an NSTextView.

What I need to know is how to use NSScanner or something similar for this purpose.

JAL
  • 41,701
  • 23
  • 172
  • 300
Sebbern
  • 23
  • 3

1 Answers1

2

My answer to this question will probably help with the mechanics of hooking syntax colouring into NSTextView.

To do the actual tokenisation you should have a look at NSScanner. You will probably need to parse the text in multiple passes, for each of the tokens. You could also use regular expressions, using something like RegexKitLite.

Here is a simple demonstration of NSScanner:

NSScanner* scanner = [NSScanner scannerWithString:@"A string <with> <tokens>"];

NSString* token = @"<";

NSMutableArray* ranges = [NSMutableArray array];

while(![scanner isAtEnd])
{
    [scanner scanUpToString:token intoString:nil];
    if(![scanner isAtEnd])
    {
        NSRange tokenRange = NSMakeRange([scanner scanLocation], 1);
        [ranges addObject:[NSValue valueWithRange:tokenRange]];
        [scanner scanString:token intoString:nil];
    }
}
Community
  • 1
  • 1
Rob Keniger
  • 45,830
  • 6
  • 101
  • 134
  • RegexKitLite just wouldn't get the matches, and I don't know how to use NSScanner in this case. – Sebbern Jun 13 '11 at 00:38
  • Post your code. RegexKitLite will definitely match the tokens. I'll update the answer with more NSScanner detail. – Rob Keniger Jun 13 '11 at 00:39