on master help sign in
vs-code-ormolu/src/extension.ts
73 lines 2.3 kB history raw
1// The module 'vscode' contains the VS Code extensibility API
2// Import the module and reference it with the alias vscode in your code below
3import * as vscode from 'vscode';
4import * as proc from 'child_process';
5import { Range } from 'vscode';
7// this method is called when your extension is activated
8// your extension is activated the very first time the command is executed
9const haskellLangId = 'haskell';
10export function activate(context: vscode.ExtensionContext) {
11 vscode.languages.registerDocumentRangeFormattingEditProvider(haskellLangId, {
12 provideDocumentRangeFormattingEdits(document, range, options, token) {
13 const showErrorMessage = (friendlyText: string, error: { stderr: { toString: () => void; }; }) => {
14 vscode.window.showWarningMessage(`${friendlyText}\n${error.stderr.toString()}`);
15 return [];
16 };
18 const cfg = vscode.workspace.getConfiguration("ormolu");
20 try {
21 proc.execSync(cfg.executablePath + ' --help');
22 } catch (e) {
23 return showErrorMessage("Ormolu is not installed", e);
24 }
26 let command = cfg.executablePath;
28 command += ` --start-line ${range.start.line + 1} --end-line ${range.end.line + (range.end.character == 0 ? 0 : 1)}`
29 command += ` --stdin-input-file ${document.fileName}`
31 for (let [key, value] of Object.entries(cfg.extensions)) {
32 if (value) {
33 command += " -o -X" + key;
34 }
35 }
37 if (cfg.customArguments !== null) {
38 command += " " + cfg.customArguments;
39 }
41 if (cfg.tolerateCpp) {
42 command += " -p";
43 }
45 if (cfg.unsafe) {
46 command += " -u";
47 }
49 if (cfg.checkIdempotency) {
50 command += " -c";
51 }
53 const text = document.getText();
54 let formattedText;
55 try {
56 formattedText = proc.execSync(command, { input: text }).toString();
57 } catch (e) {
58 return showErrorMessage('Ormolu failed to format the code', e);
59 }
61 const fullDocumentRange =
62 new Range
63 (document.lineAt(0).range.start
64 , document.lineAt(document.lineCount - 1).range.end
65 );
67 return [vscode.TextEdit.replace(fullDocumentRange, formattedText)];
68 }
69 });
72// this method is called when your extension is deactivated
73export function deactivate() { }