Файли
openidea/src/editor/api.ts
T
l0ng-ai 24ae0feaa5 fix(format): reformat a directory without opening an editor for each file
Reformat Code and Code Cleanup on a directory opened every file in a focused editor tab,
formatted it and moved on, so tabs flickered for the whole run. As in IDEA, files that
are not open are now formatted (and imports optimized) on their shared document and
saved without a tab; open files are changed in place, keeping the active tab and focus,
one undo step each. Options, progress, cancellation and the summary are unchanged.

Fixes #7221
2026-12-01 21:04:24 +08:00

1165 рядки
44 KiB
TypeScript
Неформатований Анотація Історія

Цей файл містить неоднозначні символи Юнікоду
Цей файл містить символи Юнікоду, які можна сплутати з іншими символами. Якщо ви вважаєте, що це зроблено навмисно, можете сміливо ігнорувати це попередження. Щоб показати їх, скористайтеся кнопкою Escape.
/**
* Editor extension contract (CodeMirror 6).
*
* `editor/core` owns EditorView creation, document sync with the backend,
* tabs/splits and the base IDEA keymap. Other features (LSP, VCS gutter,
* breakpoints, inline debug values…) never import editor internals; they
* contribute CodeMirror extensions per document through this module and read
* the active editor through `activeEditor()`.
*
* Notes for contributors:
* - A `TextEditorHandle` exists only while its tab is visible (background tabs
* keep just their EditorState); use `onEditorEvent` / `editorsFor` to react.
* - Contribution gutters render right of core's line numbers, change lane
* (`gutterLaneMarkers`) and fold chevrons, in contribution order.
* - Transactions applied from the backend carry `remoteChange`; ones mirrored
* from a split pane carry `mirroredChange` (see `isExternalChange`).
* - Right-hand overview marks: `scrollbarMarks`; save hooks:
* `registerSaveParticipant`; Back/Forward history: `getNavigationHistory`.
*/
import {
Annotation,
Compartment,
Facet,
type ChangeSet,
type ChangeSpec,
StateEffect,
type EditorState,
type Extension,
type RangeSet,
type Text,
type Transaction,
} from "@codemirror/state";
import { GutterMarker, ViewPlugin, type EditorView, type ViewUpdate } from "@codemirror/view";
import type { LanguageDescription } from "@codemirror/language";
import type { HunkKind } from "@/bindings";
import type { CodeAction, LineEnding } from "@/platform/ipc";
import { create } from "zustand";
import { maybeEditorService, type EditorInput, type MenuGroupContext } from "@/workbench/contributions";
import { isSameOrInside } from "@/platform/paths";
import { useProject } from "@/platform/project";
import { rootOfPath } from "@/platform/projectRoots";
import { isVirtualUri } from "@/platform/virtualDocs";
import { cornerInset } from "@/editor/core/cm/cornerInset";
export { iconAreaSource, mapLineStart, type IconAreaSource } from "@/editor/core/cm/iconArea";
export {
invalidateNavigationProviders,
navigationEpoch,
onNavigationProvidersChanged,
registerNavigationProvider,
type NavigationMatch,
} from "@/editor/navigationProviders";
export { registerRelatedProvider, type RelatedContext, type RelatedItem } from "@/editor/relatedProviders";
export {
contributedUsages,
registerRenameProvider,
registerUsageProvider,
type ContributedRename,
type UsageQuery,
} from "@/editor/refactorProviders";
export { offsetsToRange, offsetToPos, posToOffset, rangeToOffsets, textEditsToChanges } from "@/editor/lsp/positions";
/** Documents above this size (UTF-16 units) skip per-line decorations. */
export const HEAVY_LIMIT = 8_000_000;
export interface EditorDocContext {
doc: number;
path: string;
/** Backend language id, e.g. `rust`. */
language: string;
/** `@codemirror/language-data` name, e.g. `Rust`, if any. */
uiMode: string | null;
readOnly: boolean;
/**
* A read-only virtual document (library class contents from a language
* server); `path` is then its URI, not a file: skip file-based features
* (VCS, local history, TODO scanning…). JDT class documents support breakpoints.
*/
virtual?: boolean;
}
export interface EditorContribution {
id: string;
/** Lower runs first; affects precedence of keymaps/decorations. Default 100. */
order?: number;
/** Return extensions for one editor instance (called on creation). */
extensions: (ctx: EditorDocContext) => Extension | Extension[];
/**
* Also applies to editable editors outside editor/core (the diff viewer's
* editable side, the merge result), which get `doc: -1`. Default false.
*/
embedded?: boolean;
/**
* Extensions for a notebook code cell's editor, whose `doc` and `path` are the cell's
* language-server document and URI (see {@link cellEditorExtensions}).
*/
cellExtensions?: (ctx: EditorDocContext) => Extension | Extension[];
/**
* Extensions for a diff viewer pane that shows a file's open document (the working copy,
* Compare Files): `ctx` is that document's (see {@link diffSideExtensions}).
*/
diffExtensions?: (ctx: EditorDocContext) => Extension | Extension[];
}
/**
* Editor extensions whose code loads with the first editor that wants them: `wants`
* decides synchronously, `load` resolves the real `extensions`. Until it has, the editor
* runs without them and reconfigures once loaded.
*/
export function lazyEditorExtension(
wants: (ctx: EditorDocContext) => boolean,
load: () => Promise<(ctx: EditorDocContext) => Extension>,
): (ctx: EditorDocContext) => Extension {
let loaded: ((ctx: EditorDocContext) => Extension) | null = null;
let pending: Promise<(ctx: EditorDocContext) => Extension> | null = null;
const get = () =>
(pending ??= load().then(
(f) => (loaded = f),
(e: unknown) => {
pending = null;
throw e;
},
));
return (ctx) => {
if (!wants(ctx)) return [];
if (loaded) return loaded(ctx);
const slot = new Compartment();
return [
slot.of([]),
ViewPlugin.define((view) => {
let live = true;
get().then(
(f) => live && view.dispatch({ effects: slot.reconfigure(f(ctx)) }),
(e: unknown) => console.error("could not load editor extensions", e),
);
return {
destroy: () => {
live = false;
},
};
}),
];
};
}
export interface TextEditorHandle {
view: EditorView;
ctx: EditorDocContext;
/** The editor tab it shows, for the editors of tabs (not diff sides, previews…). */
tabId?: string;
}
interface EditorRegistry {
contributions: Map<string, EditorContribution>;
/** Focused text editor, or the last focused one when focus is elsewhere. */
active: TextEditorHandle | null;
/** All live text editors (one per visible editor pane). */
editors: Set<TextEditorHandle>;
}
export const useEditorRegistry = create<EditorRegistry>(() => ({
contributions: new Map(),
active: null,
editors: new Set(),
}));
/**
* Registers per-editor extensions. Existing editors are reconfigured by
* editor/core when contributions change (via a Compartment), so features may
* register at any time.
*/
export function registerEditorContribution(c: EditorContribution): () => void {
useEditorRegistry.setState((s) => ({ contributions: new Map(s.contributions).set(c.id, c) }));
return () =>
useEditorRegistry.setState((s) => {
const contributions = new Map(s.contributions);
contributions.delete(c.id);
return { contributions };
});
}
export function editorContributions(): EditorContribution[] {
return [...useEditorRegistry.getState().contributions.values()].sort((a, b) => (a.order ?? 100) - (b.order ?? 100));
}
const embeddedCompartment = new Compartment();
const embeddedViews = new Map<EditorView, EditorDocContext>();
function embeddedContributions(ctx: EditorDocContext): Extension[] {
const out: Extension[] = [];
for (const c of editorContributions()) {
if (!c.embedded) continue;
try {
out.push(c.extensions(ctx));
} catch (e) {
console.error(`editor contribution ${c.id} failed`, e);
}
}
return out;
}
/**
* Contributions flagged `embedded` for an editable editor that editor/core
* does not own (diff viewer, merge result). Reconfigured live when
* contributions change.
*/
export function embeddedEditorExtensions(path: string): Extension {
const ctx: EditorDocContext = { doc: -1, path, language: "", uiMode: null, readOnly: false };
return [
embeddedCompartment.of(embeddedContributions(ctx)),
ViewPlugin.define((view) => {
embeddedViews.set(view, ctx);
return { destroy: () => void embeddedViews.delete(view) };
}),
];
}
const embeddedOf = (m: Map<string, EditorContribution>) => [...m.values()].filter((c) => c.embedded);
/** The `diffExtensions` of every contribution, for a diff pane showing the open document of `ctx`. */
export function diffSideExtensions(ctx: EditorDocContext): Extension[] {
const out: Extension[] = [];
for (const c of editorContributions()) {
if (!c.diffExtensions) continue;
try {
out.push(c.diffExtensions(ctx));
} catch (e) {
console.error(`editor contribution ${c.id} failed`, e);
}
}
return out;
}
/** The `cellExtensions` of every contribution, for the editor of a notebook code cell. */
export function cellEditorExtensions(ctx: EditorDocContext): Extension[] {
const out: Extension[] = [];
for (const c of editorContributions()) {
if (!c.cellExtensions) continue;
try {
out.push(c.cellExtensions(ctx));
} catch (e) {
console.error(`editor contribution ${c.id} failed`, e);
}
}
return out;
}
useEditorRegistry.subscribe((s, prev) => {
if (s.contributions === prev.contributions) return;
const now = embeddedOf(s.contributions);
const before = embeddedOf(prev.contributions);
if (now.length === before.length && now.every((c, i) => c === before[i])) return;
for (const [view, ctx] of embeddedViews)
view.dispatch({ effects: embeddedCompartment.reconfigure(embeddedContributions(ctx)) });
});
export function activeEditor(): TextEditorHandle | null {
return useEditorRegistry.getState().active;
}
/** Editors currently showing `path` (split panes may show the same file). */
export function editorsFor(path: string): TextEditorHandle[] {
return [...useEditorRegistry.getState().editors].filter((e) => e.ctx.path === path);
}
/**
* While a cell editor of a custom editor (a notebook) has focus, it stands in for the
* active editor's view: the notebook publishes the editor context keys for it and
* editor actions resolve to it, like a text tab's view. The owner keeps this current
* on focus changes (see `_setFocusedCellEditor`); editor/core re-reads it whenever it
* republishes contexts, so actions never fall back to the last text tab.
*/
let focusedCell: EditorView | null = null;
/** The focused cell editor standing in for the active editor's view, if any. */
export function focusedCellEditor(): EditorView | null {
return focusedCell;
}
/** Published by the custom editor owning the cell editors (a notebook); `null` once none has focus. */
export function _setFocusedCellEditor(view: EditorView | null) {
focusedCell = view;
}
// --- called by editor/core only ---------------------------------------------
export function _setActiveEditor(handle: TextEditorHandle | null) {
useEditorRegistry.setState({ active: handle });
}
export function _addEditor(handle: TextEditorHandle) {
useEditorRegistry.setState((s) => ({ editors: new Set(s.editors).add(handle) }));
}
export function _removeEditor(handle: TextEditorHandle) {
useEditorRegistry.setState((s) => {
const editors = new Set(s.editors);
editors.delete(handle);
return { editors, active: s.active === handle ? null : s.active };
});
}
// ===========================================================================
// Additive extension points (owned by editor/core). Everything below is safe to
// use from any feature; none of it requires importing editor internals.
// ===========================================================================
/**
* Set on transactions that editor/core applies on behalf of the backend
* (`docPatched` events, resync after `outOfSync`). Such changes are already in
* the backend document; don't react to them as user typing (e.g. don't trigger
* completion).
*/
export const remoteChange = Annotation.define<boolean>();
/**
* Set on transactions mirrored from another view of the same document (split
* panes share one document model; each pane has its own selection/undo).
*/
export const mirroredChange = Annotation.define<boolean>();
/**
* A temporary change that must not reach the document model or the backend
* (an IME composition's preedit, which the feature removes again when the
* composition ends).
*/
export const transientChange = Annotation.define<boolean>();
/**
* Provided by editor/core per editor: resolves once the editor's local edits
* reached the backend document. Language-server requests read the backend's
* copy, so position-based requests that edit (format, rename) await it first.
*/
export const documentSynced = Facet.define<() => Promise<void>, (() => Promise<void>) | null>({
combine: (values) => values[0] ?? null,
});
/**
* Undo / Redo of an editor whose history is kept outside CodeMirror (notebook cells share
* the notebook's backend history). Commands that would call CodeMirror's history (Vim's
* `u` / `Ctrl-R`) go through it instead.
*/
export interface ExternalHistory {
undo(): void;
redo(): void;
}
export const externalHistory = Facet.define<ExternalHistory, ExternalHistory | null>({
combine: (values) => values[0] ?? null,
});
/**
* Provided by a host of several editors in a column (notebook cells): moves the caret into the
* editor before (`-1`) or after (`1`) this one, at `column` of its nearest line, when a line
* motion leaves this editor's first or last line. Returns false when there is none.
*/
export type AdjacentEditor = (direction: 1 | -1, column: number) => boolean;
export const adjacentEditor = Facet.define<AdjacentEditor, AdjacentEditor | null>({
combine: (values) => values[0] ?? null,
});
export function whenSynced(view: EditorView): Promise<void> {
return view.state.facet(documentSynced)?.() ?? Promise.resolve();
}
/** Edits made outside text editors (notebook cells) that language servers must have before a request. */
const pendingEdits = new Set<() => Promise<void>>();
/** `settled` resolves once the owner's edits reached the backend; included in {@link whenAllSynced}. */
export function registerPendingEdits(settled: () => Promise<void>): () => void {
pendingEdits.add(settled);
return () => void pendingEdits.delete(settled);
}
/** Every open editor's edits reached the backend (language servers answer from its copy). */
export function whenAllSynced(): Promise<void> {
const editors = useEditorRegistry.getState().editors;
const waits = [...[...editors].map((e) => whenSynced(e.view)), ...[...pendingEdits].map((settled) => settled())];
return waits.length ? Promise.all(waits).then(() => {}) : Promise.resolve();
}
/** True for doc changes that did not originate from typing in *this* view. */
export function isExternalChange(tr: Transaction): boolean {
return !!tr.annotation(remoteChange) || !!tr.annotation(mirroredChange);
}
/**
* A mark in the editor's right-hand overview lane (the 10px strip over the
* scrollbar, as in IDEA). Positions are document offsets of the state the
* facet value was computed for; editor/core maps them to the lane height.
*
* const marks = StateField.define<ScrollbarMark[]>({ … });
* registerEditorContribution({ id: "vcs.marks", extensions: () => [
* marks, scrollbarMarks.from(marks) ] });
*/
export interface ScrollbarMark {
from: number;
/** End offset; marks spanning several lines become taller. Defaults to `from`. */
to?: number;
/** CSS colour, normally a token such as `var(--danger)`. */
color: string;
/**
* `line` (default): 4px-wide bar on the lane; `thin`: 2px bar (search hits, occurrences);
* `full`: the lane's whole width, from the top of the first line to the top of the last (IDEA's
* diff and merge error stripe, so a one-line change is a min-height dash).
*/
kind?: "line" | "thin" | "full";
/** Shown on hover. */
tooltip?: string;
/** Higher wins when marks overlap. Default 0. */
priority?: number;
}
export const scrollbarMarks = Facet.define<readonly ScrollbarMark[], readonly ScrollbarMark[]>({
combine: (values) => (values.length === 1 ? values[0]! : values.flat()),
});
/**
* The 3px change-marker lane right of the line numbers (VCS added / modified /
* deleted bars, as in the design). Provide a `RangeSet<GutterMarker>` whose
* markers start at line starts; `LaneMarker` draws the bar:
*
* gutterLaneMarkers.compute([hunksField], (s) => RangeSet.of(
* s.field(hunksField).map((h) => new LaneMarker("var(--gutter-added)").range(s.doc.line(h.line + 1).from))))
*
* Several providers are layered (later ones on top).
*/
export const gutterLaneMarkers = Facet.define<RangeSet<GutterMarker>>();
/**
* The VCS changes the change-marker lane shows, as document offsets of this state (mapped
* through edits), in file order. `to <= from` draws a deletion notch on the line at `from`.
* Editor panels read them (`openidea.editor.changes()`).
*/
export interface LineChange {
kind: HunkKind;
from: number;
to: number;
}
export const lineChanges = Facet.define<readonly LineChange[], readonly LineChange[]>({
combine: (values) => values[0] ?? [],
});
/**
* Settings › Editor › General › Gutter: where the VCS change markers show. Set from the
* editor settings; the scrollbar marks follow the gutter setting, as in IDEA.
*/
export interface ChangeMarkerDisplay {
gutter: boolean;
scrollbar: boolean;
}
export const changeMarkerDisplay = Facet.define<ChangeMarkerDisplay, ChangeMarkerDisplay>({
combine: (values) => values[0] ?? { gutter: true, scrollbar: true },
});
/** Marker for `gutterLaneMarkers`: a solid 3px bar (or a small wedge for `deleted`). */
export class LaneMarker extends GutterMarker {
constructor(
readonly color: string,
readonly kind: "bar" | "deleted" = "bar",
readonly title?: string,
) {
super();
}
override eq(other: GutterMarker): boolean {
return (
other instanceof LaneMarker &&
other.color === this.color &&
other.kind === this.kind &&
other.title === this.title
);
}
override toDOM(): Node {
const el = document.createElement("div");
el.className = this.kind === "deleted" ? "cm-openidea-laneDeleted" : "cm-openidea-laneBar";
el.style.setProperty("--lane-color", this.color);
if (this.title) el.title = this.title;
return el;
}
}
/**
* A gutter spacer that renders nothing: pair it with `gutter`'s `updateSpacer`
* to reserve icon width only while the file has something to show.
*/
export const emptyGutterSpacer = new (class extends GutterMarker {})();
/** A gutter spacer reserving one icon of width, styled by `className`. */
export const gutterSpacer = (className: string) =>
new (class extends GutterMarker {
override toDOM(): Node {
const el = document.createElement("span");
el.className = className;
return el;
}
})();
/**
* The floating row at the editor's top-right (IDEA's inspection widget area): widgets
* append their element to it (CSS `order` sorts them; lower first) and remove it when
* done. The inspection widget sits there; code review adds its Review Mode group.
*
* const el = document.createElement("div");
* el.style.order = "-1";
* editorCorner(view).appendChild(el);
*/
export function editorCorner(view: EditorView): HTMLElement {
const found = view.dom.querySelector<HTMLElement>(":scope > .cm-openidea-corner");
if (found) return found;
const el = document.createElement("div");
el.className = "cm-openidea-corner";
Object.assign(el.style, {
position: "absolute",
top: "4px",
right: "16px",
zIndex: "5",
display: "flex",
alignItems: "center",
gap: "4px",
});
view.dom.appendChild(el);
// The lines leave room for its measured width, so it never covers a line end.
view.plugin(cornerInset)?.track(el);
return el;
}
// --- language support without a language server ----------------------------------
/**
* Language-data keys through which a feature answers editor requests for its
* documents before the language server is asked (the database console's SQL):
*
* EditorState.languageData.of(() => [{ [CONTRIBUTED_HOVER]: sqlHover }])
*/
export const CONTRIBUTED_FORMAT = "openideaFormat";
export const CONTRIBUTED_DEFINITION = "openideaDefinition";
export const CONTRIBUTED_HOVER = "openideaHover";
/** Reformat Code: replacements for `range` (the selection) or the whole document. */
export type ContributedFormatter = (
state: EditorState,
range: { from: number; to: number } | null,
) => Array<{ from: number; to: number; insert: string }>;
/** Go to Declaration / ⌘-click: `true` when it handled `pos`. May be async when
* the answer needs a lookup; `false` hands the position back to the language server. */
export interface ContributedDefinition {
(view: EditorView, pos: number): boolean | Promise<boolean>;
/** Cheap, side-effect-free eligibility for hover underline and navigation probing. */
canHandle?(state: EditorState, pos: number): boolean;
}
/** Hover and Quick Documentation: Markdown about the symbol at `pos`. */
export type ContributedHover = (
state: EditorState,
pos: number,
) => { from: number; to: number; markdown: string } | null;
export function contributedAt<T>(state: EditorState, key: string, pos: number): T | undefined {
return state.languageDataAt<T>(key, pos)[0];
}
/**
* Every provider registered for a contributed language-data key at `pos`. A provider may
* be present for the document but decline this particular position (the MyBatis SQL
* provider on a Maven POM, for example), so callers that dispatch a request must not stop
* at the first entry when it returns "not handled".
*/
export function contributedAtAll<T>(state: EditorState, key: string, pos: number): readonly T[] {
return state.languageDataAt<T>(key, pos);
}
/**
* A problem a feature marks on its own text (the database console's run errors
* and unsafe-query warnings): the editor's hover shows it like a diagnostic.
*
* problemProviders.of((state) => state.field(myField).problems)
*/
export interface ContributedProblem {
from: number;
to: number;
severity: "error" | "warning" | "info";
message: string;
}
export const problemProviders = Facet.define<(state: EditorState) => readonly ContributedProblem[]>();
/** The contributed problems whose range covers `pos`. */
export function contributedProblemsAt(state: EditorState, pos: number): ContributedProblem[] {
return state
.facet(problemProviders)
.flatMap((provider) => provider(state))
.filter((p) => p.from <= pos && pos <= p.to);
}
/** A context action a feature offers at the caret, listed by Show Context Actions (⌥↵). */
export interface ContributedIntention {
id: string;
label: string;
icon?: string;
quickFix?: boolean;
/** The preferred fix: bold, and first among the fixes. */
emphasis?: boolean;
run: () => void | Promise<void>;
/** A fallback for what the language server may offer itself: left out of ⌥↵ when one of its actions matches. */
supersededBy?: (action: CodeAction) => boolean;
}
/** A background provider has new context actions for the current document. */
export const intentionsChanged = StateEffect.define<null>();
/**
* A hidden editor view is shown again. Recently used tabs keep their view, detached from the
* document, while hidden; plugins that skip work while `view.dom` is disconnected redo it when
* `shownAgain`.
*/
export const viewShown = StateEffect.define<null>();
export function shownAgain(u: ViewUpdate): boolean {
return u.transactions.some((tr) => tr.effects.some((e) => e.is(viewShown)));
}
/** Local fixes of a diagnostic range (hover link and Apply Quick Fix). */
export const quickFixProviders = Facet.define<(view: EditorView, from: number, to: number) => ContributedIntention[]>();
export function contributedQuickFixes(view: EditorView, from: number, to: number): ContributedIntention[] {
return view.state.facet(quickFixProviders).flatMap((provider) => provider(view, from, to));
}
/**
* Extra rows for the ⌥↵ submenu of inspection `inspectionId` at the caret (after Edit
* inspection profile setting and Disable inspection), such as Suppress for statement.
* The producer's suppressed-rule list is part of `intentionControls` itself.
*/
export const inspectionControlProviders =
Facet.define<(view: EditorView, inspectionId: string) => readonly ContributedIntention[]>();
/** Providers of `ContributedIntention`s for the caret of `view` (cheap and synchronous: also drives the light bulb). */
export const intentionProviders = Facet.define<(view: EditorView) => ContributedIntention[]>();
export function contributedIntentions(view: EditorView): ContributedIntention[] {
return view.state.facet(intentionProviders).flatMap((p) => {
try {
return p(view);
} catch (e) {
console.error("intention provider failed", e);
return [];
}
});
}
/**
* Providers of context actions that need an answer from the language server first. ⌥↵ waits for
* them along with the server's code actions; the light bulb does too. `signal` aborts when the
* answer is no longer wanted (the caret moved on).
*/
export const asyncIntentionProviders =
Facet.define<(view: EditorView, signal: AbortSignal) => Promise<ContributedIntention[]>>();
export async function contributedIntentionsAsync(
view: EditorView,
signal: AbortSignal,
): Promise<ContributedIntention[]> {
const found = await Promise.all(
view.state.facet(asyncIntentionProviders).map((p) =>
Promise.resolve()
.then(() => p(view, signal))
.catch((e: unknown) => {
if (!signal.aborted) console.error("intention provider failed", e);
return [];
}),
),
);
return found.flat();
}
// --- navigation history ------------------------------------------------------
/** One entry of the Back/Forward (⌘[ / ⌘]) history. 0-based line, UTF-16 col. */
export interface NavigationLocation {
path: string;
line: number;
col: number;
/** `Date.now()` when the location was last visited. */
time: number;
/** A place that is a tab rather than a text position (diff, agent chat, terminal tab…), opened with this input on Back. */
input?: EditorInput;
/** Split pane holding the editor tab when recorded, so Back/Forward returns to the same split when it still exists. */
paneId?: string;
}
export interface NavigationHistorySnapshot {
/** Oldest first. */
entries: NavigationLocation[];
/** Index of the current location in `entries` (-1 when empty). */
index: number;
}
let navigationHistoryProvider: (() => NavigationHistorySnapshot) | null = null;
/** Location history recorded by editor/core (file switches and big caret jumps). */
export function getNavigationHistory(): NavigationHistorySnapshot {
return navigationHistoryProvider?.() ?? { entries: [], index: -1 };
}
/** @internal editor/core only. */
export function _provideNavigationHistory(provider: () => NavigationHistorySnapshot) {
navigationHistoryProvider = provider;
}
/** A project↔file-editor switch is clearing and re-filling the tabs. @internal editor/core only. */
let editorSwitchingFlag = false;
export function _setEditorSwitching(value: boolean) {
editorSwitchingFlag = value;
}
export function editorSwitching(): boolean {
return editorSwitchingFlag;
}
// --- editor events ------------------------------------------------------------
export type EditorEvent =
| { type: "inputModeChanged"; path: string; mode: string; sub: string | null }
| { type: "docOpened"; doc: number; path: string; language: string }
| { type: "docClosed"; doc: number; path: string }
/** After the backend wrote the file. */
| { type: "docSaved"; doc: number; path: string }
/** A local edit accepted by the shared document model. UTF-16 offsets. */
| {
type: "docChanged";
doc: number;
path: string;
baseVersion: number;
version: number;
changes: Array<{ from: number; to: number; insert: string }>;
}
/** The active (focused or last focused) editor tab changed; `path` is null for non-file tabs. */
| { type: "activeEditorChanged"; path: string | null; doc: number | null }
/** Caret moved in the active text editor (throttled to animation frames). 0-based. */
| { type: "caretMoved"; doc: number; path: string; line: number; col: number; offset: number };
/** Reports the focused editor's input mode from an editor contribution. */
export function reportInputMode(path: string, mode: string, sub: string | null) {
_emitEditorEvent({ type: "inputModeChanged", path, mode, sub });
}
type EditorEventListener = (e: EditorEvent) => void;
const editorEventListeners = new Set<EditorEventListener>();
export function onEditorEvent(listener: EditorEventListener): () => void {
editorEventListeners.add(listener);
return () => editorEventListeners.delete(listener);
}
/** @internal editor/core only. */
export function _emitEditorEvent(e: EditorEvent) {
for (const l of [...editorEventListeners]) {
try {
l(e);
} catch (err) {
console.error("editor event listener failed", err);
}
}
}
// --- save participants ----------------------------------------------------------
/**
* Runs before a modified document is written (format on save, organise imports…).
* Participants may edit the document through `handle.view` (normal
* transactions); editor/core waits for them, then trims whitespace / adds the
* final newline per settings, flushes the edit pipeline and saves. `handle`
* is null when no editor shows the document. Keep them fast; failures are
* logged and do not block saving.
*/
export interface SaveParticipant {
id: string;
/** Lower runs first. Default 100. */
order?: number;
/** `explicit` = ⌘S / Save All; participants are not run for autosave. */
beforeSave: (ctx: EditorDocContext, handle: TextEditorHandle | null, reason: "explicit") => Promise<void> | void;
}
const saveParticipants = new Map<string, SaveParticipant>();
export function registerSaveParticipant(p: SaveParticipant): () => void {
saveParticipants.set(p.id, p);
return () => {
if (saveParticipants.get(p.id) === p) saveParticipants.delete(p.id);
};
}
/** @internal editor/core only. */
export function _saveParticipants(): SaveParticipant[] {
return [...saveParticipants.values()].sort((a, b) => (a.order ?? 100) - (b.order ?? 100));
}
// --- helpers ------------------------------------------------------------------
/**
* Opens `path` (if needed) and selects/reveals `range` (0-based line, UTF-16
* col), recording a navigation history entry. Equivalent to
* `editorService().openFile(path, { selection })`.
*/
export async function revealRange(
path: string,
range: { start: { line: number; col: number }; end?: { line: number; col: number } },
options: { preview?: boolean; focus?: boolean; external?: boolean } = {},
): Promise<void> {
const service = maybeEditorService();
if (!service) return;
await service.openFile(path, {
...options,
selection: { line: range.start.line, col: range.start.col, endLine: range.end?.line, endCol: range.end?.col },
});
}
// --- code lenses -----------------------------------------------------------------
/**
* A code lens: a small clickable hint line rendered above a declaration, like
* IDEA's "3 usages" / "Run test" inlays. Several providers may contribute
* lenses for the same line; editor/core renders them in one row ordered by
* `order`. Positions are document offsets of the state the facet value was
* computed for (any offset on the target line).
*
* const lenses = StateField.define<CodeLens[]>({ … map through changes … });
* registerEditorContribution({ id: "run.lens", extensions: () => [
* lenses, codeLenses.from(lenses) ] });
*/
export interface CodeLens {
pos: number;
title: string;
tooltip?: string;
/** Icon name from `ui/icons`. */
icon?: string;
/** Click handler; lenses without one render as plain text. */
run?: (view: EditorView, event: MouseEvent) => void;
/** Lower first within a line. Default 100. */
order?: number;
/** The Code Vision setting that places it ("usages", "author"); a lens without one goes above the line. */
kind?: string;
}
export const codeLenses = Facet.define<readonly CodeLens[], readonly CodeLens[]>({
combine: (values) => (values.length === 1 ? values[0]! : values.flat()),
});
// --- open editors -------------------------------------------------------------------
let openPathsProvider: (() => string[]) | null = null;
/** Paths of every file open in an editor tab (all panes, visual order, unique). */
/**
* 0-based source line at the top of a view that shows a file instead of its text
* editor (Markdown Preview only), per path. Structure's Autoscroll from Source
* follows it while set; the owning view clears it when it stops standing in.
*/
const useShownLines = create<Record<string, number>>(() => ({}));
export function setShownLine(path: string, line: number | null) {
if ((useShownLines.getState()[path] ?? null) === line) return;
useShownLines.setState((s) => {
const next = { ...s };
if (line === null) delete next[path];
else next[path] = line;
return next;
}, true);
}
export function shownLine(path: string): number | null {
return useShownLines.getState()[path] ?? null;
}
export function useShownLine(path: string | null): number | null {
return useShownLines((s) => (path ? (s[path] ?? null) : null));
}
export function openEditorPaths(): string[] {
return openPathsProvider?.() ?? [];
}
/** @internal editor/core only. */
export function _provideOpenEditorPaths(provider: () => string[]) {
openPathsProvider = provider;
}
// --- library sources -----------------------------------------------------------------
const libraryRoots = new Map<string, readonly string[]>();
/**
* Folders of library / SDK sources ("External Libraries") contributed by `owner`;
* files below them open read-only, like IDEA's library sources. Replaces the
* owner's previous roots; returns a disposer.
*/
export function setLibraryRoots(owner: string, roots: readonly string[]): () => void {
libraryRoots.set(owner, roots);
return () => {
if (libraryRoots.get(owner) === roots) libraryRoots.delete(owner);
};
}
export function isLibraryPath(path: string): boolean {
if (navigatedLibraryFiles.has(path)) return true;
for (const roots of libraryRoots.values())
for (const r of roots) if (path === r || path.startsWith(r.endsWith("/") ? r : `${r}/`)) return true;
return false;
}
/** Whether `path` lies outside every folder of the open project (or workspace). */
function outsideProject(path: string): boolean {
const project = useProject.getState().project;
if (!project) return false;
const folders = project.workspace ? project.workspace.projects : [project.root];
return !folders.some((root) => isSameOrInside(path, root));
}
/** Files outside the project that code navigation opened: library sources, shown read-only. */
const navigatedLibraryFiles = new Set<string>();
/** Marks `path` as a library source again, for a tab restored from a saved session. */
export function markLibraryFile(path: string): void {
navigatedLibraryFiles.add(path);
}
/**
* Opens a code location a language server or the index answered (a declaration, an
* implementation, a documentation link) and selects `selection`. A file outside the project is a
* library source wherever the server keeps it (an SDK, its own cache or bundled stubs, a temporary
* copy), so it opens read-only like the External Libraries' files.
*/
export async function openCodeLocation(
path: string,
selection?: { line: number; col: number; endLine?: number; endCol?: number },
options: { focus?: boolean } = {},
): Promise<void> {
if (!isVirtualUri(path) && outsideProject(path)) navigatedLibraryFiles.add(path);
await maybeEditorService()?.openFile(path, { selection, focus: options.focus ?? true });
}
/**
* A document outside the project's own code: a server's virtual document (a library class), a
* file under the library roots or in a `node_modules` folder (the library roots list only direct
* dependencies, and a package manager's store holds the real paths), in a folder marked Excluded
* (a virtual environment, build output, a `vendor` copy the user marked; the innermost mark wins,
* so a source folder inside stays the project's), or outside the open project's folders (the stubs
* a language server ships, a standard library it resolves elsewhere). Background features skip
* what needs a search over the whole project here (usage counts, inheritor markers, server
* lenses): a library symbol is referenced everywhere, so each such request makes the server
* analyse every file, and an explicit Find Usages or Go to Implementation still answers.
*/
export function isLibrarySource(ctx: Pick<EditorDocContext, "path" | "virtual">): boolean {
if (ctx.virtual || isLibraryPath(ctx.path) || /(^|[\\/])node_modules[\\/]/.test(ctx.path)) return true;
if (!useProject.getState().project) return false;
if (outsideProject(ctx.path)) return true;
return rootOfPath(ctx.path)?.kind === "excluded";
}
// --- documents shown outside editor tabs ---------------------------------------
/**
* A live view of an open document for a CodeMirror view that is not an editor
* tab (e.g. the editable side of a diff). Edits sync both ways with the
* document shared by all editors of the file, go to the backend, and are saved
* by Save All. With `sharedHistory`, typing uses the text tab's history;
* otherwise the view keeps its own history, like a split pane.
*/
export interface DocumentAttachment {
path: string;
/** The backend document (for document-scoped commands). */
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). */
uiMode(): string | null;
/** The document's context, as editor contributions receive it. */
context(): EditorDocContext;
readOnly: boolean;
/** Watch read-only state even when this attachment has no mounted view. */
subscribeReadOnly(listener: () => void): () => void;
/** Edits from other views or the backend, in the coordinates of the previous text. */
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). */
extension: Extension;
save(options?: { exact?: boolean }): Promise<void>;
/** Resolves once local edits have reached the backend. */
synced(): Promise<void>;
/** Unsaved changes. */
dirty(): boolean;
/**
* Undo / redo of the document's history: the text editor tab's when one
* shows the file (backend edits are recorded there), else this view's.
* Returns whether anything changed.
*/
undo(): boolean;
redo(): boolean;
/**
* Applies a change made by this view's owner as one edit of the document's
* history (where `undo` works): the text editor tab's when one shows the
* 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, annotations?: readonly Annotation<unknown>[]): void;
/** Detach; the document closes when nothing else shows it. */
release(): void;
}
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<DocumentAttachment>) | null =
null;
/** Opens (or joins) the document of `path` for a non-tab view. */
export function attachDocument(path: string, options?: DocumentAttachmentOptions): Promise<DocumentAttachment> {
if (!documentAttacher) return Promise.reject(new Error("editor not started"));
return documentAttacher(path, options);
}
/** Called by editor/core only. */
export function _provideDocumentAttacher(attacher: typeof documentAttacher) {
documentAttacher = attacher;
}
// --- language modes -------------------------------------------------------------
/**
* Highlighting modes contributed by features, by `ui-mode` name (the
* `languages/<id>.toml` key). A registered mode wins over the
* `@codemirror/language-data` entry of the same name, e.g. the HTTP Client's
* `.http` request file mode.
*/
const languageModes = new Map<string, LanguageDescription>();
export function registerLanguageMode(desc: LanguageDescription): () => void {
languageModes.set(desc.name, desc);
return () => {
if (languageModes.get(desc.name) === desc) languageModes.delete(desc.name);
};
}
/** @internal editor/core only. */
export function _languageMode(name: string): LanguageDescription | undefined {
return languageModes.get(name);
}
// --- code previews ------------------------------------------------------
let codePreviewProvider: ((path: string, editable?: boolean) => Promise<Extension>) | null = null;
/**
* Extensions for a CodeMirror view showing `path` like an editor tab
* (editor font and colours, line numbers, syntax highlighting): previews
* outside editor tabs such as Find in Files. Read-only unless `editable` is true.
* Empty before editor/core starts.
*/
export function codePreviewExtensions(path: string, editable = false): Promise<Extension> {
return codePreviewProvider ? codePreviewProvider(path, editable) : Promise.resolve([]);
}
/** @internal editor/core only. */
export function _provideCodePreview(provider: typeof codePreviewProvider) {
codePreviewProvider = provider;
}
/** A row of the Copy Path/Reference… chooser. */
export interface CopyPathRow {
/** The action whose shortcut the row shows. */
id: string;
/** English label, translated by the chooser. */
label: string;
/** The copied text; a row without one is left out. */
preview: string | null;
run: () => void;
}
type CopyPathChooser = (
anchor: { x: number; y: number } | "center",
rows: readonly CopyPathRow[],
ctx: MenuGroupContext,
) => void;
let copyPathChooser: CopyPathChooser | null = null;
/**
* The editor's Copy Path/Reference… chooser for files outside an editor (the Project view's
* selection): `rows`, then the rows contributed to the `copyPath` menu for `ctx`, with previews.
*/
export function openCopyPathChooser(...args: Parameters<CopyPathChooser>): void {
copyPathChooser?.(...args);
}
/** @internal editor/core only. */
export function _provideCopyPathChooser(open: CopyPathChooser) {
copyPathChooser = open;
}
let workspaceHistory: ((id: number, redo: boolean) => Promise<void>) | null = null;
/** Undo/redo a refactoring through the same history used by editor commands. */
export function workspaceEditHistory(id: number, redo = false): Promise<void> {
return workspaceHistory ? workspaceHistory(id, redo) : Promise.reject(new Error("Editor history is unavailable"));
}
/** @internal editor/core only. */
export function _provideWorkspaceHistory(run: (id: number, redo: boolean) => Promise<void>): () => void {
workspaceHistory = run;
return () => {
if (workspaceHistory === run) workspaceHistory = null;
};
}
export interface WorkspaceEditHistoryState {
id: number;
undone: boolean;
}
const workspaceHistoryListeners = new Set<(state: WorkspaceEditHistoryState) => void>();
/** Successful workspace Undo/Redo, including commands invoked from an editor. */
export function onWorkspaceEditHistory(listener: (state: WorkspaceEditHistoryState) => void): () => void {
workspaceHistoryListeners.add(listener);
return () => {
workspaceHistoryListeners.delete(listener);
};
}
/** @internal editor/core only. */
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<number>();
/**
* 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<number>();