Skip to content

Commit

Permalink
Added reverse search option in NSAttributedString extensions (#254)
Browse files Browse the repository at this point in the history
  • Loading branch information
rajdeep authored Nov 22, 2023
1 parent a7385cd commit 7a0a81f
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
27 changes: 27 additions & 0 deletions Proton/Sources/Swift/Helpers/NSAttributedString+Range.swift
Original file line number Diff line number Diff line change
Expand Up @@ -140,4 +140,31 @@ public extension NSAttributedString {
}
return (string as NSString).substring(with: range)
}

/// Searches for given text in string
/// - Parameters:
/// - searchText: Text to search
/// - startingLocation: Starting location from which the text should be searched backwards
/// - isCaseInsensitive: Case insensitive search. Defaults to `true`
/// - Returns: Range of search text, if found.
func reverseRange(of searchText: String, startingLocation: Int, isCaseInsensitive: Bool = true) -> NSRange? {
guard startingLocation <= string.utf16.count else {
return nil
}

let string = self.string as NSString
let cursorRange = NSRange(location: 0, length: startingLocation)
let text = string.substring(with: cursorRange) as NSString
var options: NSString.CompareOptions = [.backwards, .caseInsensitive]
if isCaseInsensitive == false {
options = [.backwards]
}
let searchTextRange = text.range(of: searchText, options: options)
guard searchTextRange.location != NSNotFound else {
return nil
}

let range = NSRange(location: searchTextRange.location, length: searchText.count)
return range
}
}
24 changes: 24 additions & 0 deletions Proton/Tests/ExtensionTests/NSAttributedStringExtensionTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -164,4 +164,28 @@ class NSAttributedStringExtensionTests: XCTestCase {
let range = attributedString.rangeOf(attribute: testAttribute, at: 0)
XCTAssertNil(range)
}

func testGetsReverseRangeOfText() {
let text = NSMutableAttributedString(string: "This is a test string")
let range = text.reverseRange(of: "is", startingLocation: text.length - 1)
XCTAssertEqual(range, NSRange(location: 5, length: 2))
}

func testFailsReverseRangeOfTextCaseSensitive() {
let text = NSMutableAttributedString(string: "This is a test string")
let range = text.reverseRange(of: "Is", startingLocation: text.length - 1, isCaseInsensitive: false)
XCTAssertNil(range)
}

func testGetsReverseRangeOfTextCaseSensitive() {
let text = NSMutableAttributedString(string: "This is a test string")
let range = text.reverseRange(of: "Is", startingLocation: text.length - 1)
XCTAssertEqual(range, NSRange(location: 5, length: 2))
}

func testDoesNotFindReverseRangeOfText() {
let text = NSMutableAttributedString(string: "This is a test string")
let range = text.reverseRange(of: "isx", startingLocation: text.length - 1)
XCTAssertNil(range)
}
}

0 comments on commit 7a0a81f

Please sign in to comment.