From 65c45ffe05ba40120c9eeef8b62e560fcba3c8ce Mon Sep 17 00:00:00 2001 From: Dimas Avrian Fachriza <68158429+FForFachriza@users.noreply.github.com> Date: Fri, 27 Nov 2026 18:51:26 +0700 Subject: [PATCH] fix(editor): complete hyphenated tokens such as Tailwind classes (#6463) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Typing a hyphenated token such as items-c never offered items-center: the server's replace range covers the whole class, but the client filtered on the last word segment (c), and CodeMirror matches a one-character pattern only at a label's start. Typing - also closed the popup and re-queried. The completion now starts where the servers' single-token replace ranges start when they reach back over hyphens (the most common start wins), and the list stays valid across - while an option still starts with the typed text. Other punctuation, and lists with no option continuing the hyphen, re-query as before. CSS properties (background-c → background-color) benefit too. Closes #6462 Co-authored-by: FForFachriza <68158429+FForFachriza@users.noreply.github.com> --- src/editor/lsp/completion.test.ts | 110 ++++++++++++++++++++++++++++++ src/editor/lsp/completion.ts | 57 ++++++++++++++-- 2 files changed, 163 insertions(+), 4 deletions(-) diff --git a/src/editor/lsp/completion.test.ts b/src/editor/lsp/completion.test.ts index 4329b695f..90cbf094b 100644 --- a/src/editor/lsp/completion.test.ts +++ b/src/editor/lsp/completion.test.ts @@ -1123,3 +1123,113 @@ describe("`(` completion trigger", () => { expect(await parensTypedInto("kotlin", "Kotlin", 904)).toBe(0); }); }); + +describe("hyphenated completion tokens", () => { + let view: EditorView | null = null; + let calls = 0; + + afterEach(() => { + view?.destroy(); + view = null; + setInvokeRoute(null); + calls = 0; + }); + + /** A server item whose replace range covers `[0, end)` of the line. */ + const ranged = (label: string, end: number, start = 0) => + item({ + label, + insertText: label, + replaceRange: { start: { line: 0, col: start }, end: { line: 0, col: end } }, + }); + + function mount(doc: string, caret: number, reply: CompletionItem[], language = "typescriptreact") { + setInvokeRoute((cmd) => { + if (cmd === "cancel_request") return Promise.resolve(null); + if (cmd === "lsp_completion") { + calls++; + return Promise.resolve({ isIncomplete: false, items: reply }); + } + return Promise.resolve(null); + }); + view = new EditorView({ + state: EditorState.create({ + doc, + selection: { anchor: caret }, + extensions: [ + lspDoc.of({ doc: 950, path: "/p/a.tsx", language, uiMode: "TypeScript React", readOnly: false }), + completionExtension(), + ], + }), + parent: document.body, + }); + return view; + } + + const labels = () => currentCompletions(view!.state).map((c) => c.label); + + it("offers items-center when the caret sits after items-c", async () => { + mount("items-c", 7, [ranged("items-baseline", 7), ranged("items-center", 7)]); + startCompletion(view!); + await vi.waitFor(() => expect(labels()).toContain("items-center")); + }); + + it("keeps the list across the hyphen instead of asking again", async () => { + mount("items", 5, [ranged("items-baseline", 5), ranged("items-center", 5)]); + startCompletion(view!); + await vi.waitFor(() => expect(labels()).toHaveLength(2)); + const at = view!.state.selection.main.head; + view!.dispatch({ changes: { from: at, insert: "-" }, selection: { anchor: at + 1 }, userEvent: "input.type" }); + + view!.dispatch({ changes: { from: at + 1, insert: "c" }, selection: { anchor: at + 2 }, userEvent: "input.type" }); + + await vi.waitFor(() => expect(labels()).toEqual(["items-center"])); + expect(completionStatus(view!.state)).toBe("active"); + expect(calls).toBe(1); + }); + + it("ignores a stray item whose range starts later than the rest", async () => { + mount("items-c", 7, [ + ranged("items-baseline", 7), + ranged("items-center", 7), + ranged("items-start", 7), + ranged("items-end", 7), + ranged("items-stretch", 7), + ranged("center", 7, 6), + ]); + startCompletion(view!); + await vi.waitFor(() => expect(labels()).toContain("items-center")); + }); + + it("does not widen a range that is not a single token", async () => { + mount("this.foo", 8, [ranged("foobar", 8)], "javascript"); + startCompletion(view!); + await vi.waitFor(() => expect(labels()).toContain("foobar")); + }); + + it("still re-queries when a hyphen does not continue any option", async () => { + mount("a", 1, [ranged("alpha", 1)], "javascript"); + startCompletion(view!); + await vi.waitFor(() => expect(labels()).toEqual(["alpha"])); + const at = view!.state.selection.main.head; + view!.dispatch({ changes: { from: at, insert: "-b" }, selection: { anchor: at + 2 }, userEvent: "input.type" }); + await vi.waitFor(() => expect(completionStatus(view!.state)).not.toBe("active")); + }); + + it("completes CSS properties across the hyphen too", async () => { + mount( + "background-c", + 12, + [ + item({ + label: "background-color", + insertText: "background-color", + replaceRange: { start: { line: 0, col: 0 }, end: { line: 0, col: 12 } }, + }), + ], + "css", + ); + startCompletion(view!); + await vi.waitFor(() => expect(labels()).toContain("background-color")); + }); +}); diff --git a/src/editor/lsp/completion.ts b/src/editor/lsp/completion.ts index 85a4e8ebb..a815d2662 100644 --- a/src/editor/lsp/completion.ts +++ b/src/editor/lsp/completion.ts @@ -613,6 +613,50 @@ const SERVER_INSERT_WAIT_MS = 1000; const WORD_BEFORE = /[\p{L}\p{N}_$]+$/u; const VALID_FOR = /^[\p{L}\p{N}_$]*$/u; +/** One token a server may replace whole: a Tailwind class (`items-c`), a CSS value. */ +const TOKEN = /^[\p{L}\p{N}_$-]+$/u; + +/** + * Start of the token the server replaces, when it reaches back past our word over + * hyphens (Tailwind's `items-c`). Items from several servers can be merged, so the + * most common start among single-token ranges ending at the caret wins. + */ +function serverTokenStart(items: readonly CompletionItem[], doc: Text, pos: number, wordFrom: number): number | null { + const votes = new Map(); + for (const it of items) { + if (!it.replaceRange) continue; + const start = posToOffset(doc, it.replaceRange.start); + const end = posToOffset(doc, it.replaceRange.end); + if (start >= wordFrom || end < pos) continue; + if (!TOKEN.test(doc.sliceString(start, pos))) continue; + votes.set(start, (votes.get(start) ?? 0) + 1); + } + let best: number | null = null; + let most = 0; + for (const [start, n] of votes) { + if (n > most) { + best = start; + most = n; + } + } + return best; +} + +/** + * `validFor` for a list that may continue across a hyphen. CodeMirror re-queries + * when this returns false, so only keep the list while an option still starts + * with the typed text: `items-` continues (Tailwind), `foo-bar` in JS re-queries. + */ +function keepFiltering(items: readonly CompletionItem[]) { + let labels: string[] | null = null; // built lazily: an explicit list can hold 26k items + return (text: string): boolean => { + if (VALID_FOR.test(text)) return true; + if (!text.includes("-") || !TOKEN.test(text)) return false; + labels ??= items.map((it) => (it.filterText ?? it.label).toLowerCase()); + const typed = text.toLowerCase(); + return labels.some((label) => label.startsWith(typed)); + }; +} let inflight: RequestId | null = null; @@ -732,6 +776,12 @@ async function lspCompletionSource(ctx: CompletionContext): Promise = new Set(); if (smart) { const expected = await expectedType(ctx, doc.doc, word?.from ?? ctx.pos); @@ -745,7 +795,7 @@ async function lspCompletionSource(ctx: CompletionContext): Promise(); for (const c of graph) bases.set(c.name, [...(bases.get(c.name) ?? []), ...c.bases]); const smartResult = await smartItems(list.items, expected, (item) => resolveItem(doc.doc, item), { - typed: word?.text ?? "", + typed, member: ctx.state.sliceDoc(from - 1, from) === ".", mentioned: mentionedNames(ctx.state.doc.toString()), bases: (name) => bases.get(name) ?? [], @@ -761,7 +811,6 @@ async function lspCompletionSource(ctx: CompletionContext): Promise matchesCase(it.filterText ?? it.label, typed, prefs.caseSensitivity)) @@ -776,7 +825,7 @@ async function lspCompletionSource(ctx: CompletionContext): Promise it.kind !== "snippet" || !names.has(it.label)); } return { - from: word ? word.from : ctx.pos, + from: completionFrom, options: items.map((item) => { const option = makeCompletion(item, req); // Smart Type: an item that may fit (`Any`) follows the ones that do. @@ -787,7 +836,7 @@ async function lspCompletionSource(ctx: CompletionContext): Promise