TextKit: How is the editor placeholder feature imp

2019-04-02 13:18发布

问题:

I took a deep dive into TextKit and wondered how the editor placeholders are implemented in the Xcode code editor:

You can also try this yourself and type something along the lines of: <#Hello#>, which automatically turns into a placeholder.

The Xcode editor is built with TextKit. After some research I came up with two possible strategies:

  1. Using NSTextAttachment: as soon as a string matching the placeholder pattern <#...#> is detected, that string is removed and replaced by a NSTextAttachment, which handles drawing the "badge-shaped" background and the text.
  2. Using NSLayoutManager: not sure if this would work, but it could go like this:
    • The start and end markers (glyphs) <# + #> are hidden (layoutManager(... shouldGenerateGlyphs, forGlyphRange...))
    • The layout manager handles drawing the badge background in drawBackground(forGlyphRange glyphsToShow: NSRange, at origin: NSPoint)

I'd like to implement something similar and would appreciate any suggestions, as to which way to proceed.