63 lines
2.7 KiB
Swift
63 lines
2.7 KiB
Swift
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) }
|
|
}
|
|
}
|