Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Technique on how to format/color NSTextView's string

I'm looking for a reliable technique to do simple string formatting(bold, italic,...) in a NSTextView. The text parsing is almost done with regex, but now I need to apply font trait and also change the size.

Some code snippets on how I make a text bold

[[textView textStorage] beginEditing];
[[textView textStorage] applyFontTraits:NSFontBoldTrait range:range];
[[textView textStorage] endEditing];

This and also the size changes with

[[textView textStorage] beginEditing];  
NSFont* font = [[textView textStorage] attribute:NSFontAttributeName atIndex:range.location effectiveRange:nil];

NSFont* newFont = [NSFont fontWithName:[font familyName] 
                                  size:[font pointSize] + size];

[[textView textStorage] addAttribute:NSFontAttributeName 
                               value:newFont 
                               range:range];
[[textView textStorage] endEditing];

works fine. The only problem I have now is that in some cases, when I type new characters, those characters are bold or italic by default, even though I don't apply the properties to them.

Do I have to reset something with the setTypingAttributes of the NSTextView or do I simply miss something here?

like image 463
brutella Avatar asked Jan 25 '12 20:01

brutella


1 Answers

I think you are right with the approach to set typingAttributes. Reference for -setTypingAttributes: says

However, if you add any user actions that change text attributes, the action should use this method to apply those attributes afterwards. User actions that change attributes should always set the typing attributes because there might not be a subsequent change in selection before the next typing.

That seems to apply in your case.

I don't know if the described behaviour is only correct for WYSIWYG editors like TextEdit. You seem to work on something that is similar in behaviour to an editor with syntax highlighting. There you never really want to change text attributes manually, but rather on structure from a grammar. It probably doesn't fit in that case, and you should reset typingAttributes or set it according to parsing up to there.

like image 65
febeling Avatar answered Oct 05 '22 20:10

febeling