diff --git a/crates/ide-core/src/editor_settings.rs b/crates/ide-core/src/editor_settings.rs index c4ff484d3..78fa6853c 100644 --- a/crates/ide-core/src/editor_settings.rs +++ b/crates/ide-core/src/editor_settings.rs @@ -333,6 +333,23 @@ pub struct InlayHintsSettings { pub code_vision_usages: bool, /// Code vision: last author of a declaration (VCS blame) beside its usages. pub code_vision_author: bool, + /// Code vision: "no usages" on declarations nothing uses (IDEA shows it; clicking searches everywhere). + pub code_vision_no_usages: bool, + /// Code vision: where the usages go, above the declaration or at the end of its line. + pub code_vision_usages_position: CodeVisionPosition, + /// Code vision: where the author goes, above the declaration or at the end of its line. + pub code_vision_author_position: CodeVisionPosition, +} + +/// Editor › Inlay Hints › Code Vision position (IDEA's "Default position for metrics"). +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub enum CodeVisionPosition { + /// A row of its own above the declaration. + #[default] + Top, + /// After the end of the declaration's first line. + Right, } impl Default for InlayHintsSettings { @@ -344,6 +361,9 @@ impl Default for InlayHintsSettings { disabled_languages: Vec::new(), code_vision_usages: true, code_vision_author: true, + code_vision_no_usages: true, + code_vision_usages_position: CodeVisionPosition::Top, + code_vision_author_position: CodeVisionPosition::Top, } } } diff --git a/src/bindings.ts b/src/bindings.ts index d0e714686..1f63a69b4 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -2714,6 +2714,13 @@ export type CodeStyleSettings_Serialize = { formatterTagsRegexp: boolean, }; +/** Editor › Inlay Hints › Code Vision position (IDEA's "Default position for metrics"). */ +export type CodeVisionPosition = +/** A row of its own above the declaration. */ +"top" | +/** After the end of the declaration's first line. */ +"right"; + /** ColorInfo data. */ export type ColorInfo = { range: Range, @@ -5575,6 +5582,12 @@ export type InlayHintsSettings = { codeVisionUsages?: boolean, /** Code vision: last author of a declaration (VCS blame) beside its usages. */ codeVisionAuthor?: boolean, + /** Code vision: "no usages" on declarations nothing uses (IDEA shows it; clicking searches everywhere). */ + codeVisionNoUsages?: boolean, + /** Code vision: where the usages go, above the declaration or at the end of its line. */ + codeVisionUsagesPosition?: CodeVisionPosition, + /** Code vision: where the author goes, above the declaration or at the end of its line. */ + codeVisionAuthorPosition?: CodeVisionPosition, }; export type InlayKind = "type" | "parameter" | "other"; diff --git a/src/editor/api.ts b/src/editor/api.ts index 266747646..80a8ba4a4 100644 --- a/src/editor/api.ts +++ b/src/editor/api.ts @@ -595,6 +595,8 @@ export interface CodeLens { 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({ diff --git a/src/editor/core/cm/codeLens.test.ts b/src/editor/core/cm/codeLens.test.ts index 7e4b93d37..57aa80716 100644 --- a/src/editor/core/cm/codeLens.test.ts +++ b/src/editor/core/cm/codeLens.test.ts @@ -1,6 +1,8 @@ import { describe, expect, it } from "vitest"; import { EditorState } from "@codemirror/state"; -import { declarationStart, groupLenses, indentColumns } from "./codeLens"; +import { EditorView } from "@codemirror/view"; +import { codeLenses } from "@/editor/api"; +import { codeLensExtension, codeLensPositions, declarationStart, groupLenses, indentColumns } from "./codeLens"; const doc = (text: string) => EditorState.create({ doc: text }); @@ -34,3 +36,44 @@ describe("code lens layout", () => { expect(indentColumns(" x", 4)).toBe(4); }); }); + +describe("code lens position", () => { + const doc = "@contextmanager\ndef lifespan(app):\n pass\n"; + const lenses = [ + { pos: 16, title: "1 usage", kind: "usages", order: 10 }, + { pos: 16, title: "Denis", kind: "author", order: 20 }, + ]; + const view = (positions: Record) => + new EditorView({ + state: EditorState.create({ + doc, + extensions: [codeLensExtension, codeLenses.of(lenses), codeLensPositions.of(positions)], + }), + parent: document.body, + }); + const texts = (els: NodeListOf) => [...els].map((e) => e.textContent); + + it("puts every lens on a row above the declaration by default, with no separators", () => { + const v = view({}); + expect(texts(v.dom.querySelectorAll(".cm-openidea-lens"))).toEqual(["1 usageDenis"]); + expect(v.dom.querySelector(".cm-openidea-lens")?.closest(".cm-line")).toBeNull(); + expect(v.dom.querySelector(".cm-openidea-lensInline")).toBeNull(); + v.destroy(); + }); + + it("puts each kind where its setting says: usages at the line end, the author above", () => { + const v = view({ usages: "right" }); + expect(texts(v.dom.querySelectorAll(".cm-openidea-lens"))).toEqual(["Denis"]); + const inline = v.dom.querySelector(".cm-openidea-lensInline"); + expect(inline?.textContent).toBe("1 usage"); + expect(inline?.closest(".cm-line")?.textContent).toBe("@contextmanager1 usage"); + v.destroy(); + }); + + it("puts both at the line end", () => { + const v = view({ usages: "right", author: "right" }); + expect(v.dom.querySelector(".cm-openidea-lens")).toBeNull(); + expect(texts(v.dom.querySelectorAll(".cm-openidea-lensInline"))).toEqual(["1 usageDenis"]); + v.destroy(); + }); +}); diff --git a/src/editor/core/cm/codeLens.ts b/src/editor/core/cm/codeLens.ts index b5e605445..16ca7c065 100644 --- a/src/editor/core/cm/codeLens.ts +++ b/src/editor/core/cm/codeLens.ts @@ -1,14 +1,24 @@ /** * Renders `codeLenses` (editor/api) as one small hint row above the target - * line, indented like the line (IDEA "3 usages | Run test" inlays). + * line, indented like the line (IDEA "3 usages Run test" inlays), and those + * whose kind is set to "right" (`codeLensPositions`) after the end of that line. */ -import { EditorState, RangeSetBuilder, type Extension } from "@codemirror/state"; +import { EditorState, Facet, RangeSetBuilder, type Extension } from "@codemirror/state"; import { Decoration, EditorView, WidgetType, type DecorationSet } from "@codemirror/view"; import { getIndentUnit } from "@codemirror/language"; import { codeLenses, type CodeLens } from "@/editor/api"; import { guideVars, rainbowGuides } from "./indentGuides"; import { LINE_INSET } from "./lineInset"; +/** + * Where code lenses of each kind (`CodeLens.kind`) go: a row above the declaration (IDEA's default, also for + * kinds not listed) or after the end of its line. + */ +export const codeLensPositions = Facet.define< + Readonly>, + Readonly> +>({ combine: (v) => Object.assign({}, ...v) }); + /** Groups lenses by line start, ordered by line then `order`. Exported for tests. */ export function groupLenses( state: EditorState, @@ -71,12 +81,15 @@ class LensWidget extends WidgetType { readonly indent: number, readonly indentUnit: number, readonly rainbow: boolean, + /** After the end of the line instead of a row above it. */ + readonly inline = false, ) { super(); } private get key(): string { return ( + (this.inline ? "inline\u0000" : "") + this.indent + "\u0000" + this.indentUnit + @@ -92,8 +105,9 @@ class LensWidget extends WidgetType { } override toDOM(view: EditorView): HTMLElement { - const dom = document.createElement("div"); - dom.className = "cm-openidea-lens"; + // The inline one shares no class with the row, so none of the row's block styles reach into the line. + const dom = document.createElement(this.inline ? "span" : "div"); + dom.className = this.inline ? "cm-openidea-lensInline" : "cm-openidea-lens"; this.fill(dom, view); return dom; } @@ -105,9 +119,11 @@ class LensWidget extends WidgetType { private fill(dom: HTMLElement, view: EditorView) { dom.textContent = ""; - dom.style.paddingLeft = `${Math.round(this.indent * view.defaultCharacterWidth) + LINE_INSET}px`; // The guides of the annotated line continue through this row while indent guides are on. - const guides = guideVars(Math.floor(this.indent / this.indentUnit), this.indentUnit, this.rainbow); + const guides = this.inline + ? null + : guideVars(Math.floor(this.indent / this.indentUnit), this.indentUnit, this.rainbow); + if (!this.inline) dom.style.paddingLeft = `${Math.round(this.indent * view.defaultCharacterWidth) + LINE_INSET}px`; if (guides) { dom.style.setProperty("--openidea-guide-images", guides.images); dom.style.setProperty("--openidea-guide-positions", guides.positions); @@ -117,14 +133,7 @@ class LensWidget extends WidgetType { } dom.setAttribute("role", "group"); dom.setAttribute("aria-label", "Code lens"); - this.lenses.forEach((lens, i) => { - if (i > 0) { - const sep = document.createElement("span"); - sep.className = "cm-openidea-lensSep"; - sep.textContent = "|"; - sep.setAttribute("aria-hidden", "true"); - dom.appendChild(sep); - } + for (const lens of this.lenses) { const el = document.createElement(lens.run ? "button" : "span"); el.className = lens.run ? "cm-openidea-lensItem cm-openidea-lensAction" : "cm-openidea-lensItem"; if (lens.tooltip) el.title = lens.tooltip; @@ -154,11 +163,11 @@ class LensWidget extends WidgetType { }); } dom.appendChild(el); - }); + } } override get estimatedHeight(): number { - return 16; + return this.inline ? -1 : 16; } override ignoreEvent(): boolean { @@ -169,16 +178,28 @@ class LensWidget extends WidgetType { function buildDecorations(state: EditorState): DecorationSet { const lenses = state.facet(codeLenses); if (!lenses.length) return Decoration.none; + const positions = state.facet(codeLensPositions); + const right = (l: CodeLens) => !!l.kind && positions[l.kind] === "right"; const builder = new RangeSetBuilder(); for (const group of groupLenses(state, lenses)) { const line = state.doc.lineAt(group.lineFrom); - const widget = new LensWidget( - group.lenses, - indentColumns(line.text, state.tabSize), - Math.max(1, getIndentUnit(state)), - state.facet(rainbowGuides), - ); - builder.add(line.from, line.from, Decoration.widget({ widget, block: true, side: -1 })); + const indent = indentColumns(line.text, state.tabSize); + const unit = Math.max(1, getIndentUnit(state)); + const rainbow = state.facet(rainbowGuides); + const above = group.lenses.filter((l) => !right(l)); + const after = group.lenses.filter(right); + if (above.length) + builder.add( + line.from, + line.from, + Decoration.widget({ widget: new LensWidget(above, indent, unit, rainbow), block: true, side: -1 }), + ); + if (after.length) + builder.add( + line.to, + line.to, + Decoration.widget({ widget: new LensWidget(after, indent, unit, rainbow, true), side: 1 }), + ); } return builder.finish(); } @@ -187,7 +208,7 @@ const lensTheme = EditorView.theme({ ".cm-openidea-lens": { display: "flex", alignItems: "center", - gap: "6px", + gap: "12px", height: "16px", color: "var(--fg-muted)", WebkitUserSelect: "none", @@ -195,29 +216,37 @@ const lensTheme = EditorView.theme({ whiteSpace: "nowrap", overflow: "hidden", }, + // "right": after the line's text, on its baseline, with IDEA's spacing. + ".cm-openidea-lensInline": { + display: "inline-flex", + alignItems: "baseline", + gap: "12px", + marginLeft: "12px", + color: "var(--fg-muted)", + WebkitUserSelect: "none", + userSelect: "none", + whiteSpace: "nowrap", + }, ".cm-openidea-lensItem": { display: "inline-flex", alignItems: "center", - gap: "3px", + gap: "4px", padding: "0", border: "none", background: "none", font: "inherit", color: "inherit", - }, - // The row keeps the editor font so its `ch`-based indent guides line up with the code. - ".cm-openidea-lensItem, .cm-openidea-lensSep": { + // The items take the UI font; the row keeps the editor's, so its `ch`-based indent guides line up with the code. fontFamily: "var(--font-ui)", fontSize: "var(--fs-tiny)", }, ".cm-openidea-lensAction": { cursor: "pointer" }, ".cm-openidea-lensAction:hover": { color: "var(--accent)", textDecoration: "underline" }, - ".cm-openidea-lensSep": { color: "var(--fg-faint)" }, ".cm-openidea-lensIcon-run": { color: "var(--success)" }, }); /** Base extension (always installed): no cost until a provider contributes lenses. */ export const codeLensExtension: Extension = [ - EditorView.decorations.compute([codeLenses, rainbowGuides], buildDecorations), + EditorView.decorations.compute([codeLenses, rainbowGuides, codeLensPositions], buildDecorations), lensTheme, ]; diff --git a/src/editor/core/cm/prefs.ts b/src/editor/core/cm/prefs.ts index 8942d9ef7..889a9c751 100644 --- a/src/editor/core/cm/prefs.ts +++ b/src/editor/core/cm/prefs.ts @@ -54,6 +54,7 @@ import { skipClosingQuote, smartBackspace, smartBackspaceApplies, tabOut } from import { stringClipboard } from "./stringClipboard"; import { filterCopiedText } from "./clipboard"; import { LINE_INSET } from "./lineInset"; +import { codeLensPositions } from "./codeLens"; // --- soft wraps --------------------------------------------------------------- @@ -557,7 +558,12 @@ export function prefsExtension(o: PrefsOptions): Extension { const { prefs } = o; const g = prefs.general; const k = prefs.smartKeys; - const out: Extension[] = []; + const out: Extension[] = [ + codeLensPositions.of({ + usages: prefs.inlay.codeVisionUsagesPosition, + author: prefs.inlay.codeVisionAuthorPosition, + }), + ]; if (!o.readOnly) out.push(markdownImages({ path: o.path, folder: g.markdownImageFolder, pattern: g.markdownImageNamePattern })); if (g.scrollPastEnd) out.push(scrollPastEnd()); diff --git a/src/editor/lsp/codeLens.test.ts b/src/editor/lsp/codeLens.test.ts index eecad98d1..1650b0368 100644 --- a/src/editor/lsp/codeLens.test.ts +++ b/src/editor/lsp/codeLens.test.ts @@ -118,6 +118,18 @@ describe("background usage counts", () => { expect(executeAction).toHaveBeenCalledWith("find.showUsages"); }); + it('leaves out "no usages" when Show “no usages” is off', async () => { + ipc.lspReferences.mockResolvedValue(refs(0)); + useProject.setState({ + settings: { + editor: { inlay: { codeVisionUsages: true, codeVisionAuthor: false, codeVisionNoUsages: false } }, + } as never, + }); + const view = editor(); + await settle(); + expect(titles(view)).toEqual([]); + }); + it("does not cache an incomplete count while indexing, and retries on server refresh", async () => { ipc.lspReferences.mockResolvedValueOnce(refs(0, "indexing")); const view = editor(); diff --git a/src/editor/lsp/codeLens.ts b/src/editor/lsp/codeLens.ts index fc2f38dd4..5c8c8c886 100644 --- a/src/editor/lsp/codeLens.ts +++ b/src/editor/lsp/codeLens.ts @@ -233,14 +233,22 @@ class UsagesLensPlugin { const offset = posToOffset(text, { line: t.line, col: t.col }); const who = lines && authorSummary(lines, t.startLine, t.endLine); if (who) - lenses.push({ pos: offset, title: authorLabel(who), tooltip: authorTooltip(who), icon: "user", order: 20 }); + lenses.push({ + pos: offset, + title: authorLabel(who), + tooltip: authorTooltip(who), + icon: "user", + order: 20, + kind: "author", + }); const n = usages ? this.cache.get(key(t)) : undefined; - if (n === undefined) continue; + if (n === undefined || (n === 0 && !editorPrefs().inlay.codeVisionNoUsages)) continue; lenses.push({ pos: offset, title: usagesLabel(n), tooltip: tx`Show usages of ${t.name}`, order: 10, + kind: "usages", run: (v) => openUsages(v, Math.min(offset, v.state.doc.length)), }); } diff --git a/src/features/settings/pages/editor/general.tsx b/src/features/settings/pages/editor/general.tsx index b00c39bf4..29805d061 100644 --- a/src/features/settings/pages/editor/general.tsx +++ b/src/features/settings/pages/editor/general.tsx @@ -835,6 +835,11 @@ const INLAY: Item[] = [ }, ]; +const CODE_VISION_POSITIONS = [ + { value: "top", label: "Top" }, + { value: "right", label: "Right" }, +]; + const INLAY_HINTS = editorPage({ id: "editor.inlayHints", title: "Inlay Hints", @@ -845,8 +850,33 @@ const INLAY_HINTS = editorPage({ { title: "Code Vision", items: [ - { t: "check", key: `${P}.inlay.codeVisionUsages`, label: "Usages" }, - { t: "check", key: `${P}.inlay.codeVisionAuthor`, label: "Code author" }, + { + t: "check", + key: `${P}.inlay.codeVisionUsages`, + label: "Usages", + children: [ + { + t: "select", + key: `${P}.inlay.codeVisionUsagesPosition`, + label: "Position", + options: CODE_VISION_POSITIONS, + }, + { t: "check", key: `${P}.inlay.codeVisionNoUsages`, label: "Show “no usages”" }, + ], + }, + { + t: "check", + key: `${P}.inlay.codeVisionAuthor`, + label: "Code author", + children: [ + { + t: "select", + key: `${P}.inlay.codeVisionAuthorPosition`, + label: "Position", + options: CODE_VISION_POSITIONS, + }, + ], + }, ], }, { title: "Languages", items: [{ t: "custom", label: "Show inlay hints for:", component: InlayLanguages }] }, diff --git a/src/platform/editorSettings.ts b/src/platform/editorSettings.ts index 643461398..daaa8473f 100644 --- a/src/platform/editorSettings.ts +++ b/src/platform/editorSettings.ts @@ -179,6 +179,9 @@ export const EDITOR_EXTRA_DEFAULTS = { disabledLanguages: [] as string[], codeVisionUsages: true, codeVisionAuthor: true, + codeVisionNoUsages: true, + codeVisionUsagesPosition: "top" as "top" | "right", + codeVisionAuthorPosition: "top" as "top" | "right", }, inlineCompletion: { enabled: true, onlyOnPause: false, pauseMs: 500, disabledLanguages: [] as string[] }, gutterIconsDisabled: [] as string[], @@ -260,6 +263,8 @@ export function validateEditorExtras(raw: unknown): EditorExtras { const out = coerceLike(raw, EDITOR_EXTRA_DEFAULTS); if (!["ask", "always", "never"].includes(out.autoImport.importsOnPaste)) out.autoImport.importsOnPaste = "ask"; if (!DOCSTRING_FORMATS.includes(out.docstringFormat)) out.docstringFormat = "rest"; + for (const k of ["codeVisionUsagesPosition", "codeVisionAuthorPosition"] as const) + if (!["top", "right"].includes(out.inlay[k])) out.inlay[k] = "top"; out.fontWeight = fontWeightOf(out.fontWeight, EDITOR_EXTRA_DEFAULTS.fontWeight); out.boldFontWeight = fontWeightOf(out.boldFontWeight, EDITOR_EXTRA_DEFAULTS.boldFontWeight); return out; diff --git a/src/platform/locales/text/es.json b/src/platform/locales/text/es.json index 1cf3f66c3..364885fd6 100644 --- a/src/platform/locales/text/es.json +++ b/src/platform/locales/text/es.json @@ -2374,6 +2374,8 @@ "more": "más", "Usages": "Usos", "Code author": "Autor del código", + "Position": "Posición", + "Show “no usages”": "Mostrar «sin usos»", "Usages Detected": "Usos detectados", "Usages actions": "Acciones de usos", "Usages of '{symbol}'": "Usos de '{symbol}'", diff --git a/src/platform/locales/text/fr.json b/src/platform/locales/text/fr.json index 89c5f1cf6..c1fe952d1 100644 --- a/src/platform/locales/text/fr.json +++ b/src/platform/locales/text/fr.json @@ -2278,6 +2278,8 @@ "more": "de plus", "Usages": "Utilisations", "Code author": "Auteur du code", + "Position": "Position", + "Show “no usages”": "Afficher « aucune utilisation »", "Usages Detected": "Utilisations détectées", "Usages actions": "Actions sur les utilisations", "Usages of '{symbol}'": "Utilisations de '{symbol}'", diff --git a/src/platform/locales/text/ko.json b/src/platform/locales/text/ko.json index c1c7e42b3..36b7d87f2 100644 --- a/src/platform/locales/text/ko.json +++ b/src/platform/locales/text/ko.json @@ -2430,6 +2430,8 @@ "more": "더보기", "Usages": "사용 위치", "Code author": "코드 작성자", + "Position": "위치", + "Show “no usages”": "‘사용 위치 없음’ 표시", "Usages Detected": "사용 위치 감지됨", "Usages actions": "사용 위치 액션", "Usages of '{symbol}'": "'{symbol}'의 사용 위치", diff --git a/src/platform/locales/text/pl.json b/src/platform/locales/text/pl.json index d0a0b8eb1..b16ef9cfc 100644 --- a/src/platform/locales/text/pl.json +++ b/src/platform/locales/text/pl.json @@ -2353,6 +2353,8 @@ "more": "więcej", "Usages": "Użycia", "Code author": "Autor kodu", + "Position": "Pozycja", + "Show “no usages”": "Pokazuj „brak użyć”", "Usages Detected": "Wykryto użycia", "Usages actions": "Akcje użyć", "Usages of '{symbol}'": "Użycia symbolu '{symbol}'", diff --git a/src/platform/locales/text/pt.json b/src/platform/locales/text/pt.json index d661862f8..3d620b3ff 100644 --- a/src/platform/locales/text/pt.json +++ b/src/platform/locales/text/pt.json @@ -2354,6 +2354,8 @@ "more": "mais", "Usages": "Usos", "Code author": "Autor do código", + "Position": "Posição", + "Show “no usages”": "Mostrar “sem usos”", "Usages Detected": "Usos detectados", "Usages actions": "Ações de usos", "Usages of '{symbol}'": "Usos de '{symbol}'", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index dd9ddd2ab..02f378a46 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -2830,6 +2830,8 @@ "more": "更多", "Usages": "用法", "Code author": "代码作者", + "Position": "位置", + "Show “no usages”": "显示“无用法”", "Usages Detected": "检测到用法", "Usages actions": "用法操作", "Usages of '{symbol}'": "'{symbol}' 的用法",