File tree Expand file tree Collapse file tree 1 file changed +14
-7
lines changed
Sources/CodeEditSourceEditor/Find Expand file tree Collapse file tree 1 file changed +14
-7
lines changed Original file line number Diff line number Diff line change @@ -436,29 +436,36 @@ extension FindViewController: FindPanelDelegate {
436436 guard let cursorPosition = target? . cursorPositions. first else { return nil }
437437 let start = cursorPosition. range. location
438438
439- // Binary search for the nearest match
440- var left = 0 , right = matchRanges. count - 1
441- var bestIndex : Int ?
442- var bestDiff = Int . max
439+ var left = 0
440+ var right = matchRanges. count - 1
441+ var bestIndex = - 1
442+ var bestDiff = Int . max // Stores the closest difference
443443
444444 while left <= right {
445445 let mid = left + ( right - left) / 2
446446 let midStart = matchRanges [ mid] . location
447- let diff = abs ( midStart - targetPosition )
447+ let diff = abs ( midStart - start )
448448
449+ // If it's an exact match, return immediately
450+ if diff == 0 {
451+ return mid
452+ }
453+
454+ // If this is the closest so far, update the best index
449455 if diff < bestDiff {
450456 bestDiff = diff
451457 bestIndex = mid
452458 }
453459
454- if midStart < targetPosition {
460+ // Move left or right based on the cursor position
461+ if midStart < start {
455462 left = mid + 1
456463 } else {
457464 right = mid - 1
458465 }
459466 }
460467
461- return bestIndex
468+ return bestIndex >= 0 ? bestIndex : nil
462469 }
463470
464471 // Only re-find the part of the file that changed upwards
You can’t perform that action at this time.
0 commit comments