fix(editor): skip whitespace-only selections in selection match highlighting (#6318)

Selecting indentation (spaces or tabs) flooded the editor with occurrence highlights, because CodeMirror's highlightSelectionMatches matches whitespace-only selections verbatim. heavyExtension now uses a selectionMatches view plugin with the same bounds (min length 2, max length 200, at most 500 visible matches) that skips whitespace-only selections, as the terminal and Markdown preview already do.

Co-authored-by: dengliu <[email protected]>
Цей коміт міститься в:
Deng Liuтаdengliu authored and GitHub committed 2026-11-27 14:11:22 +08:00
1 джерело dbb6fa51c3
коміт 5b3e2b7a3d
3 files changed
+151 -2

No files matched your search

+88
Переглянути файл
@@ -0,0 +1,88 @@
import { afterEach, describe, expect, it } from "vitest";
import { EditorSelection, EditorState, type Extension } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import type { EditorSettings } from "@/platform/ipc";
import { selectionMatches } from "./selectionMatches";
import { heavyExtension } from "./setup";
const views: EditorView[] = [];
afterEach(() => views.splice(0).forEach((v) => v.destroy()));
function mount(doc: string, selection: EditorSelection, extensions: Extension = selectionMatches()) {
const parent = document.createElement("div");
document.body.appendChild(parent);
const v = new EditorView({
state: EditorState.create({
doc,
selection,
extensions: [EditorState.allowMultipleSelections.of(true), extensions],
}),
parent,
});
views.push(v);
return v;
}
const matches = (v: EditorView) => [...v.contentDOM.querySelectorAll(".cm-selectionMatch")].map((el) => el.textContent);
describe("selectionMatches", () => {
it("highlights other occurrences of a non-whitespace selection without marking the selection itself", () => {
const doc = " foo\n foo\n foobar";
const v = mount(doc, EditorSelection.single(2, 5));
expect(matches(v)).toEqual(["foo", "foo"]);
});
it.each([
["spaces", " a\n b\n c", 0, 2],
["four spaces", " a\n b\n c", 0, 4],
["tabs", "\t\ta\n\t\tb\n\t\tc", 0, 2],
["mixed spaces, tabs, and newlines", " \t\n \ta\n \t\n \tb", 0, 5],
])("skips whitespace-only selections (%s)", (_label, doc, from, to) => {
const v = mount(doc, EditorSelection.single(from, to));
expect(matches(v)).toEqual([]);
});
it("still highlights selections containing both whitespace and non-whitespace", () => {
const doc = " a: 1\n a: 2\n a: 3";
const v = mount(doc, EditorSelection.single(0, 4)); // " a:"
expect(matches(v)).toEqual([" a:", " a:"]);
});
it("respects minSelectionLength, max length, multiple selections, and maxMatches", () => {
const doc = "ab ab ab ab";
// Below minSelectionLength (default 2)
expect(matches(mount(doc, EditorSelection.single(0, 1)))).toEqual([]);
// Multiple selections
expect(
matches(mount(doc, EditorSelection.create([EditorSelection.range(0, 2), EditorSelection.range(3, 5)]))),
).toEqual([]);
// Exceeds maxMatches
expect(matches(mount(doc, EditorSelection.single(0, 2), selectionMatches({ maxMatches: 2 })))).toEqual([]);
// Exceeds 200-char limit
const long = "x".repeat(201);
expect(matches(mount(`${long}\n${long}`, EditorSelection.single(0, 201)))).toEqual([]);
});
it("updates when selection changes or document is edited", () => {
const v = mount(" foo\n foo\n bar", EditorSelection.single(2, 5));
expect(matches(v)).toEqual(["foo"]);
// Moving selection to leading spaces clears highlights.
v.dispatch({ selection: EditorSelection.single(0, 2) });
expect(matches(v)).toEqual([]);
// Moving back restores, and editing updates matches.
v.dispatch({ selection: EditorSelection.single(2, 5) });
expect(matches(v)).toEqual(["foo"]);
v.dispatch({ changes: { from: 14, to: 17, insert: "foo" } });
expect(matches(v)).toEqual(["foo", "foo"]);
});
it("wires into heavyExtension and respects codeEditing.highlightSelection", () => {
const yaml = "services:\n app:\n image: nginx\n restart: always";
expect(matches(mount(yaml, EditorSelection.single(10, 12), heavyExtension(yaml.length)))).toEqual([]);
const dup = "image: a\nimage: b";
expect(matches(mount(dup, EditorSelection.single(0, 5), heavyExtension(dup.length)))).toEqual(["image"]);
const disabled = { codeEditing: { highlightSelection: false } } as unknown as EditorSettings;
expect(matches(mount(dup, EditorSelection.single(0, 5), heavyExtension(dup.length, disabled)))).toEqual([]);
});
});
+61
Переглянути файл
@@ -0,0 +1,61 @@
/**
* Highlights other visible occurrences of the selected text (`.cm-selectionMatch`),
* skipping selections that contain only whitespace (spaces, tabs, newlines) so
* selecting indentation never floods the editor with match highlights.
*/
import type { Extension, Range } from "@codemirror/state";
import { Decoration, ViewPlugin, type DecorationSet, type EditorView, type ViewUpdate } from "@codemirror/view";
import { SearchCursor } from "@codemirror/search";
const MAX_SELECTION_LENGTH = 200;
const matchDeco = Decoration.mark({ class: "cm-selectionMatch" });
interface SelectionMatchOptions {
minSelectionLength?: number;
maxMatches?: number;
}
function matchDecorations(view: EditorView, minSelectionLength: number, maxMatches: number): DecorationSet {
const { state } = view;
const sel = state.selection;
if (sel.ranges.length > 1) return Decoration.none;
const range = sel.main;
if (range.empty) return Decoration.none;
const len = range.to - range.from;
if (len < minSelectionLength || len > MAX_SELECTION_LENGTH) return Decoration.none;
const query = state.sliceDoc(range.from, range.to);
if (!query.trim()) return Decoration.none;
const deco: Range<Decoration>[] = [];
for (const part of view.visibleRanges) {
const cursor = new SearchCursor(state.doc, query, part.from, part.to);
while (!cursor.next().done) {
const { from, to } = cursor.value;
if (from >= range.to || to <= range.from) {
deco.push(matchDeco.range(from, to));
if (deco.length > maxMatches) return Decoration.none;
}
}
}
return Decoration.set(deco);
}
/** Highlights non-whitespace selection occurrences in visible ranges. */
export function selectionMatches(options: SelectionMatchOptions = {}): Extension {
const minSelectionLength = options.minSelectionLength ?? 2;
const maxMatches = options.maxMatches ?? 500;
return ViewPlugin.fromClass(
class {
decorations: DecorationSet;
constructor(view: EditorView) {
this.decorations = matchDecorations(view, minSelectionLength, maxMatches);
}
update(u: ViewUpdate) {
if (u.selectionSet || u.docChanged || u.viewportChanged) {
this.decorations = matchDecorations(u.view, minSelectionLength, maxMatches);
}
}
},
{ decorations: (v) => v.decorations },
);
}
+2 -2
Переглянути файл
@@ -23,7 +23,6 @@ import {
} from "@codemirror/language";
import { history, indentWithTab } from "@codemirror/commands";
import { closeBrackets, closeBracketsKeymap } from "@codemirror/autocomplete";
import { highlightSelectionMatches } from "@codemirror/search";
import type { EditorConfigProps } from "@/bindings";
import type { EditorSettings } from "@/platform/ipc";
import { editorPrefs, lineCommentStyleFor, type EditorExtras } from "@/platform/editorSettings";
@@ -33,6 +32,7 @@ import { distractionFreeWidth, isDistractionFree } from "@/workbench/distraction
import { openideaHighlightStyle } from "./highlight";
import { openideaTheme } from "./theme";
import { caretRowHighlight } from "./caretRow";
import { selectionMatches } from "./selectionMatches";
import { changeLane, overviewLane } from "./lanes";
import { cornerInset } from "./cornerInset";
import { foldingExtension } from "./folding";
@@ -258,7 +258,7 @@ export function heavyExtension(docLength: number, settings?: EditorSettings): Ex
prefs.rainbowBrackets
? rainbowBrackets({ ...prefs.rainbowBracketKinds, colors: prefs.rainbowBracketColors, syntax: bracketSyntax() })
: [],
prefs.codeEditing.highlightSelection ? highlightSelectionMatches({ minSelectionLength: 2, maxMatches: 500 }) : [],
prefs.codeEditing.highlightSelection ? selectionMatches({ minSelectionLength: 2, maxMatches: 500 }) : [],
];
}