feat(editor): Toggle Sticky Selection action (#6325)

IDEA's Toggle Sticky Selection: while on, every caret move (keys, IDE actions, clicks, Find) extends the selection from its anchor. Turning it off, Esc, an edit of the document or a copy end it and remove the selection, as in IDEA. Swap Selection Boundaries keeps it going from the other end. No default shortcut, as in IDEA's default keymaps.

Closes #6324

Co-authored-by: mansur-akhmadi <[email protected]>
Цей коміт міститься в:
Mansur Akhmadiтаmansur-akhmadi authored and GitHub committed 2026-11-27 14:49:18 +08:00
1 джерело 4016c3c905
коміт 43aee8058c
17 files changed
+310 -4

No files matched your search

+1
Переглянути файл
@@ -25,6 +25,7 @@ The editor follows IntelliJ IDEA's behaviour and default keymap. Shortcuts below
- Drag with `⌥` / `Alt` held (or with the middle mouse button on macOS and Windows) to make a rectangular selection without switching modes.
- **Extend Selection** grows the selection to the enclosing word, expression, statement and block, using the syntax tree.
- **Swap Selection Boundaries** moves the caret of each selection to its other end and keeps the text selected, so `⇧` / `Shift` with the arrow keys then extends or shrink it from that side. It has no default shortcut.
- **Toggle Sticky Selection** starts a selection at each caret: arrow keys and other caret moves then extend it as if `⇧` / `Shift` were held. Run it again or press `Esc` to turn it off, which also removes the selection. Copying or editing the text turns it off too. It has no default shortcut.
- **Select Line at Caret** selects the whole line at each caret together with its line break; a selection grows to the whole lines it touches. It has no default shortcut.
## Editing lines and code
+1
Переглянути файл
@@ -25,6 +25,7 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
- 按住 `⌥` / `Alt` 拖动鼠标(macOS 和 Windows 上也可以用鼠标中键拖动)可以直接做矩形选区,不用切换模式。
- **扩展选区** 依据语法树逐级扩大到所在的单词、表达式、语句和代码块。
- **交换选区边界** 把每个选区的光标移到选区的另一端并保持选中,之后用 `⇧` / `Shift`+方向键即可从这一端扩大或缩小选区。它默认没有快捷键。
- **切换粘滞选区** 从每个光标处开始一个选区:之后方向键等光标移动会像按住 `⇧` / `Shift` 一样扩大选区。再执行一次或按 `Esc` 即可关闭,同时取消选区。复制或编辑文本也会关闭它。它默认没有快捷键。
- **选择光标所在行** 选中每个光标所在的整行及其换行符;有选区时扩大到选区涉及的所有整行。它默认没有快捷键。
## 编辑行与代码
+16 -2
Переглянути файл
@@ -96,6 +96,7 @@ import {
splitLine,
} from "./cm/caretCommands";
import { isOverwrite, toggleOverwrite } from "./cm/overwrite";
import { isStickySelection, toggleStickySelection } from "./cm/stickySelection";
import { isColumnMode, toggleColumnMode } from "./cm/columnMode";
import {
cloneCaretAbove,
@@ -1146,13 +1147,18 @@ export function registerEditorActions(): () => void {
caret(
"editor.nextWordInDifferentHumpsMode",
'Move Caret to Next Word in Different "CamelHumps" Mode',
(v) => inDifferentHumpsMode("right", editorPrefs().smartKeys.camelHumps)(v),
(v) =>
inDifferentHumpsMode(
isStickySelection(v.state) ? "selectRight" : "right",
editorPrefs().smartKeys.camelHumps,
)(v),
{ category: "Editor Actions" },
),
caret(
"editor.previousWordInDifferentHumpsMode",
'Move Caret to Previous Word in Different "CamelHumps" Mode',
(v) => inDifferentHumpsMode("left", editorPrefs().smartKeys.camelHumps)(v),
(v) =>
inDifferentHumpsMode(isStickySelection(v.state) ? "selectLeft" : "left", editorPrefs().smartKeys.camelHumps)(v),
{ category: "Editor Actions" },
),
caret(
@@ -1223,6 +1229,14 @@ export function registerEditorActions(): () => void {
return view ? isOverwrite(view.state) : false;
},
}),
text("editor.toggleStickySelection", "Toggle Sticky Selection", (v) => toggleStickySelection(v), {
category: "Editor Actions",
keywords: ["set mark", "selection mode"],
toggled: () => {
const view = focusedCellEditor() ?? activeSlot()?.view;
return view ? isStickySelection(view.state) : false;
},
}),
edit("code.joinLines", "Join Lines", (v) => joinLines(v)),
edit("code.toggleCase", "Toggle Case", (v) => toggleCase(v), { keywords: ["upper", "lower"] }),
edit("code.cycleCase", "Cycle Identifier Case", (v) => cycleCase(v), {
+6 -1
Переглянути файл
@@ -4,6 +4,7 @@
* ⌘/Ctrl+Enter is Split Line, Ctrl+M / ⌃L Scroll to Center, Ctrl+[ / ] code
* block navigation, ⌥⌘↑↓ / Ctrl+Alt+↑↓ Previous / Next Occurrence.
* Line up / down (with ⇧ too) keep the caret's visible column (`verticalMotion`).
* With sticky selection on, a caret move runs its ⇧ variant.
*/
import type { Command, KeyBinding } from "@codemirror/view";
import {
@@ -22,6 +23,7 @@ import {
selectLineUp as cmSelectLineUp,
toggleTabFocusMode,
} from "@codemirror/commands";
import { stickyMove } from "./stickySelection";
import { cursorLineDown, cursorLineUp, selectLineDown, selectLineUp } from "./verticalMotion";
const DROPPED = new Set<unknown>([
@@ -53,6 +55,9 @@ export const editorHistoryKeymap: readonly KeyBinding[] = [
];
export const editorBaseKeymap: readonly KeyBinding[] = [
...defaultKeymap.filter((b) => !DROPPED.has(b.run)).map(vertical),
...defaultKeymap
.filter((b) => !DROPPED.has(b.run))
.map(vertical)
.map(stickyMove),
...editorHistoryKeymap,
];
+2
Переглянути файл
@@ -37,6 +37,7 @@ import {
import { SearchCursor } from "@codemirror/search";
import { humpLeft, humpRight, wordStartLeft } from "../model/camelHumps";
import { cycleIdentifierCase, wordSpan } from "../model/identifierCase";
import { restartSticky } from "./stickySelection";
type Node = ReturnType<ReturnType<typeof syntaxTree>["resolveInner"]>;
@@ -1153,6 +1154,7 @@ export const swapSelectionBoundaries: Command = (view) => {
selection.ranges.map((r) => EditorSelection.range(r.head, r.anchor)),
selection.mainIndex,
),
effects: restartSticky.of(null),
scrollIntoView: true,
userEvent: "select",
});
+2 -1
Переглянути файл
@@ -69,6 +69,7 @@ import { stringClipboard } from "./stringClipboard";
import { filterCopiedText } from "./clipboard";
import { LINE_INSET } from "./lineInset";
import { codeLensPositions } from "./codeLens";
import { stickyMove } from "./stickySelection";
import { wheelZoomStep } from "@/platform/wheelZoom";
// --- soft wraps ---------------------------------------------------------------
@@ -845,6 +846,6 @@ export function prefsExtension(o: PrefsOptions): Extension {
if (!k.smartIndent) keys.push({ key: "Enter", run: insertNewlineKeepIndent });
if (k.backspaceUnindent === "none") keys.push({ key: "Backspace", run: deleteCharBackwardStrict });
else if (smartBackspaceApplies(k.backspaceUnindent, o.language)) keys.push({ key: "Backspace", run: smartBackspace });
if (keys.length) out.push(Prec.high(keymap.of(keys)));
if (keys.length) out.push(Prec.high(keymap.of(keys.map(stickyMove))));
return out;
}
+2
Переглянути файл
@@ -56,6 +56,7 @@ import { editorBaseKeymap } from "./baseKeymap";
import { occurrenceSearch } from "./editing";
import { gutterLineDrag } from "./gutterDrag";
import { overwriteField } from "./overwrite";
import { stickySelectionField } from "./stickySelection";
import { relativeLineNumbers } from "./relativeLineNumbers";
import { clipboardDocumentPath, clipboardFilesExtension } from "./clipboard";
import { clipboardHistoryExtension } from "../clipboardHistory";
@@ -400,6 +401,7 @@ export function baseExtensions(o: SetupOptions): Extension {
visibleGoalColumns,
occurrenceSearch,
overwriteField,
stickySelectionField,
gutterLineDrag,
clipboardHistoryExtension,
clipboardDocumentPath.of(o.ctx.path),
+180
Переглянути файл
@@ -0,0 +1,180 @@
import { afterEach, describe, expect, it } from "vitest";
import { EditorSelection, EditorState, type Extension } from "@codemirror/state";
import { EditorView, keymap, runScopeHandlers, type Command } from "@codemirror/view";
import { selectAll } from "@codemirror/commands";
import { editorBaseKeymap } from "./baseKeymap";
import { swapSelectionBoundaries } from "./editing";
import { cursorMatchBrace } from "./caretCommands";
import { isStickySelection, stickyMove, stickySelectionField, toggleStickySelection } from "./stickySelection";
const views: EditorView[] = [];
afterEach(() => views.splice(0).forEach((v) => v.destroy()));
/** `|` marks carets, `[`/`]` a selection. */
function make(text: string, extra: Extension = []) {
const ranges: ReturnType<typeof EditorSelection.cursor>[] = [];
let doc = "";
let anchor = -1;
for (const ch of text) {
if (ch === "|") ranges.push(EditorSelection.cursor(doc.length));
else if (ch === "[") anchor = doc.length;
else if (ch === "]") ranges.push(EditorSelection.range(anchor, doc.length));
else doc += ch;
}
const view = new EditorView({
state: EditorState.create({
doc,
selection: EditorSelection.create(ranges),
extensions: [
EditorState.allowMultipleSelections.of(true),
stickySelectionField,
keymap.of(editorBaseKeymap),
extra,
],
}),
parent: document.body,
});
views.push(view);
return view;
}
function show(view: EditorView): string {
const { doc, selection } = view.state;
let out = doc.toString();
for (const r of [...selection.ranges].sort((a, b) => b.from - a.from))
out = r.empty
? out.slice(0, r.head) + "|" + out.slice(r.head)
: out.slice(0, r.from) + "[" + out.slice(r.from, r.to) + "]" + out.slice(r.to);
return out;
}
const press = (view: EditorView, key: string, mods: KeyboardEventInit = {}) =>
runScopeHandlers(view, new KeyboardEvent("keydown", { key, ...mods }), "editor");
describe("Toggle Sticky Selection", () => {
it("extends the selection with caret moves until it is turned off", () => {
const v = make("ab|cdef\nghijkl");
toggleStickySelection(v);
expect(isStickySelection(v.state)).toBe(true);
press(v, "ArrowRight");
press(v, "ArrowRight");
expect(show(v)).toBe("ab[cd]ef\nghijkl");
press(v, "ArrowLeft");
expect(show(v)).toBe("ab[c]def\nghijkl");
press(v, "ArrowDown");
expect(v.state.selection.main).toMatchObject({ anchor: 2, head: 10 });
press(v, "ArrowRight");
toggleStickySelection(v);
expect(isStickySelection(v.state)).toBe(false);
expect(show(v)).toBe("abcdef\nghij|kl");
press(v, "ArrowRight");
expect(show(v)).toBe("abcdef\nghijk|l");
});
it("starts at the caret, not at an existing selection", () => {
const v = make("a[bc]de");
toggleStickySelection(v);
expect(show(v)).toBe("abc|de");
press(v, "ArrowRight");
expect(show(v)).toBe("abc[d]e");
});
it("extends every caret from its own start", () => {
const v = make("|abc\n|def");
toggleStickySelection(v);
press(v, "ArrowRight");
press(v, "ArrowRight");
expect(show(v)).toBe("[ab]c\n[de]f");
});
it("is turned off by Escape, which removes the selection and the other carets", () => {
const v = make("|abc\n|def");
toggleStickySelection(v);
press(v, "ArrowRight");
expect(show(v)).toBe("[a]bc\n[d]ef");
expect(press(v, "Escape")).toBe(true);
expect(isStickySelection(v.state)).toBe(false);
expect(show(v)).toBe("a|bc\ndef");
press(v, "ArrowRight");
expect(show(v)).toBe("ab|c\ndef");
});
it("leaves Escape to the editor while it is off", () => {
const v = make("[ab]c");
expect(press(v, "Escape")).toBe(true);
expect(show(v)).toBe("ab|c");
expect(isStickySelection(v.state)).toBe(false);
});
it("extends with caret moves outside the keymap and keeps its start on Select All", () => {
const v = make("x(ab|)y");
toggleStickySelection(v);
cursorMatchBrace(v);
expect(show(v)).toBe("x([ab])y");
expect(v.state.selection.main).toMatchObject({ anchor: 4, head: 2 });
selectAll(v);
expect(v.state.selection.main).toMatchObject({ anchor: 4, head: 6 });
});
it("leaves an editor without sticky selection alone", () => {
const v = new EditorView({ state: EditorState.create({ doc: "abc", selection: EditorSelection.range(0, 2) }) });
views.push(v);
expect(toggleStickySelection(v)).toBe(false);
expect(v.state.selection.main).toMatchObject({ anchor: 0, head: 2 });
});
it("runs a binding's Shift variant only while it is on", () => {
const calls: string[] = [];
const cmd =
(name: string): Command =>
() => (calls.push(name), true);
const v = make("|abc");
const b = stickyMove({ key: "Alt-ArrowRight", run: cmd("move"), shift: cmd("select") });
b.run!(v);
toggleStickySelection(v);
b.run!(v);
expect(calls).toEqual(["move", "select"]);
const same = { key: "Enter", run: cmd("enter"), shift: cmd("enter") };
same.shift = same.run;
expect(stickyMove(same)).toBe(same);
});
it("keeps going from the other end after Swap Selection Boundaries", () => {
const v = make("ab|cdef");
toggleStickySelection(v);
press(v, "ArrowRight");
press(v, "ArrowRight");
swapSelectionBoundaries(v);
press(v, "ArrowLeft");
expect(show(v)).toBe("a[bcd]ef");
expect(v.state.selection.main.head).toBe(1);
});
it("turns off when the document changes, as in IDEA", () => {
const v = make("|abc");
toggleStickySelection(v);
press(v, "ArrowRight");
v.dispatch(v.state.replaceSelection("X"));
expect(show(v)).toBe("X|bc");
expect(isStickySelection(v.state)).toBe(false);
press(v, "ArrowRight");
expect(show(v)).toBe("Xb|c");
});
it("turns off and removes the selection after a copy", async () => {
const v = make("|abc");
toggleStickySelection(v);
press(v, "ArrowRight");
v.contentDOM.dispatchEvent(new Event("copy", { bubbles: true, cancelable: true }));
await Promise.resolve();
expect(isStickySelection(v.state)).toBe(false);
expect(show(v)).toBe("a|bc");
});
it("works in a read-only editor", () => {
const v = make("|abc", EditorState.readOnly.of(true));
toggleStickySelection(v);
press(v, "ArrowRight");
expect(show(v)).toBe("[a]bc");
});
});
+84
Переглянути файл
@@ -0,0 +1,84 @@
/**
* Sticky selection (IDEA's Toggle Sticky Selection): while it is on, every caret move selects
* from the selection's anchor, which starts at the caret when it is turned on. As in IDEA, an edit
* of the document or a copy turns it off.
*/
import { EditorSelection, EditorState, StateEffect, StateField } from "@codemirror/state";
import { EditorView, type KeyBinding, keymap } from "@codemirror/view";
const setSticky = StateEffect.define<boolean>();
/** Makes the current anchors the new sticky start (Swap Selection Boundaries). */
export const restartSticky = StateEffect.define<null>();
export function isStickySelection(state: EditorState): boolean {
return state.field(stickySelectionField, false) ?? false;
}
/** Turning it on starts the selection at each caret; turning it off removes the selection, as in IDEA. */
export function toggleStickySelection(view: EditorView): boolean {
const { selection } = view.state;
if (view.state.field(stickySelectionField, false) === undefined) return false;
view.dispatch({
effects: setSticky.of(!isStickySelection(view.state)),
selection: EditorSelection.create(
selection.ranges.map((r) => EditorSelection.cursor(r.head)),
selection.mainIndex,
),
});
return true;
}
/**
* A key binding whose plain move runs its ⇧ variant while sticky selection is on: CodeMirror's
* plain moves collapse a selection to its edge instead of moving the caret.
*/
export function stickyMove(b: KeyBinding): KeyBinding {
const { run, shift } = b;
if (!run || !shift || run === shift) return b;
return { ...b, run: (view) => (isStickySelection(view.state) ? shift : run)(view) };
}
/** Any other caret move (IDE actions, clicks, Find) keeps each range's anchor; edits pass through. */
const keepAnchors = EditorState.transactionFilter.of((tr) => {
if (!tr.selection || tr.docChanged || !isStickySelection(tr.startState)) return tr;
if (tr.effects.some((e) => e.is(setSticky) || e.is(restartSticky))) return tr;
const before = tr.startState.selection.ranges;
const after = tr.newSelection;
if (after.ranges.length !== before.length) return tr;
if (after.ranges.every((r, i) => r.anchor === before[i]!.anchor)) return tr;
const ranges = after.ranges.map((r, i) => EditorSelection.range(before[i]!.anchor, r.head, r.goalColumn));
return [tr, { selection: EditorSelection.create(ranges, after.mainIndex), sequential: true }];
});
/**
* Escape turns sticky selection off and removes the selection, then lets the editor's own
* Escape (one caret) run. Popups and sessions with their own Escape handle it first.
*/
const escapeSticky = keymap.of([
{
key: "Escape",
run: (view) => {
if (isStickySelection(view.state)) toggleStickySelection(view);
return false;
},
},
]);
/** A copy turns it off and removes the selection (IDEA's `CopyAction`), once the editor has copied. */
const copySticky = EditorView.domEventHandlers({
copy: (_event, view) => {
if (isStickySelection(view.state))
queueMicrotask(() => {
if (isStickySelection(view.state)) toggleStickySelection(view);
});
return false;
},
});
export const stickySelectionField = StateField.define<boolean>({
create: () => false,
// Any document change ends it (IDEA's `EditorImpl.beforeChangedUpdate`).
update: (on, tr) => tr.effects.reduce((acc, e) => (e.is(setSticky) ? e.value : acc), tr.docChanged ? false : on),
provide: () => [keepAnchors, escapeSticky, copySticky],
});
+1
Переглянути файл
@@ -60,6 +60,7 @@ export const IDEA_ACTIONS: Readonly<Record<string, string>> = {
EditorCutLineEnd: "code.cutLineEnd",
EditorHungryBackSpace: "code.hungryBackspace",
EditorSwapSelectionBoundaries: "editor.swapSelectionBoundaries",
EditorToggleStickySelection: "editor.toggleStickySelection",
EditorSelectLine: "editor.selectLine",
CopyAsPlainText: "code.copyAsPlainText",
CopyAsRichText: "code.copyAsRichText",
+8
Переглянути файл
@@ -193,6 +193,14 @@ describe("IntelliJ IDEA keymap import", () => {
expect(k.unknownActions).toEqual([]);
});
it("maps Toggle Sticky Selection", () => {
const k = parseIdeaKeymap(
`<keymap name="S" parent="$default"><action id="EditorToggleStickySelection"><keyboard-shortcut first-keystroke="control SPACE"/></action></keymap>`,
);
expect(k.overrides["editor.toggleStickySelection"]).toEqual([normalizeBinding("Ctrl+Space")]);
expect(k.unknownActions).toEqual([]);
});
it("maps Select Line at Caret", () => {
const k = parseIdeaKeymap(
`<keymap name="S" parent="$default"><action id="EditorSelectLine"><keyboard-shortcut first-keystroke="control alt L"/></action></keymap>`,
+2
Переглянути файл
@@ -87,6 +87,8 @@ describe("IDEA keymap parity", () => {
["code.hungryBackspace", [], []],
// EditorSwapSelectionBoundaries has no shortcut.
["editor.swapSelectionBoundaries", [], []],
// EditorToggleStickySelection has no shortcut.
["editor.toggleStickySelection", [], []],
// EditorSelectLine has no shortcut.
["editor.selectLine", [], []],
// CopyAsPlainText / CopyAsRichText have no shortcut.
+1
Переглянути файл
@@ -108,6 +108,7 @@ export const intellijMacos: Record<string, string[]> = {
"code.cutLineEnd": ["Ctrl+K"],
"code.hungryBackspace": [],
"editor.swapSelectionBoundaries": [],
"editor.toggleStickySelection": [],
"code.moveLineUp": ["Alt+Shift+Up"],
"code.moveLineDown": ["Alt+Shift+Down"],
"code.moveStatementUp": ["Meta+Shift+Up"],
+1
Переглянути файл
@@ -109,6 +109,7 @@ export const intellijWindows: Record<string, string[]> = {
"code.cutLineEnd": [],
"code.hungryBackspace": [],
"editor.swapSelectionBoundaries": [],
"editor.toggleStickySelection": [],
"code.moveLineUp": ["Alt+Shift+Up"],
"code.moveLineDown": ["Alt+Shift+Down"],
"code.moveStatementUp": ["Ctrl+Shift+Up"],
+1
Переглянути файл
@@ -161,6 +161,7 @@ export const vscodeMacos: Record<string, string[]> = {
"code.cutLineEnd": [],
"code.hungryBackspace": [],
"editor.swapSelectionBoundaries": [],
"editor.toggleStickySelection": [],
"code.moveLineUp": ["Alt+Up"],
"code.moveLineDown": ["Alt+Down"],
"code.moveStatementUp": [],
+1
Переглянути файл
@@ -671,6 +671,7 @@
"Cut up to Line End": "剪下至行尾",
"Hungry Backspace": "貪婪退格",
"Swap Selection Boundaries": "交換選取範圍邊界",
"Toggle Sticky Selection": "切換黏滯選取範圍",
"Move Line Up": "上移行",
"Move Line Down": "下移行",
"Move Statement Up": "上移陳述式",
+1
Переглянути файл
@@ -1032,6 +1032,7 @@
"Cut up to Line End": "剪切到行尾",
"Hungry Backspace": "贪婪退格",
"Swap Selection Boundaries": "交换选区边界",
"Toggle Sticky Selection": "切换粘滞选区",
"Move Line Up": "上移行",
"Move Line Down": "下移行",
"Move Statement Up": "上移语句",