diff --git a/packages/codemirror/src/find_replace.ts b/packages/codemirror/src/find_replace.ts index 53bbe5b9b..4adc2d3e2 100644 --- a/packages/codemirror/src/find_replace.ts +++ b/packages/codemirror/src/find_replace.ts @@ -57,9 +57,22 @@ export function createSearchHighlighter(view: EditorView, searchTerm: string, ma return; } - const pos = this.parsedMatches[matchIndex]; + this.scrollTo(this.parsedMatches[matchIndex]); + } + + scrollToMatchNearestSelection() { + const cursorPos = this.view.state.selection.main.head; + for (const match of this.parsedMatches) { + if (match.from >= cursorPos) { + this.scrollTo(match); + return; + } + } + } + + private scrollTo(match: Match) { this.view.dispatch({ - effects: EditorView.scrollIntoView(pos.from, { y: "center" }), + effects: EditorView.scrollIntoView(match.from, { y: "center" }), scrollIntoView: true }); } diff --git a/packages/codemirror/src/index.ts b/packages/codemirror/src/index.ts index 6f7f1be9b..72efa20f2 100644 --- a/packages/codemirror/src/index.ts +++ b/packages/codemirror/src/index.ts @@ -181,7 +181,7 @@ export default class CodeMirror extends EditorView { await new Promise(requestAnimationFrame); const instance = this.plugin(plugin); if (instance) { - instance.scrollToMatch(0); + instance.scrollToMatchNearestSelection(); } return {