Branchwell

Textley / app · textley.ai / Sources / TextleyCore / TextOperations.swift

Raw 4.7 KB on 63b71f34cfe61bc6553e8463e803a45424bff4d3
1import Foundation
2
3public struct LineIndex {
4 public private(set) var starts: [Int]
5
6 public init(_ text: String) {
7 starts = [0]
8 for (index, codeUnit) in text.utf16.enumerated() where codeUnit == 10 {
9 starts.append(index + 1)
10 }
11 }
12
13 public mutating func update(in text: NSString, editedRange: NSRange, changeInLength: Int) {
14 let first = line(at: editedRange.location)
15 let oldEnd = editedRange.location + editedRange.length - changeInLength
16 let following = line(at: oldEnd)
17 var insertedStarts: [Int] = []
18 for offset in editedRange.location..<NSMaxRange(editedRange) where text.character(at: offset) == 10 {
19 insertedStarts.append(offset + 1)
20 }
21 if first == following, insertedStarts.isEmpty, changeInLength == 0 || following == starts.count {
22 return
23 }
24 var updated = Array(starts.prefix(first))
25 updated.append(contentsOf: insertedStarts)
26 updated.append(contentsOf: starts.dropFirst(following).map { $0 + changeInLength })
27 starts = updated
28 }
29
30 public func line(at offset: Int) -> Int {
31 var low = 0
32 var high = starts.count
33 while low < high {
34 let middle = (low + high) / 2
35 if starts[middle] <= offset { low = middle + 1 } else { high = middle }
36 }
37 return max(1, low)
38 }
39}
40
41public struct SearchQuery: Equatable {
42 public var pattern = ""
43 public var isRegex = false
44 public var matchCase = false
45 public var wholeWord = false
46 public var wraps = true
47
48 public init() {}
49
50 public func expression() throws -> NSRegularExpression? {
51 guard !pattern.isEmpty else { return nil }
52 let escaped = NSRegularExpression.escapedPattern(for: pattern)
53 let body = isRegex ? pattern : (wholeWord ? "(?<![\\p{L}\\p{M}\\p{N}_])" + escaped + "(?![\\p{L}\\p{M}\\p{N}_])" : escaped)
54 let options: NSRegularExpression.Options = matchCase ? [.anchorsMatchLines] : [.anchorsMatchLines, .caseInsensitive]
55 return try NSRegularExpression(pattern: body, options: options)
56 }
57
58 public func matches(in text: String) throws -> [NSTextCheckingResult] {
59 try expression()?.matches(in: text, range: NSRange(location: 0, length: text.utf16.count)) ?? []
60 }
61
62 public func count(in text: String) throws -> Int {
63 try expression()?.numberOfMatches(in: text, range: NSRange(location: 0, length: text.utf16.count)) ?? 0
64 }
65
66 public func replacementText(_ replacement: String, for match: NSTextCheckingResult, in text: String) throws -> String {
67 guard isRegex, let expression = try expression() else { return replacement }
68 return expression.replacementString(for: match, in: text, offset: 0, template: replacement)
69 }
70
71 public func replacingAll(in text: String, with replacement: String) throws -> (text: String, count: Int) {
72 guard let expression = try expression() else { return (text, 0) }
73 let mutable = NSMutableString(string: text)
74 let template = isRegex ? replacement : NSRegularExpression.escapedTemplate(for: replacement)
75 let count = expression.replaceMatches(in: mutable, range: NSRange(location: 0, length: mutable.length), withTemplate: template)
76 return (mutable as String, count)
77 }
78}
79
80public enum Cleanup: String, CaseIterable {
81 case trim = "Trim Trailing Whitespace"
82 case uppercase = "Make Uppercase"
83 case lowercase = "Make Lowercase"
84 case sort = "Sort Lines"
85
86 public func edit(in text: String, selection: NSRange) -> (range: NSRange, replacement: String) {
87 let source = text as NSString
88 let range: NSRange
89 if selection.length == 0 {
90 range = NSRange(location: 0, length: source.length)
91 } else if self == .trim || self == .sort {
92 let first = source.lineRange(for: NSRange(location: selection.location, length: 0))
93 let last = source.lineRange(for: NSRange(location: NSMaxRange(selection) - 1, length: 0))
94 range = NSUnionRange(first, last)
95 } else {
96 range = selection
97 }
98 let value = source.substring(with: range)
99 let replacement: String
100 switch self {
101 case .trim: replacement = value.replacingOccurrences(of: "[ \\t]+(?=\\n|\\z)", with: "", options: .regularExpression)
102 case .uppercase: replacement = value.uppercased()
103 case .lowercase: replacement = value.lowercased()
104 case .sort:
105 let hasFinalLineBreak = value.hasSuffix("\n")
106 var lines = value.components(separatedBy: "\n")
107 if hasFinalLineBreak { lines.removeLast() }
108 replacement = lines.sorted().joined(separator: "\n") + (hasFinalLineBreak ? "\n" : "")
109 }
110 return (range, replacement)
111 }
112}