Sources/OrgIndex/FileRecord.swift
cmc org-roam: aliases, refs, excludes, chooser tags, template choice, capture buffer
ed22b081d6 2 hours ago287 lines · 12565 bytes
1import CryptoKit
2import Foundation
3import OrgCore
4
5public enum FileKind: String, Sendable {
6 case org
7 case archive
8 /// A Syncthing conflict copy: listed, never indexed for search, agenda or IDs.
9 case conflict
10 /// Any other file: listed and openable, never read by the index.
11 case other
12}
13
14/// Everything that decides what an index row means. Bump `version` when a semantic setting
15/// changes, so files indexed under the old settings are indexed again.
16public struct IndexSettings: Sendable, Equatable {
17 public var version: Int
18 public var org: OrgSettings
19 public var semantic: SemanticSettings
20
21 /// Settings whose version follows the TODO keywords, so changing them reindexes.
22 public static func with(todoKeywords org: OrgSettings) -> IndexSettings {
23 let names = org.todoSequences.map { ($0.active.map(\.name) + ["|"] + $0.done.map(\.name)).joined(separator: " ") }.joined(separator: ";")
24 var hash: UInt64 = 0xcbf29ce484222325
25 for byte in names.utf8 {
26 hash ^= UInt64(byte)
27 hash = hash &* 0x100000001b3
28 }
29 return IndexSettings(version: 1 + Int(hash % 1_000_000), org: org)
30 }
31
32 public init(version: Int = 1, org: OrgSettings = .default, semantic: SemanticSettings = .default) {
33 self.version = version
34 self.org = org
35 self.semantic = semantic
36 }
37}
38
39public struct TagRow: Sendable, Equatable {
40 public let name: String
41 public let inherited: Bool
42}
43
44public struct PropertyRow: Sendable, Equatable {
45 /// Upper-cased.
46 public let key: String
47 public let value: String
48 public let inherited: Bool
49}
50
51public struct TimestampRow: Sendable, Equatable {
52 public enum Kind: String, Sendable { case scheduled, deadline, closed, active, inactive }
53 public let kind: Kind
54 /// `2026-10-04` or `2026-10-04T10:00`.
55 public let start: String
56 public let end: String?
57 /// As written: `+1w`, `.+2d/3d`.
58 public let repeater: String?
59 /// As written: `-2d`, `--1w`.
60 public let warning: String?
61}
62
63public struct ClockRow: Sendable, Equatable {
64 public let start: String
65 public let end: String?
66 public let minutes: Int?
67}
68
69public struct LinkRow: Sendable, Equatable {
70 /// The scheme before the first colon (`id`, `file`, `https`), or `fuzzy`.
71 public let type: String
72 public let target: String
73}
74
75public struct HeadingRecord: Sendable, Equatable {
76 /// Position in document order; parents refer to it.
77 public let ordinal: Int
78 public let parent: Int?
79 /// The section's UTF-16 range in the file's text.
80 public let start: Int
81 public let end: Int
82 public let level: Int
83 public let todo: String?
84 public let isDone: Bool
85 public let priority: String?
86 public let title: String
87 public let outlinePath: [String]
88 public let orgID: String?
89 /// Tagged `ARCHIVE`, directly or by inheritance.
90 public let archived: Bool
91 /// The heading's own text, without the heading line and child sections.
92 public let body: String
93 public let tags: [TagRow]
94 public let properties: [PropertyRow]
95 public let timestamps: [TimestampRow]
96 public let clocks: [ClockRow]
97 public let links: [LinkRow]
98}
99
100/// One file's index rows, computed without touching the database.
101public struct FileRecord: Sendable, Equatable {
102 public let path: String
103 public let root: String
104 public let kind: FileKind
105 public let size: Int
106 public let mtime: Double
107 /// SHA-256 of the bytes, hex.
108 public let hash: String
109 public let settingsVersion: Int
110 public let headings: [HeadingRecord]
111 /// Links before the first heading, the file's own.
112 public let links: [LinkRow]
113 /// The `ID` in the property drawer before the first heading: the file as an org-roam node.
114 public let fileID: String?
115 /// `#+TITLE`, joined with spaces when there are several.
116 public let title: String?
117 /// The text before the first heading, searched as the file itself.
118 public let preamble: String
119 /// `#+FILETAGS`: the file node's tags.
120 public let fileTags: [String]
121 /// The file's own `ROAM_ALIASES`, `ROAM_REFS` and `ROAM_EXCLUDE`, as written.
122 public let fileRoam: RoamProperties
123
124 public static func hash(_ bytes: [UInt8]) -> String {
125 SHA256.hash(data: Data(bytes)).map { String(format: "%02x", $0) }.joined()
126 }
127
128 public init(path: String, root: String, kind: FileKind, bytes: [UInt8], mtime: Double, settings: IndexSettings) {
129 self.path = path
130 self.root = root
131 self.kind = kind
132 self.size = bytes.count
133 self.mtime = mtime
134 self.hash = Self.hash(bytes)
135 let source = SourceText(bytes: bytes)
136 var resolved = settings
137 resolved.org = settings.org.resolvingSetupFiles(in: source.text, path: path, read: OrgSettings.readFile)
138 self.settingsVersion = Self.settingsVersion(settings, text: source.text, setupKeywords: resolved.org.setupKeywords)
139 (headings, links, fileID, title, preamble, fileTags, fileRoam) = kind == .conflict
140 ? ([], [], nil, nil, "", [], RoamProperties()) : Self.rows(source.text, settings: resolved)
141 }
142
143 /// The settings version a file's rows are built under: the index's, with the keywords of
144 /// the setup files it names mixed in, so a changed setup file indexes it again.
145 public static func settingsVersion(_ settings: IndexSettings, text: String, setupKeywords: String) -> Int {
146 guard text.containsIgnoringASCIICase("#+setupfile:") else { return settings.version }
147 var hash: UInt64 = 0xcbf29ce484222325
148 for byte in setupKeywords.utf8 {
149 hash ^= UInt64(byte)
150 hash = hash &* 0x100000001b3
151 }
152 return settings.version + 1_000_000 * (1 + Int(hash % 1_000_000))
153 }
154
155 /// `settingsVersion` for a file's bytes, reading the setup files it names.
156 public static func settingsVersion(_ settings: IndexSettings, bytes: [UInt8], path: String) -> Int {
157 let text = SourceText(bytes: bytes).text
158 guard text.containsIgnoringASCIICase("#+setupfile:") else { return settings.version }
159 let keywords = settings.org.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile).setupKeywords
160 return settingsVersion(settings, text: text, setupKeywords: keywords)
161 }
162
163 /// A file the index lists without reading: `hash` stands for its size and mtime.
164 public init(path: String, root: String, unreadSize size: Int, mtime: Double, settings: IndexSettings) {
165 self.path = path
166 self.root = root
167 self.kind = .other
168 self.size = size
169 self.mtime = mtime
170 self.hash = Self.unreadHash(size: size, mtime: mtime)
171 self.settingsVersion = settings.version
172 headings = []
173 links = []
174 fileID = nil
175 title = nil
176 preamble = ""
177 fileTags = []
178 fileRoam = RoamProperties()
179 }
180
181 public static func unreadHash(size: Int, mtime: Double) -> String { "unread:\(size):\(mtime)" }
182
183 static func rows(_ text: String, settings: IndexSettings)
184 -> (headings: [HeadingRecord], links: [LinkRow], fileID: String?, title: String?, preamble: String, fileTags: [String], fileRoam: RoamProperties) {
185 let model = DocumentModel(tree: OrgParser.parse(text, defaults: settings.org), settings: settings.semantic)
186 let utf16 = text.utf16
187 func slice(_ range: Range<Int>) -> String {
188 let start = utf16.index(utf16.startIndex, offsetBy: range.lowerBound)
189 let end = utf16.index(utf16.startIndex, offsetBy: range.upperBound)
190 return String(text[start..<end])
191 }
192 var firstChild: [Int: Int] = [:]
193 for (index, heading) in model.headings.enumerated() {
194 if let parent = heading.parent, firstChild[parent] == nil { firstChild[parent] = index }
195 }
196
197 let headings = model.headings.enumerated().map { index, heading in
198 let bodyEnd = firstChild[index].map { model.headings[$0].sectionRange.lowerBound } ?? heading.sectionRange.upperBound
199 let tags = model.tags(of: index)
200 return HeadingRecord(
201 ordinal: index,
202 parent: heading.parent,
203 start: heading.sectionRange.lowerBound,
204 end: heading.sectionRange.upperBound,
205 level: heading.level,
206 todo: heading.todo,
207 isDone: heading.isDone,
208 priority: heading.priority,
209 title: heading.title,
210 outlinePath: model.outlinePath(of: index),
211 orgID: heading.id,
212 archived: tags.contains { $0.value == "ARCHIVE" },
213 body: slice(heading.headingRange.upperBound..<bodyEnd),
214 tags: tags.map { TagRow(name: $0.value, inherited: $0.source != .heading(index)) },
215 properties: properties(model, index),
216 timestamps: timestamps(heading),
217 clocks: heading.clocks.map {
218 ClockRow(start: format($0.start), end: $0.end.map(format), minutes: $0.minutes)
219 },
220 links: heading.links.map(linkRow)
221 )
222 }
223 let fileID = model.property("ID", of: nil)?.value.trimmingCharacters(in: .whitespaces)
224 let zeroth = model.headings.first.map { slice(0..<$0.sectionRange.lowerBound) } ?? text
225 let titles = zeroth.matches(of: /(?im)^[ \t]*#\+title:[ \t]*(.*?)[ \t]*$/).map { String($0.1) }
226 let roam = RoamProperties(aliases: model.property("ROAM_ALIASES", of: nil)?.value, refs: model.property("ROAM_REFS", of: nil)?.value,
227 exclude: model.property("ROAM_EXCLUDE", of: nil)?.value)
228 return (headings, model.links.map(linkRow), fileID?.isEmpty == false ? fileID : nil, titles.isEmpty ? nil : titles.joined(separator: " "), zeroth,
229 model.fileTags, roam)
230 }
231
232 static func linkRow(_ target: String) -> LinkRow {
233 let scheme = target.prefix { $0 != ":" }
234 let isScheme = scheme.count < target.count && !scheme.isEmpty && scheme.allSatisfy { $0.isLetter || $0 == "-" }
235 return LinkRow(type: isScheme ? scheme.lowercased() : "fuzzy", target: target)
236 }
237
238 /// Own properties, plus inherited ones for keys that inherit.
239 static func properties(_ model: DocumentModel, _ index: Int) -> [PropertyRow] {
240 var keys: [String] = []
241 func add(_ entries: [Property], inheritedOnly: Bool) {
242 for entry in entries {
243 let key = entry.key.uppercased()
244 if !keys.contains(key), !inheritedOnly || model.inherits(key) { keys.append(key) }
245 }
246 }
247 add(model.headings[index].properties, inheritedOnly: false)
248 add(model.fileProperties, inheritedOnly: true)
249 for ancestor in model.ancestors(of: index) { add(model.headings[ancestor].properties, inheritedOnly: true) }
250 return keys.compactMap { key in
251 model.property(key, of: index).map {
252 PropertyRow(key: key, value: $0.value, inherited: $0.source != .heading(index))
253 }
254 }
255 }
256
257 static func timestamps(_ heading: HeadingInfo) -> [TimestampRow] {
258 var rows: [TimestampRow] = []
259 func add(_ stamp: Timestamp?, _ kind: TimestampRow.Kind) {
260 guard let stamp else { return }
261 rows.append(TimestampRow(
262 kind: kind,
263 start: format(stamp.start),
264 end: stamp.end.map(format),
265 repeater: stamp.repeater.map {
266 $0.kind.rawValue + format($0.interval) + ($0.habitDeadline.map { "/" + format($0) } ?? "")
267 },
268 warning: stamp.warning.map { ($0.firstOccurrenceOnly ? "--" : "-") + format($0.interval) }
269 ))
270 }
271 add(heading.scheduled, .scheduled)
272 add(heading.deadline, .deadline)
273 add(heading.closed, .closed)
274 for stamp in heading.timestamps { add(stamp, stamp.active ? .active : .inactive) }
275 return rows
276 }
277
278 static func format(_ point: Timestamp.Point) -> String {
279 let date = String(format: "%04d-%02d-%02d", point.year, point.month, point.day)
280 guard let hour = point.hour, let minute = point.minute else { return date }
281 return date + String(format: "T%02d:%02d", hour, minute)
282 }
283
284 static func format(_ interval: Timestamp.Interval) -> String {
285 "\(interval.value)\(interval.unit.rawValue)"
286 }
287}