diff --git a/Sources/CodeEditTextView/TextView/TextView+SetText.swift b/Sources/CodeEditTextView/TextView/TextView+SetText.swift index a3f064857..6ba66916a 100644 --- a/Sources/CodeEditTextView/TextView/TextView+SetText.swift +++ b/Sources/CodeEditTextView/TextView/TextView+SetText.swift @@ -20,6 +20,10 @@ extension TextView { public func setTextStorage(_ textStorage: NSTextStorage) { self.textStorage = textStorage + if let storageDelegate = textStorage.delegate as? MultiStorageDelegate { + self.storageDelegate = storageDelegate + } + subviews.forEach { view in view.removeFromSuperview() } diff --git a/Sources/CodeEditTextView/TextView/TextView.swift b/Sources/CodeEditTextView/TextView/TextView.swift index 9b0337f9e..4c9cf7c31 100644 --- a/Sources/CodeEditTextView/TextView/TextView.swift +++ b/Sources/CodeEditTextView/TextView/TextView.swift @@ -320,7 +320,11 @@ public class TextView: NSView, NSTextContent { super.init(frame: .zero) self.emphasisManager = EmphasisManager(textView: self) - self.storageDelegate = MultiStorageDelegate() + if let storageDelegate = textStorage.delegate as? MultiStorageDelegate { + self.storageDelegate = storageDelegate + } else { + self.storageDelegate = MultiStorageDelegate() + } wantsLayer = true postsFrameChangedNotifications = true diff --git a/Tests/CodeEditTextViewTests/TextViewTests.swift b/Tests/CodeEditTextViewTests/TextViewTests.swift index da5056d27..d8ac192b1 100644 --- a/Tests/CodeEditTextViewTests/TextViewTests.swift +++ b/Tests/CodeEditTextViewTests/TextViewTests.swift @@ -40,4 +40,28 @@ struct TextViewTests { // available in test module textView.layoutManager.lineStorage.validateInternalState() } + + @Test + func sharedTextStorage() { + let storage = NSTextStorage(string: "Hello world") + + let textView1 = TextView(string: "") + textView1.frame = NSRect(x: 0, y: 0, width: 100, height: 100) + textView1.layoutSubtreeIfNeeded() + textView1.setTextStorage(storage) + + let textView2 = TextView(string: "") + textView2.frame = NSRect(x: 0, y: 0, width: 100, height: 100) + textView2.layoutSubtreeIfNeeded() + textView2.setTextStorage(storage) + + // Expect both text views to receive edited events from the storage + #expect(textView1.layoutManager.lineCount == 1) + #expect(textView2.layoutManager.lineCount == 1) + + storage.replaceCharacters(in: NSRange(location: 11, length: 0), with: "\nMore Lines\n") + + #expect(textView1.layoutManager.lineCount == 3) + #expect(textView2.layoutManager.lineCount == 3) + } }