Sources/OrgIndex/FileRecord.swift
324 lines · 14649 bytes
26 symbols in this file
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;
11 /// never read for the agenda, IDs or links.
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 links = []
142 fileID = nil
143 fileTags = []
144 fileRoam = RoamProperties()
145 (headings, title, preamble) = Self.textRows(source.text, path: path)
146 return
147 }
148 var resolved = settings
149 resolved.org = settings.org.resolvingSetupFiles(in: source.text, path: path, read: OrgSettings.readFile)
150 self.settingsVersion = Self.settingsVersion(settings, text: source.text, setupKeywords: resolved.org.setupKeywords)
151 (headings, links, fileID, title, preamble, fileTags, fileRoam) = kind == .conflict
152 ? ([], [], nil, nil, "", [], RoamProperties()) : Self.rows(source.text, settings: resolved)
153 }
154
155 /// A Markdown file's headings, with their own text as bodies, its title and the text
156 /// before its first heading; a plain text file's text, untitled.
157 static func textRows(_ text: String, path: String) -> (headings: [HeadingRecord], title: String?, preamble: String) {
158 guard Markdown.isPath(path) else { return ([], nil, text) }
159 let u = Array(text.utf16)
160 let structure = Markdown.structure(u)
161 let headings = structure.headings
162 func slice(_ range: Range<Int>) -> String { String(decoding: u[range], as: UTF16.self) }
163 var records: [HeadingRecord] = []
164 var open: [Int] = []
165 for (index, heading) in headings.enumerated() {
166 while let last = open.last, headings[last].level >= heading.level { open.removeLast() }
167 let end = headings[(index + 1)...].first { $0.level <= heading.level }?.start ?? u.count
168 let bodyEnd = index + 1 < headings.count ? min(headings[index + 1].start, end) : end
169 records.append(HeadingRecord(
170 ordinal: index, parent: open.last, start: heading.start, end: end, level: heading.level,
171 todo: nil, isDone: false, priority: nil, title: heading.title,
172 outlinePath: open.map { headings[$0].title } + [heading.title], orgID: nil, archived: false,
173 body: slice(heading.lineEnd..<max(heading.lineEnd, bodyEnd)), tags: [], properties: [], timestamps: [], clocks: [], links: []
174 ))
175 open.append(index)
176 }
177 return (records, Markdown.title(u, structure), slice(0..<(headings.first?.start ?? u.count)))
178 }
179
180 /// The settings version a file's rows are built under: the index's, with the keywords of
181 /// the setup files it names mixed in, so a changed setup file indexes it again.
182 public static func settingsVersion(_ settings: IndexSettings, text: String, setupKeywords: String) -> Int {
183 guard text.containsIgnoringASCIICase("#+setupfile:") else { return settings.version }
184 var hash: UInt64 = 0xcbf29ce484222325
185 for byte in setupKeywords.utf8 {
186 hash ^= UInt64(byte)
187 hash = hash &* 0x100000001b3
188 }
189 return settings.version + 1_000_000 * (1 + Int(hash % 1_000_000))
190 }
191
192 /// `settingsVersion` for a file's bytes, reading the setup files it names.
193 public static func settingsVersion(_ settings: IndexSettings, bytes: [UInt8], path: String) -> Int {
194 let text = SourceText(bytes: bytes).text
195 guard text.containsIgnoringASCIICase("#+setupfile:") else { return settings.version }
196 let keywords = settings.org.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile).setupKeywords
197 return settingsVersion(settings, text: text, setupKeywords: keywords)
198 }
199
200 /// A file the index lists without reading: `hash` stands for its size and mtime.
201 public init(path: String, root: String, unreadSize size: Int, mtime: Double, settings: IndexSettings) {
202 self.path = path
203 self.root = root
204 self.kind = .other
205 self.size = size
206 self.mtime = mtime
207 self.hash = Self.unreadHash(size: size, mtime: mtime)
208 self.settingsVersion = settings.version
209 headings = []
210 links = []
211 fileID = nil
212 title = nil
213 preamble = ""
214 fileTags = []
215 fileRoam = RoamProperties()
216 }
217
218 public static func unreadHash(size: Int, mtime: Double) -> String { "unread:\(size):\(mtime)" }
219
220 static func rows(_ text: String, settings: IndexSettings)
221 -> (headings: [HeadingRecord], links: [LinkRow], fileID: String?, title: String?, preamble: String, fileTags: [String], fileRoam: RoamProperties) {
222 let model = DocumentModel(tree: OrgParser.parse(text, defaults: settings.org), settings: settings.semantic)
223 let utf16 = text.utf16
224 func slice(_ range: Range<Int>) -> String {
225 let start = utf16.index(utf16.startIndex, offsetBy: range.lowerBound)
226 let end = utf16.index(utf16.startIndex, offsetBy: range.upperBound)
227 return String(text[start..<end])
228 }
229 var firstChild: [Int: Int] = [:]
230 for (index, heading) in model.headings.enumerated() {
231 if let parent = heading.parent, firstChild[parent] == nil { firstChild[parent] = index }
232 }
233
234 let headings = model.headings.enumerated().map { index, heading in
235 let bodyEnd = firstChild[index].map { model.headings[$0].sectionRange.lowerBound } ?? heading.sectionRange.upperBound
236 let tags = model.tags(of: index)
237 return HeadingRecord(
238 ordinal: index,
239 parent: heading.parent,
240 start: heading.sectionRange.lowerBound,
241 end: heading.sectionRange.upperBound,
242 level: heading.level,
243 todo: heading.todo,
244 isDone: heading.isDone,
245 priority: heading.priority,
246 title: heading.title,
247 outlinePath: model.outlinePath(of: index),
248 orgID: heading.id,
249 archived: tags.contains { $0.value == "ARCHIVE" },
250 body: slice(heading.headingRange.upperBound..<bodyEnd),
251 tags: tags.map { TagRow(name: $0.value, inherited: $0.source != .heading(index)) },
252 properties: properties(model, index),
253 timestamps: timestamps(heading),
254 clocks: heading.clocks.map {
255 ClockRow(start: format($0.start), end: $0.end.map(format), minutes: $0.minutes)
256 },
257 links: heading.links.map(linkRow)
258 )
259 }
260 let fileID = model.property("ID", of: nil)?.value.trimmingCharacters(in: .whitespaces)
261 let zeroth = model.headings.first.map { slice(0..<$0.sectionRange.lowerBound) } ?? text
262 let titles = zeroth.matches(of: /(?im)^[ \t]*#\+title:[ \t]*(.*?)[ \t]*$/).map { String($0.1) }
263 let roam = RoamProperties(aliases: model.property("ROAM_ALIASES", of: nil)?.value, refs: model.property("ROAM_REFS", of: nil)?.value,
264 exclude: model.property("ROAM_EXCLUDE", of: nil)?.value)
265 return (headings, model.links.map(linkRow), fileID?.isEmpty == false ? fileID : nil, titles.isEmpty ? nil : titles.joined(separator: " "), zeroth,
266 model.fileTags, roam)
267 }
268
269 static func linkRow(_ target: String) -> LinkRow {
270 let scheme = target.prefix { $0 != ":" }
271 let isScheme = scheme.count < target.count && !scheme.isEmpty && scheme.allSatisfy { $0.isLetter || $0 == "-" }
272 return LinkRow(type: isScheme ? scheme.lowercased() : "fuzzy", target: target)
273 }
274
275 /// Own properties, plus inherited ones for keys that inherit.
276 static func properties(_ model: DocumentModel, _ index: Int) -> [PropertyRow] {
277 var keys: [String] = []
278 func add(_ entries: [Property], inheritedOnly: Bool) {
279 for entry in entries {
280 let key = entry.key.uppercased()
281 if !keys.contains(key), !inheritedOnly || model.inherits(key) { keys.append(key) }
282 }
283 }
284 add(model.headings[index].properties, inheritedOnly: false)
285 add(model.fileProperties, inheritedOnly: true)
286 for ancestor in model.ancestors(of: index) { add(model.headings[ancestor].properties, inheritedOnly: true) }
287 return keys.compactMap { key in
288 model.property(key, of: index).map {
289 PropertyRow(key: key, value: $0.value, inherited: $0.source != .heading(index))
290 }
291 }
292 }
293
294 static func timestamps(_ heading: HeadingInfo) -> [TimestampRow] {
295 var rows: [TimestampRow] = []
296 func add(_ stamp: Timestamp?, _ kind: TimestampRow.Kind) {
297 guard let stamp else { return }
298 rows.append(TimestampRow(
299 kind: kind,
300 start: format(stamp.start),
301 end: stamp.end.map(format),
302 repeater: stamp.repeater.map {
303 $0.kind.rawValue + format($0.interval) + ($0.habitDeadline.map { "/" + format($0) } ?? "")
304 },
305 warning: stamp.warning.map { ($0.firstOccurrenceOnly ? "--" : "-") + format($0.interval) }
306 ))
307 }
308 add(heading.scheduled, .scheduled)
309 add(heading.deadline, .deadline)
310 add(heading.closed, .closed)
311 for stamp in heading.timestamps { add(stamp, stamp.active ? .active : .inactive) }
312 return rows
313 }
314
315 static func format(_ point: Timestamp.Point) -> String {
316 let date = String(format: "%04d-%02d-%02d", point.year, point.month, point.day)
317 guard let hour = point.hour, let minute = point.minute else { return date }
318 return date + String(format: "T%02d:%02d", hour, minute)
319 }
320
321 static func format(_ interval: Timestamp.Interval) -> String {
322 "\(interval.value)\(interval.unit.rawValue)"
323 }
324}