Tuesday, March 18, 2008

Implementing XCode 3 parenthesis highlighting

One of the things I like about XCode 3 is the parenthesis matching. It seems very obtrusive at first, but I find it works better than the more subtle Emacs-style matching once you get used to it. For the R GUI I wanted to implement the same thing, which turned out to be fairly simple.

The highlighter is implemented using the new [NSTextView showFindIndicatorInRange:] so there's literally no work to do there.

The first thing you need to know is that adding this functionality in textView:shouldChangeTextInRange:replacementString: won't work because the text is added after the method executes and that removes the find indicator. Fortunately, we just implemented a custom keybinding in the last post so all we need to do is bind the various close delimiters to special selectors (fancyCloseParen: for example). Then we can do things in doCommandBySelector:

// ...
} else if(@selector(fancyCloseParen:) == aSelector) {
[self insertDelimiter:')' withMatch:'(' inTextView:aTextView atPosition:aRange.location];
return YES;
} // ...

next all we have to do is find the delimiter (which we do with a category on NSString) and then insert the find indicator:

- (void)insertDelimiter:(unichar)aDelim withMatch:(unichar)aMatch inTextView:(NSTextView*)aTextView atPosition:(NSInteger)aPos {
[aTextView insertText:[NSString stringWithFormat:@"%c",aDelim]];
NSRange where = [[aTextView string] rangeOfDelimiter:aMatch matching:aDelim inRange:NSMakeRange(lastPrompt,aPos-lastPrompt)];
if(where.location == NSNotFound)
[aTextView showFindIndicatorForRange:where];

Easy as pie.

No comments: