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 {
114 public let fileID: String? 114 public let fileID: String?
115 /// `#+TITLE`, joined with spaces when there are several. 115 /// `#+TITLE`, joined with spaces when there are several.
116 public let title: String? 116 public let title: String?
117 /// The text before the first heading, searched as the file itself.
118 public let preamble: String
117 119
118 public static func hash(_ bytes: [UInt8]) -> String { 120 public static func hash(_ bytes: [UInt8]) -> String {
119 SHA256.hash(data: Data(bytes)).map { String(format: "%02x", $0) }.joined() 121 SHA256.hash(data: Data(bytes)).map { String(format: "%02x", $0) }.joined()
@@ -130,7 +132,7 @@ public struct FileRecord: Sendable, Equatable {
130 var resolved = settings 132 var resolved = settings
131 resolved.org = settings.org.resolvingSetupFiles(in: source.text, path: path, read: OrgSettings.readFile) 133 resolved.org = settings.org.resolvingSetupFiles(in: source.text, path: path, read: OrgSettings.readFile)
132 self.settingsVersion = Self.settingsVersion(settings, text: source.text, setupKeywords: resolved.org.setupKeywords) 134 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)
134 } 136 }
135 137
136 /// The settings version a file's rows are built under: the index's, with the keywords of 138 /// 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 {
166 links = [] 168 links = []
167 fileID = nil 169 fileID = nil
168 title = nil 170 title = nil
171 preamble = ""
169 } 172 }
170 173
171 public static func unreadHash(size: Int, mtime: Double) -> String { "unread:\(size):\(mtime)" } 174 public static func unreadHash(size: Int, mtime: Double) -> String { "unread:\(size):\(mtime)" }
172 175
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) {
174 let model = DocumentModel(tree: OrgParser.parse(text, defaults: settings.org), settings: settings.semantic) 177 let model = DocumentModel(tree: OrgParser.parse(text, defaults: settings.org), settings: settings.semantic)
175 let utf16 = text.utf16 178 let utf16 = text.utf16
176 func slice(_ range: Range<Int>) -> String { 179 func slice(_ range: Range<Int>) -> String {
@@ -212,7 +215,7 @@ public struct FileRecord: Sendable, Equatable {
212 let fileID = model.property("ID", of: nil)?.value.trimmingCharacters(in: .whitespaces) 215 let fileID = model.property("ID", of: nil)?.value.trimmingCharacters(in: .whitespaces)
213 let zeroth = model.headings.first.map { slice(0..<$0.sectionRange.lowerBound) } ?? text 216 let zeroth = model.headings.first.map { slice(0..<$0.sectionRange.lowerBound) } ?? text
214 let titles = zeroth.matches(of: /(?im)^[ \t]*#\+title:[ \t]*(.*?)[ \t]*$/).map { String($0.1) } 217 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)
216 } 219 }
217 220
218 static func linkRow(_ target: String) -> LinkRow { 221 static func linkRow(_ target: String) -> LinkRow {
Sources/OrgIndex/IndexStore.swift +54 −10
@@ -26,6 +26,8 @@ public struct HeadingLocation: Sendable, Hashable {
26 public let title: String 26 public let title: String
27 public let start: Int 27 public let start: Int
28 public let contentHash: String 28 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?
29 31
30 public init(path: String, ordinal: Int, title: String, start: Int, contentHash: String) { 32 public init(path: String, ordinal: Int, title: String, start: Int, contentHash: String) {
31 self.path = path 33 self.path = path
@@ -163,6 +165,16 @@ public final class IndexStore: Sendable {
163 UPDATE files SET settings_version = -1; 165 UPDATE files SET settings_version = -1;
164 """) 166 """)
165 } 167 }
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 }
166 return migrator 178 return migrator
167 } 179 }
168 180
@@ -203,6 +215,9 @@ public final class IndexStore: Sendable {
203 record.settingsVersion, Date().timeIntervalSince1970, record.fileID, record.title] 215 record.settingsVersion, Date().timeIntervalSince1970, record.fileID, record.title]
204 ) 216 )
205 let fileID = db.lastInsertedRowID 217 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 }
206 for link in record.links { 221 for link in record.links {
207 try db.execute(sql: "INSERT INTO file_links VALUES (?, ?, ?)", arguments: [fileID, link.type, link.target]) 222 try db.execute(sql: "INSERT INTO file_links VALUES (?, ?, ?)", arguments: [fileID, link.type, link.target])
208 } 223 }
@@ -270,37 +285,66 @@ public final class IndexStore: Sendable {
270 // `overlay` holds records for open documents with unsaved edits, keyed by path. Their rows 285 // `overlay` holds records for open documents with unsaved edits, keyed by path. Their rows
271 // replace that file's indexed rows in every query. 286 // replace that file's indexed rows in every query.
272 287
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.
274 public func search(_ query: String, overlay: [String: FileRecord] = [:], limit: Int = 50) throws -> [HeadingLocation] { 291 public func search(_ query: String, overlay: [String: FileRecord] = [:], limit: Int = 50) throws -> [HeadingLocation] {
275 let terms = query.split(whereSeparator: \.isWhitespace).map(String.init) 292 let terms = query.split(whereSeparator: \.isWhitespace).map(String.init)
276 guard !terms.isEmpty else { return [] } 293 guard !terms.isEmpty else { return [] }
277 let match = terms.map { "\"" + $0.replacingOccurrences(of: "\"", with: "\"\"") + "\"*" }.joined(separator: " ") 294 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 }
278 let indexed = try database.read { db in 301 let indexed = try database.read { db in
279 try Row.fetchAll( 302 let headings = try Row.fetchAll(
280 db, 303 db,
281 sql: """ 304 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
283 FROM headings_fts 306 FROM headings_fts
284 JOIN headings h ON h.id = headings_fts.rowid 307 JOIN headings h ON h.id = headings_fts.rowid
285 JOIN files f ON f.id = h.file_id 308 JOIN files f ON f.id = h.file_id
286 WHERE headings_fts MATCH ? 309 WHERE headings_fts MATCH ?
287 ORDER BY bm25(headings_fts) 310 ORDER BY rank
288 LIMIT ? 311 LIMIT ?
289 """, 312 """,
290 arguments: [match, limit + overlay.count * 10] 313 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)
292 } 328 }
293 // Unsaved buffers get the same word-prefix matching as the full-text index. 329 // 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 }
295 let live = overlay.values.sorted { $0.path < $1.path }.flatMap { record in 334 let live = overlay.values.sorted { $0.path < $1.path }.flatMap { record in
296 record.headings.filter { heading in 335 let file = matches(record.preamble) ? [withSnippet(fileLocation(record.path, title: record.title, hash: record.hash), record.preamble)] : []
297 let words = Self.words(heading.title + "\n" + heading.body) 336 return file + record.headings.filter { matches($0.title + "\n" + $0.body) }.map { withSnippet(location(record, $0), $0.body) }
298 return prefixes.allSatisfy { prefix in words.contains { $0.hasPrefix(prefix) } }
299 }.map { location(record, $0) }
300 } 337 }
301 return Array((live + indexed.filter { overlay[$0.path] == nil }).prefix(limit)) 338 return Array((live + indexed.filter { overlay[$0.path] == nil }).prefix(limit))
302 } 339 }
303 340
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
304 /// Headings down to `maxLevel` in org files (not archives or conflict copies), with their 348 /// Headings down to `maxLevel` in org files (not archives or conflict copies), with their
305 /// levels and outline paths, in file order: refile targets. 349 /// levels and outline paths, in file order: refile targets.
306 public func outline(maxLevel: Int) throws -> [IndexedHeading] { 350 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 {
15 } label: { 15 } label: {
16 VStack(alignment: .leading, spacing: 2) { 16 VStack(alignment: .leading, spacing: 2) {
17 Text(location.title.isEmpty ? "(untitled)" : location.title).lineLimit(1) 17 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)
19 } 22 }
20 } 23 }
21 .buttonStyle(.plain) 24 .buttonStyle(.plain)
Sources/OrgstarMobile/SearchScreen.swift +6 −3
@@ -24,13 +24,16 @@ struct SearchScreen: View {
24 } 24 }
25 } 25 }
26 let headings = Perf.measure("search.headings") { workspace.search(trimmed, overlay: workspace.overlay(session.openDocuments)) } 26 let headings = Perf.measure("search.headings") { workspace.search(trimmed, overlay: workspace.overlay(session.openDocuments)) }
27 Section("Headings") { 27 Section("Notes") {
28 if headings.isEmpty { Text("No headings match").foregroundStyle(.secondary) } 28 if headings.isEmpty { Text("No notes match").foregroundStyle(.secondary) }
29 ForEach(headings, id: \.self) { location in 29 ForEach(headings, id: \.self) { location in
30 NavigationLink(value: ReaderRoute.heading(location)) { 30 NavigationLink(value: ReaderRoute.heading(location)) {
31 VStack(alignment: .leading, spacing: 2) { 31 VStack(alignment: .leading, spacing: 2) {
32 Text(location.title.isEmpty ? "(untitled)" : location.title).lineLimit(2) 32 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)
34 } 37 }
35 } 38 }
36 } 39 }
Tests/OrgIndexTests/IndexStoreTests.swift +45
@@ -1,3 +1,4 @@
1import Foundation
1import OrgCore 2import OrgCore
2import Testing 3import Testing
3@testable import OrgIndex 4@testable import OrgIndex
@@ -13,6 +14,50 @@ struct IndexStoreTests {
13 #expect(try store.search(" ").isEmpty) 14 #expect(try store.search(" ").isEmpty)
14 } 15 }
15 16
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
16 @Test func rewritingAFileReplacesItsRows() throws { 61 @Test func rewritingAFileReplacesItsRows() throws {
17 let store = try IndexStore() 62 let store = try IndexStore()
18 try store.write(record("/notes/a.org", "* Old title\n")) 63 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
175 175
176The 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. 176The 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.
177 177
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.
179 179
180How matching works: 180How matching works:
181 181
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. 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: =proj= finds =project= and =projection=. 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. 184- Every word must match within the same heading, or within the text before the first heading.
185- Up to 50 results show, best matches first. 185- Up to 50 results show, best matches first.
186- Open buffers with unsaved edits are searched as they are in the buffer, not as they are on disk. 186- Open buffers with unsaved edits are searched as they are in the buffer, not as they are on disk.
187 187
docs/manual/guide/14-ios.org +1 −1
@@ -177,7 +177,7 @@ See [[file:03-keys.org][Keys and commands]] for the Emacs bindings.
177Search finds: 177Search finds:
178 178
179- Files :: up to eight org files whose path matches what you type, ranked as Quick Open ranks them on the Mac. 179- 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.
181 181
182Tap a result to open it in the reader. A heading result opens at that heading. 182Tap a result to open it in the reader. A heading result opens at that heading.
183 183
docs/manual/quickstart.org +1 −1
@@ -80,7 +80,7 @@ first folder. See [[file:guide/08-capture.org][Capture]].
80 80
81* Search 81* Search
82 82
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.
84 84
85* Next 85* Next
86 86