Commit 0c3d86f109

0c3d86f10908663b74dce7a6f0bd0503fe820846

parent: 9dbb9003d3

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-14 04:10 UTC

Search Notes: text before the first heading; snippets with highlighted matches

The full-text index had one row per heading, so text before a file's first
heading, and the whole of a file without headings, was not searchable. Each
file's text before the first heading now goes in files_fts (migration v4,
which reindexes), and search merges its matches with the headings' by bm25,
as file results titled by #+TITLE or the file name. Unsaved buffers'
preambles are matched as their headings are.

Each result carries a Snippet: the passage around the first matched word on
one line, about 160 characters, with the matched words marked (compared
without case or diacritics, as the index does). Search Notes on the Mac and
Search on iOS show it under the title with the matches in bold.

Closes #76

Layout: unified · split

Sources/OrgIndex/FileRecord.swift +6 −3
@@ -114,6 +114,8 @@ public struct FileRecord: Sendable, Equatable {
114114 public let fileID: String?
115115 /// `#+TITLE`, joined with spaces when there are several.
116116 public let title: String?
117 /// The text before the first heading, searched as the file itself.
118 public let preamble: String
117119
118120 public static func hash(_ bytes: [UInt8]) -> String {
119121 SHA256.hash(data: Data(bytes)).map { String(format: "%02x", $0) }.joined()
@@ -130,7 +132,7 @@ public struct FileRecord: Sendable, Equatable {
130132 var resolved = settings
131133 resolved.org = settings.org.resolvingSetupFiles(in: source.text, path: path, read: OrgSettings.readFile)
132134 self.settingsVersion = Self.settingsVersion(settings, text: source.text, setupKeywords: resolved.org.setupKeywords)
133 (headings, links, fileID, title) = kind == .conflict ? ([], [], nil, nil) : Self.rows(source.text, settings: resolved)
135 (headings, links, fileID, title, preamble) = kind == .conflict ? ([], [], nil, nil, "") : Self.rows(source.text, settings: resolved)
134136 }
135137
136138 /// The settings version a file's rows are built under: the index's, with the keywords of
@@ -166,11 +168,12 @@ public struct FileRecord: Sendable, Equatable {
166168 links = []
167169 fileID = nil
168170 title = nil
171 preamble = ""
169172 }
170173
171174 public static func unreadHash(size: Int, mtime: Double) -> String { "unread:\(size):\(mtime)" }
172175
173 static func rows(_ text: String, settings: IndexSettings) -> (headings: [HeadingRecord], links: [LinkRow], fileID: String?, title: String?) {
176 static func rows(_ text: String, settings: IndexSettings) -> (headings: [HeadingRecord], links: [LinkRow], fileID: String?, title: String?, preamble: String) {
174177 let model = DocumentModel(tree: OrgParser.parse(text, defaults: settings.org), settings: settings.semantic)
175178 let utf16 = text.utf16
176179 func slice(_ range: Range<Int>) -> String {
@@ -212,7 +215,7 @@ public struct FileRecord: Sendable, Equatable {
212215 let fileID = model.property("ID", of: nil)?.value.trimmingCharacters(in: .whitespaces)
213216 let zeroth = model.headings.first.map { slice(0..<$0.sectionRange.lowerBound) } ?? text
214217 let titles = zeroth.matches(of: /(?im)^[ \t]*#\+title:[ \t]*(.*?)[ \t]*$/).map { String($0.1) }
215 return (headings, model.links.map(linkRow), fileID?.isEmpty == false ? fileID : nil, titles.isEmpty ? nil : titles.joined(separator: " "))
218 return (headings, model.links.map(linkRow), fileID?.isEmpty == false ? fileID : nil, titles.isEmpty ? nil : titles.joined(separator: " "), zeroth)
216219 }
217220
218221 static func linkRow(_ target: String) -> LinkRow {
Sources/OrgIndex/IndexStore.swift +54 −10
@@ -26,6 +26,8 @@ public struct HeadingLocation: Sendable, Hashable {
2626 public let title: String
2727 public let start: Int
2828 public let contentHash: String
29 /// The text around the match, for search results whose match is in the text.
30 public internal(set) var snippet: Snippet?
2931
3032 public init(path: String, ordinal: Int, title: String, start: Int, contentHash: String) {
3133 self.path = path
@@ -163,6 +165,16 @@ public final class IndexStore: Sendable {
163165 UPDATE files SET settings_version = -1;
164166 """)
165167 }
168 migrator.registerMigration("v4") { db in
169 // Text before a file's first heading, searched as the file; files are read again to fill it.
170 try db.execute(sql: """
171 CREATE VIRTUAL TABLE files_fts USING fts5(body, tokenize = 'unicode61 remove_diacritics 2');
172 CREATE TRIGGER files_fts_delete AFTER DELETE ON files BEGIN
173 DELETE FROM files_fts WHERE rowid = old.id;
174 END;
175 UPDATE files SET settings_version = -1;
176 """)
177 }
166178 return migrator
167179 }
168180
@@ -203,6 +215,9 @@ public final class IndexStore: Sendable {
203215 record.settingsVersion, Date().timeIntervalSince1970, record.fileID, record.title]
204216 )
205217 let fileID = db.lastInsertedRowID
218 if !record.preamble.allSatisfy(\.isWhitespace) {
219 try db.execute(sql: "INSERT INTO files_fts (rowid, body) VALUES (?, ?)", arguments: [fileID, record.preamble])
220 }
206221 for link in record.links {
207222 try db.execute(sql: "INSERT INTO file_links VALUES (?, ?, ?)", arguments: [fileID, link.type, link.target])
208223 }
@@ -270,37 +285,66 @@ public final class IndexStore: Sendable {
270285 // `overlay` holds records for open documents with unsaved edits, keyed by path. Their rows
271286 // replace that file's indexed rows in every query.
272287
273 /// Headings whose title or body contain every word of `query` as a word prefix.
288 /// Headings whose title or body contain every word of `query` as a word prefix, and files
289 /// whose text before the first heading does, best first, each with a snippet of the text
290 /// when the match is there.
274291 public func search(_ query: String, overlay: [String: FileRecord] = [:], limit: Int = 50) throws -> [HeadingLocation] {
275292 let terms = query.split(whereSeparator: \.isWhitespace).map(String.init)
276293 guard !terms.isEmpty else { return [] }
277294 let match = terms.map { "\"" + $0.replacingOccurrences(of: "\"", with: "\"\"") + "\"*" }.joined(separator: " ")
295 let prefixes = terms.flatMap(Self.words)
296 func withSnippet(_ location: HeadingLocation, _ body: String) -> HeadingLocation {
297 var location = location
298 location.snippet = Snippet(text: body, prefixes: prefixes)
299 return location
300 }
278301 let indexed = try database.read { db in
279 try Row.fetchAll(
302 let headings = try Row.fetchAll(
280303 db,
281304 sql: """
282 SELECT f.path, f.hash, h.ordinal, h.title, h.start_offset
305 SELECT f.path, f.hash, h.ordinal, h.title, h.start_offset, headings_fts.body, bm25(headings_fts) AS rank
283306 FROM headings_fts
284307 JOIN headings h ON h.id = headings_fts.rowid
285308 JOIN files f ON f.id = h.file_id
286309 WHERE headings_fts MATCH ?
287 ORDER BY bm25(headings_fts)
310 ORDER BY rank
288311 LIMIT ?
289312 """,
290313 arguments: [match, limit + overlay.count * 10]
291 ).map(location)
314 ).map { (location: withSnippet(location($0), $0["body"]), rank: $0["rank"] as Double) }
315 let files = try Row.fetchAll(
316 db,
317 sql: """
318 SELECT f.path, f.hash, f.title, files_fts.body, bm25(files_fts) AS rank
319 FROM files_fts
320 JOIN files f ON f.id = files_fts.rowid
321 WHERE files_fts MATCH ?
322 ORDER BY rank
323 LIMIT ?
324 """,
325 arguments: [match, limit + overlay.count]
326 ).map { (location: withSnippet(fileLocation($0["path"], title: $0["title"], hash: $0["hash"]), $0["body"]), rank: $0["rank"] as Double) }
327 return (headings + files).sorted { $0.rank < $1.rank }.map(\.location)
292328 }
293329 // Unsaved buffers get the same word-prefix matching as the full-text index.
294 let prefixes = terms.flatMap(Self.words)
330 func matches(_ text: String) -> Bool {
331 let words = Self.words(text)
332 return prefixes.allSatisfy { prefix in words.contains { $0.hasPrefix(prefix) } }
333 }
295334 let live = overlay.values.sorted { $0.path < $1.path }.flatMap { record in
296 record.headings.filter { heading in
297 let words = Self.words(heading.title + "\n" + heading.body)
298 return prefixes.allSatisfy { prefix in words.contains { $0.hasPrefix(prefix) } }
299 }.map { location(record, $0) }
335 let file = matches(record.preamble) ? [withSnippet(fileLocation(record.path, title: record.title, hash: record.hash), record.preamble)] : []
336 return file + record.headings.filter { matches($0.title + "\n" + $0.body) }.map { withSnippet(location(record, $0), $0.body) }
300337 }
301338 return Array((live + indexed.filter { overlay[$0.path] == nil }).prefix(limit))
302339 }
303340
341 /// The file before its first heading, titled by its `#+TITLE` or else its name.
342 private func fileLocation(_ path: String, title: String?, hash: String) -> HeadingLocation {
343 let file = HeadingLocation.file(path, contentHash: hash)
344 guard let title, !title.isEmpty else { return file }
345 return HeadingLocation(path: path, ordinal: file.ordinal, title: title, start: 0, contentHash: hash)
346 }
347
304348 /// Headings down to `maxLevel` in org files (not archives or conflict copies), with their
305349 /// levels and outline paths, in file order: refile targets.
306350 public func outline(maxLevel: Int) throws -> [IndexedHeading] {
Sources/OrgIndex/Snippet.swift added +51
@@ -0,0 +1,51 @@
1import Foundation
2
3/// A short passage around the first word a search matched, on one line, with the matched words
4/// marked: what a search result shows under its title.
5public struct Snippet: Sendable, Hashable {
6 public let text: String
7 /// The matched words, as UTF-16 ranges of `text`.
8 public let matches: [Range<Int>]
9
10 /// The passage of `text` around the first word starting with one of `prefixes`, compared
11 /// without case or diacritics as the full-text index compares them; nil when none does.
12 public init?(text: String, prefixes: [String], width: Int = 160) {
13 let folded = prefixes.map(Self.fold).filter { !$0.isEmpty }
14 let line = text.split(whereSeparator: \.isWhitespace).joined(separator: " ") as NSString
15 guard !folded.isEmpty, line.length > 0 else { return nil }
16 var words: [(range: NSRange, matches: Bool)] = []
17 let pattern = try! NSRegularExpression(pattern: "[\\p{L}\\p{N}]+")
18 for match in pattern.matches(in: line as String, range: NSRange(location: 0, length: line.length)) {
19 let word = Self.fold(line.substring(with: match.range))
20 words.append((match.range, folded.contains { word.hasPrefix($0) }))
21 }
22 guard let first = words.first(where: \.matches) else { return nil }
23 // Start a few words before the match, at a word's start; end at the last whole word.
24 var start = max(0, first.range.location - 50)
25 if start > 0 { start = words.first { $0.range.location >= start }?.range.location ?? first.range.location }
26 var end = min(line.length, start + width)
27 if end < line.length { end = words.last { NSMaxRange($0.range) <= end }.map { NSMaxRange($0.range) } ?? end }
28 let lead = start > 0 ? "…" : ""
29 self.text = lead + line.substring(with: NSRange(location: start, length: end - start)) + (end < line.length ? "…" : "")
30 let shift = lead.utf16.count - start
31 matches = words.filter { $0.matches && $0.range.location >= start && NSMaxRange($0.range) <= end }
32 .map { ($0.range.location + shift)..<(NSMaxRange($0.range) + shift) }
33 }
34
35 static func fold(_ word: String) -> String {
36 word.folding(options: [.caseInsensitive, .diacriticInsensitive], locale: nil)
37 }
38
39 /// `text` with the matched words strongly emphasized, for a SwiftUI `Text`.
40 public var attributed: AttributedString {
41 var result = AttributedString(text)
42 let utf16 = text.utf16
43 for match in matches {
44 let lower = String.Index(utf16.index(utf16.startIndex, offsetBy: match.lowerBound), within: text)
45 let upper = String.Index(utf16.index(utf16.startIndex, offsetBy: match.upperBound), within: text)
46 guard let lower, let upper, let range = Range(lower..<upper, in: result) else { continue }
47 result[range].inlinePresentationIntent = .stronglyEmphasized
48 }
49 return result
50 }
51}
Sources/Orgstar/SearchViews.swift +4 −1
@@ -15,7 +15,10 @@ struct SearchResults: View {
1515 } label: {
1616 VStack(alignment: .leading, spacing: 2) {
1717 Text(location.title.isEmpty ? "(untitled)" : location.title).lineLimit(1)
18 Text((location.path as NSString).lastPathComponent).font(.caption).foregroundStyle(.secondary)
18 if let snippet = location.snippet {
19 Text(snippet.attributed).font(.callout).foregroundStyle(.secondary).lineLimit(3)
20 }
21 Text((location.path as NSString).lastPathComponent).font(.caption).foregroundStyle(.tertiary)
1922 }
2023 }
2124 .buttonStyle(.plain)
Sources/OrgstarMobile/SearchScreen.swift +6 −3
@@ -24,13 +24,16 @@ struct SearchScreen: View {
2424 }
2525 }
2626 let headings = Perf.measure("search.headings") { workspace.search(trimmed, overlay: workspace.overlay(session.openDocuments)) }
27 Section("Headings") {
28 if headings.isEmpty { Text("No headings match").foregroundStyle(.secondary) }
27 Section("Notes") {
28 if headings.isEmpty { Text("No notes match").foregroundStyle(.secondary) }
2929 ForEach(headings, id: \.self) { location in
3030 NavigationLink(value: ReaderRoute.heading(location)) {
3131 VStack(alignment: .leading, spacing: 2) {
3232 Text(location.title.isEmpty ? "(untitled)" : location.title).lineLimit(2)
33 Text((location.path as NSString).lastPathComponent).font(.caption).foregroundStyle(.secondary)
33 if let snippet = location.snippet {
34 Text(snippet.attributed).font(.subheadline).foregroundStyle(.secondary).lineLimit(3)
35 }
36 Text((location.path as NSString).lastPathComponent).font(.caption).foregroundStyle(.tertiary)
3437 }
3538 }
3639 }
Tests/OrgIndexTests/IndexStoreTests.swift +45
@@ -1,3 +1,4 @@
1import Foundation
12import OrgCore
23import Testing
34@testable import OrgIndex
@@ -13,6 +14,50 @@ struct IndexStoreTests {
1314 #expect(try store.search(" ").isEmpty)
1415 }
1516
17 @Test func searchFindsTextBeforeTheFirstHeading() throws {
18 let store = try IndexStore()
19 try store.write(record("/notes/flat.org", "#+TITLE: Field notes\nThe heron came back to the pond.\n"))
20 try store.write(record("/notes/b.org", "Preamble about otters.\n* Rivers\nwater\n"))
21 let flat = try store.search("heron")
22 #expect(flat.map(\.title) == ["Field notes"])
23 #expect(flat.first?.ordinal == HeadingLocation.fileOrdinal && flat.first?.start == 0)
24 #expect(try store.search("otters").map(\.path) == ["/notes/b.org"])
25 #expect(try store.search("water").map(\.title) == ["Rivers"])
26 // Rewritten and removed files take their preamble rows with them.
27 try store.write(record("/notes/flat.org", "Nothing here.\n"))
28 #expect(try store.search("heron").isEmpty)
29 var change = IndexChange()
30 change.removals = ["/notes/b.org"]
31 try store.apply(change)
32 #expect(try store.search("otters").isEmpty)
33 // Unsaved text before the first heading is searched too.
34 let overlay = ["/notes/flat.org": record("/notes/flat.org", "Kingfishers now.\n")]
35 #expect(try store.search("kingfish", overlay: overlay).map(\.ordinal) == [HeadingLocation.fileOrdinal])
36 }
37
38 @Test func snippetsMarkTheMatches() throws {
39 let store = try IndexStore()
40 try store.write(record("/notes/a.org", "* Trip\nWe walked along the river bank and saw a heron fishing in the reeds near the old mill.\n"))
41 let hit = try #require(try store.search("heron reed").first)
42 let snippet = try #require(hit.snippet)
43 let marked = snippet.matches.map { (snippet.text as NSString).substring(with: NSRange($0)) }
44 #expect(marked == ["heron", "reeds"])
45 #expect(snippet.text.contains("saw a heron fishing"))
46 // A title-only match has no snippet.
47 #expect(try store.search("trip").first?.snippet == nil)
48 }
49
50 @Test func snippetWindow() {
51 let long = (1...80).map { "word\($0)" }.joined(separator: " ")
52 let snippet = Snippet(text: long + "\nneedle\n" + long, prefixes: ["needle"])
53 #expect(snippet != nil)
54 #expect(snippet!.text.hasPrefix("…") && snippet!.text.hasSuffix("…"))
55 #expect(snippet!.text.utf16.count < 200)
56 #expect(!snippet!.text.contains("\n"))
57 #expect(Snippet(text: "nothing", prefixes: ["zzz"]) == nil)
58 #expect(Snippet(text: "Héron here", prefixes: ["heron"])?.matches.count == 1)
59 }
60
1661 @Test func rewritingAFileReplacesItsRows() throws {
1762 let store = try IndexStore()
1863 try store.write(record("/notes/a.org", "* Old title\n"))
docs/manual/guide/01-files-and-folders.org +4 −4
@@ -175,13 +175,13 @@ View ▸ Show Tab Bar shows a row of tabs above each pane, one per buffer that p
175175
176176The search field in the toolbar searches every org file in your folders. Click it or choose Edit ▸ Search Notes (=⇧⌘F=; =SPC /= or =SPC s p= in Doom normal state) and type.
177177
178While the field holds text, the outline pane shows the results in place of the outline. Each result is a heading, with its file's name below it. Click a result to open the file at that heading. Clear the field to get the outline back.
178While the field holds text, the outline pane shows the results in place of the outline. Each result is a heading, or a file when the match is in the text before its first heading, titled by its =#+TITLE= or its name. Under the title is the passage the words were found in, with them in bold, then the file's name. Click a result to open the file at that heading. Clear the field to get the outline back.
179179
180180How matching works:
181181
182- orgstar searches heading titles and the text under each heading, in =.org= and =.org_archive= files. Text before the first heading and files that aren't org are not searched. Syncthing conflict copies are not searched.
183- Each word you type matches words that start with it: =proj= finds =project= and =projection=.
184- Every word must match within the same heading.
182- orgstar searches heading titles, the text under each heading and the text before a file's first heading, in =.org= and =.org_archive= files. Files that aren't org are not searched. Syncthing conflict copies are not searched.
183- Each word you type matches words that start with it, ignoring case and accents: =proj= finds =project= and =projection=.
184- Every word must match within the same heading, or within the text before the first heading.
185185- Up to 50 results show, best matches first.
186186- Open buffers with unsaved edits are searched as they are in the buffer, not as they are on disk.
187187
docs/manual/guide/14-ios.org +1 −1
@@ -177,7 +177,7 @@ See [[file:03-keys.org][Keys and commands]] for the Emacs bindings.
177177Search finds:
178178
179179- Files :: up to eight org files whose path matches what you type, ranked as Quick Open ranks them on the Mac.
180- Headings :: headings whose title or text contains your words, including unsaved edits in the open file.
180- Notes :: headings whose title or text contains your words, and files whose text before the first heading does, including unsaved edits in the open file. Under each is the passage the words were found in, with them in bold.
181181
182182Tap a result to open it in the reader. A heading result opens at that heading.
183183
docs/manual/quickstart.org +1 −1
@@ -80,7 +80,7 @@ first folder. See [[file:guide/08-capture.org][Capture]].
8080
8181* Search
8282
83=⇧⌘F= searches the text of every indexed file. Results open at the matching line.
83=⇧⌘F= searches the headings and text of every indexed file. Each result shows the passage it matched; click it to open the file there.
8484
8585* Next
8686