Sources/OrgIndex/IndexStore.swift

73b5c3d29343d6a3801f3a9a591fa434c01c9f06
orgstar/Sources/OrgIndex/IndexStore.swift

633 lines · 32776 bytes

34 symbols in this file
  1import Foundation
  2import GRDB
  3import OrgCore
  4
  5/// What the index knows about a file without reading it.
  6public struct FileState: Sendable, Equatable {
  7    public let kind: FileKind
  8    public let size: Int
  9    public let mtime: Double
 10    public let hash: String
 11    public let settingsVersion: Int
 12}
 13
 14/// A heading as found by a query. `contentHash` is the hash of the text the offsets refer to,
 15/// so a caller can tell whether they still apply to an open buffer.
 16public struct IndexedHeading: Sendable, Hashable {
 17    public let location: HeadingLocation
 18    public let level: Int
 19    /// Titles from the top-level ancestor down to the heading itself.
 20    public let outlinePath: [String]
 21}
 22
 23public struct HeadingLocation: Sendable, Hashable {
 24    /// Locations are equal by where they are; the snippet is for showing them.
 25    public static func == (a: HeadingLocation, b: HeadingLocation) -> Bool {
 26        a.path == b.path && a.ordinal == b.ordinal && a.title == b.title && a.start == b.start && a.contentHash == b.contentHash
 27    }
 28
 29    public func hash(into hasher: inout Hasher) {
 30        hasher.combine(path)
 31        hasher.combine(ordinal)
 32        hasher.combine(start)
 33    }
 34
 35    public let path: String
 36    /// `fileOrdinal` for the file itself, before its first heading.
 37    public let ordinal: Int
 38    public let title: String
 39    public let start: Int
 40    public let contentHash: String
 41    /// The text around the match: a search's words, or a backlink's link.
 42    public var snippet: Snippet?
 43    /// The titles from the top-level heading down to this one; set by `search`, empty for the
 44    /// file itself.
 45    public var outlinePath: [String] = []
 46
 47    public init(path: String, ordinal: Int, title: String, start: Int, contentHash: String) {
 48        self.path = path
 49        self.ordinal = ordinal
 50        self.title = title
 51        self.start = start
 52        self.contentHash = contentHash
 53    }
 54
 55    public static let fileOrdinal = -1
 56
 57    /// The file before its first heading, titled by its name.
 58    public static func file(_ path: String, contentHash: String) -> HeadingLocation {
 59        HeadingLocation(path: path, ordinal: fileOrdinal, title: (path as NSString).lastPathComponent, start: 0, contentHash: contentHash)
 60    }
 61}
 62
 63/// One reconciliation's worth of changes, applied in a single transaction.
 64public struct IndexChange: Sendable {
 65    public var records: [FileRecord] = []
 66    /// Unchanged content with a new modification time.
 67    public var touches: [(path: String, mtime: Double)] = []
 68    /// Renamed files whose content didn't change.
 69    public var moves: [(from: String, to: String, mtime: Double)] = []
 70    public var removals: [String] = []
 71
 72    public init() {}
 73
 74    public var isEmpty: Bool { records.isEmpty && touches.isEmpty && moves.isEmpty && removals.isEmpty }
 75}
 76
 77/// The SQLite index. A cache: deleting it loses nothing that the files don't hold.
 78public final class IndexStore: Sendable {
 79    let database: DatabaseQueue
 80
 81    /// `path` nil opens an in-memory index.
 82    public init(path: String? = nil) throws {
 83        database = try path.map { try DatabaseQueue(path: $0) } ?? DatabaseQueue()
 84        try Self.migrator.migrate(database)
 85    }
 86
 87    static var migrator: DatabaseMigrator {
 88        var migrator = DatabaseMigrator()
 89        migrator.registerMigration("v1") { db in
 90            try db.execute(sql: """
 91                CREATE TABLE files (
 92                    id INTEGER PRIMARY KEY,
 93                    path TEXT NOT NULL UNIQUE,
 94                    root TEXT NOT NULL,
 95                    kind TEXT NOT NULL,
 96                    size INTEGER NOT NULL,
 97                    mtime REAL NOT NULL,
 98                    hash TEXT NOT NULL,
 99                    settings_version INTEGER NOT NULL,
100                    parsed_at REAL NOT NULL
101                );
102                CREATE INDEX files_root ON files(root);
103                CREATE TABLE headings (
104                    id INTEGER PRIMARY KEY,
105                    file_id INTEGER NOT NULL REFERENCES files(id) ON DELETE CASCADE,
106                    ordinal INTEGER NOT NULL,
107                    parent_ordinal INTEGER,
108                    start_offset INTEGER NOT NULL,
109                    end_offset INTEGER NOT NULL,
110                    level INTEGER NOT NULL,
111                    todo TEXT,
112                    is_done INTEGER NOT NULL,
113                    priority TEXT,
114                    title TEXT NOT NULL,
115                    outline_path TEXT NOT NULL,
116                    org_id TEXT,
117                    archived INTEGER NOT NULL
118                );
119                CREATE INDEX headings_file ON headings(file_id);
120                CREATE INDEX headings_org_id ON headings(org_id);
121                CREATE TABLE tags (
122                    heading_id INTEGER NOT NULL REFERENCES headings(id) ON DELETE CASCADE,
123                    tag TEXT NOT NULL,
124                    inherited INTEGER NOT NULL
125                );
126                CREATE INDEX tags_heading ON tags(heading_id);
127                CREATE TABLE properties (
128                    heading_id INTEGER NOT NULL REFERENCES headings(id) ON DELETE CASCADE,
129                    key TEXT NOT NULL,
130                    value TEXT NOT NULL,
131                    inherited INTEGER NOT NULL
132                );
133                CREATE INDEX properties_heading ON properties(heading_id);
134                CREATE TABLE timestamps (
135                    heading_id INTEGER NOT NULL REFERENCES headings(id) ON DELETE CASCADE,
136                    kind TEXT NOT NULL,
137                    start_at TEXT NOT NULL,
138                    end_at TEXT,
139                    repeater TEXT,
140                    warning TEXT
141                );
142                CREATE INDEX timestamps_heading ON timestamps(heading_id);
143                CREATE TABLE clocks (
144                    heading_id INTEGER NOT NULL REFERENCES headings(id) ON DELETE CASCADE,
145                    start_at TEXT NOT NULL,
146                    end_at TEXT,
147                    minutes INTEGER
148                );
149                CREATE INDEX clocks_heading ON clocks(heading_id);
150                CREATE TABLE links (
151                    heading_id INTEGER NOT NULL REFERENCES headings(id) ON DELETE CASCADE,
152                    type TEXT NOT NULL,
153                    target TEXT NOT NULL
154                );
155                CREATE INDEX links_heading ON links(heading_id);
156                CREATE VIRTUAL TABLE headings_fts USING fts5(title, body, tokenize = 'unicode61 remove_diacritics 2');
157                CREATE TRIGGER headings_fts_delete AFTER DELETE ON headings BEGIN
158                    DELETE FROM headings_fts WHERE rowid = old.id;
159                END;
160                """)
161        }
162        migrator.registerMigration("v2") { db in
163            // Links before a file's first heading; files are read again to fill it.
164            try db.execute(sql: """
165                CREATE TABLE file_links (
166                    file_id INTEGER NOT NULL REFERENCES files(id) ON DELETE CASCADE,
167                    type TEXT NOT NULL,
168                    target TEXT NOT NULL
169                );
170                CREATE INDEX file_links_file ON file_links(file_id);
171                UPDATE files SET settings_version = -1;
172                """)
173        }
174        migrator.registerMigration("v3") { db in
175            // File-level IDs and titles, for org-roam file nodes; files are read again to fill them.
176            try db.execute(sql: """
177                ALTER TABLE files ADD COLUMN org_id TEXT;
178                ALTER TABLE files ADD COLUMN title TEXT;
179                CREATE INDEX files_org_id ON files(org_id);
180                UPDATE files SET settings_version = -1;
181                """)
182        }
183        migrator.registerMigration("v4") { db in
184            // Text before a file's first heading, searched as the file; files are read again to fill it.
185            try db.execute(sql: """
186                CREATE VIRTUAL TABLE files_fts USING fts5(body, tokenize = 'unicode61 remove_diacritics 2');
187                CREATE TRIGGER files_fts_delete AFTER DELETE ON files BEGIN
188                    DELETE FROM files_fts WHERE rowid = old.id;
189                END;
190                UPDATE files SET settings_version = -1;
191                """)
192        }
193        migrator.registerMigration("v5") { db in
194            // File tags and org-roam properties, for file nodes; files are read again to fill them.
195            try db.execute(sql: """
196                ALTER TABLE files ADD COLUMN tags TEXT;
197                ALTER TABLE files ADD COLUMN roam_aliases TEXT;
198                ALTER TABLE files ADD COLUMN roam_refs TEXT;
199                ALTER TABLE files ADD COLUMN roam_exclude TEXT;
200                UPDATE files SET settings_version = -1;
201                """)
202        }
203        migrator.registerMigration("v6") { db in
204            // Denote's links in Markdown and text files, and Denote titles of text files; they are read again.
205            try db.execute(sql: "UPDATE files SET settings_version = -1 WHERE kind = 'text'")
206        }
207        return migrator
208    }
209
210    // MARK: - Writing
211
212    public func write(_ record: FileRecord) throws {
213        var change = IndexChange()
214        change.records = [record]
215        try apply(change)
216    }
217
218    public func apply(_ change: IndexChange) throws {
219        guard !change.isEmpty else { return }
220        try database.write { db in
221            for path in change.removals {
222                try db.execute(sql: "DELETE FROM files WHERE path = ?", arguments: [path])
223            }
224            for move in change.moves {
225                try db.execute(sql: "UPDATE files SET path = ?, mtime = ? WHERE path = ?", arguments: [move.to, move.mtime, move.from])
226            }
227            for touch in change.touches {
228                try db.execute(sql: "UPDATE files SET mtime = ? WHERE path = ?", arguments: [touch.mtime, touch.path])
229            }
230            for record in change.records {
231                try insert(record, db)
232            }
233        }
234    }
235
236    private func insert(_ record: FileRecord, _ db: Database) throws {
237        try db.execute(sql: "DELETE FROM files WHERE path = ?", arguments: [record.path])
238        try db.execute(
239            sql: """
240                INSERT INTO files (path, root, kind, size, mtime, hash, settings_version, parsed_at, org_id, title,
241                                   tags, roam_aliases, roam_refs, roam_exclude)
242                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
243                """,
244            arguments: [record.path, record.root, record.kind.rawValue, record.size, record.mtime, record.hash,
245                        record.settingsVersion, Date().timeIntervalSince1970, record.fileID, record.title,
246                        record.fileTags.isEmpty ? nil : record.fileTags.joined(separator: ":"),
247                        record.fileRoam.aliases, record.fileRoam.refs, record.fileRoam.exclude]
248        )
249        let fileID = db.lastInsertedRowID
250        if !record.preamble.allSatisfy(\.isWhitespace) {
251            try db.execute(sql: "INSERT INTO files_fts (rowid, body) VALUES (?, ?)", arguments: [fileID, record.preamble])
252        }
253        for link in record.links {
254            try db.execute(sql: "INSERT INTO file_links VALUES (?, ?, ?)", arguments: [fileID, link.type, link.target])
255        }
256        for heading in record.headings {
257            try db.execute(
258                sql: """
259                    INSERT INTO headings (file_id, ordinal, parent_ordinal, start_offset, end_offset, level, todo,
260                                          is_done, priority, title, outline_path, org_id, archived)
261                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
262                    """,
263                arguments: [fileID, heading.ordinal, heading.parent, heading.start, heading.end, heading.level, heading.todo,
264                            heading.isDone, heading.priority, heading.title, heading.outlinePath.joined(separator: "\u{1F}"),
265                            heading.orgID, heading.archived]
266            )
267            let id = db.lastInsertedRowID
268            try db.execute(sql: "INSERT INTO headings_fts (rowid, title, body) VALUES (?, ?, ?)", arguments: [id, heading.title, heading.body])
269            for tag in heading.tags {
270                try db.execute(sql: "INSERT INTO tags VALUES (?, ?, ?)", arguments: [id, tag.name, tag.inherited])
271            }
272            for property in heading.properties {
273                try db.execute(sql: "INSERT INTO properties VALUES (?, ?, ?, ?)", arguments: [id, property.key, property.value, property.inherited])
274            }
275            for stamp in heading.timestamps {
276                try db.execute(
277                    sql: "INSERT INTO timestamps VALUES (?, ?, ?, ?, ?, ?)",
278                    arguments: [id, stamp.kind.rawValue, stamp.start, stamp.end, stamp.repeater, stamp.warning]
279                )
280            }
281            for clock in heading.clocks {
282                try db.execute(sql: "INSERT INTO clocks VALUES (?, ?, ?, ?)", arguments: [id, clock.start, clock.end, clock.minutes])
283            }
284            for link in heading.links {
285                try db.execute(sql: "INSERT INTO links VALUES (?, ?, ?)", arguments: [id, link.type, link.target])
286            }
287        }
288    }
289
290    // MARK: - Reading
291
292    /// Indexed files under `root`, by path.
293    public func fileStates(root: String) throws -> [String: FileState] {
294        try database.read { db in
295            let rows = try Row.fetchAll(db, sql: "SELECT path, kind, size, mtime, hash, settings_version FROM files WHERE root = ?", arguments: [root])
296            var states: [String: FileState] = [:]
297            for row in rows {
298                states[row["path"]] = FileState(
299                    kind: FileKind(rawValue: row["kind"]) ?? .org,
300                    size: row["size"], mtime: row["mtime"], hash: row["hash"], settingsVersion: row["settings_version"]
301                )
302            }
303            return states
304        }
305    }
306
307    public func files() throws -> [(path: String, kind: FileKind)] {
308        try database.read { db in
309            try Row.fetchAll(db, sql: "SELECT path, kind FROM files ORDER BY path").map {
310                (path: $0["path"], kind: FileKind(rawValue: $0["kind"]) ?? .org)
311            }
312        }
313    }
314
315    // MARK: - Queries
316    //
317    // `overlay` holds records for open documents with unsaved edits, keyed by path. Their rows
318    // replace that file's indexed rows in every query.
319
320    /// Headings whose title or body contain every word of `query` as a word prefix, and files
321    /// whose text before the first heading does, best first, each with a snippet of the text
322    /// when the match is there.
323    public func search(_ query: String, overlay: [String: FileRecord] = [:], limit: Int = 50) throws -> [HeadingLocation] {
324        let terms = query.split(whereSeparator: \.isWhitespace).map(String.init)
325        guard !terms.isEmpty else { return [] }
326        let match = terms.map { "\"" + $0.replacingOccurrences(of: "\"", with: "\"\"") + "\"*" }.joined(separator: " ")
327        let prefixes = terms.flatMap(Self.words)
328        func withSnippet(_ location: HeadingLocation, _ body: String) -> HeadingLocation {
329            var location = location
330            location.snippet = Snippet(text: body, prefixes: prefixes)
331            return location
332        }
333        let indexed = try database.read { db in
334            let headings = try Row.fetchAll(
335                db,
336                sql: """
337                    SELECT f.path, f.hash, h.ordinal, h.title, h.start_offset, h.outline_path, headings_fts.body, bm25(headings_fts) AS rank
338                    FROM headings_fts
339                    JOIN headings h ON h.id = headings_fts.rowid
340                    JOIN files f ON f.id = h.file_id
341                    WHERE headings_fts MATCH ?
342                    ORDER BY rank
343                    LIMIT ?
344                    """,
345                arguments: [match, limit + overlay.count * 10]
346            ).map { row in
347                var found = withSnippet(location(row), row["body"])
348                found.outlinePath = (row["outline_path"] as String).split(separator: "\u{1F}", omittingEmptySubsequences: false).map(String.init)
349                return (location: found, rank: row["rank"] as Double)
350            }
351            let files = try Row.fetchAll(
352                db,
353                sql: """
354                    SELECT f.path, f.hash, f.title, files_fts.body, bm25(files_fts) AS rank
355                    FROM files_fts
356                    JOIN files f ON f.id = files_fts.rowid
357                    WHERE files_fts MATCH ?
358                    ORDER BY rank
359                    LIMIT ?
360                    """,
361                arguments: [match, limit + overlay.count]
362            ).map { (location: withSnippet(fileLocation($0["path"], title: $0["title"], hash: $0["hash"]), $0["body"]), rank: $0["rank"] as Double) }
363            return (headings + files).sorted { $0.rank < $1.rank }.map(\.location)
364        }
365        // Unsaved buffers get the same word-prefix matching as the full-text index.
366        func matches(_ text: String) -> Bool {
367            let words = Self.words(text)
368            return prefixes.allSatisfy { prefix in words.contains { $0.hasPrefix(prefix) } }
369        }
370        let live = overlay.values.sorted { $0.path < $1.path }.flatMap { record in
371            let file = matches(record.preamble) ? [withSnippet(fileLocation(record.path, title: record.title, hash: record.hash), record.preamble)] : []
372            return file + record.headings.filter { matches($0.title + "\n" + $0.body) }.map { heading in
373                var found = withSnippet(location(record, heading), heading.body)
374                found.outlinePath = heading.outlinePath
375                return found
376            }
377        }
378        return Array((live + indexed.filter { overlay[$0.path] == nil }).prefix(limit))
379    }
380
381    /// The file before its first heading, titled by its `#+TITLE` or else its name.
382    private func fileLocation(_ path: String, title: String?, hash: String) -> HeadingLocation {
383        let file = HeadingLocation.file(path, contentHash: hash)
384        guard let title, !title.isEmpty else { return file }
385        return HeadingLocation(path: path, ordinal: file.ordinal, title: title, start: 0, contentHash: hash)
386    }
387
388    /// Headings down to `maxLevel` in org files (not archives or conflict copies), with their
389    /// levels and outline paths, in file order: refile targets.
390    public func outline(maxLevel: Int) throws -> [IndexedHeading] {
391        try database.read { db in
392            try Row.fetchAll(
393                db,
394                sql: """
395                    SELECT f.path, f.hash, h.ordinal, h.title, h.start_offset, h.level, h.outline_path
396                    FROM headings h JOIN files f ON f.id = h.file_id
397                    WHERE h.level <= ? AND f.kind = 'org' ORDER BY f.path, h.ordinal
398                    """,
399                arguments: [maxLevel]
400            ).map { row in
401                IndexedHeading(
402                    location: location(row), level: row["level"],
403                    outlinePath: (row["outline_path"] as String).split(separator: "\u{1F}", omittingEmptySubsequences: false).map(String.init)
404                )
405            }
406        }
407    }
408
409    /// Headings with `:ID: id`. More than one means the ID is duplicated.
410    /// Every tag a heading has, most used first.
411    public func tags() throws -> [String] {
412        try database.read { db in
413            try String.fetchAll(db, sql: "SELECT tag FROM tags WHERE inherited = 0 GROUP BY tag ORDER BY count(*) DESC, tag")
414        }
415    }
416
417    /// Files with a heading tagged `tag` itself, not by inheritance: org-fc's flashcards for
418    /// `fc`. Unsaved buffers' in place of their files'.
419    public func files(withLocalTag tag: String, overlay: [String: FileRecord] = [:]) throws -> [String] {
420        let indexed = try database.read { db in
421            try String.fetchAll(db, sql: """
422                SELECT DISTINCT f.path FROM tags t JOIN headings h ON h.id = t.heading_id JOIN files f ON f.id = h.file_id
423                WHERE t.tag = ? AND t.inherited = 0 ORDER BY f.path
424                """, arguments: [tag])
425        }
426        let live = overlay.values.filter { $0.headings.contains { $0.tags.contains { $0.name == tag && !$0.inherited } } }.map(\.path)
427        return (indexed.filter { overlay[$0] == nil } + live).sorted()
428    }
429
430    public func headings(withID id: String, overlay: [String: FileRecord] = [:]) throws -> [HeadingLocation] {
431        let indexed = try database.read { db in
432            try Row.fetchAll(
433                db,
434                sql: """
435                    SELECT f.path, f.hash, h.ordinal, h.title, h.start_offset
436                    FROM headings h JOIN files f ON f.id = h.file_id
437                    WHERE h.org_id = ? ORDER BY f.path, h.ordinal
438                    """,
439                arguments: [id]
440            ).map(location)
441        }
442        let files = try database.read { db in
443            try Row.fetchAll(db, sql: "SELECT path, hash FROM files WHERE org_id = ? ORDER BY path", arguments: [id])
444                .map { HeadingLocation.file($0["path"], contentHash: $0["hash"]) }
445        }
446        let live = overlay.values.sorted { $0.path < $1.path }.flatMap { record in
447            (record.fileID == id ? [HeadingLocation.file(record.path, contentHash: record.hash)] : [])
448                + record.headings.filter { $0.orgID == id }.map { location(record, $0) }
449        }
450        return (files + indexed).filter { overlay[$0.path] == nil } + live
451    }
452
453    /// A heading or file with an ID: an org-roam node.
454    public struct Node: Sendable, Hashable {
455        public let id: String
456        public let title: String
457        public let location: HeadingLocation
458        /// `ROAM_ALIASES`: other titles the node is found by.
459        public var aliases: [String] = []
460        /// `ROAM_REFS`: links and `cite:` keys the node stands for.
461        public var refs: [String] = []
462        /// A file's `#+FILETAGS`; a heading's tags, inherited ones first.
463        public var tags: [String] = []
464    }
465
466    /// Every heading and file with an ID and without `ROAM_EXCLUDE`, files first, unsaved
467    /// buffers' in place of their files'. A file's title is its `#+TITLE`, else its name
468    /// without `.org`.
469    public func nodes(overlay: [String: FileRecord] = [:]) throws -> [Node] {
470        func fileTitle(_ path: String, _ title: String?) -> String { title ?? ((path as NSString).lastPathComponent as NSString).deletingPathExtension }
471        func node(_ id: String, _ title: String, _ location: HeadingLocation, _ roam: RoamProperties, _ tags: [String]) -> Node? {
472            roam.excluded ? nil : Node(id: id, title: title, location: location, aliases: roam.aliasList, refs: roam.refList, tags: tags)
473        }
474        func tags(_ joined: String?) -> [String] { joined?.split(separator: ":").map(String.init) ?? [] }
475        let indexed = try database.read { db in
476            let files = try Row.fetchAll(
477                db,
478                sql: "SELECT path, hash, org_id, title, tags, roam_aliases, roam_refs, roam_exclude FROM files WHERE org_id IS NOT NULL AND kind = 'org' ORDER BY path"
479            ).compactMap { row in
480                node(row["org_id"], fileTitle(row["path"], row["title"]), .file(row["path"], contentHash: row["hash"]),
481                     RoamProperties(aliases: row["roam_aliases"], refs: row["roam_refs"], exclude: row["roam_exclude"]), tags(row["tags"]))
482            }
483            let headings = try Row.fetchAll(
484                db,
485                sql: """
486                    SELECT f.path, f.hash, h.ordinal, h.title, h.start_offset, h.org_id,
487                        (SELECT value FROM properties WHERE heading_id = h.id AND key = 'ROAM_ALIASES' AND inherited = 0) AS aliases,
488                        (SELECT value FROM properties WHERE heading_id = h.id AND key = 'ROAM_REFS' AND inherited = 0) AS refs,
489                        (SELECT value FROM properties WHERE heading_id = h.id AND key = 'ROAM_EXCLUDE' AND inherited = 0) AS exclude,
490                        (SELECT group_concat(tag, ':') FROM (SELECT tag FROM tags WHERE heading_id = h.id ORDER BY rowid)) AS tags
491                    FROM headings h JOIN files f ON f.id = h.file_id
492                    WHERE h.org_id IS NOT NULL AND f.kind = 'org' ORDER BY f.path, h.ordinal
493                    """
494            ).compactMap { row in
495                node(row["org_id"], row["title"], location(row), RoamProperties(aliases: row["aliases"], refs: row["refs"], exclude: row["exclude"]), tags(row["tags"]))
496            }
497            return files + headings
498        }
499        let live = overlay.values.sorted { $0.path < $1.path }.flatMap { record in
500            (record.fileID.flatMap { node($0, fileTitle(record.path, record.title), .file(record.path, contentHash: record.hash), record.fileRoam, record.fileTags) }.map { [$0] } ?? [])
501                + record.headings.compactMap { heading in
502                    heading.orgID.flatMap { node($0, heading.title, location(record, heading), RoamProperties(heading.properties), heading.tags.map(\.name)) }
503                }
504        }
505        return indexed.filter { overlay[$0.location.path] == nil } + live
506    }
507
508    /// Every Org, Markdown (`.md`) and text file with a Denote identifier in its name, as a
509    /// node with that identifier, titled by its front matter (an Org file's `#+TITLE`, a
510    /// Markdown file's first heading without one), else its name; unsaved buffers' titles in
511    /// place of their files'.
512    public func denoteNodes(overlay: [String: FileRecord] = [:]) throws -> [Node] {
513        func node(_ path: String, _ title: String?, _ hash: String) -> Node? {
514            guard Denote.FileType(path: path) != nil, let id = Denote.identifier(ofFile: path) else { return nil }
515            return Node(id: id, title: title ?? ((path as NSString).lastPathComponent as NSString).deletingPathExtension, location: .file(path, contentHash: hash))
516        }
517        let indexed = try database.read { db in
518            try Row.fetchAll(db, sql: "SELECT path, hash, title FROM files WHERE kind IN ('org', 'text') ORDER BY path").compactMap { node($0["path"], $0["title"], $0["hash"]) }
519        }
520        let live = overlay.values.sorted { $0.path < $1.path }.compactMap { node($0.path, $0.title, $0.hash) }
521        return indexed.filter { overlay[$0.location.path] == nil } + live
522    }
523
524    /// Where every heading with an ID and without `ROAM_EXCLUDE` starts and ends, subtree
525    /// included, by file: the text each of org-roam's heading nodes covers. Unsaved buffers' in place of their files'.
526    public func nodeSections(overlay: [String: FileRecord] = [:]) throws -> [String: [(id: String, range: Range<Int>)]] {
527        var sections: [String: [(id: String, range: Range<Int>)]] = [:]
528        try database.read { db in
529            let rows = try Row.fetchAll(db, sql: """
530                SELECT f.path, h.org_id, h.start_offset, h.end_offset,
531                    (SELECT value FROM properties WHERE heading_id = h.id AND key = 'ROAM_EXCLUDE' AND inherited = 0) AS exclude
532                FROM headings h JOIN files f ON f.id = h.file_id
533                WHERE h.org_id IS NOT NULL AND f.kind = 'org' ORDER BY f.path, h.ordinal
534                """)
535            for row in rows where overlay[row["path"]] == nil && !RoamProperties(exclude: row["exclude"]).excluded {
536                sections[row["path"], default: []].append((row["org_id"], (row["start_offset"] as Int)..<(row["end_offset"] as Int)))
537            }
538        }
539        for record in overlay.values {
540            sections[record.path] = record.headings.compactMap { heading in
541                RoamProperties(heading.properties).excluded ? nil : heading.orgID.map { ($0, heading.start..<heading.end) }
542            }
543        }
544        return sections
545    }
546
547    /// Every link and the heading it's in, or the file for links before its first heading,
548    /// unsaved buffers' in place of their files'. Of Markdown and text files, Denote's links.
549    public func links(overlay: [String: FileRecord] = [:]) throws -> [(source: HeadingLocation, target: String)] {
550        let indexed = try database.read { db in
551            try Row.fetchAll(
552                db,
553                sql: """
554                    SELECT f.path, f.hash, -1 AS ordinal, '' AS title, 0 AS start_offset, l.target
555                    FROM file_links l JOIN files f ON f.id = l.file_id WHERE f.kind IN ('org', 'text')
556                    UNION ALL
557                    SELECT f.path, f.hash, h.ordinal, h.title, h.start_offset, l.target
558                    FROM links l JOIN headings h ON h.id = l.heading_id JOIN files f ON f.id = h.file_id
559                    WHERE f.kind IN ('org', 'text') ORDER BY 1, 3
560                    """
561            ).map { row in
562                let location = location(row)
563                return (source: location.ordinal == HeadingLocation.fileOrdinal ? .file(location.path, contentHash: location.contentHash) : location,
564                        target: row["target"] as String)
565            }
566        }
567        let live = overlay.values.sorted { $0.path < $1.path }.flatMap { record in
568            record.links.map { (source: HeadingLocation.file(record.path, contentHash: record.hash), target: $0.target) }
569                + record.headings.flatMap { heading in heading.links.map { (source: location(record, heading), target: $0.target) } }
570        }
571        return indexed.filter { overlay[$0.source.path] == nil } + live
572    }
573
574    /// The text under a heading, or before a file's first heading, that a location from
575    /// `links` or `search` stands for.
576    public func text(of location: HeadingLocation, overlay: [String: FileRecord] = [:]) throws -> String? {
577        if let record = overlay[location.path] {
578            if location.ordinal == HeadingLocation.fileOrdinal { return record.preamble }
579            return record.headings.first { $0.ordinal == location.ordinal }?.body
580        }
581        return try database.read { db in
582            if location.ordinal == HeadingLocation.fileOrdinal {
583                return try String.fetchOne(db, sql: """
584                    SELECT files_fts.body FROM files_fts JOIN files f ON f.id = files_fts.rowid WHERE f.path = ?
585                    """, arguments: [location.path])
586            }
587            return try String.fetchOne(db, sql: """
588                SELECT headings_fts.body FROM headings_fts JOIN headings h ON h.id = headings_fts.rowid
589                JOIN files f ON f.id = h.file_id WHERE f.path = ? AND h.ordinal = ?
590                """, arguments: [location.path, location.ordinal])
591        }
592    }
593
594    /// IDs used by more than one heading.
595    public func duplicateIDs(overlay: [String: FileRecord] = [:]) throws -> [String: [HeadingLocation]] {
596        let indexed = try database.read { db in
597            try Row.fetchAll(
598                db,
599                sql: """
600                    SELECT h.org_id, f.path, f.hash, h.ordinal, h.title, h.start_offset
601                    FROM headings h JOIN files f ON f.id = h.file_id
602                    WHERE h.org_id IN (SELECT org_id FROM headings WHERE org_id IS NOT NULL GROUP BY org_id HAVING count(*) > 1)
603                       OR (h.org_id IS NOT NULL AND ? > 0)
604                    ORDER BY f.path, h.ordinal
605                    """,
606                arguments: [overlay.count]
607            ).map { (id: $0["org_id"] as String, location: location($0)) }
608        }
609        var byID: [String: [HeadingLocation]] = [:]
610        for row in indexed where overlay[row.location.path] == nil {
611            byID[row.id, default: []].append(row.location)
612        }
613        for record in overlay.values.sorted(by: { $0.path < $1.path }) {
614            for heading in record.headings {
615                if let id = heading.orgID { byID[id, default: []].append(location(record, heading)) }
616            }
617        }
618        return byID.filter { $0.value.count > 1 }
619    }
620
621    /// Lower-cased runs of letters and digits, as the unicode61 tokenizer splits them.
622    static func words(_ text: String) -> [String] {
623        text.lowercased().split { !$0.isLetter && !$0.isNumber }.map(String.init)
624    }
625
626    private func location(_ row: Row) -> HeadingLocation {
627        HeadingLocation(path: row["path"], ordinal: row["ordinal"], title: row["title"], start: row["start_offset"], contentHash: row["hash"])
628    }
629
630    private func location(_ record: FileRecord, _ heading: HeadingRecord) -> HeadingLocation {
631        HeadingLocation(path: record.path, ordinal: heading.ordinal, title: heading.title, start: heading.start, contentHash: record.hash)
632    }
633}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form