Created
December 12, 2016 21:36
-
-
Save daboe01/597478ef112f7eee28a88326e1b70faf to your computer and use it in GitHub Desktop.
Colorizing TextView
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@import <Foundation/CPObject.j> | |
@import <Foundation/CPAttributedString.j> | |
var _regexColors; | |
@implementation ColorizingTextView : KVOCPText | |
{ | |
} | |
+ (void)initialize | |
{ | |
_regexColors = @{ | |
'0tags': [ /(<[^>]+>)/gi, [CPColor grayColor] ], | |
'strings': [ /['"](.+?)['"]/gi, [CPColor blueColor] ], | |
'between': [ />(.+?)</gi, [CPColor blackColor] ] | |
}; | |
} | |
- (CPAttributedString) colorizedStringForString:(CPString)str | |
{ | |
var keys = [[_regexColors allKeys] sortedArrayUsingSelector:@selector(compare:)], | |
result = [[CPAttributedString alloc] initWithString:str]; | |
[keys enumerateObjectsUsingBlock:function(key, idx, stop) | |
{ | |
var val = [_regexColors objectForKey:key], | |
re = val[0], | |
col = val[1], | |
match; | |
while ((match = re.exec(str)) != null) | |
{ | |
[result setAttributes:@{CPForegroundColorAttributeName:col} range:CPMakeRange(match.index, match[0].length)]; | |
} | |
}]; | |
return result; | |
} | |
- (void)setObjectValue:(CPString)aString | |
{ | |
[_textStorage beginEditing]; | |
[_textStorage replaceCharactersInRange:CPMakeRange(0, [_layoutManager numberOfCharacters]) withAttributedString:[self colorizedStringForString:aString]]; | |
[_textStorage endEditing]; | |
[self setSelectedRange:CPMakeRange(0,0)] | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment