diff --git a/src/editor/api.ts b/src/editor/api.ts index f7c0136a02..3912dc91db 100644 --- a/src/editor/api.ts +++ b/src/editor/api.ts @@ -27,6 +27,7 @@ import { type EditorState, type Extension, type RangeSet, + type Text, type Transaction, } from "@codemirror/state"; import { GutterMarker, ViewPlugin, type EditorView, type ViewUpdate } from "@codemirror/view"; @@ -1104,3 +1105,23 @@ export function onWorkspaceEditHistory(listener: (state: WorkspaceEditHistorySta export function _emitWorkspaceEditHistory(state: WorkspaceEditHistoryState) { for (const listener of workspaceHistoryListeners) listener(state); } + +/** On the transaction that puts refactoring `id`'s history marker into an editor. */ +export const workspaceEditMarker = Annotation.define(); + +/** + * Local edits that finished a refactoring in one editor (its reformatting, the in-place rename + * of an introduced name), kept out of the undo history. Undoing the refactoring reverts them + * first, while the text is still `end`; redoing it applies `changes` again. + */ +export interface WorkspaceEditFollowUp { + changes: ChangeSet; + revert: ChangeSet; + end: Text; +} + +/** Looks up the follow-up edits of refactoring `id` recorded in an editor state. */ +export const workspaceEditFollowUps = Facet.define<(state: EditorState, id: number) => WorkspaceEditFollowUp | null>(); + +/** Asks an editor to finish an interactive edit (an in-place rename) before refactoring `id` is undone. */ +export const settleWorkspaceEdit = StateEffect.define(); diff --git a/src/editor/core/model/workspaceHistory.ts b/src/editor/core/model/workspaceHistory.ts index 6b30b61fdd..656c1a666c 100644 --- a/src/editor/core/model/workspaceHistory.ts +++ b/src/editor/core/model/workspaceHistory.ts @@ -1,8 +1,16 @@ /** Workspace edits contribute history markers; their text patches never enter local history. */ import { invertedEffects, isolateHistory, redo, undo } from "@codemirror/commands"; -import { EditorState, Prec, StateEffect, type Transaction, type Extension } from "@codemirror/state"; +import { EditorState, Prec, StateEffect, Transaction, type Extension } from "@codemirror/state"; import { EditorView, keymap } from "@codemirror/view"; -import { _emitWorkspaceEditHistory, _provideWorkspaceHistory, isExternalChange } from "@/editor/api"; +import { + _emitWorkspaceEditHistory, + _provideWorkspaceHistory, + isExternalChange, + settleWorkspaceEdit, + workspaceEditFollowUps, + workspaceEditMarker, + type WorkspaceEditFollowUp, +} from "@/editor/api"; import { editorsFollowAppliedMoves, reversedMoves, withEditorsFollowing } from "@/editor/fileMoves"; import { call, commands, onIdeEvent, type FileMove } from "@/platform/ipc"; import { useProject } from "@/platform/project"; @@ -25,6 +33,8 @@ export class WorkspaceHistory { private project = useProject.getState().project; private busy = false; private moving = false; + /** Reverting or reapplying a refactoring's follow-up edits while `busy`. */ + private following = false; constructor( private synced: () => Promise, @@ -116,13 +126,16 @@ export class WorkspaceHistory { } return null; }), - EditorState.changeFilter.of((tr) => !this.busy || isExternalChange(tr)), + EditorState.changeFilter.of((tr) => !this.busy || this.following || isExternalChange(tr)), ]; } private mark(target: WorkspaceHistoryTarget, id: number) { target.dispatch( - target.state().update({ effects: marker.of({ id, redo: true }), annotations: isolateHistory.of("full") }), + target.state().update({ + effects: marker.of({ id, redo: true }), + annotations: [isolateHistory.of("full"), workspaceEditMarker.of(id)], + }), ); } @@ -143,9 +156,46 @@ export class WorkspaceHistory { return result; } + /** The follow-up edits each affected editor recorded for refactoring `id`. */ + private followUps(id: number, paths: string[]): Array<[WorkspaceHistoryTarget, WorkspaceEditFollowUp]> { + const out: Array<[WorkspaceHistoryTarget, WorkspaceEditFollowUp]> = []; + for (const target of this.targets) { + if (!this.affects(paths, target.path)) continue; + const state = target.state(); + for (const lookup of state.facet(workspaceEditFollowUps)) { + const followUp = lookup(state, id); + if (followUp) { + out.push([target, followUp]); + break; + } + } + } + return out; + } + + /** Applies a follow-up edit (or its revert) as a local, synced edit outside the undo history. */ + private applyFollowUp(target: WorkspaceHistoryTarget, changes: WorkspaceEditFollowUp["changes"]) { + if (target.state().doc.length !== changes.length) return; + this.following = true; + try { + target.dispatch( + target.state().update({ changes, annotations: Transaction.addToHistory.of(false), scrollIntoView: false }), + ); + } finally { + this.following = false; + } + } + async run(id: number, forward = false, source?: WorkspaceHistoryTarget): Promise { if (this.busy) throw new Error("A refactoring history operation is in progress"); + if (!source) { + // Finish an in-place rename still open after the refactoring: its edits become follow-ups. + for (const target of this.targets) + target.dispatch(target.state().update({ effects: settleWorkspaceEdit.of(id) })); + await Promise.resolve(); + } this.busy = true; + let reverted: Array<[WorkspaceHistoryTarget, WorkspaceEditFollowUp]> = []; try { // Yield before reading a source: its marker transaction is still being built. await this.synced(); @@ -157,15 +207,29 @@ export class WorkspaceHistory { for (const target of targets) if (!this.step(target, id, forward)) throw new Error("Undo newer editor changes before undoing this refactoring"); + const followUps = this.followUps(id, record.paths); + if (!forward) { + // The backend restores the files only while they hold the refactoring's own text. + for (const [target, followUp] of followUps) + if (!target.state().doc.eq(followUp.end)) + throw new Error("Undo newer editor changes before undoing this refactoring"); + for (const [target, followUp] of followUps) this.applyFollowUp(target, followUp.revert); + reverted = followUps; + await this.synced(); + } await withEditorsFollowing( async () => { await call(forward ? commands.redoWorkspaceEdit(id) : commands.undoWorkspaceEdit(id)); + reverted = []; await this.synced(); for (const target of targets) { if (!this.targets.has(target)) continue; const tr = this.step(target, id, forward); if (tr) target.dispatch(tr); } + if (forward) + for (const [target, followUp] of followUps) + if (this.targets.has(target)) this.applyFollowUp(target, followUp.changes); // Editors reopened at moved paths build their history from the record: settle it first. record.undone = !forward; }, @@ -174,6 +238,9 @@ export class WorkspaceHistory { ); _emitWorkspaceEditHistory({ id, undone: record.undone }); } catch (error) { + // A refused backend restore puts the follow-up edits back as well. + for (const [target, followUp] of reverted) + if (this.targets.has(target)) this.applyFollowUp(target, followUp.changes); // A refused backend restore must leave the initiating editor's history intact. if (source && this.targets.has(source)) { const tr = this.step(source, id, !forward); diff --git a/src/editor/lsp/historyGroup.test.ts b/src/editor/lsp/historyGroup.test.ts index aedbe5c2f7..f62cc9396f 100644 --- a/src/editor/lsp/historyGroup.test.ts +++ b/src/editor/lsp/historyGroup.test.ts @@ -1,9 +1,15 @@ -import { afterEach, describe, expect, it } from "vitest"; -import { EditorState } from "@codemirror/state"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { EditorState, Transaction } from "@codemirror/state"; import { EditorView } from "@codemirror/view"; -import { history, redo, undo, undoDepth } from "@codemirror/commands"; +import { history, redo, redoDepth, undo, undoDepth } from "@codemirror/commands"; +import { remoteChange, workspaceEditHistory } from "@/editor/api"; +import { WorkspaceHistory } from "@/editor/core/model/workspaceHistory"; +import { emitLocalIdeEvent } from "@/platform/ipc"; import { beginHistoryGroup, endHistoryGroup, historyGroupExtension } from "./historyGroup"; -import { endInplaceRename, inplaceRenameExtension, startInplaceRename } from "./inplaceRename"; +import { endInplaceRename, inplaceRenameActive, inplaceRenameExtension, startInplaceRename } from "./inplaceRename"; + +const commands = vi.hoisted(() => ({ undoWorkspaceEdit: vi.fn(), redoWorkspaceEdit: vi.fn() })); +vi.mock("@/bindings", () => ({ commands })); const views: EditorView[] = []; afterEach(() => views.splice(0).forEach((v) => v.destroy())); @@ -82,3 +88,138 @@ describe("history group", () => { expect(undoDepth(view.state)).toBe(1); }); }); + +describe("history group around a workspace refactoring", () => { + const BEFORE = "f(1 + 2);"; + // The server's edit (the refactoring), then the in-place rename of `v` to `sum`. + const SERVER = "int v = 1 + 2;\nf(v);"; + const RENAMED = "int sum = 1 + 2;\nf(sum);"; + const cleanups: Array<() => void> = []; + afterEach(() => cleanups.splice(0).forEach((c) => c())); + + function setup() { + const notify = vi.fn(); + const workspace = new WorkspaceHistory(async () => {}, notify); + cleanups.push(workspace.start()); + let view: EditorView | null = null; + const target = { path: "/p/A.java", state: () => view!.state, dispatch: (tr: Transaction) => view!.dispatch(tr) }; + view = new EditorView({ + state: EditorState.create({ + doc: BEFORE, + extensions: [history(), historyGroupExtension, inplaceRenameExtension(), workspace.extension(target)], + }), + }); + views.push(view); + cleanups.push(workspace.attach(target)); + const remote = (text: string) => + view!.dispatch({ + changes: { from: 0, to: view!.state.doc.length, insert: text }, + annotations: [remoteChange.of(true), Transaction.addToHistory.of(false)], + }); + const seen: string[] = []; + commands.undoWorkspaceEdit.mockReset().mockImplementation(async () => { + seen.push(view!.state.doc.toString()); + remote(BEFORE); + return { status: "ok", data: null }; + }); + commands.redoWorkspaceEdit.mockReset().mockImplementation(async () => { + seen.push(view!.state.doc.toString()); + remote(SERVER); + return { status: "ok", data: null }; + }); + const refactor = () => { + beginHistoryGroup(view!); + remote(SERVER); + emitLocalIdeEvent({ type: "workspaceEditApplied", id: 9, paths: ["/p/A.java"], moves: [], byAgent: false }); + }; + // "int v = 1 + 2;\nf(v);": v at 4 and 17. + const rename = () => + startInplaceRename(view!, { + primary: { from: 17, to: 18 }, + others: [{ from: 4, to: 5 }], + hint: "", + commit: (name) => + view!.dispatch({ + changes: [ + { from: 4, to: 5, insert: name }, + { from: 17, to: 18, insert: name }, + ], + }), + dialog: () => {}, + onEnd: () => endHistoryGroup(view!, "refactor.introduce"), + }); + return { view, notify, seen, refactor, rename }; + } + + it("undoes the refactoring with the rename that finished it in one step, and redoes both", async () => { + const { view, notify, seen, refactor, rename } = setup(); + refactor(); + rename(); + view.dispatch({ changes: { from: 17, to: 18, insert: "sum" } }); + endInplaceRename(view, "commit"); + expect(view.state.doc.toString()).toBe(RENAMED); + expect(undoDepth(view.state)).toBe(1); + + expect(undo(view)).toBe(true); + await vi.waitFor(() => expect(view.state.doc.toString()).toBe(BEFORE)); + // The backend restores the files while they still hold the refactoring's own text. + expect(seen).toEqual([SERVER]); + expect(redoDepth(view.state)).toBe(1); + + expect(redo(view)).toBe(true); + await vi.waitFor(() => expect(view.state.doc.toString()).toBe(RENAMED)); + expect(undoDepth(view.state)).toBe(1); + + await workspaceEditHistory(9); + expect(view.state.doc.toString()).toBe(BEFORE); + expect(seen).toEqual([SERVER, BEFORE, SERVER]); + expect(notify).not.toHaveBeenCalled(); + }); + + it("undoes a quick fix with its reformatting in one step; a nested group leaves it to the outer one", async () => { + const { view, seen, refactor } = setup(); + refactor(); + expect(beginHistoryGroup(view)).toBe(false); + view.dispatch({ changes: { from: 0, insert: " " }, userEvent: "format" }); + endHistoryGroup(view, "quickfix"); + expect(undoDepth(view.state)).toBe(1); + expect(undo(view)).toBe(true); + await vi.waitFor(() => expect(view.state.doc.toString()).toBe(BEFORE)); + expect(seen).toEqual([SERVER]); + }); + + it("finishes an open in-place rename before the notification's Undo", async () => { + const { view, seen, refactor, rename } = setup(); + refactor(); + rename(); + view.dispatch({ changes: { from: 17, to: 18, insert: "sum" } }); + await workspaceEditHistory(9); + expect(inplaceRenameActive(view.state)).toBe(false); + expect(view.state.doc.toString()).toBe(BEFORE); + expect(seen).toEqual([SERVER]); + }); + + it("refuses the notification's Undo after newer typing, keeping the rename", async () => { + const { view, refactor, rename } = setup(); + refactor(); + rename(); + view.dispatch({ changes: { from: 17, to: 18, insert: "sum" } }); + endInplaceRename(view, "commit"); + view.dispatch({ changes: { from: 0, insert: "// x\n" }, userEvent: "input.type" }); + await expect(workspaceEditHistory(9)).rejects.toThrow("Undo newer editor changes"); + expect(commands.undoWorkspaceEdit).not.toHaveBeenCalled(); + expect(view.state.doc.toString()).toBe(`// x\n${RENAMED}`); + }); + + it("puts the rename back when the backend refuses the restore", async () => { + const { view, refactor, rename } = setup(); + refactor(); + rename(); + view.dispatch({ changes: { from: 17, to: 18, insert: "sum" } }); + endInplaceRename(view, "commit"); + commands.undoWorkspaceEdit.mockResolvedValue({ status: "error", error: { kind: "outOfSync", message: "changed" } }); + await expect(workspaceEditHistory(9)).rejects.toThrow(); + expect(view.state.doc.toString()).toBe(RENAMED); + expect(undoDepth(view.state)).toBe(1); + }); +}); diff --git a/src/editor/lsp/historyGroup.ts b/src/editor/lsp/historyGroup.ts index a37704c540..a7c7129d3c 100644 --- a/src/editor/lsp/historyGroup.ts +++ b/src/editor/lsp/historyGroup.ts @@ -2,31 +2,82 @@ * One undo step for an edit made of several transactions (a server refactoring, its * reformatting and the in-place rename after it): while a group is open its * transactions stay out of the undo history, and closing it records the net change once. + * + * A server edit applied as a workspace refactoring brings its own history marker (undone + * through the backend, every file at once). Then the marker is the group's undo step, and the + * local edits after the server's are kept as the refactoring's follow-up edits: undoing the + * refactoring reverts them first, redoing it applies them again. */ -import { EditorState, StateEffect, StateField, Transaction, type Text } from "@codemirror/state"; +import { ChangeSet, EditorState, StateEffect, StateField, Transaction, type Text } from "@codemirror/state"; import type { EditorView } from "@codemirror/view"; +import { + isExternalChange, + workspaceEditFollowUps, + workspaceEditMarker, + type WorkspaceEditFollowUp, +} from "@/editor/api"; + +interface Group { + start: Text; + /** The text after the last change that came from elsewhere (the server's workspace edit). */ + base: Text; + /** The local changes since `base`. */ + local: ChangeSet; + /** The workspace refactoring whose marker landed while the group was open. */ + marker: number | null; +} const setGroup = StateEffect.define(); +const addFollowUp = StateEffect.define<{ id: number; followUp: WorkspaceEditFollowUp }>(); -const groupStart = StateField.define({ +const groupField = StateField.define({ create: () => null, - update(value, tr) { - for (const e of tr.effects) if (e.is(setGroup)) return e.value; - return value; + update(group, tr) { + for (const e of tr.effects) + if (e.is(setGroup)) + return e.value ? { start: e.value, base: e.value, local: ChangeSet.empty(e.value.length), marker: null } : null; + if (!group) return group; + const marker = tr.annotation(workspaceEditMarker) ?? group.marker; + if (!tr.docChanged) return marker === group.marker ? group : { ...group, marker }; + if (isExternalChange(tr)) return { ...group, marker, base: tr.newDoc, local: ChangeSet.empty(tr.newDoc.length) }; + return { ...group, marker, local: group.local.compose(tr.changes) }; }, }); +/** The follow-up edits of the refactorings made in this editor (the latest few). */ +const followUpField = StateField.define>({ + create: () => new Map(), + update(value, tr) { + let next: Map | null = null; + for (const e of tr.effects) + if (e.is(addFollowUp)) { + next ??= new Map(value); + next.set(e.value.id, e.value.followUp); + while (next.size > 20) next.delete(next.keys().next().value!); + } + return next ?? value; + }, +}); + +// Only edits stay out of the history: a refactoring's marker (effects alone) must stay in it. const outOfHistory = EditorState.transactionExtender.of((tr) => - tr.startState.field(groupStart, false) && !tr.effects.some((e) => e.is(setGroup)) + tr.docChanged && tr.startState.field(groupField, false) && !tr.effects.some((e) => e.is(setGroup)) ? { annotations: Transaction.addToHistory.of(false) } : null, ); -export const historyGroupExtension = [groupStart, outOfHistory]; +export const historyGroupExtension = [ + groupField, + followUpField, + outOfHistory, + workspaceEditFollowUps.of((state, id) => state.field(followUpField, false)?.get(id) ?? null), +]; -export function beginHistoryGroup(view: EditorView): void { - if (view.state.field(groupStart, false) === undefined) return; +/** Opens a group; false when one is already open (the outer one then covers the edit) or unsupported. */ +export function beginHistoryGroup(view: EditorView): boolean { + if (view.state.field(groupField, false) !== null) return false; view.dispatch({ effects: setGroup.of(view.state.doc) }); + return true; } /** The one replacement turning `a` into `b` (common prefix and suffix kept). */ @@ -43,9 +94,28 @@ function difference(a: Text, b: Text): { from: number; to: number; insert: strin /** Closes the group: its net change becomes one undo step (`userEvent`). */ export function endHistoryGroup(view: EditorView, userEvent: string): void { - const start = view.state.field(groupStart, false); - if (!start) return; + const group = view.state.field(groupField, false); + if (!group) return; const end = view.state.doc; + if (group.marker !== null) { + // The refactoring's marker is the undo step; the edits after the server's go with it. + const changed = !group.base.eq(end); + view.dispatch({ + effects: [ + setGroup.of(null), + ...(changed + ? [ + addFollowUp.of({ + id: group.marker, + followUp: { changes: group.local, revert: group.local.invert(group.base), end }, + }), + ] + : []), + ], + }); + return; + } + const { start } = group; const selection = view.state.selection; const back = difference(end, start); if (!back) { diff --git a/src/editor/lsp/inplaceRename.ts b/src/editor/lsp/inplaceRename.ts index 9181f1a404..e9cff612b1 100644 --- a/src/editor/lsp/inplaceRename.ts +++ b/src/editor/lsp/inplaceRename.ts @@ -31,7 +31,7 @@ import { type ViewUpdate, } from "@codemirror/view"; import { completionStatus } from "@codemirror/autocomplete"; -import { isExternalChange } from "@/editor/api"; +import { isExternalChange, settleWorkspaceEdit } from "@/editor/api"; import { tooltipBounds } from "@/editor/core/cm/setup"; import { tx } from "@/platform/i18n"; @@ -301,7 +301,10 @@ const watcher = ViewPlugin.fromClass( !changesWithin(tr.changes, before.primary) ); }); - if (outside || foreignEdit) queueMicrotask(() => endInplaceRename(this.view, "commit")); + // Undoing the refactoring from its notification puts the introduced name back first. + const settle = u.transactions.some((tr) => tr.effects.some((e) => e.is(settleWorkspaceEdit))); + if (settle) queueMicrotask(() => endInplaceRename(this.view, "cancel")); + else if (outside || foreignEdit) queueMicrotask(() => endInplaceRename(this.view, "commit")); } }, ); diff --git a/src/editor/lsp/intentions.ts b/src/editor/lsp/intentions.ts index 2f26c8a849..d93a34bfe2 100644 --- a/src/editor/lsp/intentions.ts +++ b/src/editor/lsp/intentions.ts @@ -3,6 +3,7 @@ * intentions popup (quick fixes first, preferred in bold), Optimize Imports and * Generate. Refactor This and the Refactor menu live in `@/editor/refactor`. */ +import { beginHistoryGroup, endHistoryGroup } from "./historyGroup"; import { StateEffect, StateField, type Extension, type Text } from "@codemirror/state"; import { EditorView, ViewPlugin, type ViewUpdate } from "@codemirror/view"; import { forEachDiagnostic } from "@codemirror/lint"; @@ -262,14 +263,20 @@ export async function applyCodeAction(view: EditorView, action: EditorQuickFix) const client = !action.edit && action.command ? clientCommands.get(action.command.command) : undefined; if (client && (await client(view, action.command!.arguments.map(parseArgument)))) return; const before = view.state.doc; + // The server's edit and its reformatting undo as one step (with the refactoring's own Undo). + const grouped = beginHistoryGroup(view); try { - if (!(await runInteractiveCodeAction(doc.doc, action))) return; - } catch (e) { - reportLspError(view, e, true); - return; + try { + if (!(await runInteractiveCodeAction(doc.doc, action))) return; + } catch (e) { + reportLspError(view, e, true); + return; + } + if (!action.kind?.startsWith("source.organizeImports") && !action.kind?.startsWith("source.fixAll")) + await reformatGenerated(view, before); + } finally { + if (grouped) endHistoryGroup(view, "quickfix"); } - if (!action.kind?.startsWith("source.organizeImports") && !action.kind?.startsWith("source.fixAll")) - await reformatGenerated(view, before); } /**