The IDE you know, rebuilt in Rust. IntelliJ IDEA–style keymap, tool windows and search-everywhere in a fast native app: editor, code insight, debugger, Git, terminal, database and HTTP clients for 60+ languages.
TypeScript code-editorcross-platformdapdatabase-clientdebuggerdesktop-appdeveloper-toolsgithttp-clientideintellijlsprusttauriterminal
fix(editor): tighter text insets and full-row selection painting (#2420)
Elmir Abkerimovb08a9bedf9de
diff --git a/src/editor/core/cm/caretRow.test.ts b/src/editor/core/cm/caretRow.test.tsnew file mode 100644index 000000000..7f8b6c99a--- /dev/null+++ b/src/editor/core/cm/caretRow.test.ts@@ -0,0 +1,39 @@+import { describe, expect, it } from "vitest";+import { EditorSelection, EditorState } from "@codemirror/state";+import { EditorView } from "@codemirror/view";+import { caretRowHighlight } from "./caretRow";++const rows = (selection: EditorSelection) => {+ const view = new EditorView({+ state: EditorState.create({+ doc: "one\ntwo\nthree\nfour",+ selection,+ extensions: [caretRowHighlight, EditorState.allowMultipleSelections.of(true)],+ }),+ parent: document.body,+ });+ const out = [...view.dom.querySelectorAll(".cm-activeLine")].map((l) => l.textContent);+ view.destroy();+ return out;+};++describe("caret row", () => {+ it("highlights the caret's row", () => {+ expect(rows(EditorSelection.single(5))).toEqual(["two"]);+ });++ it("keeps the row highlighted under a selected word, as IDEA", () => {+ expect(rows(EditorSelection.single(4, 7))).toEqual(["two"]);+ });++ it("highlights the row of the caret (the head) under a selection over several lines", () => {+ expect(rows(EditorSelection.single(0, 10))).toEqual(["three"]);+ expect(rows(EditorSelection.single(10, 0))).toEqual(["one"]);+ });++ it("highlights each caret's row once", () => {+ expect(+ rows(EditorSelection.create([EditorSelection.cursor(1), EditorSelection.range(2, 3), EditorSelection.cursor(9)])),+ ).toEqual(["one", "three"]);+ });+});diff --git a/src/editor/core/cm/caretRow.ts b/src/editor/core/cm/caretRow.tsindex bbd75c59d..e443f691a 100644--- a/src/editor/core/cm/caretRow.ts+++ b/src/editor/core/cm/caretRow.ts@@ -7,8 +7,8 @@ function rows(view: EditorView): DecorationSet {const out: Range<Decoration>[] = [];let last = -1;for (const r of view.state.selection.ranges) {- // IntelliJ drops the caret-row highlight under a selection; the opaque row would hide it.- if (!r.empty) continue;+ // The caret's row stays highlighted under a selection too, as in IDEA; the row paints beneath the+ // selection layer (theme.ts), so it does not hide the selection.const from = view.lineBlockAt(r.head).from;if (from > last) out.push(caretRow.range(from));last = from;@@ -16,7 +16,7 @@ function rows(view: EditorView): DecorationSet {return Decoration.set(out, true);}-/** `highlightActiveLine` that only marks lines holding an empty cursor. */+/** `highlightActiveLine` that marks the line of each caret (the head of each selection range). */export const caretRowHighlight: Extension = ViewPlugin.fromClass(class {decorations: DecorationSet;diff --git a/src/editor/core/cm/codeLens.ts b/src/editor/core/cm/codeLens.tsindex f6165221a..4a18648a7 100644--- a/src/editor/core/cm/codeLens.ts+++ b/src/editor/core/cm/codeLens.ts@@ -7,6 +7,7 @@ import { Decoration, EditorView, WidgetType, type DecorationSet } from "@codemirimport { getIndentUnit } from "@codemirror/language";import { codeLenses, type CodeLens } from "@/editor/api";import { guideVars } from "./indentGuides";+import { LINE_INSET } from "./lineInset";/** Groups lenses by line start, ordered by line then `order`. Exported for tests. */export function groupLenses(@@ -101,7 +102,7 @@ class LensWidget extends WidgetType {private fill(dom: HTMLElement, view: EditorView) {dom.textContent = "";- dom.style.paddingLeft = `${Math.round(this.indent * view.defaultCharacterWidth) + 6}px`;+ 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);if (guides) {diff --git a/src/editor/core/cm/indentGuides.test.ts b/src/editor/core/cm/indentGuides.test.tsindex 701527dbf..cfe756a41 100644--- a/src/editor/core/cm/indentGuides.test.ts+++ b/src/editor/core/cm/indentGuides.test.ts@@ -40,23 +40,23 @@ describe("indent guides", () => {expect(guideVars(1, 4)).toBeNull();expect(guideVars(3, 4)).toEqual({images: "var(--openidea-guide), var(--openidea-guide)",- positions: "calc(6px + 4ch) 0, calc(6px + 8ch) 0",+ positions: "calc(2.5px + 4ch) 0, calc(2.5px + 8ch) 0",});});it("positions each guide the same way on lines of different depth", () => {const v = mount(SOURCE);expect(line(v, 1).classList.contains("cm-openidea-guides")).toBe(false);- expect(line(v, 2).style.getPropertyValue("--openidea-guide-positions")).toBe("calc(6px + 4ch) 0");+ expect(line(v, 2).style.getPropertyValue("--openidea-guide-positions")).toBe("calc(2.5px + 4ch) 0");expect(line(v, 3).style.getPropertyValue("--openidea-guide-positions")).toBe(- "calc(6px + 4ch) 0, calc(6px + 8ch) 0",+ "calc(2.5px + 4ch) 0, calc(2.5px + 8ch) 0",);});it("keeps guides through blank lines inside a block", () => {const v = mount(SOURCE);expect(line(v, 4).style.getPropertyValue("--openidea-guide-positions")).toBe(- "calc(6px + 4ch) 0, calc(6px + 8ch) 0",+ "calc(2.5px + 4ch) 0, calc(2.5px + 8ch) 0",);});@@ -71,7 +71,7 @@ describe("indent guides", () => {]);const [implLens, fnLens] = [...v.contentDOM.querySelectorAll<HTMLElement>(".cm-openidea-lens")];expect(v.contentDOM.classList.contains("cm-openidea-guidesOn")).toBe(true);- expect(fnLens!.style.getPropertyValue("--openidea-guide-positions")).toBe("calc(6px + 4ch) 0");+ expect(fnLens!.style.getPropertyValue("--openidea-guide-positions")).toBe("calc(2.5px + 4ch) 0");expect(implLens!.style.getPropertyValue("--openidea-guide-positions")).toBe("");});});diff --git a/src/editor/core/cm/indentGuides.ts b/src/editor/core/cm/indentGuides.tsindex 3aee71016..6bfbb64e3 100644--- a/src/editor/core/cm/indentGuides.ts+++ b/src/editor/core/cm/indentGuides.ts@@ -10,6 +10,7 @@import { RangeSetBuilder, type EditorState, type Extension } from "@codemirror/state";import { Decoration, EditorView, ViewPlugin, type DecorationSet, type ViewUpdate } from "@codemirror/view";import { getIndentUnit } from "@codemirror/language";+import { LINE_INSET } from "./lineInset";/*** Values of `--openidea-guide-images` / `--openidea-guide-positions` for an@@ -23,7 +24,7 @@ export function guideVars(levels: number, step: number): { images: string; positconst positions: string[] = [];for (let level = 1; level < levels; level++) {images.push("var(--openidea-guide)");- positions.push(`calc(6px + ${level * step}ch) 0`);+ positions.push(`calc(${LINE_INSET}px + ${level * step}ch) 0`);}return { images: images.join(", "), positions: positions.join(", ") };}diff --git a/src/editor/core/cm/lineInset.ts b/src/editor/core/cm/lineInset.tsnew file mode 100644index 000000000..948d7e7df--- /dev/null+++ b/src/editor/core/cm/lineInset.ts@@ -0,0 +1,2 @@+/** Space (px) between the gutter and column 0 of the text: the left padding of `.cm-line` (IDEA's text sits 2.5px in). */+export const LINE_INSET = 2.5;diff --git a/src/editor/core/cm/prefs.ts b/src/editor/core/cm/prefs.tsindex 50484b401..0ccb0d3ed 100644--- a/src/editor/core/cm/prefs.ts+++ b/src/editor/core/cm/prefs.ts@@ -52,6 +52,7 @@ import { enterInDocComment } from "./docComment";import { skipClosingQuote, smartBackspace, smartBackspaceApplies, tabOut } from "./smartKeys";import { stringClipboard } from "./stringClipboard";import { filterCopiedText } from "./clipboard";+import { LINE_INSET } from "./lineInset";// --- soft wraps ---------------------------------------------------------------@@ -82,7 +83,9 @@ const wrapIndentCache = new Map<number, Decoration>();function wrapIndentDeco(cols: number) {let d = wrapIndentCache.get(cols);if (!d) {- d = Decoration.line({ attributes: { style: `padding-left: calc(6px + ${cols}ch); text-indent: -${cols}ch` } });+ d = Decoration.line({+ attributes: { style: `padding-left: calc(${LINE_INSET}px + ${cols}ch); text-indent: -${cols}ch` },+ });wrapIndentCache.set(cols, d);}return d;@@ -164,7 +167,7 @@ export function marginGuides(columns: readonly number[]): Extension {const image = cols.map((c) =>- `linear-gradient(to right, transparent calc(6px + ${c}ch), var(--border-right-margin, var(--border)) calc(6px + ${c}ch), var(--border-right-margin, var(--border)) calc(7px + ${c}ch), transparent calc(7px + ${c}ch))`,+ `linear-gradient(to right, transparent calc(${LINE_INSET}px + ${c}ch), var(--border-right-margin, var(--border)) calc(${LINE_INSET}px + ${c}ch), var(--border-right-margin, var(--border)) calc(${LINE_INSET + 1}px + ${c}ch), transparent calc(${LINE_INSET + 1}px + ${c}ch))`,).join(", ");return EditorView.contentAttributes.of({ style: `background-image: ${image}` });diff --git a/src/editor/core/cm/selectionLayer.test.ts b/src/editor/core/cm/selectionLayer.test.tsindex 3d489439a..9e7407957 100644--- a/src/editor/core/cm/selectionLayer.test.ts+++ b/src/editor/core/cm/selectionLayer.test.ts@@ -1,6 +1,15 @@import { describe, expect, it } from "vitest";-import { RectangleMarker } from "@codemirror/view";-import { snapMarkers } from "./selectionLayer";+import { BlockType, RectangleMarker, type BlockInfo } from "@codemirror/view";+import {+ cutOutGaps,+ fillGaps,+ fillRowEnds,+ growToLineBoxes,+ snapMarkers,+ textBlock,+ textBlocks,+ widenToRightEdge,+} from "./selectionLayer";describe("snapMarkers", () => {it("makes stacked selection rectangles share their edge exactly", () => {@@ -19,3 +28,171 @@ describe("snapMarkers", () => {expect(m.width).toBe(100);});});++describe("widenToRightEdge", () => {+ const C = "cm-selectionBackground";+ const box = (m: RectangleMarker) => [m.left, m.top, m.width, m.height];++ it("widens the rectangles that run past a line end to the editor's right edge", () => {+ const markers = [+ new RectangleMarker(C, 120, 0, 380, 18), // first line, from column 10 past its end+ new RectangleMarker(C, 2, 18, 498, 36), // the lines in between+ ];+ expect(widenToRightEdge(markers, C, 500, 16).map(box)).toEqual([+ [120, 0, 396, 18],+ [2, 18, 514, 36],+ ]);+ });++ it("keeps rectangles that end inside a line", () => {+ const markers = [new RectangleMarker(C, 2, 54, 40, 18), new RectangleMarker(C, 80, 0, 60, 18)];+ expect(widenToRightEdge(markers, C, 500, 16).map(box)).toEqual([+ [2, 54, 40, 18],+ [80, 0, 60, 18],+ ]);+ });+});++describe("growToLineBoxes", () => {+ const C = "cm-selectionBackground";+ const box = (m: RectangleMarker) => [m.left, m.top, m.width, m.height];+ const rows20 = (y: number) => ({ top: Math.floor(y / 20) * 20, bottom: Math.floor(y / 20) * 20 + 20 });++ it("grows the first and last rows of a selection to their line boxes", () => {+ // 20px rows, 16px glyph boxes: CodeMirror leaves 2px above the first row and below the last.+ const markers = [+ new RectangleMarker(C, 40, 2, 100, 16), // first row+ new RectangleMarker(C, 2, 18, 500, 24), // rows in between+ new RectangleMarker(C, 2, 42, 30, 16), // last row+ ];+ expect(growToLineBoxes(markers, C, rows20).map(box)).toEqual([+ [40, 0, 100, 18],+ [2, 18, 500, 24],+ [2, 42, 30, 18],+ ]);+ });++ it("uses the line boxes when CodeMirror has already met two adjacent rows in the middle", () => {+ // two lines: CodeMirror stretches both to the 20px boundary, so the rectangles are 18px, not glyph-high+ const markers = [new RectangleMarker(C, 40, 2, 100, 18), new RectangleMarker(C, 2, 20, 30, 18)];+ expect(growToLineBoxes(markers, C, rows20).map(box)).toEqual([+ [40, 0, 100, 20],+ [2, 20, 30, 20],+ ]);+ });++ it("grows a single-row selection both ways", () => {+ expect(growToLineBoxes([new RectangleMarker(C, 40, 22, 60, 16)], C, rows20).map(box)).toEqual([[40, 20, 60, 20]]);+ });+});++describe("fillRowEnds", () => {+ const C = "cm-selectionBackground";+ const box = (m: RectangleMarker) => [m.left, m.top, m.width, m.height];++ it("fills a row the selection runs past from where its rectangles stop to the edge (a folded first line)", () => {+ const markers = [+ new RectangleMarker(C, 2, 0, 110, 20), // `import asyncio`, then the fold placeholder+ new RectangleMarker(C, 2, 20, 514, 40), // the rows below, already to the edge+ ];+ const rows = [+ { top: 0, bottom: 20 },+ { top: 20, bottom: 40 },+ ];+ expect(fillRowEnds(markers, C, rows, 516).map(box)).toEqual([+ [2, 0, 110, 20],+ [2, 20, 514, 40],+ [112, 0, 404, 20],+ ]);+ });++ it("does not count the rectangle below that only reaches into a row's leading", () => {+ // a folded first row, then CodeMirror's block for the rows below starting at its glyph bottom (18)+ const markers = [new RectangleMarker(C, 2, 0, 110, 20), new RectangleMarker(C, 2, 18, 514, 42)];+ expect(fillRowEnds(markers, C, [{ top: 0, bottom: 20 }], 516).map(box)).toEqual([+ [2, 0, 110, 20],+ [2, 18, 514, 42],+ [112, 0, 404, 20],+ ]);+ });++ it("matches the height of the row's own rectangle", () => {+ // CodeMirror's block for the rows below starts at 18, so this row's rectangle (and the fill) ends there+ const markers = [new RectangleMarker(C, 2, 0, 110, 18), new RectangleMarker(C, 2, 18, 514, 42)];+ expect(box(fillRowEnds(markers, C, [{ top: 0, bottom: 20 }], 516)[2]!)).toEqual([112, 0, 404, 18]);+ });++ it("leaves rows with no rectangle alone", () => {+ expect(fillRowEnds([], C, [{ top: 0, bottom: 20 }], 516)).toEqual([]);+ });+});++describe("textBlock / textBlocks", () => {+ const block = (top: number, height: number, type: BlockInfo["type"], from = 0, to = 10) =>+ ({ from, to, top, height, bottom: top + height, type, length: to - from }) as unknown as BlockInfo;+ // A line with a code lens above it: one block whose type lists the widget, then the text.+ const lens = block(100, 14, BlockType.WidgetBefore, 20, 20);+ const text = block(114, 20, BlockType.Text, 20, 40);+ const line = block(100, 34, [lens, text], 20, 40);++ it("takes the text row out of a line that carries a block widget", () => {+ expect(textBlock(line, 120)).toBe(text);+ // A point over the lens still resolves to the line's text, not to the lens.+ expect(textBlock(line, 105)).toBe(text);+ });++ it("returns plain lines as they are", () => {+ const plain = block(0, 20, BlockType.Text);+ expect(textBlock(plain, 5)).toBe(plain);+ });++ it("lists the text rows of the visible lines, lenses left out", () => {+ const plain = block(0, 20, BlockType.Text, 0, 10);+ const widget = block(20, 30, BlockType.WidgetRange, 10, 12);+ expect(textBlocks([plain, widget, line])).toEqual([plain, text]);+ });+});++describe("cutOutGaps", () => {+ const C = "cm-selectionBackground";+ const box = (m: RectangleMarker) => [m.left, m.top, m.width, m.height];++ it("leaves the code lens above the line a selection ends at the start of unpainted", () => {+ // A selected line (0-20), then CodeMirror's rectangle down to the next line's text (20-34) over its lens.+ const markers = [new RectangleMarker(C, 0, 0, 300, 20), new RectangleMarker(C, 0, 20, 300, 14)];+ expect(cutOutGaps(markers, C, [{ top: 20, bottom: 34 }]).map(box)).toEqual([[0, 0, 300, 20]]);+ });++ it("splits a rectangle that runs across a lens into the rows above and below it", () => {+ const markers = [new RectangleMarker(C, 0, 0, 300, 60)];+ expect(cutOutGaps(markers, C, [{ top: 20, bottom: 34 }]).map(box)).toEqual([+ [0, 0, 300, 20],+ [0, 34, 300, 26],+ ]);+ });++ it("keeps rectangles away from any widget as they are", () => {+ const m = new RectangleMarker(C, 10, 40, 100, 20);+ expect(cutOutGaps([m], C, [{ top: 20, bottom: 34 }])[0]).toBe(m);+ });+});++describe("fillGaps", () => {+ const C = "cm-selectionBackground";+ const box = (m: RectangleMarker) => [m.left, m.top, m.width, m.height];++ it("paints a code lens the selection runs through whole, from the text's left to the right edge", () => {+ // Rows above and below the lens, with the lens (20-34) already cut out of CodeMirror's rectangles.+ const rows = [new RectangleMarker(C, 0, 0, 300, 20), new RectangleMarker(C, 0, 34, 60, 20)];+ expect(fillGaps(rows, C, [{ top: 20, bottom: 34 }], 0, 300).map(box)).toEqual([+ [0, 0, 300, 20],+ [0, 34, 60, 20],+ [0, 20, 300, 14],+ ]);+ });++ it("adds nothing without gaps", () => {+ const rows = [new RectangleMarker(C, 0, 0, 300, 20)];+ expect(fillGaps(rows, C, [], 0, 300)).toEqual(rows);+ });+});diff --git a/src/editor/core/cm/selectionLayer.ts b/src/editor/core/cm/selectionLayer.tsindex 034c4589b..b00c2ef14 100644--- a/src/editor/core/cm/selectionLayer.ts+++ b/src/editor/core/cm/selectionLayer.ts@@ -1,5 +1,5 @@-import { EditorView, RectangleMarker, layer } from "@codemirror/view";-import type { Extension } from "@codemirror/state";+import { BlockType, Direction, EditorView, RectangleMarker, layer, type BlockInfo } from "@codemirror/view";+import type { Extension, SelectionRange } from "@codemirror/state";/** Rounds a CSS length to the nearest device pixel. */export function snapToDevicePixel(v: number, dpr: number): number {@@ -19,17 +19,246 @@ export function snapMarkers(markers: readonly RectangleMarker[], className: stri});}+/**+ * Widens the rectangles that end at the lines' right padding (`rightSide`, where CodeMirror stops a selection+ * that runs past a line end) by that padding (`pad`), so selected lines fill the editor to its right edge as in+ * IDEA. Rectangles that end inside a line stay as they are.+ */+export function widenToRightEdge(+ markers: readonly RectangleMarker[],+ className: string,+ rightSide: number,+ pad: number,+): RectangleMarker[] {+ if (pad <= 0) return [...markers];+ return markers.map((m) =>+ m.width !== null && m.width > 0 && Math.abs(m.left + m.width - rightSide) < 0.5+ ? new RectangleMarker(className, m.left, m.top, m.width + pad, m.height)+ : m,+ );+}++/** A visual row's line box, top and bottom, in layer coordinates. */+export type RowBox = { top: number; bottom: number };++/**+ * Grows a selection's outer rectangles to whole line boxes (`rowAt(y)` gives the box of the row at `y`).+ * CodeMirror sizes the first and last row of a selection to the text's glyph box, so the line's leading+ * stayed unselected above and below it; IDEA fills the full line height.+ */+export function growToLineBoxes(+ markers: readonly RectangleMarker[],+ className: string,+ rowAt: (y: number) => RowBox,+): RectangleMarker[] {+ if (!markers.length) return [];+ const top = Math.min(...markers.map((m) => m.top));+ const bottom = Math.max(...markers.map((m) => m.top + m.height));+ return markers.map((m) => {+ const end = m.top + m.height;+ const t = Math.abs(m.top - top) < 0.5 ? Math.min(m.top, rowAt(m.top + 0.5).top) : m.top;+ const b = Math.abs(end - bottom) < 0.5 ? Math.max(end, rowAt(end - 0.5).bottom) : end;+ return t !== m.top || b !== end ? new RectangleMarker(className, m.left, t, m.width, b - t) : m;+ });+}++/**+ * Adds what is missing up to `right` on rows (`{ top, bottom }`, layer coordinates) the selection runs past the+ * end of. CodeMirror skips folded ranges, so a selection starting on a folded line stopped at its visible text,+ * short of the placeholder and the edge. Rows with no rectangle at all are left alone.+ */+export function fillRowEnds(+ markers: readonly RectangleMarker[],+ className: string,+ rows: readonly RowBox[],+ right: number,+): RectangleMarker[] {+ const out = [...markers];+ for (const row of rows) {+ // Only rectangles across the row's middle count (the one below may reach into its leading), and the fill+ // takes their height: flush with them, and no overlap to darken a translucent selection colour.+ const mid = (row.top + row.bottom) / 2;+ let end = -Infinity;+ let top = Infinity;+ let bottom = -Infinity;+ for (const m of markers) {+ if (m.top >= mid || m.top + m.height <= mid) continue;+ end = Math.max(end, m.width === null ? Infinity : m.left + m.width);+ top = Math.min(top, m.top);+ bottom = Math.max(bottom, m.top + m.height);+ }+ if (end === -Infinity || end >= right - 0.5) continue;+ out.push(+ new RectangleMarker(+ className,+ end,+ Math.max(top, row.top),+ right - end,+ Math.min(bottom, row.bottom) - Math.max(top, row.top),+ ),+ );+ }+ return out;+}++/**+ * Cuts the vertical spans in `gaps` (`{ top, bottom }`, layer coordinates) out of the rectangles. CodeMirror fills+ * everything between a selection's first and last line with one rectangle, which runs over the block widgets+ * (code lenses) in between, or over part of one.+ */+export function cutOutGaps(+ markers: readonly RectangleMarker[],+ className: string,+ gaps: readonly RowBox[],+): RectangleMarker[] {+ if (!gaps.length) return [...markers];+ const out: RectangleMarker[] = [];+ for (const m of markers) {+ let pieces: Array<[number, number]> = [[m.top, m.top + m.height]];+ for (const g of gaps) {+ pieces = pieces.flatMap(([t, b]): Array<[number, number]> =>+ g.bottom <= t || g.top >= b+ ? [[t, b]]+ : (+ [+ [t, Math.min(b, g.top)],+ [Math.max(t, g.bottom), b],+ ] as Array<[number, number]>+ ).filter(([pt, pb]) => pb - pt > 0.5),+ );+ }+ if (pieces.length === 1 && pieces[0]![0] === m.top && pieces[0]![1] === m.top + m.height) out.push(m);+ else for (const [t, b] of pieces) out.push(new RectangleMarker(className, m.left, t, m.width, b - t));+ }+ return out;+}++/** Adds one rectangle from `left` to `right` over each of `gaps` (layer coordinates). */+export function fillGaps(+ markers: readonly RectangleMarker[],+ className: string,+ gaps: readonly RowBox[],+ left: number,+ right: number,+): RectangleMarker[] {+ if (!gaps.length || !(right > left)) return [...markers];+ return [...markers, ...gaps.map((g) => new RectangleMarker(className, left, g.top, right - left, g.bottom - g.top))];+}++/**+ * A line block's parts. A line with block widgets attached (a code lens above it, say) comes back from+ * `lineBlockAt*` and `viewportLineBlocks` as one block whose `type` lists the widgets and the text.+ */+const parts = (block: BlockInfo): readonly BlockInfo[] =>+ Array.isArray(block.type) ? (block.type as readonly BlockInfo[]) : [block];++/** The text part of a line block at document `y` (the one nearest to it when `y` is on a widget). */+export function textBlock(block: BlockInfo, y: number): BlockInfo {+ const texts = parts(block).filter((b) => b.type === BlockType.Text);+ return (+ texts.find((b) => y >= b.top && y < b.bottom) ??+ texts.reduce<BlockInfo | null>(+ (best, b) =>+ !best || Math.abs(y - (b.top + b.bottom) / 2) < Math.abs(y - (best.top + best.bottom) / 2) ? b : best,+ null,+ ) ??+ block+ );+}++/** The text blocks among `blocks`, taken out of lines that carry block widgets. */+export function textBlocks(blocks: readonly BlockInfo[]): BlockInfo[] {+ return blocks.flatMap((b) => parts(b).filter((p) => p.type === BlockType.Text));+}+const CLASS = "cm-selectionBackground";+/** Where CodeMirror ends a selection past the line end, in layer coordinates, and the lines' right padding (screen px). */+function lineRightEdge(view: EditorView): { rightSide: number; pad: number } {+ const line = view.contentDOM.querySelector(".cm-line");+ const pad = (line ? parseFloat(getComputedStyle(line).paddingRight) || 0 : 0) * view.scaleX;+ const scroller = view.scrollDOM.getBoundingClientRect();+ const base = scroller.left - view.scrollDOM.scrollLeft * view.scaleX;+ return { rightSide: view.contentDOM.getBoundingClientRect().right - pad - base, pad };+}++/** Layer y = document y + this offset. */+function layerOffset(view: EditorView): number {+ const scroller = view.scrollDOM.getBoundingClientRect();+ return view.documentTop - (scroller.top - view.scrollDOM.scrollTop * view.scaleY);+}++/** The box of the visual row at layer `y`: its line's text, or for a wrapped line the row of it. */+function rowAt(view: EditorView, offset: number, y: number): RowBox {+ const block = textBlock(view.lineBlockAtHeight(y - offset), y - offset);+ const lh = view.defaultLineHeight;+ if (block.height < lh * 1.5) return { top: offset + block.top, bottom: offset + block.bottom };+ const top = block.top + Math.min(Math.floor((y - offset - block.top) / lh), Math.round(block.height / lh) - 1) * lh;+ return { top: offset + top, bottom: offset + top + lh };+}++/** The line boxes (layer coordinates) of the visible rows that `r` runs past the end of. */+function rowsPastEnd(view: EditorView, offset: number, r: SelectionRange): RowBox[] {+ return textBlocks(view.viewportLineBlocks)+ .filter((b) => b.to >= r.from && b.to < r.to)+ .map((b) => ({ top: offset + b.top, bottom: offset + b.bottom }));+}++/**+ * The visible block widgets attached to lines (code lenses and the like, layer coordinates) around `r`. IDEA paints+ * the ones the selection runs through (`fill`: it selects text on both sides) whole, and leaves the ones it stops at+ * (`cut`: it ends at the start of the line below one, or starts at the end of the line above one) unpainted.+ */+function lineWidgets(view: EditorView, offset: number, r: SelectionRange): { cut: RowBox[]; fill: RowBox[] } {+ const cut: RowBox[] = [];+ const fill: RowBox[] = [];+ for (const line of view.viewportLineBlocks) {+ if (!Array.isArray(line.type) || line.to < r.from || line.from > r.to) continue;+ for (const w of parts(line)) {+ if (w.height <= 0 || (w.type !== BlockType.WidgetBefore && w.type !== BlockType.WidgetAfter)) continue;+ // A widget before a line sits at the line's start, one after it at the line's end.+ const at = w.type === BlockType.WidgetBefore ? line.from : line.to;+ (r.from < at && r.to > at ? fill : cut).push({ top: offset + w.top, bottom: offset + w.bottom });+ }+ }+ return { cut, fill };+}+const snappedSelectionLayer = layer({above: false,class: "cm-selectionLayer",mount: (dom) => dom.classList.add("cm-openidea-selectionLayer"),markers(view) {+ const ranges = view.state.selection.ranges.filter((r) => !r.empty);+ if (!ranges.length) return [];const dpr = window.devicePixelRatio || 1;+ const edge = view.textDirection === Direction.LTR ? lineRightEdge(view) : null;+ const offset = layerOffset(view);const out: RectangleMarker[] = [];- for (const r of view.state.selection.ranges)- if (!r.empty) out.push(...snapMarkers(RectangleMarker.forRange(view, CLASS, r), CLASS, dpr));+ for (const r of ranges) {+ const lines = growToLineBoxes(RectangleMarker.forRange(view, CLASS, r), CLASS, (y) => rowAt(view, offset, y));+ const full = edge+ ? fillRowEnds(+ widenToRightEdge(lines, CLASS, edge.rightSide, edge.pad),+ CLASS,+ rowsPastEnd(view, offset, r),+ edge.rightSide + edge.pad,+ )+ : lines;+ // Block widgets: cut them all out of CodeMirror's rectangles, then paint the ones the selection runs through+ // with one rectangle each, so a translucent selection colour never doubles up over them.+ const widgets = lineWidgets(view, offset, r);+ const left = Math.min(...full.map((m) => m.left));+ const right = edge ? edge.rightSide + edge.pad : Math.max(...full.map((m) => m.left + (m.width ?? 0)));+ const painted = fillGaps(+ cutOutGaps(full, CLASS, [...widgets.cut, ...widgets.fill]),+ CLASS,+ widgets.fill,+ left,+ right,+ );+ out.push(...snapMarkers(painted, CLASS, dpr));+ }return out;},update: (u) => u.docChanged || u.selectionSet || u.viewportChanged,@@ -43,6 +272,10 @@ export function seamlessSelection(): Extension {".cm-selectionLayer:not(.cm-openidea-selectionLayer)": {display: "none",},+ // drawSelection hides the native selection inside the lines only. WebKit also fills the gaps left of+ // selected lines (the text inset) with the content's own ::selection colour, which showed as small+ // blocks next to the gutter.+ ".cm-content::selection": { backgroundColor: "transparent" },}),];}diff --git a/src/editor/core/cm/stickyScroll.test.ts b/src/editor/core/cm/stickyScroll.test.tsnew file mode 100644index 000000000..7e7a54d54--- /dev/null+++ b/src/editor/core/cm/stickyScroll.test.ts@@ -0,0 +1,40 @@+import { describe, expect, it } from "vitest";+import { selectedSpans } from "./stickyScroll";++describe("selectedSpans", () => {+ // the sticky line `def run():` at 100..110+ it("is empty when no range covers the line", () => {+ expect(selectedSpans([{ from: 0, to: 50 }], 100, 110)).toEqual([]);+ expect(selectedSpans([{ from: 105, to: 105 }], 100, 110)).toEqual([]);+ // a selection that ends at the line's start selects nothing on it+ expect(selectedSpans([{ from: 40, to: 100 }], 100, 110)).toEqual([]);+ });++ it("covers the whole line and runs past it for a selection through the line", () => {+ expect(selectedSpans([{ from: 0, to: 500 }], 100, 110)).toEqual([{ start: 0, end: 10, pastEnd: true }]);+ });++ it("covers part of the line", () => {+ expect(selectedSpans([{ from: 104, to: 107 }], 100, 110)).toEqual([{ start: 4, end: 7, pastEnd: false }]);+ expect(selectedSpans([{ from: 104, to: 300 }], 100, 110)).toEqual([{ start: 4, end: 10, pastEnd: true }]);+ expect(selectedSpans([{ from: 20, to: 103 }], 100, 110)).toEqual([{ start: 0, end: 3, pastEnd: false }]);+ });+});++describe("disjoint sticky selections", () => {+ it("keeps gaps between selected occurrences", () => {+ expect(+ selectedSpans(+ [+ { from: 101, to: 103 },+ { from: 107, to: 109 },+ ],+ 100,+ 110,+ ),+ ).toEqual([+ { start: 1, end: 3, pastEnd: false },+ { start: 7, end: 9, pastEnd: false },+ ]);+ });+});diff --git a/src/editor/core/cm/stickyScroll.ts b/src/editor/core/cm/stickyScroll.tsindex 7bb8b4aa4..f3a090cf0 100644--- a/src/editor/core/cm/stickyScroll.ts+++ b/src/editor/core/cm/stickyScroll.ts@@ -10,6 +10,7 @@ import { foldNodeProp, syntaxTree } from "@codemirror/language";import { highlightTree } from "@lezer/highlight";import { backendFolds } from "./folding";import { openideaHighlightStyle } from "./highlight";+import { LINE_INSET } from "./lineInset";/** Maximum number of sticky lines (Settings › Editor › Code Editing). */export const stickyMaxLines = Facet.define<number, number>({@@ -97,6 +98,42 @@ export function offsetAtX(inner: HTMLElement, clientX: number): number {return offset;}+/** Selected portions of a sticky line, preserving gaps between selection ranges. */+export function selectedSpans(+ ranges: readonly { from: number; to: number }[],+ from: number,+ to: number,+): { start: number; end: number; pastEnd: boolean }[] {+ const spans: { start: number; end: number; pastEnd: boolean }[] = [];+ for (const r of ranges) {+ if (r.from === r.to || r.to < from || r.from > to || (r.to === from && r.from < from)) continue;+ const start = Math.max(r.from, from) - from;+ const end = Math.min(r.to, to) - from;+ const pastEnd = r.to > to;+ if (end !== start || pastEnd) spans.push({ start, end, pastEnd });+ }+ return spans;+}++/** Client x of the start of character `offset` in a rendered sticky line (its end past the last character). */+function xAtOffset(inner: HTMLElement, offset: number): number {+ const range = document.createRange();+ const walker = document.createTreeWalker(inner, NodeFilter.SHOW_TEXT);+ let last: Text | null = null;+ for (let node = walker.nextNode() as Text | null; node; node = walker.nextNode() as Text | null) {+ if (offset < node.length) {+ range.setStart(node, offset);+ range.setEnd(node, offset + 1);+ return range.getBoundingClientRect().left;+ }+ offset -= node.length;+ last = node;+ }+ if (!last) return inner.getBoundingClientRect().left + parseFloat(inner.style.paddingLeft || "0");+ range.selectNodeContents(last);+ return range.getBoundingClientRect().right;+}+class StickyScroll {dom: HTMLElement;private lines: number[] = [];@@ -105,6 +142,8 @@ class StickyScroll {private gutterWidth = 0;private numberLeft = 0;private scheduled = false;+ private selectionDirty = true;+ private scrollLeft = 0;constructor(private view: EditorView) {this.dom = document.createElement("div");@@ -118,8 +157,11 @@ class StickyScroll {}update(u: ViewUpdate) {+ if (u.docChanged || u.selectionSet || u.geometryChanged) this.selectionDirty = true;if (u.docChanged ||+ u.selectionSet ||+ u.focusChanged ||u.viewportChanged ||u.geometryChanged ||syntaxTree(u.startState) !== syntaxTree(u.state) ||@@ -184,7 +226,8 @@ class StickyScroll {return;}this.dom.style.display = "";- if (!same || gutterWidth !== this.gutterWidth || numberLeft !== this.numberLeft) {+ const rebuild = !same || gutterWidth !== this.gutterWidth || numberLeft !== this.numberLeft;+ if (rebuild) {this.lines = lines;this.renderedFrom = { texts, tree };this.gutterWidth = gutterWidth;@@ -205,7 +248,7 @@ class StickyScroll {const inner = document.createElement("span");inner.className = "cm-openidea-stickyInner";inner.style.display = "inline-block";- inner.style.paddingLeft = "6px";+ inner.style.paddingLeft = `${LINE_INSET}px`;renderLineContent(this.view.state, n, inner);text.appendChild(inner);row.append(num, text);@@ -213,8 +256,51 @@ class StickyScroll {}this.dom.replaceChildren(frag);}- for (const inner of this.dom.querySelectorAll<HTMLElement>(".cm-openidea-stickyInner"))- inner.style.transform = scrollLeft ? `translateX(${-scrollLeft}px)` : "";+ if (rebuild || scrollLeft !== this.scrollLeft) {+ for (const inner of this.dom.querySelectorAll<HTMLElement>(".cm-openidea-stickyInner"))+ inner.style.transform = scrollLeft ? `translateX(${-scrollLeft}px)` : "";+ this.selectionDirty = true;+ }+ this.scrollLeft = scrollLeft;+ if (this.selectionDirty) {+ this.selectionDirty = false;+ this.paintSelection();+ }+ },+ });+ }++ private paintSelection() {+ this.view.requestMeasure({+ key: this.paintSelection,+ read: () => {+ const state = this.view.state;+ return Array.from(this.dom.querySelectorAll<HTMLElement>(".cm-openidea-stickyLine"), (row) => {+ const text = row.querySelector<HTMLElement>(".cm-openidea-stickyText")!;+ const inner = text.querySelector<HTMLElement>(".cm-openidea-stickyInner")!;+ const line = state.doc.line(Math.min(Number(row.dataset.line), state.doc.lines));+ const spans = selectedSpans(state.selection.ranges, line.from, line.to);+ if (!spans.length) return { text, marks: [] };+ const box = text.getBoundingClientRect();+ const marks = spans.map((span) => {+ const left = Math.max(0, xAtOffset(inner, span.start) - box.left);+ const right = span.pastEnd ? box.width : Math.max(left, xAtOffset(inner, span.end) - box.left);+ return { left, width: right - left };+ });+ return { text, marks };+ });+ },+ write: (rows) => {+ for (const { text, marks } of rows) {+ for (const mark of text.querySelectorAll(".cm-openidea-stickySelection")) mark.remove();+ for (const { left, width } of marks) {+ const mark = document.createElement("span");+ mark.className = "cm-openidea-stickySelection";+ mark.style.left = `${left}px`;+ mark.style.width = `${width}px`;+ text.prepend(mark);+ }+ }},});}diff --git a/src/editor/core/cm/theme.ts b/src/editor/core/cm/theme.tsindex ac1a8da87..594dbe974 100644--- a/src/editor/core/cm/theme.ts+++ b/src/editor/core/cm/theme.ts@@ -7,6 +7,7 @@*/import { EditorView } from "@codemirror/view";import { BRACKET_COLORS } from "./rainbowBrackets";+import { LINE_INSET } from "./lineInset";/** The `--editor-*` locals of `findStyles`, for the `&` rule. */export const findLocals = {@@ -150,12 +151,13 @@ export const openideaTheme = EditorView.theme({overscrollBehavior: "contain",},".cm-content": {- padding: "4px 0 8px 0",+ // no top padding: the first line starts at the top edge, as in IDEA, and so does its selection+ padding: "0 0 8px 0",caretColor: "var(--caret, var(--fg-strong))",cursor: "text",},// The right side also leaves room for the floating corner widgets (core/cm/cornerInset.ts).- ".cm-line": { padding: "0 calc(16px + var(--cm-corner-inset, 0px)) 0 6px" },+ ".cm-line": { padding: `0 calc(16px + var(--cm-corner-inset, 0px)) 0 ${LINE_INSET}px` },...caretStyles,"&.cm-openidea-ligatures .cm-scroller, &.cm-openidea-ligatures .cm-openidea-sticky": {fontVariantLigatures: "normal",@@ -171,7 +173,9 @@ export const openideaTheme = EditorView.theme({"&.cm-openidea-hideGutter-inheritors :is(.cm-openidea-lineMarker-implemented, .cm-openidea-lineMarker-overridden), &.cm-openidea-hideGutter-supers :is(.cm-openidea-lineMarker-implementing, .cm-openidea-lineMarker-overriding)":{ display: "none" },// Distraction Free Mode: no gutter; the text column (n chars + line padding) is centred.- "&.cm-openidea-distractionFree": { "--openidea-df-width": "calc(var(--openidea-df-columns, 80) * 1ch + 22px)" },+ "&.cm-openidea-distractionFree": {+ "--openidea-df-width": `calc(var(--openidea-df-columns, 80) * 1ch + ${16 + LINE_INSET}px)`,+ },"&.cm-openidea-distractionFree .cm-gutters": { display: "none" },"&.cm-openidea-distractionFree .cm-content": {marginInlineStart: "max(0px, calc((100% - var(--openidea-df-width)) / 2))",@@ -369,7 +373,17 @@ export const openideaTheme = EditorView.theme({boxSizing: "border-box",paddingRight: "8px",},- ".cm-openidea-stickyText": { flex: "1", overflow: "hidden" },+ ".cm-openidea-stickyText": { flex: "1", overflow: "hidden", position: "relative" },+ ".cm-openidea-stickyInner": { position: "relative" },+ // The selection on a pinned line, under its text (as the selection layer in the editor).+ ".cm-openidea-stickySelection": {+ position: "absolute",+ top: "0",+ bottom: "0",+ background: "var(--editor-selection-inactive)",+ pointerEvents: "none",+ },+ "&.cm-focused .cm-openidea-stickySelection": { background: "var(--editor-selection)" },// Soft-wrap: continuation rows indent slightly, like IDEA's wrap sign column."&.cm-lineWrapping .cm-line, .cm-lineWrapping .cm-line": {diff --git a/src/features/vcs/cm.ts b/src/features/vcs/cm.tsindex 1c63aa9fc..ea0e2a65d 100644--- a/src/features/vcs/cm.ts+++ b/src/features/vcs/cm.ts@@ -33,6 +33,7 @@ import { tags as t } from "@lezer/highlight";import { scrollbarMarks, type ScrollbarMark } from "@/editor/api";import { findExtension } from "@/editor/core/cm/find";import { overviewLane, overviewLaneIn } from "@/editor/core/cm/lanes";+import { LINE_INSET } from "@/editor/core/cm/lineInset";import { caretExtension } from "@/editor/core/cm/prefs";import { fontExtension } from "@/editor/core/cm/setup";import { caretStyles, findLocals, findStyles, overviewStyles } from "@/editor/core/cm/theme";@@ -327,7 +328,13 @@ export const viewerTheme = EditorView.theme(fontVariantLigatures: "none",},"&.cm-openidea-ligatures .cm-scroller": { fontVariantLigatures: "normal" },- ".cm-content": { caretColor: "var(--caret, var(--fg-strong))", WebkitUserSelect: "text", userSelect: "text" },+ ".cm-content": {+ padding: "0 0 4px",+ caretColor: "var(--caret, var(--fg-strong))",+ WebkitUserSelect: "text",+ userSelect: "text",+ },+ ".cm-line": { padding: `0 2px 0 ${LINE_INSET}px` },...caretStyles,"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, ::selection, .cm-openidea-selected, &.cm-focused .cm-openidea-selected":{