File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -73,6 +73,17 @@ - (void)edited:(NSTextStorageEditActions)editedMask range:(NSRange)editedRange c
7373 [self .textStorageDelegate textStorage: self edited: editedMask in: editedRange changeInLength: delta];
7474}
7575
76+ - (NSAttributedString *)attributedSubstringFromRange : (NSRange )range {
77+ NSRange rangeToUse =[self clampedWithUpperBound: self .length location: range.location length: range.length];
78+ return [super attributedSubstringFromRange: rangeToUse];
79+ }
80+
81+ - (NSRange )clampedWithUpperBound : (NSInteger )upperBound location : (NSInteger )location length : (NSInteger )length {
82+ NSInteger clampedLocation = MAX (MIN (location, upperBound), 0 );
83+ NSInteger clampedLength = MAX (MIN (length, upperBound - clampedLocation), 0 );
84+ return NSMakeRange (clampedLocation, clampedLength);
85+ }
86+
7687- (void )replaceCharactersInRange : (NSRange )range withAttributedString : (NSAttributedString *)attrString {
7788 // TODO: Add undo behaviour
7889
Original file line number Diff line number Diff line change @@ -131,4 +131,13 @@ class TextStorageTests: XCTestCase {
131131 XCTAssertEqual ( attrs [ NSAttributedString . Key ( " attr2 " ) ] as? Int , 2 )
132132 XCTAssertEqual ( attrs [ NSAttributedString . Key ( " attr3 " ) ] as? Int , 3 )
133133 }
134+
135+ func testReturnsSubstringWithClampedRange( ) {
136+ let textStorage = PRTextStorage ( )
137+ let testString = NSAttributedString ( string: " test string " )
138+ textStorage. replaceCharacters ( in: . zero, with: testString)
139+
140+ let substring = textStorage. attributedSubstring ( from: NSRange ( location: 5 , length: 50 ) )
141+ XCTAssertEqual ( substring. string, " string " )
142+ }
134143}
You can’t perform that action at this time.
0 commit comments