Sources/OrgCore/Links/DenoteSequence.swift
357 lines · 17406 bytes
1import Foundation
2
3/// denote-sequence 0.3: a note's place in a hierarchy, kept as its Denote signature. Numeric
4/// sequences (`1=1=2`), alphanumeric ones (`1a2`) and alphanumeric delimited ones (`1=a1b=2`),
5/// each level one deeper. Ported as written, quirks included, so the sequences new notes get
6/// are the ones Emacs gives.
7public struct DenoteSequence: Sendable {
8 public enum Scheme: String, Sendable, CaseIterable, Codable {
9 case numeric, alphanumeric, alphanumericDelimited = "alphanumeric-delimited"
10 }
11
12 /// `denote-sequence-scheme`.
13 public var scheme: Scheme
14
15 public init(scheme: Scheme = .numeric) { self.scheme = scheme }
16
17 struct Failure: Error, CustomStringConvertible {
18 let description: String
19 }
20
21 static func isLetter(_ c: Character) -> Bool { c.isLetter }
22 static func hasLetter(_ s: String) -> Bool { s.contains(where: isLetter) }
23 static func allDigits(_ s: String) -> Bool { !s.isEmpty && s.allSatisfy(\.isASCIIDigit) }
24
25 // MARK: - Schemes
26
27 /// `denote-sequence-numeric-p`.
28 public static func isNumeric(_ s: String) -> Bool {
29 s.contains(where: \.isASCIIDigit) && !hasLetter(s) && !s.hasSuffix("=")
30 }
31
32 /// `denote-sequence-alphanumeric-p`.
33 public static func isAlphanumeric(_ s: String) -> Bool {
34 s.first?.isASCIIDigit == true && !s.contains("=")
35 }
36
37 /// The parts of an alphanumeric delimited sequence: runs of digits, runs of letters, `=`.
38 static func delimitedParts(_ s: String) -> [String] {
39 s.matches(of: /[0-9]+|\p{L}+|=/).map { String($0.0) }
40 }
41
42 /// `denote-sequence-alphanumeric-delimited-p`.
43 public static func isAlphanumericDelimited(_ s: String) -> Bool {
44 if allDigits(s) { return true }
45 guard s.contains("="), !isNumeric(s) else { return false }
46 let parts = delimitedParts(s)
47 // Numbers and letters alternate.
48 var last: Bool?
49 for part in parts where part != "=" {
50 let numeric = part.first!.isASCIIDigit
51 if last == numeric { return false }
52 last = numeric
53 }
54 // One level before the first `=`, then up to three a stretch, all but the last full.
55 var levels: [Int] = [], depth = 0
56 for part in parts {
57 if part == "=" { levels.append(depth); depth = 0 } else { depth += 1 }
58 }
59 levels.append(depth)
60 guard levels[0] == 1, levels.dropFirst().allSatisfy({ $0 <= 3 }) else { return false }
61 if levels.count > 2 { return levels.dropFirst().dropLast().allSatisfy { $0 == 3 } }
62 return true
63 }
64
65 /// `denote-sequence-p`.
66 public static func isSequence(_ s: String) -> Bool { isNumeric(s) || isAlphanumeric(s) || isAlphanumericDelimited(s) }
67
68 /// `denote-sequence-user-selected-scheme-p`.
69 func isInScheme(_ s: String) -> Bool { has(s, scheme) }
70
71 func has(_ s: String, _ scheme: Scheme) -> Bool {
72 switch scheme {
73 case .numeric: Self.isNumeric(s)
74 case .alphanumeric: Self.isAlphanumeric(s)
75 case .alphanumericDelimited: Self.isAlphanumericDelimited(s)
76 }
77 }
78
79 static func isNumericPartial(_ s: String) -> Bool { s.contains(where: \.isASCIIDigit) && !s.contains(where: { $0.isLetter || $0.isPunctuation || $0.isSymbol }) }
80 static func isAlphaPartial(_ s: String) -> Bool { hasLetter(s) && !s.contains(where: { $0.isASCIIDigit || $0.isPunctuation || $0.isSymbol }) }
81
82 /// `denote-sequence-and-scheme-p`: the sequence's scheme.
83 func schemeOf(_ s: String, partial: Bool = false) throws -> Scheme {
84 if !partial, Self.allDigits(s) { return scheme }
85 if !partial, !Self.hasLetter(s), scheme == .numeric { return .numeric }
86 if partial ? Self.isAlphaPartial(s) : Self.isAlphanumeric(s) { return .alphanumeric }
87 if partial ? Self.isNumericPartial(s) : Self.isNumeric(s) { return .numeric }
88 if partial ? (Self.isNumericPartial(s) || Self.isAlphaPartial(s)) : Self.isAlphanumericDelimited(s) { return .alphanumericDelimited }
89 throw Failure(description: "The sequence `\(s)' does not pass `denote-sequence-and-scheme-p'")
90 }
91
92 /// `denote-sequence-split`: a level of depth each.
93 func split(_ s: String, partial: Bool = false) throws -> [String] {
94 switch try schemeOf(s, partial: partial) {
95 case .numeric:
96 return s.split(separator: "=").map(String.init)
97 case .alphanumeric, .alphanumericDelimited:
98 let plain = s.replacingOccurrences(of: "=", with: "")
99 var parts: [String] = []
100 for match in plain.matches(of: /([0-9]+)(\p{L}+)?/) {
101 parts.append(String(match.1))
102 if let letters = match.2 { parts.append(String(letters)) }
103 }
104 return parts.isEmpty ? plain.map(String.init) : parts
105 }
106 }
107
108 /// `denote-sequence-join`.
109 static func join(_ parts: [String], _ scheme: Scheme) -> String {
110 switch scheme {
111 case .numeric: return parts.joined(separator: "=")
112 case .alphanumeric: return parts.joined()
113 case .alphanumericDelimited:
114 var out = ""
115 for (count, part) in parts.enumerated() {
116 out += part
117 if count % 3 == 0, count + 1 < parts.count { out += "=" }
118 }
119 return out
120 }
121 }
122
123 public func depth(_ s: String) throws -> Int { try split(s).count }
124
125 // MARK: - Counting
126
127 /// `denote-sequence-increment-partial`.
128 static func increment(_ s: String) throws -> String {
129 if isNumericPartial(s) { return String((Int(s) ?? 0) + 1) }
130 guard isAlphaPartial(s) else { throw Failure(description: "The string `\(s)' must contain only numbers or letters") }
131 let letters = Array(s)
132 if letters.count == 1 { return letters[0] == "z" ? "za" : String(UnicodeScalar(letters[0].unicodeScalars.first!.value + 1)!) }
133 if letters.last == "z" { return s + "a" }
134 return String(letters.dropLast()) + String(UnicodeScalar(letters.last!.unicodeScalars.first!.value + 1)!)
135 }
136
137 /// `denote-sequence-decrement-partial`; nil below the first.
138 static func decrement(_ s: String) throws -> String? {
139 if isNumericPartial(s) { let n = Int(s) ?? 0; return n == 1 ? nil : String(n - 1) }
140 guard isAlphaPartial(s) else { throw Failure(description: "The string `\(s)' must contain only numbers or letters") }
141 let letters = Array(s)
142 if letters.count == 1 { return letters[0] == "a" ? nil : String(UnicodeScalar(letters[0].unicodeScalars.first!.value - 1)!) }
143 if letters.last == "a" { return String(letters.dropLast()) }
144 return String(letters.dropLast()) + String(UnicodeScalar(letters.last!.unicodeScalars.first!.value - 1)!)
145 }
146
147 /// `denote-sequence--alpha-to-number`.
148 func alphaToNumber(_ s: String) throws -> String {
149 let total = try split(s, partial: true).reduce(0) { sum, letter in
150 let n = Int(letter.unicodeScalars.first!.value) - 96
151 if n > 0, n <= 26 { return sum + n }
152 let times = n / 26, mod = n % 26
153 return sum + times * 26 + (mod > 0 ? mod + 96 : 0)
154 }
155 return String(total)
156 }
157
158 /// `denote-sequence--number-to-alpha`.
159 static func numberToAlpha(_ s: String) -> String {
160 let n = Int(s) ?? 0
161 if n == 0 { return "a" }
162 if n <= 26 { return String(UnicodeScalar(UInt8(n + 96))) }
163 let times = n / 26, mod = n % 26
164 return String(repeating: "z", count: times) + (mod > 0 ? String(UnicodeScalar(UInt8(mod + 96))) : "")
165 }
166
167 /// `denote-sequence-make-conversion` of a whole sequence to `target`.
168 public func converted(_ s: String, to target: Scheme) throws -> String {
169 if target == .numeric {
170 if Self.isNumeric(s) { return s }
171 return Self.join(try split(s).map { Self.isNumericPartial($0) ? $0 : try alphaToNumber($0) }, .numeric)
172 }
173 if Self.isAlphanumeric(s) { return s }
174 let parts = try split(s).enumerated().map { index, part in
175 index % 2 == 0 || Self.isAlphaPartial(part) ? part : Self.numberToAlpha(part)
176 }
177 return Self.join(parts, target)
178 }
179
180 // MARK: - Ordering
181
182 /// `combine-and-quote-strings`' quoting of one string.
183 static func quoted(_ s: String) -> String {
184 guard s.contains(where: { $0 == "\"" || $0 == "\\" || $0 == " " || $0 == "\t" || $0 == "\n" }) else { return s }
185 return "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\""
186 }
187
188 static func padded(_ s: String, _ width: Int) -> String { s.count >= width ? s : String(repeating: " ", count: width - s.count) + s }
189
190 enum Kind { case all, parent, sibling, child }
191
192 /// `denote-sequence--pad`: the key sequences sort by.
193 func pad(_ s: String, _ kind: Kind) throws -> String {
194 let parts = try split(s)
195 let list: [String]?, single: String?
196 switch (kind, parts.count > 1) {
197 case (.all, _): (list, single) = (parts, nil)
198 case (.parent, true): (list, single) = (nil, parts[0])
199 case (.sibling, true): (list, single) = (parts, nil)
200 case (.child, true): (list, single) = (nil, parts.last!)
201 default: (list, single) = (nil, s)
202 }
203 if let list { return list.map { Self.quoted(Self.padded($0, 5)) }.joined(separator: "=") }
204 return Self.padded(single!, 32)
205 }
206
207 /// What `denote-sequence-sort-files` compares: the sequence with every level padded.
208 public func sortKey(_ s: String) -> String { (try? pad(s, .all)) ?? s }
209
210 /// `denote-sequence-sort-sequences`.
211 public func sorted(_ sequences: [String]) -> [String] {
212 stableSorted(sequences) { (try? pad($0, .all)) ?? $0 }
213 }
214
215 func stableSorted(_ items: [String], by key: (String) -> String) -> [String] {
216 let keys = items.map(key)
217 return items.indices.sorted { keys[$0] == keys[$1] ? $0 < $1 : keys[$0] < keys[$1] }.map { items[$0] }
218 }
219
220 func largestByOrder(_ sequences: [String], _ kind: Kind) -> String? {
221 stableSorted(sequences) { (try? pad($0, kind)) ?? $0 }.last
222 }
223
224 /// `denote-sequence--get-largest`.
225 func largest(_ sequences: [String], _ kind: Kind) -> String? {
226 guard kind == .child else { return largestByOrder(sequences, kind) }
227 func length(_ s: String) -> Int { scheme == .alphanumeric ? s.count : s.replacingOccurrences(of: "=", with: "").count }
228 guard let longest = sequences.map(length).max() else { return nil }
229 let tied = sequences.filter { length($0) == longest }
230 return tied.count == 1 ? tied[0] : largestByOrder(tied, .child)
231 }
232
233 /// `denote-sequence--get-start`.
234 func start(_ sequence: String? = nil) -> String {
235 guard scheme != .numeric, let last = sequence?.last else { return "1" }
236 return last.isLetter ? "1" : "a"
237 }
238
239 /// `denote-sequence--sequence-prefix-p`.
240 func hasPrefix(_ prefix: [String], _ sequence: String) -> Bool {
241 guard isInScheme(sequence), let parts = try? split(sequence) else { return false }
242 return parts.count >= prefix.count && Array(parts.prefix(prefix.count)) == prefix
243 }
244
245 func withPrefix(_ sequence: String, _ sequences: [String]) -> [String] {
246 guard !sequence.isEmpty, let prefix = try? split(sequence) else { return [] }
247 return sequences.filter { hasPrefix(prefix, $0) }
248 }
249
250 /// `denote-sequence-get-all-sequences-with-max-depth`: each cut to `depth` levels.
251 func withMaxDepth(_ depth: Int, _ sequences: [String]) -> [String] {
252 var seen = Set<String>(), out: [String] = []
253 for s in sequences {
254 guard let parts = try? split(s), parts.count <= depth else { continue }
255 let joined = Self.join(Array(parts.prefix(depth)), scheme)
256 if seen.insert(joined).inserted { out.append(joined) }
257 }
258 return out
259 }
260
261 // MARK: - New sequences
262
263 /// `denote-sequence-get-new` for `parent`: one after the largest first level.
264 public func newParent(among sequences: [String]) throws -> String {
265 guard let top = largest(sequences, .parent) else { return start() }
266 return String((Int(try split(top)[0]) ?? 0) + 1)
267 }
268
269 /// `denote-sequence-get-new` for `child` of `sequence`.
270 public func newChild(of sequence: String, among sequences: [String]) throws -> String {
271 let depth = try self.depth(sequence) + 1
272 let unfiltered = withPrefix(sequence, sequences)
273 guard !unfiltered.isEmpty else { throw Failure(description: "Cannot find sequences given sequence `\(sequence)' using scheme `\(scheme.rawValue)'") }
274 let first = Self.join(try split(sequence) + [start(sequence)], scheme)
275 guard unfiltered.count > 1 else { return first }
276 let cut = withMaxDepth(depth, unfiltered)
277 guard let largest = largest((cut.isEmpty ? unfiltered : cut).filter(isInScheme), .child) else { return first }
278 guard try self.depth(largest) > 1 else { return Self.join(try split(largest) + [start(sequence)], scheme) }
279 var parts = try split(largest)
280 let last = parts.removeLast()
281 return Self.join(parts + [try Self.increment(last)], try schemeOf(largest))
282 }
283
284 /// `denote-sequence-get-new` for `sibling` of `sequence`.
285 public func newSibling(of sequence: String, among sequences: [String]) throws -> String {
286 let parts = try split(sequence)
287 let nested = parts.count > 1
288 let unfiltered = nested ? withPrefix(Self.join(Array(parts.dropLast()), try schemeOf(sequence)), sequences) : sequences
289 let all = withMaxDepth(parts.count, unfiltered).filter(isInScheme)
290 guard all.contains(sequence), let largest = largest(all, nested ? .sibling : .parent) else {
291 throw Failure(description: "Cannot find sequences given sequence `\(sequence)' using scheme `\(scheme.rawValue)'")
292 }
293 guard nested else { return String((Int(largest) ?? 0) + 1) }
294 var largestParts = try split(largest)
295 let last = largestParts.removeLast()
296 return Self.join(largestParts + [try Self.increment(last)], try schemeOf(largest))
297 }
298
299 /// `denote-sequence--infer-sibling`: the sequence one before or after, existing or not.
300 public func neighbor(of sequence: String, next: Bool) throws -> String? {
301 var parts = try split(sequence)
302 let last = parts.removeLast()
303 guard let changed = next ? try Self.increment(last) : try Self.decrement(last) else { return nil }
304 return Self.join(parts + [changed], try schemeOf(sequence))
305 }
306
307 // MARK: - Relatives
308
309 public enum Relation: String, Sendable, CaseIterable {
310 case allParents = "all-parents", parent, siblings, children, allChildren = "all-children"
311 }
312
313 /// `denote-sequence-get-relative` among `files` (path and sequence), in their order.
314 public func relatives(of sequence: String, _ relation: Relation, in files: [(path: String, sequence: String)]) throws -> [String] {
315 let depth = try self.depth(sequence), sequenceScheme = try schemeOf(sequence)
316 let parts = try split(sequence)
317 func common(_ compare: (Int, Int) -> Bool, _ prefix: String) -> [(path: String, sequence: String)] {
318 let pool = prefix.isEmpty ? files : (try? split(prefix)).map { prefix in files.filter { hasPrefix(prefix, $0.sequence) } } ?? []
319 return pool.filter { compare((try? self.depth($0.sequence)) ?? 0, depth) }
320 }
321 switch relation {
322 case .allParents:
323 var likely = Set<String>(), cut = Array(parts.dropLast())
324 while !cut.isEmpty { likely.insert(Self.join(cut, sequenceScheme)); cut.removeLast() }
325 return files.filter { likely.contains($0.sequence) }.map(\.path)
326 case .parent:
327 let parent = Self.join(Array(parts.dropLast()), sequenceScheme)
328 return files.first { $0.sequence == parent }.map { [$0.path] } ?? []
329 case .siblings:
330 let siblings = common(==, Self.join(Array(parts.dropLast()), sequenceScheme))
331 guard let current = Self.path(of: sequence, in: files) else { return [] }
332 return siblings.map(\.path).filter { $0 != current }
333 case .allChildren:
334 return common(>, sequence).map(\.path)
335 case .children:
336 return common(>, sequence).filter { (try? self.depth($0.sequence)) == depth + 1 }.map(\.path)
337 }
338 }
339
340 /// `denote-sequence-get-path`: the file with `sequence`, an Org one when there are several.
341 public static func path(of sequence: String, in files: [(path: String, sequence: String)]) -> String? {
342 let matches = files.filter { $0.sequence == sequence }.map(\.path)
343 return matches.count < 2 ? matches.first : matches.first { ($0 as NSString).pathExtension == "org" } ?? matches.first
344 }
345
346 /// The files with sequences among `paths`: their signatures that are sequences.
347 public static func files(_ paths: [String]) -> [(path: String, sequence: String)] {
348 paths.compactMap { path in
349 guard let signature = Denote.name(ofFile: path).signature, isSequence(signature) else { return nil }
350 return (path, signature)
351 }
352 }
353}
354
355private extension Character {
356 var isASCIIDigit: Bool { isASCII && isNumber }
357}