diff --git a/src/editor/api.ts b/src/editor/api.ts index ab51b7b48..daec15af5 100644 --- a/src/editor/api.ts +++ b/src/editor/api.ts @@ -972,6 +972,8 @@ export interface DocumentAttachment { doc: number; /** Current document text; build the view's state from it. */ text(): string; + /** Current document text as a CodeMirror snapshot, with UTF-16 offsets. */ + contents(): Text; /** The document's line ending (detected on load, as the status bar shows). */ lineEnding(): LineEnding; /** The document's language mode name (backend-assigned, as the editor tabs use). */ @@ -985,6 +987,8 @@ export interface DocumentAttachment { subscribeExternalChanges(listener: (changes: ChangeSet) => void): () => void; /** Last view state, kept current while unmounted; use it when remounting this attachment. */ editorState(): EditorState | null; + /** Formatting state with the document's Code Style and any contributed formatter. */ + formattingState(): EditorState; /** Dispatch typing through the document history when `sharedHistory` was requested. */ dispatchTransactions(transactions: readonly Transaction[], view: EditorView): void; /** Add to the view (one view at a time). */ @@ -1007,7 +1011,7 @@ export interface DocumentAttachment { * file, so Undo there reverts it too; else this view's. Before either exists, * applies the edit directly to the document. */ - edit(changes: ChangeSpec, userEvent?: string): void; + edit(changes: ChangeSpec, userEvent?: string, annotations?: readonly Annotation[]): void; /** Detach; the document closes when nothing else shows it. */ release(): void; } @@ -1015,6 +1019,8 @@ export interface DocumentAttachment { export interface DocumentAttachmentOptions { /** Record typing in the text tab's history when one exists. Use `dispatchTransactions` on the view. */ sharedHistory?: boolean; + /** Load the history of an existing text tab that has yet to be shown. */ + preserveTabHistory?: boolean; } let documentAttacher: ((path: string, options?: DocumentAttachmentOptions) => Promise) | null = diff --git a/src/editor/core/controller.ts b/src/editor/core/controller.ts index 7c80f3715..13313441a 100644 --- a/src/editor/core/controller.ts +++ b/src/editor/core/controller.ts @@ -24,6 +24,7 @@ import { isLibraryPath, markLibraryFile, shownLine, + type DocumentAttachmentOptions, type NavigationLocation, } from "@/editor/api"; import { @@ -102,6 +103,7 @@ import { type TabsState, } from "./model/tabs"; import { DocumentManager, useDocMeta } from "./model/document"; +import { attachDocument } from "./model/attachment"; import { installDiskSync } from "./diskSync"; import { closedDocuments, @@ -773,6 +775,23 @@ export class EditorController implements SlotHost { return this.slots.get(tabId) ?? null; } + /** Attach to a file for an edit without selecting its tab or creating a new one. */ + async attachDocument(path: string, options?: DocumentAttachmentOptions) { + const doc = await attachDocument(this.manager, path, options); + if (options?.preserveTabHistory) { + const existing = findTab(useTabs.getState(), fileKey(path)); + if (existing) { + try { + await this.ensureSlot(existing.tab.id); + } catch (e) { + doc.release(); + throw e; + } + } + } + return doc; + } + /** Creates the slot of a file tab (opening its document) if needed. */ ensureSlot(tabId: string, init?: { from?: EditorSlot }): Promise { const existing = this.slots.get(tabId); diff --git a/src/editor/core/index.ts b/src/editor/core/index.ts index 97104ac2b..d3e5b9de6 100644 --- a/src/editor/core/index.ts +++ b/src/editor/core/index.ts @@ -17,7 +17,6 @@ import { formatDocument } from "@/editor/lsp/format"; import { chooserTitle, locationItems, pinToFind } from "@/editor/lsp/navigation"; import { openPopup } from "@/editor/lsp/popupStore"; import { editorController, useTabs } from "./controller"; -import { attachDocument } from "./model/attachment"; import { previewExtensions } from "./cm/preview"; import { registerEditorActions } from "./actions"; import { registerLibrarySourcesActions } from "./librarySources"; @@ -83,7 +82,7 @@ export function activate(): void | (() => void) { return !!handle && (await formatDocument(handle.view, { explicit: false, selectionOnly: false })).applied; }, }); - _provideDocumentAttacher((path, options) => attachDocument(ctrl.manager, path, options)); + _provideDocumentAttacher((path, options) => ctrl.attachDocument(path, options)); _provideCopyPathChooser(openCopyPathChooser); _provideCodePreview((path, editable) => previewExtensions(path, ctrl.manager.settings()?.editor, ctrl.manager.backend, editable), diff --git a/src/editor/core/model/attachment.ts b/src/editor/core/model/attachment.ts index c3f4175d3..089a96131 100644 --- a/src/editor/core/model/attachment.ts +++ b/src/editor/core/model/attachment.ts @@ -27,6 +27,7 @@ import { import { restoresVcsText, useDocMeta, type DocAttachmentTarget, type DocumentManager } from "./document"; import { saveOnBlur } from "../saveOnBlur"; import { editorHistoryKeymap } from "../cm/baseKeymap"; +import { contributionExtensions, indentExtension } from "../cm/setup"; class AttachedView implements DocAttachmentTarget { view: EditorView | null = null; @@ -125,6 +126,7 @@ export async function attachDocument( path, doc: model.doc, text: () => model.sync.localText.toString(), + contents: () => model.sync.localText, lineEnding: () => model.getMeta().lineEnding, uiMode: () => model.getMeta().uiMode, context: () => model.ctx(), @@ -140,6 +142,16 @@ export async function attachDocument( return () => void target.listeners.delete(listener); }, editorState: () => target.view?.state ?? target.storedState, + formattingState: () => + model.primarySlot()?.currentState() ?? + EditorState.create({ + doc: model.sync.localText, + extensions: [ + model.language ?? [], + indentExtension(model.effectiveIndent(), model.formatIndent()), + contributionExtensions(model.ctx()), + ], + }), dispatchTransactions: (transactions, view) => { for (const tr of transactions) { const slot = options.sharedHistory && model.primarySlot(); @@ -213,12 +225,12 @@ export async function attachDocument( dirty: () => model.getMeta().dirty, undo: () => historyCommand(undo), redo: () => historyCommand(redo), - edit: (changes, userEvent = "input") => { + edit: (changes, userEvent = "input", annotations) => { if (released || model.closed || model.ctx().readOnly) return; // Into the document's history, like a typed edit: the text tab's when there is one. const slot = model.primarySlot(); - if (slot) slot.dispatchLocal({ changes, userEvent }); - else if (target.view) target.view.dispatch({ changes, userEvent }); + if (slot) slot.dispatchLocal({ changes, userEvent, annotations }); + else if (target.view) target.view.dispatch({ changes, userEvent, annotations }); else { const edit = ChangeSet.of(changes, model.sync.localText.length); if (edit.empty) return; diff --git a/src/editor/lsp/actions.ts b/src/editor/lsp/actions.ts index 9dede46ce..9ad3a813a 100644 --- a/src/editor/lsp/actions.ts +++ b/src/editor/lsp/actions.ts @@ -5,10 +5,12 @@ import type { EditorView } from "@codemirror/view"; import { executeAction, registerActions, type Action } from "@/platform/actions"; import { activeEditor, + attachDocument, editorsFor, focusedCellEditor, registerSaveParticipant, whenSynced, + type DocumentAttachment, type TextEditorHandle, } from "@/editor/api"; import { call, commands } from "@/platform/ipc"; @@ -29,7 +31,7 @@ import { languageSemantics } from "./semantic"; import { caretAnchor, openPopup } from "./popupStore"; import { workflowSettings, type ActionsOnSaveValid } from "@/platform/workflowSettings"; import { startRename } from "./rename"; -import { fixRuffDocument, formatDocument, reformatDialog, type FormatResult } from "./format"; +import { fixRuffDocument, formatAttachedDocument, formatDocument, reformatDialog, type FormatResult } from "./format"; import { showHint } from "./hint"; import { refactorThis, @@ -139,10 +141,10 @@ const fixStylelintProblems = (v: EditorView) => const REMOVE_UNUSED_IMPORTS_FIRST = new Set(["javascript", "javascriptreact", "typescript", "typescriptreact"]); /** Removes unused imports where the server keeps that apart from organizing them; true when it did. */ -export async function removeUnusedImports(view: EditorView): Promise { - const language = docOf(view)?.language; +export async function removeUnusedImports(target: EditorView | DocumentAttachment): Promise { + const language = ("context" in target ? target.context() : docOf(target))?.language; if (!language || !REMOVE_UNUSED_IMPORTS_FIRST.has(language)) return false; - return applyKindSilently(view, "source.removeUnusedImports"); + return applyKindSilently(target, "source.removeUnusedImports"); } const optimizeImports = async (v: EditorView) => { @@ -191,43 +193,50 @@ export interface CleanupOptions { } /** The lines changed since the last commit, as document ranges; none outside version control. */ -async function vcsChangedRanges(view: EditorView): Promise> { - const path = docOf(view)?.path; +async function vcsChangedRanges(target: EditorView | DocumentAttachment): Promise> { + const path = "context" in target ? target.path : docOf(target)?.path; if (!path) return []; // The hunks are computed against the backend's copy of the text. - await whenSynced(view); + if ("context" in target) await target.synced(); + else await whenSynced(target); let hunks; try { hunks = await call(commands.vcsLineHunks(path)); } catch { return []; } - const doc = view.state.doc; + const doc = "context" in target ? target.contents() : target.state.doc; return hunks .filter((h) => h.lines > 0 && h.start < doc.lines) .map((h) => ({ from: doc.line(h.start + 1).from, to: doc.line(Math.min(h.start + h.lines, doc.lines)).to })); } /** Code Cleanup of one document: the server's fix-all, organize imports, then reformat (whose result it returns). */ -async function cleanup(view: EditorView, o: CleanupOptions): Promise { - if (o.fixAll !== false) await applyKindSilently(view, "source.fixAll"); +async function cleanup(target: EditorView | DocumentAttachment, o: CleanupOptions): Promise { + if (o.fixAll !== false) await applyKindSilently(target, "source.fixAll"); if (o.optimizeImports !== false) { - await removeUnusedImports(view); - await applyKindSilently(view, "source.organizeImports"); + await removeUnusedImports(target); + await applyKindSilently(target, "source.organizeImports"); } if (o.reformat === false) return null; - const ranges = o.changedTextOnly ? await vcsChangedRanges(view) : undefined; - return formatDocument(view, { explicit: false, selectionOnly: false, ranges }); + const ranges = o.changedTextOnly ? await vcsChangedRanges(target) : undefined; + return "context" in target + ? formatAttachedDocument(target, ranges) + : formatDocument(target, { explicit: false, selectionOnly: false, ranges }); } -/** - * Code Cleanup of the file at `path`, opened in the editor first: the batch step of - * Code Cleanup and of Reformat Code on a directory. The reformat's result, or `null` - * when the file has no text editor or reformatting was not asked for. - */ +/** Clean up and save one file of a background batch through its shared document. */ export async function cleanupFile(path: string, o: CleanupOptions): Promise { - const ed = await editorAt(path); - return ed && ed.ctx.path === path ? cleanup(ed.view, o) : null; + const doc = await attachDocument(path, { preserveTabHistory: true }).catch(() => null); + if (!doc) return null; + try { + const result = await cleanup(doc, o); + // Save actions could reformat the entire file after a changed-text-only reformat. + await doc.save({ exact: true }); + return result; + } finally { + doc.release(); + } } /** Code action titles of Implement Methods (⌃I) and Override Methods (⌃O). */ diff --git a/src/editor/lsp/format.ts b/src/editor/lsp/format.ts index 9f70c8d7b..3ced01488 100644 --- a/src/editor/lsp/format.ts +++ b/src/editor/lsp/format.ts @@ -23,7 +23,13 @@ import { type FormatGuardOptions, } from "@/platform/formatGuard"; import { useProject } from "@/platform/project"; -import { CONTRIBUTED_FORMAT, contributedAt, whenSynced, type ContributedFormatter } from "@/editor/api"; +import { + CONTRIBUTED_FORMAT, + contributedAt, + whenSynced, + type ContributedFormatter, + type DocumentAttachment, +} from "@/editor/api"; import { docOf, isUnavailable, lspRequest, reportLspError } from "./lsp"; import { formatIndentFacet } from "../core/cm/setup"; import { offsetToPos, textEditsToChanges } from "./positions"; @@ -142,30 +148,45 @@ export async function formatDocument( return result; } +/** Reformat through the shared document, including the history of any open tab. */ +export function formatAttachedDocument( + doc: DocumentAttachment, + ranges?: readonly OffsetRange[], +): Promise { + return format(doc, { explicit: false, selectionOnly: false, ranges }); +} + /** Ruff's safe lint fixes on save, before the file is written and independently of formatting. */ export async function fixRuffDocument(view: EditorView): Promise { return format(view, { explicit: false, selectionOnly: false, onSave: true, safeFix: true }); } -async function format(view: EditorView, opts: FormatDocumentOptions): Promise { +async function format(target: EditorView | DocumentAttachment, opts: FormatDocumentOptions): Promise { const { project, settings } = useProject.getState(); const guard = formatGuardOptions(settings); - const path = docOf(view)?.path; + const view = "context" in target ? null : target; + const doc = "context" in target ? target.context() : docOf(target); + const path = doc?.path; if (!opts.safeFix && path && formatExcluded(path, project?.root ?? null, guard.doNotFormat)) { - if (opts.explicit) + if (view && opts.explicit) showHint(view, "Formatting is turned off for this file (Code Style › Formatter › Do not format)"); return NOTHING; } - const own = contributedAt(view.state, CONTRIBUTED_FORMAT, 0); + if ("context" in target) { + if (target.readOnly) return NOTHING; + await target.synced(); + } + const stateBeforeSync = "context" in target ? target.formattingState() : target.state; + const own = contributedAt(stateBeforeSync, CONTRIBUTED_FORMAT, 0); if (own && !opts.tool && !opts.safeFix) { - if (opts.onSave && !settings?.editor?.formatOnSave) return NOTHING; - return applyContributedFormat(view, own, opts, guard); + if (stateBeforeSync.readOnly || (opts.onSave && !settings?.editor?.formatOnSave)) return NOTHING; + const changes = contributedFormatChanges(stateBeforeSync, own, opts, guard); + return applyFormatChanges(target, stateBeforeSync.doc, changes, opts); } - const doc = docOf(view); if (!doc || doc.readOnly) return NOTHING; // The server formats the backend's copy: let pending keystrokes reach it first. - await whenSynced(view); - const state = view.state; + if (view) await whenSynced(view); + const state = view?.state ?? stateBeforeSync; const targets = targetRanges(state, opts); if (!targets.length) return NOTHING; const options = formatOptionsOf(state); @@ -225,28 +246,35 @@ async function format(view: EditorView, opts: FormatDocumentOptions): Promise @@ -314,17 +340,6 @@ function applyContributedFormat( ), guard, ); - if (!changes.length) { - if (opts.explicit) showHint(view, "No lines changed: content is already properly formatted"); - return NOTHING; - } - view.dispatch({ - changes, - userEvent: "format.reformat", - annotations: isolateHistory.of("full"), - scrollIntoView: false, - }); - return { applied: true, changes: changes.length, lines: formattedLines(state.doc, changes) }; } /** The dialog's last choices, as IDEA remembers them. */ diff --git a/src/editor/lsp/intentions.ts b/src/editor/lsp/intentions.ts index 3864bb33e..4d85a84fe 100644 --- a/src/editor/lsp/intentions.ts +++ b/src/editor/lsp/intentions.ts @@ -21,6 +21,7 @@ import { intentionsChanged, whenSynced, type ContributedIntention, + type DocumentAttachment, } from "@/editor/api"; import { shortcutLabel } from "@/platform/keymap"; import { debounce, docOf, isUnavailable, lspRequest, reportLspError } from "./lsp"; @@ -361,19 +362,24 @@ export function changedLines(before: Text, after: Text): Array<{ from: number; t return spans; } -/** - * Applies the first enabled whole-file action of `kind` without UI (Actions on - * Save). Waits until the backend edit reached this editor; false when none. - */ /** * Applies the server's `kind` action to the whole document without UI (Actions on Save, * Code Cleanup). Fix-all runs once per server that offers it, one after another, each * asked again for the document as the previous one left it (VS Code's codeActionsOnSave): * vtsls and ESLint both answer `source.fixAll` for a TypeScript file. */ -export async function applyKindSilently(view: EditorView, kind: string): Promise { - const doc = docOf(view); +export async function applyKindSilently(target: EditorView | DocumentAttachment, kind: string): Promise { + const doc = "context" in target ? target.context() : docOf(target); if (!doc || doc.readOnly) return false; + const text = () => ("context" in target ? target.contents() : target.state.doc); + const fetch = async () => { + if (!("context" in target)) return fetchActions(target, [kind], true); + if (target.readOnly) return []; + await target.synced(); + const content = target.contents(); + const range = offsetsToRange(content, 0, content.length); + return lspRequest(() => commands.lspCodeActions(doc.doc, range, [kind])); + }; const matching = (actions: CodeAction[], server?: CodeAction["server"]) => actions.filter( (a) => @@ -385,7 +391,7 @@ export async function applyKindSilently(view: EditorView, kind: string): Promise const pick = (actions: CodeAction[]) => actions.find((a) => a.isPreferred) ?? actions[0]; let actions: CodeAction[]; try { - actions = matching(await fetchActions(view, [kind], true)); + actions = matching(await fetch()); } catch (e) { console.warn(`[lsp] ${kind} on ${doc.path} failed`, e); return false; @@ -402,15 +408,18 @@ export async function applyKindSilently(view: EditorView, kind: string): Promise // The previous server's edit changed the document: this one's answer must be fresh. try { // oxlint-disable-next-line no-await-in-loop -- the previous server's edit changed the document; this answer must be fresh - action = pick(matching(await fetchActions(view, [kind], true), server)); + action = pick(matching(await fetch(), server)); } catch (e) { console.warn(`[lsp] ${kind} on ${doc.path} failed`, e); continue; } if (!action) continue; } - const before = view.state.doc; - const chosen = action; + const before = text(); + // A resolved plugin action (server 0) can carry a file to show in its data. + // Apply its edit in the background while leaving navigation where it is. + const chosen = + "context" in target && action.server === 0 && action.edit && !action.command ? { ...action, data: null } : action; try { // oxlint-disable-next-line no-await-in-loop -- each server's edit is applied before the next server is queried await lspRequest(() => commands.lspApplyCodeAction(doc.doc, chosen)); @@ -419,7 +428,7 @@ export async function applyKindSilently(view: EditorView, kind: string): Promise continue; } applied = true; - for (let i = 0; i < 25 && view.state.doc === before; i++) { + for (let i = 0; i < 25 && text() === before; i++) { // oxlint-disable-next-line no-await-in-loop -- polls for this server's edit before moving to the next server await new Promise((r) => setTimeout(r, 20)); } diff --git a/src/features/analysis/cleanup.ts b/src/features/analysis/cleanup.ts index 62228543c..bf7c8be4d 100644 --- a/src/features/analysis/cleanup.ts +++ b/src/features/analysis/cleanup.ts @@ -1,14 +1,13 @@ /** * Code › Code Cleanup… and Reformat Code on directories or several files (project * view): the language servers' fix-all, organize imports and reformat, one file - * after another (opened, cleaned, saved; tabs opened only for the run are closed - * again). Cancellable from the Background Tasks popup. + * after another through the shared documents. Cancellable from the Background + * Tasks popup. */ -import { attachDocument } from "@/editor/api"; import { cleanupFile, type CleanupOptions as FileCleanupOptions } from "@/editor/lsp/actions"; import { call, commands, isTauri, type FileEntry } from "@/platform/ipc"; import { useProject } from "@/platform/project"; -import { maybeEditorService, notifications } from "@/workbench/contributions"; +import { notifications } from "@/workbench/contributions"; import { confirm } from "@/workbench/messages"; import { removeTask, upsertTask } from "@/workbench/tasks"; import { changedFiles, currentFile, type ScopeChoice } from "./scope"; @@ -92,20 +91,6 @@ export async function cleanupFiles(choice: ScopeChoice): Promise { - const document = await attachDocument(path).catch(() => null); - if (!document) return; - try { - await document.save({ exact: true }); - } finally { - document.release(); - } -} - interface RunSummary { /** Files processed before the end or a cancel. */ done: number; @@ -128,8 +113,7 @@ async function runOverFiles( if (running) return null; if (files.length > CONFIRM_ABOVE && !(await confirm({ title: task.title, message: task.confirm, ok: task.ok }))) return null; - const editors = maybeEditorService(); - const wasOpen = new Set(editors?.openPaths?.() ?? []); + if (running) return null; const run: { cancelled: boolean } = { cancelled: false }; running = run; const summary: RunSummary = { done: 0, formatted: 0, noFormatter: [], cancelled: false }; @@ -144,17 +128,10 @@ async function runOverFiles( done: false, cancel: () => (run.cancelled = true), }); - // oxlint-disable-next-line no-await-in-loop -- cleanup runs one file at a time so cancel, progress and open/close state stay ordered + // oxlint-disable-next-line no-await-in-loop -- clean and save each file before updating progress const result = await cleanupFile(path, options); if (result?.applied) summary.formatted++; if (result?.noFormatter) summary.noFormatter.push(path); - // oxlint-disable-next-line no-await-in-loop -- save the file just cleaned before its tab is closed - await saveCleaned(path); - // oxlint-disable-next-line no-await-in-loop -- a refused close cancels the run; editors must settle before the next file - if (!wasOpen.has(path) && (await editors?.closePath?.(path)) === false) { - run.cancelled = true; - break; - } summary.done++; } } finally { diff --git a/src/features/analysis/cleanupBatch.test.ts b/src/features/analysis/cleanupBatch.test.ts new file mode 100644 index 000000000..657c79b19 --- /dev/null +++ b/src/features/analysis/cleanupBatch.test.ts @@ -0,0 +1,229 @@ +import { undo } from "@codemirror/commands"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { _provideDocumentAttacher, editorsFor, registerSaveParticipant } from "@/editor/api"; +import { createMemoryBackend } from "@/editor/core/backend"; +import { EditorController, useTabs } from "@/editor/core/controller"; +import { storeSession } from "@/editor/core/model/session"; +import { initialTabsState } from "@/editor/core/model/tabs"; +import type { CodeAction, FileEntry } from "@/platform/ipc"; +import * as workbench from "@/workbench/contributions"; +import { runReformat } from "./cleanup"; + +const ipc = vi.hoisted(() => ({ + isTauri: vi.fn(), + languages: vi.fn(), + fsReadDir: vi.fn(), + lspFormat: vi.fn(), + lspCodeActions: vi.fn(), + lspApplyCodeAction: vi.fn(), + vcsStatus: vi.fn(), + vcsLineHunks: vi.fn(), +})); + +vi.mock("@/platform/ipc", async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, isTauri: ipc.isTauri, commands: { ...actual.commands, ...ipc } }; +}); + +const root = "/batch-reformat"; +const entry = (path: string, kind: FileEntry["kind"] = "file"): FileEntry => ({ + path, + name: path.slice(path.lastIndexOf("/") + 1), + kind, + size: 0, + mtimeMs: null, + ignored: false, + excluded: false, + hidden: false, +}); +const ok = (data: T) => ({ status: "ok" as const, data }); +const range = (line: number, end: number) => ({ start: { line, col: 0 }, end: { line, col: end } }); +const notify = vi.fn(); +let editor: EditorController | undefined; + +beforeEach(() => { + vi.resetAllMocks(); + ipc.isTauri.mockReturnValue(false); + ipc.languages.mockResolvedValue([{ extensions: ["java"] }]); + vi.spyOn(workbench, "notifications").mockReturnValue({ notify }); +}); + +afterEach(() => { + editor?.stop(); + editor = undefined; + _provideDocumentAttacher(null); + workbench.provideEditorService(undefined); + useTabs.setState(initialTabsState(), true); + storeSession(root, null); + vi.restoreAllMocks(); +}); + +function setup(files: Record) { + const backend = createMemoryBackend(files); + const controller = (editor = new EditorController(backend)); + controller.start(); + _provideDocumentAttacher((path, options) => controller.attachDocument(path, options)); + const openFile = vi.fn(controller.openFile.bind(controller)); + const closePath = vi.fn(controller.closePath.bind(controller)); + workbench.provideEditorService({ + openFile, + closePath, + openInput: controller.openInput.bind(controller), + activePath: controller.activePath.bind(controller), + activeCursor: controller.activeCursor.bind(controller), + openPaths: controller.openPaths.bind(controller), + saveAll: controller.saveAll.bind(controller), + }); + return { backend, controller, openFile, closePath }; +} + +it("reformats a directory and optimizes imports without opening, closing, or selecting tabs", async () => { + const active = `${root}/Active.java`; + const inactive = `${root}/Inactive.java`; + const unopened = `${root}/src/Unopened.java`; + const masked = `${root}/src/Skipped.java`; + const input = "import z.Z;\nclass C{}\n"; + const organized = "import a.A;\n"; + const formatted = `${organized}class C {}\n`; + const { backend, controller, openFile, closePath } = setup({ + [active]: input, + [inactive]: input, + [unopened]: input, + [masked]: input, + }); + storeSession(root, { + version: 1, + layout: { kind: "pane", tabs: [{ path: inactive }, { path: active }], active: 1 }, + activePane: 0, + files: {}, + }); + await controller.restoreSession(root); + const tabs = useTabs.getState().panes[useTabs.getState().activePane]!.tabs; + const activeSlot = await controller.ensureSlot(tabs[1]!.id); + expect(controller.slotFor(tabs[0]!.id)).toBeNull(); + const parent = document.createElement("div"); + document.body.append(parent); + const view = activeSlot!.mount(parent); + controller.onMounted(activeSlot!); + view.focus(); + const focused = document.activeElement; + const tabsChanged = vi.fn(); + const unsubscribe = useTabs.subscribe(tabsChanged); + try { + ipc.isTauri.mockReturnValue(true); + ipc.fsReadDir.mockImplementation(async (path) => + ok( + path === root + ? [entry(active), entry(inactive), entry(`${root}/src`, "dir")] + : [entry(unopened), entry(masked)], + ), + ); + const organize: CodeAction = { + kind: "source.organizeImports", + title: "Organize Imports", + isPreferred: true, + disabledReason: null, + edit: null, + command: { title: "Organize Imports", command: "organizeImports", arguments: [] }, + data: null, + server: 1, + }; + const pluginOrganize: CodeAction = { + ...organize, + server: 0, + edit: { files: [], preconditions: [] }, + command: null, + data: JSON.stringify({ plugin: "test", open: unopened }), + }; + ipc.lspCodeActions.mockImplementation(async (doc) => + ok([backend.docs.get(doc)?.path === inactive ? pluginOrganize : organize]), + ); + ipc.lspApplyCodeAction.mockImplementation(async (doc) => { + backend.patch(doc, [{ from: 0, to: organized.length, insert: organized }]); + return ok(null); + }); + ipc.lspFormat.mockImplementation(async (doc, target) => { + expect(target).toBeNull(); + expect((await backend.snapshot(doc)).text).toBe(`${organized}class C{}\n`); + return ok([{ range: range(1, 9), new_text: "class C {}" }]); + }); + + await runReformat([{ path: root, dir: true }], { + recursive: true, + optimizeImports: true, + mask: "*.java, !Skipped.java", + changedTextOnly: false, + }); + + expect(openFile).not.toHaveBeenCalled(); + expect(closePath).not.toHaveBeenCalled(); + expect(tabsChanged).not.toHaveBeenCalled(); + expect(controller.activeInput()?.path).toBe(active); + expect(document.activeElement).toBe(focused); + expect(view.state.doc.toString()).toBe(formatted); + expect(controller.slotFor(tabs[0]!.id)?.state.doc.toString()).toBe(formatted); + expect(editorsFor(unopened)).toEqual([]); + expect(backend.files.get(active)).toBe(formatted); + expect(backend.files.get(inactive)).toBe(formatted); + expect(backend.files.get(unopened)).toBe(formatted); + expect(backend.files.get(masked)).toBe(input); + await vi.waitFor(() => expect(controller.manager.get(unopened)).toBeUndefined()); + expect(ipc.lspApplyCodeAction).toHaveBeenCalledTimes(3); + expect(ipc.lspApplyCodeAction).toHaveBeenCalledWith(controller.slotFor(tabs[0]!.id)?.model.doc, { + ...pluginOrganize, + data: null, + }); + expect(notify).toHaveBeenCalledWith(expect.objectContaining({ title: "Reformatted 3 of 3 files" })); + + expect(undo(view)).toBe(true); + expect(view.state.doc.toString()).toBe(`${organized}class C{}\n`); + const inactiveSlot = controller.slotFor(tabs[0]!.id)!; + expect(undo({ state: inactiveSlot.state, dispatch: (tr) => inactiveSlot.dispatchLocal(tr) })).toBe(true); + expect(inactiveSlot.state.doc.toString()).toBe(`${organized}class C{}\n`); + await Promise.all([activeSlot!.model.sync.whenIdle(), inactiveSlot.model.sync.whenIdle()]); + } finally { + unsubscribe(); + activeSlot!.unmount(false); + parent.remove(); + } +}); + +it("formats only changed lines of an unopened file and saves without running save actions", async () => { + const changed = `${root}/Changed.java`; + const clean = `${root}/Clean.java`; + const nested = `${root}/src/Nested.java`; + const input = "class C{\nint n;\n}\n"; + const { backend, openFile } = setup({ [changed]: input, [clean]: input, [nested]: input }); + ipc.isTauri.mockReturnValue(true); + ipc.fsReadDir.mockResolvedValue(ok([entry(changed), entry(clean), entry(`${root}/src`, "dir")])); + ipc.vcsStatus.mockResolvedValue(ok([{ path: changed }, { path: nested }])); + ipc.vcsLineHunks.mockResolvedValue(ok([{ start: 1, lines: 1 }])); + ipc.lspFormat.mockResolvedValue( + ok([ + { range: range(0, 8), new_text: "class C {" }, + { range: range(1, 6), new_text: " int n;" }, + ]), + ); + const beforeSave = vi.fn(); + const dispose = registerSaveParticipant({ id: "test.formatOnSave", order: 50, beforeSave }); + try { + await runReformat([{ path: root, dir: true }], { + recursive: false, + optimizeImports: false, + mask: "", + changedTextOnly: true, + }); + + expect(openFile).not.toHaveBeenCalled(); + expect(ipc.fsReadDir).toHaveBeenCalledExactlyOnceWith(root); + expect(ipc.vcsLineHunks).toHaveBeenCalledExactlyOnceWith(changed); + expect(ipc.lspFormat).toHaveBeenCalledExactlyOnceWith(expect.any(Number), range(1, 6), expect.any(Object)); + expect(ipc.lspCodeActions).not.toHaveBeenCalled(); + expect(beforeSave).not.toHaveBeenCalled(); + expect(backend.files.get(changed)).toBe("class C{\n int n;\n}\n"); + expect(backend.files.get(clean)).toBe(input); + expect(backend.files.get(nested)).toBe(input); + } finally { + dispose(); + } +}); diff --git a/src/features/todo/PreviewEditor.test.tsx b/src/features/todo/PreviewEditor.test.tsx index 86c8a216d..cda242790 100644 --- a/src/features/todo/PreviewEditor.test.tsx +++ b/src/features/todo/PreviewEditor.test.tsx @@ -1,5 +1,6 @@ import { afterEach, describe, expect, it } from "vitest"; import { render, screen, waitFor } from "@testing-library/react"; +import { EditorState, Text } from "@codemirror/state"; import { EditorView } from "@codemirror/view"; import { _provideDocumentAttacher, type DocumentAttachment } from "@/editor/api"; import { PreviewEditor, heldAttachment } from "./PreviewEditor"; @@ -16,6 +17,7 @@ function stubAttacher(docs: Map docs.get(path)!.text, + contents: () => Text.of(docs.get(path)!.text.split("\n")), lineEnding: () => "lf", dirty: () => !!docs.get(path)!.dirty, uiMode: () => null, @@ -24,6 +26,7 @@ function stubAttacher(docs: Map () => {}, subscribeExternalChanges: () => () => {}, editorState: () => null, + formattingState: () => EditorState.create({ doc: docs.get(path)!.text }), dispatchTransactions: (trs, view) => view.update(trs), extension: EditorView.updateListener.of((u) => { for (const tr of u.transactions)