Sources/OrgCore/Replace/ProposedChange.swift
161 lines · 7467 bytes
14 symbols in this file
1import Foundation
2
3/// One change that Replace in Files or a rename proposes in a file: the line it is on, the part
4/// of the line that changes, what takes its place, and the edit to the whole text.
5public struct ProposedChange: Sendable, Equatable, Identifiable {
6 /// Its index among the file's changes.
7 public let id: Int
8 /// 1-based.
9 public let line: Int
10 /// The line as it is, without its line break.
11 public let lineText: String
12 /// The part of `lineText` that changes, in UTF-16 offsets; for a match that runs past the
13 /// line, from its start to the end of the line.
14 public let changed: Range<Int>
15 /// What replaces `changed`.
16 public let replacement: String
17 public let edit: TextEdit
18
19 public init(id: Int, line: Int, lineText: String, changed: Range<Int>, replacement: String, edit: TextEdit) {
20 self.id = id
21 self.line = line
22 self.lineText = lineText
23 self.changed = changed
24 self.replacement = replacement
25 self.edit = edit
26 }
27
28 /// `text` with `changes` applied.
29 public static func apply(_ changes: [ProposedChange], to text: String) -> String {
30 var result = text
31 for change in changes.sorted(by: { $0.edit.range.lowerBound > $1.edit.range.lowerBound }) { result = change.edit.apply(to: result) }
32 return result
33 }
34}
35
36/// Where each line of a text starts, to describe an offset by its line.
37struct LineStarts {
38 let text: NSString
39 private let starts: [Int]
40
41 init(_ text: NSString) {
42 self.text = text
43 var starts = [0]
44 for at in 0..<text.length where text.character(at: at) == 10 { starts.append(at + 1) }
45 self.starts = starts
46 }
47
48 /// The 0-based line holding `offset`.
49 func line(of offset: Int) -> Int {
50 var low = 0, high = starts.count - 1
51 while low < high {
52 let mid = (low + high + 1) / 2
53 if starts[mid] <= offset { low = mid } else { high = mid - 1 }
54 }
55 return low
56 }
57
58 /// The line's text without its line break.
59 func content(ofLine index: Int) -> Range<Int> {
60 let start = starts[index]
61 var end = index + 1 < starts.count ? starts[index + 1] : text.length
62 while end > start, [10, 13].contains(text.character(at: end - 1)) { end -= 1 }
63 return start..<end
64 }
65
66 /// A change for `edit`, described on the line it starts on.
67 /// `shown`, when given, is what the list shows changing, in place of `edit`.
68 func change(id: Int, _ edit: TextEdit, shown: TextEdit? = nil) -> ProposedChange {
69 let index = line(of: edit.range.lowerBound)
70 let content = content(ofLine: index)
71 let lineText = text.substring(with: NSRange(content))
72 let display = shown ?? edit
73 let start = display.range.lowerBound - content.lowerBound
74 let end = min(display.range.upperBound, content.upperBound) - content.lowerBound
75 return ProposedChange(id: id, line: index + 1, lineText: lineText, changed: start..<max(start, end), replacement: display.replacement, edit: edit)
76 }
77
78 /// `edit` (from `edit(lineStart:from:to:)`) widened to whole words of the line, for showing.
79 func wholeWords(_ edit: TextEdit) -> TextEdit {
80 func blank(_ at: Int) -> Bool { [32, 9, 10, 13].contains(text.character(at: at)) }
81 var start = edit.range.lowerBound, end = edit.range.upperBound
82 var before = "", after = ""
83 while start > 0, !blank(start - 1) {
84 start -= 1
85 before = text.substring(with: NSRange(location: start, length: 1)) + before
86 }
87 while end < text.length, !blank(end) {
88 after += text.substring(with: NSRange(location: end, length: 1))
89 end += 1
90 }
91 return TextEdit(range: start..<end, replacement: before + edit.replacement + after)
92 }
93
94 /// The edit that turns the line at `lineStart` from `old` into `new`, the parts both
95 /// share left out, at whole characters.
96 static func edit(lineStart: Int, from old: String, to new: String) -> TextEdit? {
97 guard old != new else { return nil }
98 let a = Array(old.unicodeScalars), b = Array(new.unicodeScalars)
99 var prefix = 0
100 while prefix < a.count, prefix < b.count, a[prefix] == b[prefix] { prefix += 1 }
101 var suffix = 0
102 while suffix < a.count - prefix, suffix < b.count - prefix, a[a.count - 1 - suffix] == b[b.count - 1 - suffix] { suffix += 1 }
103 func utf16(_ scalars: ArraySlice<Unicode.Scalar>) -> Int { scalars.reduce(0) { $0 + $1.utf16.count } }
104 let start = lineStart + utf16(a[..<prefix])
105 let removed = utf16(a[prefix..<(a.count - suffix)])
106 var replacement = String.UnicodeScalarView()
107 replacement.append(contentsOf: b[prefix..<(b.count - suffix)])
108 return TextEdit(range: start..<(start + removed), replacement: String(replacement))
109 }
110}
111
112/// org-crypt's encrypted entries and encrypted files, which searches and renames leave alone.
113public enum EncryptedText {
114 /// A file encrypted as a whole (`notes.org.gpg`), by its extension.
115 public static func isEncryptedFile(_ path: String) -> Bool {
116 path.lowercased().hasSuffix(".gpg")
117 }
118
119 /// The armored PGP messages (`-----BEGIN PGP MESSAGE-----` to `-----END PGP MESSAGE-----`)
120 /// in the entries of headings tagged `tag`, their own tag or inherited: the entries
121 /// org-crypt encrypted. Whole lines.
122 public static func ranges(in text: String, tag: String = "crypt") -> [Range<Int>] {
123 guard text.contains("-----BEGIN PGP MESSAGE-----") else { return [] }
124 let ns = text as NSString
125 var ranges: [Range<Int>] = []
126 // Levels of the headings above the line, with whether each has the tag.
127 var stack: [(level: Int, tagged: Bool)] = []
128 var begin: Int?
129 var at = 0
130 while at < ns.length {
131 let lineRange = ns.lineRange(for: NSRange(location: at, length: 0))
132 let line = ns.substring(with: lineRange).trimmingCharacters(in: .newlines)
133 at = NSMaxRange(lineRange)
134 if let match = line.firstMatch(of: /^(\*+)[ \t]/) {
135 if let open = begin {
136 ranges.append(open..<lineRange.location)
137 begin = nil
138 }
139 let level = match.1.count
140 while let last = stack.last, last.level >= level { stack.removeLast() }
141 let tags = line.firstMatch(of: /[ \t]:([\p{L}\p{N}_@#%:]+):[ \t]*$/).map { $0.1.split(separator: ":").map(String.init) } ?? []
142 stack.append((level, tags.contains(tag) || (stack.last?.tagged ?? false)))
143 continue
144 }
145 let trimmed = line.trimmingCharacters(in: .whitespaces)
146 if begin == nil, trimmed == "-----BEGIN PGP MESSAGE-----", stack.last?.tagged == true {
147 begin = lineRange.location
148 } else if let open = begin, trimmed == "-----END PGP MESSAGE-----" {
149 ranges.append(open..<NSMaxRange(lineRange))
150 begin = nil
151 }
152 }
153 if let open = begin { ranges.append(open..<ns.length) }
154 return ranges
155 }
156
157 /// Whether `range` touches one of `ranges`.
158 static func overlaps(_ range: Range<Int>, _ ranges: [Range<Int>]) -> Bool {
159 ranges.contains { $0.overlaps(range) || ($0.contains(range.lowerBound) && range.isEmpty) }
160 }
161}