It's common to have a text editor for code or other structured content that balances delimiters of some sort; when you double click on a { it selects to the matching }, or similarly for ( ) pairs, [ ] pairs, etc. How can I implement this behavior in NSTextView
in Cocoa/Obj-C?
(I will be posting an answer momentarily, since I found nothing on SO about this and spent today implementing a solution. Better answers are welcome.)
ADDENDUM:
This is not the same as this question, which is about NSTextField
and is primarily concerned with NSTextField
and field editor issues. If that question is solved by substituting a custom NSTextView
subclass into the field editor, then that custom subclass could use the solution given here, of course; but there might be many other ways to solve the problem for NSTextField
, and substituting a custom NSTextView
subclass into the field editor is not obviously the right solution to that problem, and in any case a programmer concerned with delimiter balancing in NSTextView
(which is presumably the more common problem) could care less about all of those NSTextField
and field editor issues. So that is a different question – although I will add a link from that question to this one, as one possible direction it could go.
This is also not the same as this question, which is really about changing the definition of a "word" in NSTextView
when a double-click occurs. As per Apple's documentation, these are different problems with different solutions; for delimiter-balancing (this question) Apple specifically recommends the use of NSTextView
's selectionRangeForProposedRange:granularity:
method, whereas for changing the definition of a word (that question) Apple specifically states that the selectionRangeForProposedRange:granularity:
method should not be used.