import Foundation /// A line of the page that starts with one `=` directly followed by a title, as `=update on this`. public struct Bookmark: Equatable, Sendable { /// The text after the `=`, without the spaces at its end. public var title: String /// The whole line, the `=` included, without its newline. public var range: NSRange public init(title: String, range: NSRange) { self.title = title self.range = range } /// The bookmarks of a text, top to bottom. public static func find(in text: NSString) -> [Bookmark] { var bookmarks: [Bookmark] = [] var start = 0 while start < text.length { if text.character(at: start) == 0x3D, let bookmark = bookmark(in: text, at: start) { bookmarks.append(bookmark) } let next = text.range(of: "\n=", range: NSRange(location: start, length: text.length - start)) guard next.location != NSNotFound else { break } start = next.location + 1 } return bookmarks } private static func bookmark(in text: NSString, at start: Int) -> Bookmark? { guard start + 1 < text.length else { return nil } let first = text.character(at: start + 1) guard first != 0x3D, let scalar = Unicode.Scalar(first), !CharacterSet.whitespacesAndNewlines.contains(scalar) else { return nil } let newline = text.range(of: "\n", range: NSRange(location: start, length: text.length - start)) let end = newline.location == NSNotFound ? text.length : newline.location let range = NSRange(location: start, length: end - start) let title = text.substring(with: NSRange(location: start + 1, length: end - start - 1)).trimmingCharacters(in: .whitespaces) return title.isEmpty ? nil : Bookmark(title: title, range: range) } }