Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get & Highlight Current Word in an NSTextView

OK, so this is what I want :

  • We have an NSTextView
  • Get "current" word (as an NSRange?), at cursor position (how could this be determined?)
  • Highlight it (change its attributes)

I'm not sure how to go about this : I mean my main concern is getting current position within NSTextView and getting the word at point (I know some Text plugins support that, but I'm not sure as of the original NSTextView implementation...)

Is there any built-in function for that? Or, if not, any ideas?


UPDATE : Cursor position (SOLVED)

NSInteger insertionPoint = [[[myTextView selectedRanges] objectAtIndex:0] rangeValue].location;

Now, still trying to find a workaround for a specifying the underlying word...

like image 367
Dr.Kameleon Avatar asked Sep 23 '12 17:09

Dr.Kameleon


1 Answers

Here's one way:

NSUInteger insertionPoint = [myTextView selectedRange].location;
NSString *string = [myTextView string];

[string enumerateSubstringsInRange:(NSRange){ 0, [string length] } options:NSStringEnumerationByWords usingBlock:^(NSString *word, NSRange wordRange, NSRange enclosingRange, BOOL *stop) {
if (NSLocationInRange(insertionPoint, wordRange)) {
    NSTextStorage *textStorage = [myTextView textStorage];
    NSDictionary *attributes = @{ NSForegroundColorAttributeName: [NSColor redColor] }; // e.g.
    [textStorage addAttributes:attributes range:wordRange];
    *stop = YES;
}}];
like image 186
Wevah Avatar answered Sep 23 '22 08:09

Wevah