Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -33,21 +33,43 @@ public enum SQLCompletionWindow {
let located = SQLStatementScanner.locatedStatementAtCursor(
in: source as String, cursorPosition: caret, grammar: grammar
)
let end = max(caret, min(NSMaxRange(located.range), caret + radius))
var start = min(located.offset, caret)
return cut(source, around: caret, statement: located.range, grammar: grammar)
}

// For a caller that already holds the caret's statement, located on this text with this grammar.
@concurrent
public static func cut(
_ text: String,
around offset: Int,
statement: NSRange,
grammar: SQLLexicalGrammar
) async -> (text: String, start: Int)? {
cut(text as NSString, around: offset, statement: statement, grammar: grammar)
}

// Costs the statement up to the end of the cut, not the document before it.
public static func cut(
_ text: NSString,
around offset: Int,
statement: NSRange,
grammar: SQLLexicalGrammar
) -> (text: String, start: Int)? {
let length = text.length
let caret = min(max(offset, 0), length)
let end = max(caret, min(NSMaxRange(statement), caret + radius, length))
var start = min(max(statement.location, 0), caret)
if caret - start > radius {
guard let resumed = codeStart(in: source, units: units, from: start, around: caret, grammar: grammar) else {
guard let resumed = codeStart(in: text, from: start, around: caret, grammar: grammar) else {
return nil
}
start = resumed
}
return (source.substring(with: NSRange(location: start, length: end - start)), start)
return (text.substring(with: NSRange(location: start, length: end - start)), start)
}

// A start glued to the word before it is passed over: `E'` and `$$` read differently with nothing in front.
private static func codeStart(
in text: NSString,
units: [UInt16],
from statementStart: Int,
around caret: Int,
grammar: SQLLexicalGrammar
Expand All @@ -58,7 +80,7 @@ public enum SQLCompletionWindow {
while index < caret {
if index >= target {
if firstCodePosition == nil { firstCodePosition = index }
if !SqlDollarQuote.isIdentifierContinuation(units[index - 1]) { return index }
if !SqlDollarQuote.isIdentifierContinuation(text.character(at: index - 1)) { return index }
}
guard let span = SQLNonCodeSpan.span(at: index, in: text, grammar: grammar),
span.kind != .executableComment else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,45 @@ struct LongSpanCase: Sendable, CustomTestStringConvertible {
let engine: String
}

struct LocatedCutCase: Sendable, CustomTestStringConvertible {
let testDescription: String
let text: String
let engine: String
}

private final class CountingString: NSString {
private let base: NSString
private(set) var unitsRead = 0

init(_ string: String) {
base = string as NSString
super.init()
}

override init() {
base = ""
super.init()
}

required init?(coder: NSCoder) {
nil
}

override var length: Int {
base.length
}

override func character(at index: Int) -> unichar {
unitsRead += 1
return base.character(at: index)
}

override func getCharacters(_ buffer: UnsafeMutablePointer<unichar>, range: NSRange) {
unitsRead += range.length
base.getCharacters(buffer, range: range)
}
}

struct SQLCompletionWindowTests {
static let notes = String(repeating: "notes about the nightly load and its retries\n", count: 140)
static let body = String(repeating: " PERFORM pg_sleep(0);\n", count: 300)
Expand Down Expand Up @@ -132,4 +171,80 @@ struct SQLCompletionWindowTests {
func statementBreak(text: String, offset: Int, suppressed: Bool) {
#expect(SQLCompletionTriggerPolicy.suppressesAfterStatementBreak(in: text as NSString, at: offset) == suppressed)
}

static let locatedCutCases: [LocatedCutCase] = [
LocatedCutCase(testDescription: "short text", text: "SELECT * FROM or", engine: "ANSI"),
LocatedCutCase(testDescription: "long statement", text: String(repeating: "x", count: 12_000), engine: "ANSI"),
LocatedCutCase(
testDescription: "last of many statements",
text: "SELECT 1;\n" + String(repeating: "SELECT 2;\n", count: 2_000) + "SELECT * FROM or",
engine: "ANSI"
),
LocatedCutCase(
testDescription: "token boundary",
text: "SELECT " + String(repeating: "alpha, ", count: 1_000) + "o FROM t WHERE x",
engine: "ANSI"
),
LocatedCutCase(
testDescription: "quoted name",
text: "SELECT * FROM \"" + String(repeating: "n", count: 6_000) + " Det",
engine: "PostgreSQL"
),
LocatedCutCase(testDescription: "long block comment", text: "/*\n" + notes + "SELECT * FROM or", engine: "PostgreSQL"),
LocatedCutCase(
testDescription: "dollar body",
text: "CREATE FUNCTION f() RETURNS void AS $$\nBEGIN\n" + body + " SELECT * FROM or",
engine: "PostgreSQL"
),
LocatedCutCase(testDescription: "open string", text: "INSERT INTO notes VALUES ('" + notes + "SELECT * FROM or", engine: "MySQL"),
LocatedCutCase(
testDescription: "code after a dollar body",
text: "CREATE FUNCTION f() RETURNS void AS $$\nBEGIN\n" + body + "END\n$$ LANGUAGE plpgsql;\nSELECT * FROM or",
engine: "PostgreSQL"
),
LocatedCutCase(
testDescription: "code after a closed string",
text: "INSERT INTO notes VALUES ('" + notes + "');\nSELECT * FROM or",
engine: "MySQL"
),
LocatedCutCase(
testDescription: "comment across the cut",
text: "SELECT a, /* " + notes + " it's */ b FROM orders WHERE st",
engine: "PostgreSQL"
),
LocatedCutCase(
testDescription: "MySQL delimiter",
text: "DELIMITER //\nCREATE PROCEDURE p() BEGIN SELECT 1; END //\nDELIMITER ;\nSELECT * FROM or",
engine: "MySQL"
)
]

@Test("A cut from the located statement equals a cut from the whole text", arguments: SQLCompletionWindowTests.locatedCutCases)
func cutFromALocatedStatementEqualsTheWholeTextCut(_ example: LocatedCutCase) {
let text = example.text as NSString
let grammar = SQLLexicalGrammar.engine(example.engine)
let carets = Set([0, text.length / 3, text.length / 2, text.length - 1, text.length].filter { $0 >= 0 })
for caret in carets.sorted() {
let located = SQLStatementScanner.locatedStatementAtCursor(
in: example.text, cursorPosition: caret, grammar: grammar
)
let whole = SQLCompletionWindow.cut(text, around: caret, grammar: grammar)
let fromStatement = SQLCompletionWindow.cut(text, around: caret, statement: located.range, grammar: grammar)
#expect(fromStatement?.text == whole?.text, "caret \(caret)")
#expect(fromStatement?.start == whole?.start, "caret \(caret)")
}
}

@Test("A cut from the located statement near the end of a long script reads only that statement and the radius")
func cutFromALocatedStatementReadsOnlyItsStatement() {
let script = String(repeating: "SELECT id, name FROM users WHERE id = 1;\n", count: 10_000) + "SELECT * FROM or"
let text = CountingString(script)
let caret = text.length
let located = SQLStatementScanner.locatedStatementAtCursor(in: script, cursorPosition: caret, grammar: .ansi)

let window = SQLCompletionWindow.cut(text, around: caret, statement: located.range, grammar: .ansi)

#expect(window?.text == "\nSELECT * FROM or")
#expect(text.unitsRead <= located.range.length + SQLCompletionWindow.radius)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ extension FindViewController {

// Smooth out the animation by placing the find panel just outside the correct position before animating.
installFindPanel().isHidden = false
viewModel.refreshMatchesIfStale()
findPanelVerticalConstraint?.constant = resolvedTopPadding - viewModel.panelHeight

view.layoutSubtreeIfNeeded()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ extension FindPanelViewModel {
guard let target = target, let emphasisManager = target.textView.emphasisManager else {
return
}
refreshMatchesIfStale()

// Clear existing emphases
emphasisManager.removeEmphases(for: EmphasisGroup.find)
Expand All @@ -32,6 +33,7 @@ extension FindPanelViewModel {
}

func flashCurrentMatch() {
refreshMatchesIfStale()
guard let target = target,
let emphasisManager = target.textView.emphasisManager,
let currentFindMatchIndex else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,11 @@ extension FindPanelViewModel {
/// Performs a find operation on the find target and updates both the ``findMatches`` array and the emphasis
/// manager's emphases.
func find() {
staleMatchesCaret = nil
findMatches = searchResults().map(\.range)

// Find the nearest match to the current cursor position
currentFindMatchIndex = getNearestEmphasisIndex(matchRanges: findMatches)
currentFindMatchIndex = getNearestEmphasisIndex(matchRanges: findMatches, caret: caretLocation)

// Only add emphasis layers if the find panel is focused
if isFocused {
Expand All @@ -28,8 +29,36 @@ extension FindPanelViewModel {
/// so the stored matches would otherwise point into text that is gone.
func documentDidReplace() {
clearMatchEmphases()
if defersSearch, !findText.isEmpty {
staleMatchesCaret = StaleMatchesCaret(location: caretLocation)
return
}
staleMatchesCaret = nil
findMatches = searchResults().map(\.range)
currentFindMatchIndex = getNearestEmphasisIndex(matchRanges: findMatches)
currentFindMatchIndex = getNearestEmphasisIndex(matchRanges: findMatches, caret: caretLocation)
}

func findAfterEdit() {
if defersSearch {
staleMatchesCaret = StaleMatchesCaret(location: caretLocation)
} else {
find()
}
}

func refreshMatchesIfStale() {
guard let stale = staleMatchesCaret else { return }
staleMatchesCaret = nil
findMatches = searchResults().map(\.range)
currentFindMatchIndex = getNearestEmphasisIndex(matchRanges: findMatches, caret: stale.location)
}

private var defersSearch: Bool {
!isShowingFindPanel && !isFocused
}

private var caretLocation: Int? {
target?.cursorPositions.first?.range.location
}

/// The find text's matches in the document as it is now. Empty when there is no target, no find text, or a
Expand Down Expand Up @@ -81,13 +110,12 @@ extension FindPanelViewModel {

// MARK: - Get Nearest Emphasis Index

private func getNearestEmphasisIndex(matchRanges: [NSRange]) -> Int? {
private func getNearestEmphasisIndex(matchRanges: [NSRange], caret: Int?) -> Int? {
// order the array as follows
// Found: 1 -> 2 -> 3 -> 4
// Cursor: |
// Result: 3 -> 4 -> 1 -> 2
guard let cursorPosition = target?.cursorPositions.first else { return nil }
let start = cursorPosition.range.location
guard let start = caret else { return nil }

var left = 0
var right = matchRanges.count - 1
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ extension FindPanelViewModel {

private func moveMatch(forwards: Bool) {
guard let target = target else { return }
refreshMatchesIfStale()

guard !findMatches.isEmpty else {
showWrapNotification(forwards: forwards, error: true, targetView: target.findPanelTargetView)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ extension FindPanelViewModel {
/// Matches are searched for again after the edit rather than shifted by hand: a pattern can stop or start matching
/// around the replacement, and a stored range past the end of the text is a crash in the text storage.
func replace() {
refreshMatchesIfStale()
guard let target, canReplace,
let index = currentFindMatchIndex, findMatches.indices.contains(index) else {
return
Expand Down Expand Up @@ -52,6 +53,8 @@ extension FindPanelViewModel {
/// match is replaced once, so text a replacement inserts is never searched again.
func replaceAll() {
guard let target, canReplace else { return }
// All searches the text it edits, so matches the panel never showed need no search of their own.
staleMatchesCaret = nil

let text = target.textView.string
let replacements = searchResults().map {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,14 @@ class FindPanelViewModel: ObservableObject {
/// Set while Replace or All edits the document, which searches once when the edit is done.
var isReplacingMatches = false

// Set when the document changed while the panel was hidden and unfocused. Nothing shows the matches then, so the
// search waits for the next command that reads them and uses the caret the edit left.
var staleMatchesCaret: StaleMatchesCaret?

struct StaleMatchesCaret {
let location: Int?
}

/// Replace is withheld from a document that is read-only, as the native find bar withholds it. With no target
/// there is nothing to edit either way, and Replace and All already do nothing.
var canReplace: Bool {
Expand Down Expand Up @@ -95,11 +103,9 @@ class FindPanelViewModel: ObservableObject {

// MARK: - Text Listeners

/// Find target's text content changed, we need to re-search the contents and emphasize results.
@objc private func textDidChange() {
// Only update if we have find text
if !findText.isEmpty, !isReplacingMatches, !isReplayingUndo {
find()
findAfterEdit()
}
}

Expand All @@ -112,7 +118,7 @@ class FindPanelViewModel: ObservableObject {
!findText.isEmpty else {
return
}
find()
findAfterEdit()
}

private var isReplayingUndo: Bool {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ extension TextView {
// MARK: Text Ranges

override open func accessibilityNumberOfCharacters() -> Int {
string.count
textStorage.length
}

override open func accessibilityRange(forLine line: Int) -> NSRange {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -370,7 +370,8 @@ open class TextView: NSView, NSTextContent {

editorUndoManager = CEUndoManager(textView: self)

layoutManager.layoutLines()
// Unhosted, `visibleRect` is infinite, so the default band would be the whole document.
layoutManager.layoutLines(in: bounds)
setUpDragGesture()
}

Expand Down
Loading
Loading