// The whole VS Code extension: start `lucisv-server` over stdio, let the // language client do the rest, and paint one thing the protocol has no request // for — the `begin`/`end` rainbow, whose ranges the server computes and hands // over through the custom `lucisv/scopePairs` request. // // Every *answer* still comes from the server: nothing here parses Verilog, and // the only reason this file is longer than the language client's setup is that // LSP has no "decorate these ranges" notification, so the painting has to be // driven from the client side (docs/features/editor-scopes). const vscode = require('vscode'); const { LanguageClient, ProposedFeatures, TransportKind } = require('vscode-languageclient/node'); /** The single client, kept only so `deactivate` can stop it. */ let client; /** The languages this extension attaches to. */ const LANGUAGES = ['verilog', 'systemverilog']; /** * How many colours the rainbow cycles through. Six, to match VS Code's own * bracket colouring — but the colours are **this extension's own** * (`lucisv.rainbow1..6`, contributed with visible defaults for every theme kind * in `package.json`), not `editorBracketHighlight.foreground1..6`. Those look * like the obvious thing to borrow and are a trap: VS Code's registry defaults * `foreground4`, `5` and `6` to `#00000000` — fully transparent — and leaves it * to themes to define them, which most do not. Painting with them made every * `begin` at depth 3, 4 or 5 invisible. */ const RAINBOW_COLORS = 6; /** How long to let typing settle before re-asking for pairs. */ const REPAINT_DEBOUNCE_MS = 250; /** One decoration type per colour, created once and reused. */ let decorationTypes = []; /** The decoration for a `begin`/`end` whose counterpart is missing. */ let unmatchedType; /** Whether the rainbow is on, per `lucisv.rainbowBeginEnd`. */ let rainbowEnabled = true; /** The pending debounced repaint, if any. */ let repaintTimer; /** Spawn the server and attach it to Verilog/SystemVerilog documents. */ function activate(context) { const serverPath = vscode.workspace.getConfiguration('lucisv').get('serverPath') || 'lucisv-server'; // No arguments: `lucisv-server` takes none and speaks LSP on stdin/stdout. // `editors/vscode/smoke.js` spawns it exactly this way. const serverOptions = { command: serverPath, args: [], transport: TransportKind.stdio, }; // No `scheme` filter: the server serves `untitled:` buffers too, for // everything single-file (docs/features/lucisv-server/README.md). const clientOptions = { documentSelector: LANGUAGES.map((language) => ({ language })), // Push the whole `lucisv` section to the server as // `workspace/didChangeConfiguration` — once when the client initializes // and again on every change. The server reads `lucisv.lineLength`, // `lucisv.indent` and `lucisv.exclude` from it and ignores the rest // (docs/features/editor-settings/README.md). synchronize: { configurationSection: 'lucisv' }, }; client = new LanguageClient('lucisv', 'lucisv', serverOptions, clientOptions); // `textDocument/inlineCompletion` is LSP 3.18 and still proposed, so // vscode-languageclient 9 does not register its client feature by default — // without this, the server's `inlineCompletionProvider` capability is read // and then ignored, and the request is never sent. The feature itself uses // only stable VS Code API (`languages.registerInlineCompletionItemProvider`), // so nothing here needs an API proposal (docs/features/inline-templates). // Must happen before `start()`: features are registered at initialize time. client.registerFeatures(ProposedFeatures.createAll(client)); context.subscriptions.push(client); // Every colour is one this extension contributes, so every one of them has // an opaque default in every theme kind: a theme that says nothing about // `lucisv.rainbowN` gets our default, and a theme or user that overrides it // gets what they asked for. Nothing here may ever be transparent — the // rainbow colours code, it never hides it. decorationTypes = Array.from({ length: RAINBOW_COLORS }, (_, index) => vscode.window.createTextEditorDecorationType({ color: new vscode.ThemeColor(`lucisv.rainbow${index + 1}`), }), ); // Half a pair has no nesting level and therefore no rainbow colour. It is // still real text, so it is painted in the error colour rather than left // undecorated: a `begin` that lost its `end` is exactly what the user wants // to see. unmatchedType = vscode.window.createTextEditorDecorationType({ color: new vscode.ThemeColor('lucisv.rainbowUnmatched'), }); context.subscriptions.push(...decorationTypes, unmatchedType); rainbowEnabled = readRainbowSetting(); context.subscriptions.push( // A new editor has no decorations of its own; paint it as it appears. vscode.window.onDidChangeActiveTextEditor(() => repaintVisible()), // Covers splits, tab drags, and an editor becoming visible again. vscode.window.onDidChangeVisibleTextEditors(() => repaintVisible()), // Typing moves every range after the cursor, so the answer is stale the // moment it arrives; debounce rather than ask on every keystroke. vscode.workspace.onDidChangeTextDocument((event) => { if (isVerilog(event.document)) scheduleRepaint(); }), vscode.workspace.onDidChangeConfiguration((event) => { if (!event.affectsConfiguration('lucisv.rainbowBeginEnd')) return; rainbowEnabled = readRainbowSetting(); // Honoured immediately, both ways: turning it off has to take the // colours away, or "off" would only mean "off after a reload". repaintVisible(); }), ); // Closing an editor disposes its decorations with it, so there is nothing to // clear on close; the only explicit clearing is turning the setting off, // which `repaintVisible` does by painting empty ranges. client.start().then( () => repaintVisible(), // The client reports a server that will not start, in its own output // channel and its own words. Decorations are cosmetic; there is nothing // useful to add here, and a second error popup would only be noise. () => {}, ); } /** Stop the server; VS Code waits on the returned promise. */ function deactivate() { clearTimeout(repaintTimer); return client ? client.stop() : undefined; } /** True for the documents this extension knows about. */ function isVerilog(document) { return LANGUAGES.includes(document.languageId); } function readRainbowSetting() { return vscode.workspace.getConfiguration('lucisv').get('rainbowBeginEnd') !== false; } /** Coalesce a burst of edits into one repaint. */ function scheduleRepaint() { clearTimeout(repaintTimer); repaintTimer = setTimeout(() => repaintVisible(), REPAINT_DEBOUNCE_MS); } /** Repaint every visible Verilog editor. */ function repaintVisible() { for (const editor of vscode.window.visibleTextEditors) { if (isVerilog(editor.document)) paint(editor); } } /** * Ask the server where this buffer's blocks are and colour them by depth. * * Turning the rainbow off paints empty ranges rather than skipping the editor: * `setDecorations` with `[]` is how a decoration type is removed, so "off" and * "no blocks here" are the same operation. */ async function paint(editor) { const document = editor.document; const askedAbout = document.version; const buckets = decorationTypes.map(() => []); const unmatched = []; if (rainbowEnabled) { let result; try { result = await client.sendRequest('lucisv/scopePairs', { textDocument: { uri: document.uri.toString() }, }); } catch { // The server is gone, restarting, or older than this extension. The // client says so where it says everything else; leaving the old colours // alone is better than blanking the file over a transient failure. return; } // The answer describes the version we asked about. If the user typed while // it was in flight, every range after the edit is now wrong — drop it and // let the debounced repaint that the edit already scheduled do the work. if (document.version !== askedAbout) return; // The editor may have been closed while the request was in flight. if (!vscode.window.visibleTextEditors.includes(editor)) return; for (const pair of (result && result.pairs) || []) { // `depth` is a `u32` from our own server; a server that answered // anything else would otherwise index the buckets with `NaN`. const depth = Number.isInteger(pair.depth) && pair.depth >= 0 ? pair.depth : 0; const ranges = buckets[depth % RAINBOW_COLORS]; ranges.push(asRange(pair.open), asRange(pair.close)); } // A server older than this extension answers without the field; `|| []` // is what lets that pairing keep the rainbow and simply skip the reds. for (const range of (result && result.unmatched) || []) { unmatched.push(asRange(range)); } } for (const [index, ranges] of buckets.entries()) { editor.setDecorations(decorationTypes[index], ranges); } editor.setDecorations(unmatchedType, unmatched); } /** An LSP range (UTF-16, which is what the server advertises) as a VS Code one. */ function asRange(range) { return client.protocol2CodeConverter.asRange(range); } module.exports = { activate, deactivate };