restores Helder in all its glory
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
import Foundation
|
||||
|
||||
public enum Fuzzy {
|
||||
/// Case-insensitive subsequence match: the matched character offsets in `text`, or nil.
|
||||
public static func match(_ query: String, in text: String) -> [Int]? {
|
||||
let q = Array(query.lowercased())
|
||||
var indices: [Int] = []
|
||||
var qi = 0
|
||||
for (offset, ch) in text.lowercased().enumerated() where qi < q.count {
|
||||
if ch == q[qi] {
|
||||
indices.append(offset)
|
||||
qi += 1
|
||||
}
|
||||
}
|
||||
return qi == q.count ? indices : nil
|
||||
}
|
||||
|
||||
/// File-name results: basename matches before path matches, then earlier first hit, then shorter path.
|
||||
public static func rankFileNames(query: String, paths: [String], showHidden: Bool) -> [FileNameMatch] {
|
||||
let term = query.trimmingCharacters(in: .whitespaces)
|
||||
guard !term.isEmpty else { return [] }
|
||||
var out: [FileNameMatch] = []
|
||||
for path in paths {
|
||||
if !showHidden && PathUtils.isHidden(path) { continue }
|
||||
if let indices = match(term, in: PathUtils.basename(path)) {
|
||||
out.append(FileNameMatch(path: path, nameIndices: indices, rank: 0, position: indices[0]))
|
||||
} else if let indices = match(term, in: path) {
|
||||
out.append(FileNameMatch(path: path, nameIndices: nil, rank: 1, position: indices[0]))
|
||||
}
|
||||
}
|
||||
return out.sorted {
|
||||
($0.rank, $0.position, $0.path.count) < ($1.rank, $1.position, $1.path.count)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public enum InFileSearch {
|
||||
/// Case-insensitive substring hits in one buffer, for the search overlay's "this file" column.
|
||||
public static func hits(query: String, in text: String) -> [ContentHit] {
|
||||
let term = query.trimmingCharacters(in: .whitespaces)
|
||||
guard !term.isEmpty else { return [] }
|
||||
var hits: [ContentHit] = []
|
||||
for (index, line) in text.components(separatedBy: "\n").enumerated() {
|
||||
if let range = line.range(of: term, options: .caseInsensitive) {
|
||||
hits.append(ContentHit(line: index + 1, text: line, matchOffset: line.utf16.distance(from: line.startIndex, to: range.lowerBound)))
|
||||
}
|
||||
}
|
||||
return hits
|
||||
}
|
||||
|
||||
/// Extension chips for the result set: most matches first, then alphabetical, capped at 12.
|
||||
public static func extensionCounts(paths: [String]) -> [(ext: String, count: Int)] {
|
||||
var counts: [String: Int] = [:]
|
||||
for path in paths {
|
||||
let e = FileType.ext(path)
|
||||
if !e.isEmpty { counts[e, default: 0] += 1 }
|
||||
}
|
||||
return counts.sorted { $0.value != $1.value ? $0.value > $1.value : $0.key < $1.key }
|
||||
.prefix(SearchLimits.maxExtensionChips)
|
||||
.map { (ext: $0.key, count: $0.value) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import Foundation
|
||||
|
||||
/// One `"type":"match"` event from `rg --json`.
|
||||
public struct RipgrepMatch: Sendable, Equatable {
|
||||
/// The path as ripgrep printed it (absolute when the search root was absolute).
|
||||
public var path: String
|
||||
public var line: Int
|
||||
/// The line text without its trailing newline.
|
||||
public var text: String
|
||||
/// Byte offset of the first submatch, as ripgrep reports it.
|
||||
public var byteOffset: Int
|
||||
|
||||
public init(path: String, line: Int, text: String, byteOffset: Int) {
|
||||
self.path = path
|
||||
self.line = line
|
||||
self.text = text
|
||||
self.byteOffset = byteOffset
|
||||
}
|
||||
}
|
||||
|
||||
public enum RipgrepJSON {
|
||||
/// Decodes one line of `rg --json` output; nil for every event that is not a match.
|
||||
///
|
||||
/// An event carrying `path.bytes` or `lines.bytes` (base64, non-UTF-8 data) is skipped.
|
||||
/// Offsets stay in bytes here; `ContentGrouper` turns them into UTF-16.
|
||||
public static func parseLine(_ line: String) -> RipgrepMatch? {
|
||||
guard line.contains("\"match\""),
|
||||
let event = try? JSONDecoder().decode(Event.self, from: Data(line.utf8)),
|
||||
event.type == "match",
|
||||
let data = event.data,
|
||||
let path = data.path?.text,
|
||||
var text = data.lines?.text
|
||||
else { return nil }
|
||||
if text.unicodeScalars.last == "\n" { text.unicodeScalars.removeLast() }
|
||||
if text.unicodeScalars.last == "\r" { text.unicodeScalars.removeLast() }
|
||||
return RipgrepMatch(path: path, line: data.line_number ?? 0, text: text, byteOffset: data.submatches?.first?.start ?? 0)
|
||||
}
|
||||
|
||||
/// The slice of an `rg --json` event this reader needs; a `bytes` field decodes as a nil `text`.
|
||||
private struct Event: Decodable {
|
||||
struct TextField: Decodable {
|
||||
var text: String?
|
||||
}
|
||||
struct Submatch: Decodable {
|
||||
var start: Int
|
||||
}
|
||||
struct Payload: Decodable {
|
||||
var path: TextField?
|
||||
var lines: TextField?
|
||||
var line_number: Int?
|
||||
var submatches: [Submatch]?
|
||||
}
|
||||
var type: String
|
||||
var data: Payload?
|
||||
}
|
||||
|
||||
/// Makes a ripgrep path relative to the project root, "/"-separated.
|
||||
public static func relativePath(_ path: String, root: String) -> String {
|
||||
let base = root.hasSuffix("/") ? root : root + "/"
|
||||
return path.hasPrefix(base) ? String(path.dropFirst(base.count)) : path
|
||||
}
|
||||
}
|
||||
|
||||
/// Collects matches into per-file groups in first-seen order, honouring the search limits.
|
||||
public struct ContentGrouper: Sendable {
|
||||
public let root: String
|
||||
public private(set) var groups: [ContentGroup] = []
|
||||
|
||||
public init(root: String) {
|
||||
self.root = root
|
||||
}
|
||||
|
||||
/// Adds a match: new files beyond `SearchLimits.maxFiles` are dropped, the line text is
|
||||
/// capped at `maxLineLength`, and the byte offset becomes a clamped UTF-16 `matchOffset`.
|
||||
public mutating func add(_ match: RipgrepMatch) {
|
||||
let path = RipgrepJSON.relativePath(match.path, root: root)
|
||||
let index: Int
|
||||
if let existing = indexByPath[path] {
|
||||
index = existing
|
||||
} else {
|
||||
guard groups.count < SearchLimits.maxFiles else { return }
|
||||
index = groups.count
|
||||
indexByPath[path] = index
|
||||
groups.append(ContentGroup(path: path, hits: []))
|
||||
}
|
||||
guard groups[index].hits.count < SearchLimits.maxHitsPerFile else { return }
|
||||
let text = ContentGrouper.capped(match.text)
|
||||
let offset = ContentGrouper.utf16Offset(ofByte: match.byteOffset, in: match.text)
|
||||
groups[index].hits.append(ContentHit(line: match.line, text: text, matchOffset: min(offset, text.utf16.count)))
|
||||
}
|
||||
|
||||
private var indexByPath: [String: Int] = [:]
|
||||
|
||||
/// The line cut to `SearchLimits.maxLineLength` UTF-16 units, never inside a surrogate pair.
|
||||
static func capped(_ text: String) -> String {
|
||||
let utf16 = text.utf16
|
||||
guard utf16.count > SearchLimits.maxLineLength else { return text }
|
||||
var end = utf16.index(utf16.startIndex, offsetBy: SearchLimits.maxLineLength)
|
||||
while end > utf16.startIndex && UTF16.isTrailSurrogate(utf16[end]) { end = utf16.index(before: end) }
|
||||
return String(utf16[..<end]) ?? String(text.prefix(SearchLimits.maxLineLength))
|
||||
}
|
||||
|
||||
/// ripgrep counts UTF-8 bytes; the views count UTF-16 units.
|
||||
static func utf16Offset(ofByte byteOffset: Int, in text: String) -> Int {
|
||||
let utf8 = text.utf8
|
||||
guard byteOffset > 0 else { return 0 }
|
||||
guard byteOffset < utf8.count else { return text.utf16.count }
|
||||
var index = utf8.index(utf8.startIndex, offsetBy: byteOffset)
|
||||
while index > utf8.startIndex && UTF8.isContinuation(utf8[index]) {
|
||||
index = utf8.index(before: index)
|
||||
}
|
||||
return text.utf16.distance(from: text.utf16.startIndex, to: index)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import Foundation
|
||||
|
||||
/// One matching line.
|
||||
public struct ContentHit: Sendable, Equatable {
|
||||
/// 1-based line number.
|
||||
public var line: Int
|
||||
/// The line text, capped at `SearchLimits.maxLineLength` characters.
|
||||
public var text: String
|
||||
/// UTF-16 offset of the first match in `text`, clamped to its length.
|
||||
public var matchOffset: Int
|
||||
|
||||
public init(line: Int, text: String, matchOffset: Int) {
|
||||
self.line = line
|
||||
self.text = text
|
||||
self.matchOffset = matchOffset
|
||||
}
|
||||
}
|
||||
|
||||
/// All hits in one file, in the order ripgrep reported them.
|
||||
public struct ContentGroup: Sendable, Equatable, Identifiable {
|
||||
public var path: String
|
||||
public var hits: [ContentHit]
|
||||
public var id: String { path }
|
||||
|
||||
public init(path: String, hits: [ContentHit]) {
|
||||
self.path = path
|
||||
self.hits = hits
|
||||
}
|
||||
}
|
||||
|
||||
/// A file-name match in the search overlay's right column.
|
||||
public struct FileNameMatch: Sendable, Equatable {
|
||||
public var path: String
|
||||
/// Matched character offsets in the basename; nil when only the full path matched.
|
||||
public var nameIndices: [Int]?
|
||||
/// 0 = basename match, 1 = path-only match; lower sorts first.
|
||||
public var rank: Int
|
||||
/// Offset of the first matched character; lower sorts first.
|
||||
public var position: Int
|
||||
|
||||
public init(path: String, nameIndices: [Int]?, rank: Int, position: Int) {
|
||||
self.path = path
|
||||
self.nameIndices = nameIndices
|
||||
self.rank = rank
|
||||
self.position = position
|
||||
}
|
||||
}
|
||||
|
||||
public enum SearchLimits {
|
||||
/// Content search starts at two characters; the in-file column at one.
|
||||
public static let minContentQuery = 2
|
||||
public static let maxFiles = 400
|
||||
public static let maxLineLength = 1000
|
||||
public static let maxHitsPerFile = 50
|
||||
public static let maxFileNameResults = 40
|
||||
public static let maxInFileResults = 200
|
||||
public static let maxExtensionChips = 12
|
||||
/// Keystroke debounce before a content search runs.
|
||||
public static let debounceMilliseconds = 120
|
||||
}
|
||||
Reference in New Issue
Block a user