Sebbern Sebbern - 5 months ago 20
Brainfuck Question

How can I loop through individual NSStrings in a NSString? (Syntax highlighting/coloring)

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

I want to predefine a

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


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
using the
of an

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


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];