views:

33

answers:

2

Hello,

I have been recently working on an easy to use Syntax Highlighting system for a personal project. So far, I have everything working properly by finding the range of specific strings and highlighting that range in the NSTextView. Everything works until you try to type a highlighted word twice, which causes the error demonstrated below:

<div class="container">
    <div> <!-- This <div> would not get highlighted -->
        Hello World
    </div>
</div> <!-- this </div> would not get highlighted -->

I believe this is occurring because I am only getting the first occurrence of an NSString using the rangeOfString method, and for that reason, only the first highlighted item is being highlighted.

Sorry for the long explanation! Anyway, I was wondering if there was an rangesOfString method or something similar that can give me an NSArray of NSRanges for each occurrence of an NSString inside of another NSString. Below is the line of code I am using to get my range currently:

NSString *textViewString = [textView string];
NSString *textToHighlight = @"<div>";
NSRange area;

area.location = 0;
area.length = [textViewString length];

NSRange range = [textViewString rangeOfString: textToHighlight 
                                      options: NSCaseInsensitiveSearch 
                                        range: area];

What I would like is something like this:

NSString *textViewString = [textView string];
NSString *textToHighlight = @"<div>";
NSRange area;

area.location = 0;
area.length = [textViewString length];

NSArray *ranges = [textViewString rangesOfString: textToHighlight
                                         options: NSCaseInsensitiveSearch
                                           range: area];

int i;
int total = [ranges count];
for (i = 0; i < total; i++) {
    NSRange occurrence = [ranges objectAtIndex: i];
    // Apply color highlighting here
}

If this is not possible, could someone please point me in the right direction or suggest an alternative way of doing syntax highlighting? Thank you!

+1  A: 

NSRange is not an object, so you need to put it in one. Look at NSValues +valueWithRange: class method.

jer
Thank you. I can see myself having trouble with something like that, so I'll defiantly keep NSValue in mind. I believe I still have the problem of getting the NSRanges in the first place, though...
Jesse
+2  A: 

There is no such method. You can use rangeOfSubstring:options:range: to get each match, and narrow down the range as you go: After each match, you change the search range's location to the character after (location + length of) the match range and reduce the search range's length by the difference.

Peter Hosey
Thank you, I'll try that.
Jesse