Searching NSString Before the Insertion Point

Although I was gratified to have achieved my basic objective — getting a mathematical expression as a string to actually spit out a numerical answer — it felt like a kludge. The biggest sacrifice I made right away was to limit my calculations to appearing as the last bit of text in the document. Recall my method for grabbing the expression string:

aRange = [[self string] rangeOfString:newline options:(NSBackwardsSearch)];

The [self string] means that I’m looking at the whole contents of the NSTextView, going backwards till I find a carriage return. That’s no good if you have some content in your Napkin document, and want to go up earlier to enter an equation. So tonight’s project was to fix that.

The key to this is finding out how to search backwards from the insertion point, rather than from the end of the NSTextView. Again, I thought I was going to have to write some kind of fancy-ass category method for NSString, but that’s the n00b in me talking again. STFU n00b!

Here’s some code to help explain how I did it. First, we need to get the current insertion point location:

NSRange currentLocation = [self selectedRange]; // where the insertion point is right now

The result of this expression will be a struct with a location of x, and a length of 0. We only care about the former value. Let’s now prepare our new string to search:

NSRange currentRange = NSMakeRange(0, currentLocation.location);

Check that out, bitches! This range is going to replace the [self string] that I so blithely used before. This range is from the beginning of the text view to the insertion point. Now we use it:

aRange = [[self string] rangeOfString:newline options:(NSBackwardsSearch) range:currentRange];

What? Still using [self string]? Yeah, but this isn’t the same method call; it’s got the added range: argument that makes all the magic happen. So while I’m searching the entire TextView, it’s only looking at the range that I supply. Backwards. With gerbils.

Buid, run, and check this out!

My face is starting to hurt! 8*8=64 But look at this! I can write expressions anywhere!

Not bad for a Saturday night. I’m going to watch an episode of The Wire and call it.