Skip to content

Instantly share code, notes, and snippets.

@Uncommon
Created October 16, 2019 17:09
Show Gist options
  • Save Uncommon/d5960daba473dcba5d2ec1e1f78d08aa to your computer and use it in GitHub Desktop.
Save Uncommon/d5960daba473dcba5d2ec1e1f78d08aa to your computer and use it in GitHub Desktop.
Custom text storage
// https://stackoverflow.com/a/32671117/310159
/// Abstract custom text storage
class CustomTextStorage: NSTextStorage
{
var contents: NSMutableAttributedString
override var string: String { return contents.string }
override init(attributedString attrStr: NSAttributedString)
{
self.contents = attrStr.mutableCopy() as! NSMutableAttributedString
super.init()
}
override init()
{
self.contents = NSMutableAttributedString()
super.init()
}
required init?(coder: NSCoder)
{
fatalError("init(coder:) has not been implemented")
}
required init?(pasteboardPropertyList propertyList: Any,
ofType type: NSPasteboard.PasteboardType)
{
fatalError("init(pasteboardPropertyList:ofType:) has not been implemented")
}
override func attributes(at location: Int,
effectiveRange range: NSRangePointer?)
-> [NSAttributedString.Key : Any]
{
return contents.attributes(at: location, effectiveRange: range)
}
override func replaceCharacters(in range: NSRange, with str: String)
{
let originalLength = length
contents.replaceCharacters(in: range, with: str)
edited(.editedCharacters, range: range,
changeInLength: length - originalLength)
}
override func setAttributes(_ attrs: [NSAttributedString.Key : Any]?, range: NSRange)
{
contents.setAttributes(attrs, range: range)
edited(.editedAttributes, range: range, changeInLength: 0)
}
}
/// The entire text is always a "word"
class OneWordTextStorage: CustomTextStorage
{
override func doubleClick(at location: Int) -> NSRange
{
return string.fullNSRange // extension method
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment