Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save theredhead/35a92fba203790e9f7ad36a1ede2a0fc to your computer and use it in GitHub Desktop.
Save theredhead/35a92fba203790e9f7ad36a1ede2a0fc to your computer and use it in GitHub Desktop.
Colorizing TextView
@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