Syntax coloring a NSTextView
Syntax coloring a NSTextView
- Subject: Syntax coloring a NSTextView
- From: Johann Hibschman <email@hidden>
- Date: Sat, 20 Oct 2001 20:51:45 -0700
Hi folks,
I'm trying to include a basic editor in one of my apps, and I'd like to
have active syntax coloring, but I can't seem to get it to work. I
want "--" to set off a colored comment.
In pseudocode, I'm doing something like
- (BOOL)textView:(NSTextView *)aTextView
shouldChangeTextInRange:(NSRange)aRange
replacementString:(NSString *)str
{
loc = aRange.location; len = aRange.length;
if (<we typed "-", and the previous character is "-">) {
// Color the first "-" red.
[aTextView setTextColor: [NSColor redColor] range:
NSMakeRange(loc-1, 1)];
// Insert the next one. This should also be red, but isn't.
[aTextView replaceCharactersInRange:NSMakeRange(loc, len)
withString:str];
return NO; // Already inserted the text.
}
return YES;
}
(And yes, I know this isn't general, but I want to understand this very
simplistic version before I try to be exactly correct.)
Now, what happens is that the first "-" is colored red, but the
second "-" remains black. This goes against the docs for
replaceCharactersInRange:withString:, which claim that the characters
inserted, if the length of the range is 0, should take the
characteristics of the first character in the range. For some reason,
that doesn't happen here.
(By the way, I have tried not inserting the second "-" and returning
YES. It doesn't change anything.)
Is there some magic going on that I'm unaware of? Does anyone have a
better suggestion for how to do this? I'd subclass NSTextView and
override the replace function, but the docs heavily suggest _not_
subclassing NSTextView.
Thanks,
--Johann