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