|
| 1 | +import vscode from "vscode"; |
| 2 | +import { spawn } from "child_process"; |
| 3 | + |
| 4 | +function runClangFormat(text, fileName, formatterPath = "clang-format") { |
| 5 | + return new Promise((resolve, reject) => { |
| 6 | + const args = []; |
| 7 | + |
| 8 | + if (fileName) { |
| 9 | + args.push("-assume-filename", fileName); |
| 10 | + } |
| 11 | + |
| 12 | + const proc = spawn(formatterPath, args); |
| 13 | + |
| 14 | + let stdout = ""; |
| 15 | + let stderr = ""; |
| 16 | + |
| 17 | + proc.stdout.on("data", (data) => (stdout += data)); |
| 18 | + proc.stderr.on("data", (data) => (stderr += data)); |
| 19 | + |
| 20 | + proc.on("error", reject); |
| 21 | + |
| 22 | + proc.on("close", (code) => { |
| 23 | + if (code !== 0) { |
| 24 | + return reject(new Error(`clang-format exited with code ${code}: ${stderr}`)); |
| 25 | + } |
| 26 | + |
| 27 | + resolve(stdout); |
| 28 | + }); |
| 29 | + |
| 30 | + proc.stdin.end(text); |
| 31 | + }); |
| 32 | +} |
| 33 | + |
| 34 | +export async function setupFormat(context) { |
| 35 | + const fmtConfig = vscode.workspace.getConfiguration("c3.format"); |
| 36 | + const fmtPath = fmtConfig.get("path") || "clang-format"; |
| 37 | + |
| 38 | + context.subscriptions.push( |
| 39 | + // Format full document |
| 40 | + vscode.languages.registerDocumentFormattingEditProvider( |
| 41 | + [ |
| 42 | + { language: "c3", scheme: "file" }, // files on disk |
| 43 | + { language: "c3", scheme: "untitled" }, // unsaved files |
| 44 | + ], { |
| 45 | + async provideDocumentFormattingEdits(document) { |
| 46 | + try { |
| 47 | + const input = document.getText(); |
| 48 | + const result = await runClangFormat(input, document.fileName, fmtPath); |
| 49 | + |
| 50 | + const fullRange = new vscode.Range( |
| 51 | + document.positionAt(0), |
| 52 | + document.positionAt(input.length) |
| 53 | + ); |
| 54 | + |
| 55 | + return [ |
| 56 | + vscode.TextEdit.replace(fullRange, result) |
| 57 | + ]; |
| 58 | + } catch (err) { |
| 59 | + vscode.window.showErrorMessage( |
| 60 | + `Error formatting c3 document: ${err.message}` |
| 61 | + ); |
| 62 | + return []; |
| 63 | + } |
| 64 | + } |
| 65 | + }) |
| 66 | + ); |
| 67 | +} |
0 commit comments