I'm working on a Cocoa text editor which uses an NSTextView. Is it possible to change the color of certain portions of the text?
Sure. You can give the NSTextView
an NSAttributedString
, and some of the stuff you can do with the attributed string is apply colors to certain subranges of the string.
Or you can search on Google and see that a lot of people have done stuff with this before.
I'd probably recommend using OkudaKit.
I recommend you to start by reading the CocoaDev page about Syntax Highlighing. A lot of people have come with solutions for various goals.
If you want to perform source code syntax highlighting, I suggest you to take a look at the UKSyntaxColoredTextDocument from Uli Kusterer.
You should add your controller as the delegate of the NSTextView
and then implement the delegate method -textStorageDidProcessEditing:
. This is called whenever the text changes.
In the delegate method you need to get the current NSTextStorage
object from the text view using the -textStorage
method of NSTextView
. NSTextStorage
is a subclass of NSAttributedString
and contains the attributed contents of the view.
Your code must then parse the string and apply coloring to whatever ranges of text are interesting to you. You apply color to a range using something like this, which will apply a yellow color to the whole string:
//get the range of the entire run of text
NSRange area = NSMakeRange(0, [textStorage length]);
//remove existing coloring
[textStorage removeAttribute:NSForegroundColorAttributeName range:area];
//add new coloring
[textStorage addAttribute:NSForegroundColorAttributeName
value:[NSColor yellowColor]
range:area];
How you parse the text is up to you. NSScanner
is a useful class to use when parsing text.
Note that this method is by no means the most efficient way of handling syntax coloring. If the documents you are editing are very large you will most likely want to consider offloading the parsing to a separate thread and/or being clever about which sections of text are reparsed.