When editing code, Xcode is capabale of displaying in-text controls, like drop down buttons which can show context menu’s. I’ve seen other OS X apps that handle text capable of similar features. See the attached sample.

I presume this effect is obtained using NSTextAttachmentCell – although I’m not sure whether this is the proper way to implement this.
For my own app I would like to use this technique as well.
I have the following questions:
-
Is
NSTextAttachmentCellthe correct way to implement such a feature? If not, what would be? -
How do I attach a control -comparable to the one in the above sample- to a specific range of text so that its location within
NSTextViewis dynamic and follows layout actions?
I found this which gives some hints but does not cover the attachment to specific text ranges.
Although
NSTextAttachmentCellwill work, it has a disadvantage: the cell will become just a glyph in the text which was not what I wanted. It distorts the layout of the text, is selectable etc. I wanted the cell to be drawn over the text, just like the behaviour in Xcode.The challenge was to find a way of translating a point from a Mouse Moved event to the position of a particular string of characters inside the
NSTextView.After some more digging I found a little gem in Apple’s demo apps called LayoutManagerDemo. This demo shows a custom subclass of
NSTextViewcapable of highlighting individual characters, words and lines while the mouse is hoovering its view. From there on it was pretty easy to fade in a button at the requiredNSPointand then show a popup menu with some options.