TextKit: How is the editor placeholder feature implemented in Xcode?

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.

Asked By: Mark
||
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .



# More Articles