Sources/OrgIndex/IndexStore.swift

7e98a2ca205eea3866d838a6b794b9a2e5627cfd
orgstar/Sources/OrgIndex/IndexStore.swift

603 lines · 30933 bytes

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