diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..4bfca33 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,9 @@ +root = true + +[*] +indent_size = 2 +indent_style = space +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true diff --git a/src/extension.ts b/src/extension.ts index 3313b96..f65ac4e 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -1,8 +1,8 @@ -import * as vscode from 'vscode'; +import * as vscode from "vscode"; -import ValeServerProvider from './features/vsProvider'; +import ValeServerProvider from "./features/vsProvider"; export function activate(context: vscode.ExtensionContext) { - let linter = new ValeServerProvider(); - linter.activate(context.subscriptions); + let linter = new ValeServerProvider(); + linter.activate(context.subscriptions); } diff --git a/src/features/vsCommands.ts b/src/features/vsCommands.ts index f74a627..0a92069 100644 --- a/src/features/vsCommands.ts +++ b/src/features/vsCommands.ts @@ -1,139 +1,148 @@ -import * as vscode from 'vscode'; +import * as vscode from "vscode"; -import * as path from 'path'; -import * as request from 'request-promise-native'; +import * as path from "path"; +import * as request from "request-promise-native"; /** * An Alert From Vale. */ interface IValeConfigJSON { - readonly Project: string; - readonly StylesPath: string; + readonly Project: string; + readonly StylesPath: string; } export default function InitCommands(subscriptions: vscode.Disposable[]) { - subscriptions.push( - vscode.commands.registerCommand('vale.addToAccept', addToAccept), - vscode.commands.registerCommand('vale.addToReject', addToReject), + subscriptions.push( + vscode.commands.registerCommand("vale.addToAccept", addToAccept), + vscode.commands.registerCommand("vale.addToReject", addToReject), - vscode.commands.registerCommand('vale.openAccept', openAccept), - vscode.commands.registerCommand('vale.openReject', openReject) - ); + vscode.commands.registerCommand("vale.openAccept", openAccept), + vscode.commands.registerCommand("vale.openReject", openReject) + ); } const addToAccept = async () => { - await addToVocab("accept"); + await addToVocab("accept"); }; const addToReject = async () => { - await addToVocab("reject"); + await addToVocab("reject"); }; const openAccept = async () => { - await openVocabFile("accept"); + await openVocabFile("accept"); }; const openReject = async () => { - await openVocabFile("reject"); + await openVocabFile("reject"); }; /** * Get the user's active Vale Server configuration. */ const getConfig = async (server: string): Promise => { - let config: IValeConfigJSON = {} as IValeConfigJSON; + let config: IValeConfigJSON = {} as IValeConfigJSON; - await request.get({ uri: server + '/config', json: true }) - .catch((error) => { - throw new Error(`Vale Server could not connect: ${error}.`); - }) - .then((body) => { - config = body; - }); + await request + .get({ uri: server + "/config", json: true }) + .catch((error) => { + throw new Error(`Vale Server could not connect: ${error}.`); + }) + .then((body) => { + config = body; + }); - return config; + return config; }; const openVocabFile = async (name: string) => { - const configuration = vscode.workspace.getConfiguration(); - const server: string = configuration.get( - 'vale.server.serverURL', - 'http://localhost:7777' - ); - const config: IValeConfigJSON = await getConfig(server); - - const src = path.join( - config.StylesPath, - 'Vocab', - config.Project, - name + '.txt'); - vscode.workspace.openTextDocument(src).then( - doc => vscode.window.showTextDocument(doc) - ); + const configuration = vscode.workspace.getConfiguration(); + const server: string = configuration.get( + "vale.server.serverURL", + "http://localhost:7777" + ); + const config: IValeConfigJSON = await getConfig(server); + + const src = path.join( + config.StylesPath, + "Vocab", + config.Project, + name + ".txt" + ); + vscode.workspace + .openTextDocument(src) + .then((doc) => vscode.window.showTextDocument(doc)); }; /** * Add the currently-selected word to the user's active Vocab. */ const addToVocab = async (filename: string) => { - const editor = vscode.window.activeTextEditor; - if (!editor) { - return; - } - - const configuration = vscode.workspace.getConfiguration(); - const server: string = configuration.get( - 'vale.server.serverURL', - 'http://localhost:7777' - ); - const config: IValeConfigJSON = await getConfig(server); - - const word: string = editor.document.getText(editor.selection); - const name: string = config.Project; - const styles: string = config.StylesPath; - - await request.get({ - uri: server + '/vocab', - qs: { - name: name, - file: filename - }, - json: true + const editor = vscode.window.activeTextEditor; + if (!editor) { + return; + } + + const configuration = vscode.workspace.getConfiguration(); + const server: string = configuration.get( + "vale.server.serverURL", + "http://localhost:7777" + ); + const config: IValeConfigJSON = await getConfig(server); + + const word: string = editor.document.getText(editor.selection); + const name: string = config.Project; + const styles: string = config.StylesPath; + + await request + .get({ + uri: server + "/vocab", + qs: { + name: name, + file: filename, + }, + json: true, }) .catch((error) => { - throw new Error(`Vale Server could not connect: ${error}.`); + throw new Error(`Vale Server could not connect: ${error}.`); }) .then((contents: Array) => { - contents.push(word); - - // TODO: Do we need to (shoud we?) sort ourselves? - let body = [...new Set(contents)].sort((a, b) => { - if (a.toLowerCase() > b.toLowerCase()) { - return 1; - } else if (a.toLowerCase() < b.toLowerCase()) { - return -1; - } - return 0; - }); - - request.post({ - uri: server + '/update', - qs: { - path: name + '.' + filename, - text: body.join('\n') - }, - json: true - }).catch((error) => { - throw new Error(`Vale Server could not connect: ${error}.`); - }).then(() => { - const src = path.join(styles, 'Vocab', name, filename + '.txt'); - vscode.window.showInformationMessage( - `Successfully added '${word}' to '${name}' vocab.`, - ...['View File']).then(selection => { - if (selection === 'View File') { - vscode.workspace.openTextDocument(src).then( - doc => vscode.window.showTextDocument(doc) - ); - } - }); + contents.push(word); + + // TODO: Do we need to (shoud we?) sort ourselves? + let body = [...new Set(contents)].sort((a, b) => { + if (a.toLowerCase() > b.toLowerCase()) { + return 1; + } else if (a.toLowerCase() < b.toLowerCase()) { + return -1; + } + return 0; + }); + + request + .post({ + uri: server + "/update", + qs: { + path: name + "." + filename, + text: body.join("\n"), + }, + json: true, + }) + .catch((error) => { + throw new Error(`Vale Server could not connect: ${error}.`); + }) + .then(() => { + const src = path.join(styles, "Vocab", name, filename + ".txt"); + vscode.window + .showInformationMessage( + `Successfully added '${word}' to '${name}' vocab.`, + ...["View File"] + ) + .then((selection) => { + if (selection === "View File") { + vscode.workspace + .openTextDocument(src) + .then((doc) => vscode.window.showTextDocument(doc)); + } + }); }); }); }; diff --git a/src/features/vsProvider.ts b/src/features/vsProvider.ts index 0faf0d6..b8b9369 100644 --- a/src/features/vsProvider.ts +++ b/src/features/vsProvider.ts @@ -1,12 +1,12 @@ -'use strict'; +"use strict"; -import * as path from 'path'; -import * as fs from 'fs'; -import * as request from 'request-promise-native'; -import * as vscode from 'vscode'; +import * as path from "path"; +import * as fs from "fs"; +import * as request from "request-promise-native"; +import * as vscode from "vscode"; -import InitCommands from './vsCommands'; -import * as utils from './vsUtils'; +import InitCommands from "./vsCommands"; +import * as utils from "./vsUtils"; export default class ValeServerProvider implements vscode.CodeActionProvider { private diagnosticCollection!: vscode.DiagnosticCollection; @@ -16,7 +16,7 @@ export default class ValeServerProvider implements vscode.CodeActionProvider { private stylesPath!: string; private useCLI!: boolean; - private static commandId: string = 'ValeServerProvider.runCodeAction'; + private static commandId: string = "ValeServerProvider.runCodeAction"; private command!: vscode.Disposable; private async doVale(textDocument: vscode.TextDocument) { @@ -27,11 +27,11 @@ export default class ValeServerProvider implements vscode.CodeActionProvider { // Reset out alert map: this.alertMap = {}; - this.useCLI = configuration.get('vale.core.useCLI', false); + this.useCLI = configuration.get("vale.core.useCLI", false); if (!this.useCLI) { // We're using Vale Server ... - const limit = configuration.get('vale.server.lintContext', 0); + const limit = configuration.get("vale.server.lintContext", 0); let response: string = ""; if (limit < 0 || (limit > 0 && textDocument.lineCount >= limit)) { @@ -71,48 +71,48 @@ export default class ValeServerProvider implements vscode.CodeActionProvider { // because the user may simply be editing a non-Vale project/file. let stylesPath: Array = []; if (configLocation !== "" && !fs.existsSync(configLocation)) { - vscode.window.showErrorMessage( - `There was an error running Vale: '${configLocation}' does not exist.` - ); + vscode.window.showErrorMessage( + `There was an error running Vale: '${configLocation}' does not exist.` + ); } else if (configLocation !== "") { stylesPath = [ - binaryLocation, - "--no-exit", - "--config", - configLocation, - "ls-config" - ]; + binaryLocation, + "--no-exit", + "--config", + configLocation, + "ls-config", + ]; } else { - stylesPath = [ - binaryLocation, - "--no-exit", - "ls-config" - ]; - } - - const configOut = await utils.runInWorkspace(folder, stylesPath); - try { - const configCLI = JSON.parse(configOut); - - this.stylesPath = configCLI.StylesPath; - const command = utils.buildCommand( - binaryLocation, - configLocation, - file.fileName); - - const stdout = await utils.runInWorkspace(folder, command); - this.handleJSON(stdout.toString(), file, 0); - } catch (error) { - // We can't find a configuration, but this might not be an error: - // - // TODO: in case (2), how do we unintrusively communicate that we - // couldn't find a config file? - console.log(`[Vale] runtime error: ${error}`); - } + stylesPath = [binaryLocation, "--no-exit", "ls-config"]; } + const configOut = await utils.runInWorkspace(folder, stylesPath); + try { + const configCLI = JSON.parse(configOut); + + this.stylesPath = configCLI.StylesPath; + const command = utils.buildCommand( + binaryLocation, + configLocation, + file.fileName + ); + + const stdout = await utils.runInWorkspace(folder, command); + this.handleJSON(stdout.toString(), file, 0); + } catch (error) { + // We can't find a configuration, but this might not be an error: + // + // TODO: in case (2), how do we unintrusively communicate that we + // couldn't find a config file? + console.log(`[Vale] runtime error: ${error}`); + } + } - private handleJSON(contents: string, doc: vscode.TextDocument, offset: number) { + private handleJSON( + contents: string, + doc: vscode.TextDocument, + offset: number + ) { const diagnostics: vscode.Diagnostic[] = []; let body = JSON.parse(contents.toString()); const backend = this.useCLI ? "Vale" : "Vale Server"; @@ -126,7 +126,11 @@ export default class ValeServerProvider implements vscode.CodeActionProvider { this.updateStatusBarItem(readabilityMessage); } else { let diagnostic = utils.toDiagnostic( - alerts[i], this.stylesPath, backend, offset); + alerts[i], + this.stylesPath, + backend, + offset + ); let key = `${diagnostic.message}-${diagnostic.range}`; this.alertMap[key] = alerts[i]; @@ -149,7 +153,8 @@ export default class ValeServerProvider implements vscode.CodeActionProvider { document: vscode.TextDocument, range: vscode.Range, context: vscode.CodeActionContext, - token: vscode.CancellationToken): Promise { + token: vscode.CancellationToken + ): Promise { let diagnostic: vscode.Diagnostic = context.diagnostics[0]; let actions: vscode.CodeAction[] = []; @@ -160,26 +165,27 @@ export default class ValeServerProvider implements vscode.CodeActionProvider { let key = `${diagnostic.message}-${diagnostic.range}`; let alert = this.alertMap[key]; - let server: string = vscode.workspace.getConfiguration().get( - 'vale.server.serverURL', - 'http://localhost:7777' - ); + let server: string = vscode.workspace + .getConfiguration() + .get("vale.server.serverURL", "http://localhost:7777"); await request .post({ - uri: server + '/suggest', + uri: server + "/suggest", qs: { alert: JSON.stringify(alert) }, - json: true + json: true, }) .catch((error) => { return Promise.reject(`Vale Server could not connect: ${error}.`); }) .then((body) => { - for (let idx in body['suggestions']) { - const suggestion = body['suggestions'][idx]; + for (let idx in body["suggestions"]) { + const suggestion = body["suggestions"][idx]; const title = utils.toTitle(alert, suggestion); - const action = - new vscode.CodeAction(title, vscode.CodeActionKind.QuickFix); + const action = new vscode.CodeAction( + title, + vscode.CodeActionKind.QuickFix + ); action.command = { title: title, @@ -189,8 +195,8 @@ export default class ValeServerProvider implements vscode.CodeActionProvider { diagnostic, alert.Match, suggestion, - alert.Action.Name - ] + alert.Action.Name, + ], }; actions.push(action); @@ -201,14 +207,19 @@ export default class ValeServerProvider implements vscode.CodeActionProvider { } private runCodeAction( - document: vscode.TextDocument, diagnostic: vscode.Diagnostic, - error: string, suggestion: string, action: string): any { + document: vscode.TextDocument, + diagnostic: vscode.Diagnostic, + error: string, + suggestion: string, + action: string + ): any { let docError: string = document.getText(diagnostic.range); if (error === docError) { // Remove diagnostic from list - let diagnostics: vscode.Diagnostic[] = - this.diagnosticMap[document.uri.toString()]; + let diagnostics: vscode.Diagnostic[] = this.diagnosticMap[ + document.uri.toString() + ]; let index: number = diagnostics.indexOf(diagnostic); diagnostics.splice(index, 1); @@ -219,21 +230,25 @@ export default class ValeServerProvider implements vscode.CodeActionProvider { // Insert the new text let edit = new vscode.WorkspaceEdit(); - if (action !== 'remove') { + if (action !== "remove") { edit.replace(document.uri, diagnostic.range, suggestion); } else { // NOTE: we need to add a character when deleting to avoid leaving a // double space. const range = new vscode.Range( - diagnostic.range.start.line, diagnostic.range.start.character, - diagnostic.range.end.line, diagnostic.range.end.character + 1); + diagnostic.range.start.line, + diagnostic.range.start.character, + diagnostic.range.end.line, + diagnostic.range.end.character + 1 + ); edit.delete(document.uri, range); } return vscode.workspace.applyEdit(edit); } else { vscode.window.showErrorMessage( - 'The suggestion was not applied because it is out of date.'); + "The suggestion was not applied because it is out of date." + ); console.log(error, docError); } } @@ -248,23 +263,33 @@ export default class ValeServerProvider implements vscode.CodeActionProvider { ); subscriptions.push(this); - this.readabilityStatus = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left, 100); + this.readabilityStatus = vscode.window.createStatusBarItem( + vscode.StatusBarAlignment.Left, + 100 + ); this.diagnosticCollection = vscode.languages.createDiagnosticCollection(); - this.useCLI = configuration.get('vale.core.useCLI', false); + this.useCLI = configuration.get("vale.core.useCLI", false); if (!this.useCLI) { this.stylesPath = await utils.getStylesPath(); } vscode.workspace.onDidOpenTextDocument(this.doVale, this, subscriptions); - vscode.workspace.onDidCloseTextDocument((textDocument) => { - this.diagnosticCollection.delete(textDocument.uri); - }, null, subscriptions); + vscode.workspace.onDidCloseTextDocument( + (textDocument) => { + this.diagnosticCollection.delete(textDocument.uri); + }, + null, + subscriptions + ); vscode.workspace.onDidSaveTextDocument(this.doVale, this); vscode.workspace.textDocuments.forEach(this.doVale, this); - vscode.languages.registerCodeActionsProvider({ scheme: '*', language: '*' }, this); + vscode.languages.registerCodeActionsProvider( + { scheme: "*", language: "*" }, + this + ); InitCommands(subscriptions); } diff --git a/src/features/vsTypes.ts b/src/features/vsTypes.ts index d0ae395..dbf30d3 100644 --- a/src/features/vsTypes.ts +++ b/src/features/vsTypes.ts @@ -1,32 +1,32 @@ /** * A severity from Vale Server. */ -type ValeSeverity = 'suggestion' | 'warning' | 'error'; +type ValeSeverity = "suggestion" | "warning" | "error"; interface IEditorContext { - Content: string; - Offset: number; + Content: string; + Offset: number; } /** * An Action From Vale. */ interface IValeActionJSON { - readonly Name: string; - readonly Params: [string]; + readonly Name: string; + readonly Params: [string]; } /** * An Alert From Vale. */ interface IValeErrorJSON { - readonly Action: IValeActionJSON; - readonly Check: string; - readonly Match: string; - readonly Description: string; - readonly Line: number; - readonly Link: string; - readonly Message: string; - readonly Span: [number, number]; - readonly Severity: ValeSeverity; + readonly Action: IValeActionJSON; + readonly Check: string; + readonly Match: string; + readonly Description: string; + readonly Line: number; + readonly Link: string; + readonly Message: string; + readonly Span: [number, number]; + readonly Severity: ValeSeverity; } diff --git a/src/features/vsUtils.ts b/src/features/vsUtils.ts index 749ad84..56a6140 100644 --- a/src/features/vsUtils.ts +++ b/src/features/vsUtils.ts @@ -1,45 +1,45 @@ -import * as path from 'path'; +import * as path from "path"; import * as which from "which"; -import * as fs from 'fs'; -import * as request from 'request-promise-native'; +import * as fs from "fs"; +import * as request from "request-promise-native"; import { execFile } from "child_process"; -import * as vscode from 'vscode'; +import * as vscode from "vscode"; export const readBinaryLocation = (file: vscode.TextDocument) => { - const configuration = vscode.workspace.getConfiguration(); - - let customBinaryPath = configuration.get("vale.valeCLI.path"); - if (customBinaryPath) { - customBinaryPath = path.normalize(customBinaryPath); - const workspaceFolder = vscode.workspace.getWorkspaceFolder(file.uri); - if (workspaceFolder) { - customBinaryPath = customBinaryPath.replace( - "${workspaceFolder}", - workspaceFolder.uri.fsPath, - ); - } - return customBinaryPath; + const configuration = vscode.workspace.getConfiguration(); + + let customBinaryPath = configuration.get("vale.valeCLI.path"); + if (customBinaryPath) { + customBinaryPath = path.normalize(customBinaryPath); + const workspaceFolder = vscode.workspace.getWorkspaceFolder(file.uri); + if (workspaceFolder) { + customBinaryPath = customBinaryPath.replace( + "${workspaceFolder}", + workspaceFolder.uri.fsPath + ); } - return which.sync("vale"); + return customBinaryPath; + } + return which.sync("vale"); }; export const readFileLocation = (file: vscode.TextDocument) => { - const configuration = vscode.workspace.getConfiguration(); - - let customConfigPath = configuration.get("vale.valeCLI.config"); - if (customConfigPath) { - customConfigPath = path.normalize(customConfigPath); - const workspaceFolder = vscode.workspace.getWorkspaceFolder(file.uri); - if (workspaceFolder) { - customConfigPath = customConfigPath.replace( - "${workspaceFolder}", - workspaceFolder.uri.fsPath, - ); - } - return customConfigPath; + const configuration = vscode.workspace.getConfiguration(); + + let customConfigPath = configuration.get("vale.valeCLI.config"); + if (customConfigPath) { + customConfigPath = path.normalize(customConfigPath); + const workspaceFolder = vscode.workspace.getWorkspaceFolder(file.uri); + if (workspaceFolder) { + customConfigPath = customConfigPath.replace( + "${workspaceFolder}", + workspaceFolder.uri.fsPath + ); } - return ""; + return customConfigPath; + } + return ""; }; /** @@ -47,15 +47,17 @@ export const readFileLocation = (file: vscode.TextDocument) => { * * @param severity The severity to convert */ -export const toSeverity = (severity: ValeSeverity): vscode.DiagnosticSeverity => { - switch (severity) { - case 'suggestion': - return vscode.DiagnosticSeverity.Information; - case 'warning': - return vscode.DiagnosticSeverity.Warning; - case 'error': - return vscode.DiagnosticSeverity.Error; - } +export const toSeverity = ( + severity: ValeSeverity +): vscode.DiagnosticSeverity => { + switch (severity) { + case "suggestion": + return vscode.DiagnosticSeverity.Information; + case "warning": + return vscode.DiagnosticSeverity.Warning; + case "error": + return vscode.DiagnosticSeverity.Error; + } }; /** @@ -65,11 +67,11 @@ export const toSeverity = (severity: ValeSeverity): vscode.DiagnosticSeverity => * @param suggestion The vsengine-calculated suggestion */ export const toTitle = (alert: IValeErrorJSON, suggestion: string): string => { - switch (alert.Action.Name) { - case 'remove': - return 'Remove \'' + alert.Match + '\''; - } - return 'Replace with \'' + suggestion + '\''; + switch (alert.Action.Name) { + case "remove": + return "Remove '" + alert.Match + "'"; + } + return "Replace with '" + suggestion + "'"; }; /** @@ -81,11 +83,11 @@ export const toTitle = (alert: IValeErrorJSON, suggestion: string): string => { * @return Whether the document is elligible */ export const isElligibleDocument = (document: vscode.TextDocument): boolean => { - if (document.isDirty) { - vscode.window.showErrorMessage('Please save the file before linting.'); - return false; - } - return vscode.languages.match({ scheme: "file" }, document) > 0; + if (document.isDirty) { + vscode.window.showErrorMessage("Please save the file before linting."); + return false; + } + return vscode.languages.match({ scheme: "file" }, document) > 0; }; /** @@ -94,32 +96,39 @@ export const isElligibleDocument = (document: vscode.TextDocument): boolean => { * @param alert The alert to convert */ export const toDiagnostic = ( - alert: IValeErrorJSON, - styles: string, - backend: string, - offset: number + alert: IValeErrorJSON, + styles: string, + backend: string, + offset: number ): vscode.Diagnostic => { - const range = new vscode.Range( - (alert.Line - 1) + offset, - alert.Span[0] - 1, - (alert.Line - 1) + offset, - alert.Span[1] - ); - - const diagnostic = - new vscode.Diagnostic(range, alert.Message, toSeverity(alert.Severity)); - - diagnostic.source = backend; - diagnostic.code = alert.Check; - - const name = alert.Check.split('.'); - const rule = vscode.Uri.file(path.join(styles, name[0], name[1] + '.yml')); - - if (fs.existsSync(rule.fsPath)) { - diagnostic.relatedInformation = [new vscode.DiagnosticRelatedInformation( - new vscode.Location(rule, new vscode.Position(0, 0)), 'View rule')]; - } - return diagnostic; + const range = new vscode.Range( + alert.Line - 1 + offset, + alert.Span[0] - 1, + alert.Line - 1 + offset, + alert.Span[1] + ); + + const diagnostic = new vscode.Diagnostic( + range, + alert.Message, + toSeverity(alert.Severity) + ); + + diagnostic.source = backend; + diagnostic.code = alert.Check; + + const name = alert.Check.split("."); + const rule = vscode.Uri.file(path.join(styles, name[0], name[1] + ".yml")); + + if (fs.existsSync(rule.fsPath)) { + diagnostic.relatedInformation = [ + new vscode.DiagnosticRelatedInformation( + new vscode.Location(rule, new vscode.Position(0, 0)), + "View rule" + ), + ]; + } + return diagnostic; }; /** @@ -133,128 +142,137 @@ export const toDiagnostic = ( * @return The standard output of the program */ export const runInWorkspace = ( - folder: string | undefined, - command: ReadonlyArray, + folder: string | undefined, + command: ReadonlyArray ): Promise => - new Promise((resolve, reject) => { - const cwd = folder ? folder : process.cwd(); - const maxBuffer = 10 * 1024 * 1024; // 10MB buffer for large results - execFile( - command[0], - command.slice(1), - { cwd, maxBuffer }, - (error, stdout) => { - resolve(stdout); - }, - ); - }); + new Promise((resolve, reject) => { + const cwd = folder ? folder : process.cwd(); + const maxBuffer = 10 * 1024 * 1024; // 10MB buffer for large results + execFile( + command[0], + command.slice(1), + { cwd, maxBuffer }, + (error, stdout) => { + resolve(stdout); + } + ); + }); const extractParagraph = (editor: vscode.TextEditor): vscode.Range => { - let startLine = editor.selection.start.line; - let endLine = editor.selection.end.line; - - while (startLine > 0 && !editor.document.lineAt(startLine - 1).isEmptyOrWhitespace) { - startLine -= 1; - } - - while (endLine < editor.document.lineCount - 1 && - !editor.document.lineAt(endLine + 1).isEmptyOrWhitespace) { - endLine += 1; - } - - const startCharacter = 0; - const endCharacter = editor.document.lineAt(endLine).text.length; - - return new vscode.Range(startLine, startCharacter, endLine, endCharacter); + let startLine = editor.selection.start.line; + let endLine = editor.selection.end.line; + + while ( + startLine > 0 && + !editor.document.lineAt(startLine - 1).isEmptyOrWhitespace + ) { + startLine -= 1; + } + + while ( + endLine < editor.document.lineCount - 1 && + !editor.document.lineAt(endLine + 1).isEmptyOrWhitespace + ) { + endLine += 1; + } + + const startCharacter = 0; + const endCharacter = editor.document.lineAt(endLine).text.length; + + return new vscode.Range(startLine, startCharacter, endLine, endCharacter); }; export const findContext = (): IEditorContext => { - const editor = vscode.window.activeTextEditor; + const editor = vscode.window.activeTextEditor; - let context: IEditorContext = {Content: "", Offset: 0}; - if (!editor) { - return context; - } - const range = extractParagraph(editor); + let context: IEditorContext = { Content: "", Offset: 0 }; + if (!editor) { + return context; + } + const range = extractParagraph(editor); - context.Content = editor.document.getText(range); - context.Offset = range.start.line; + context.Content = editor.document.getText(range); + context.Offset = range.start.line; - return context; + return context; }; export const postFile = async (doc: vscode.TextDocument): Promise => { - let server: string = vscode.workspace.getConfiguration().get( - 'vale.server.serverURL', - 'http://localhost:7777' - ); - let response: string = ""; - - await request - .post({ - uri: server + '/file', - qs: { - file: doc.fileName, - path: path.dirname(doc.fileName) - }, - json: true - }) - .catch((error) => { - vscode.window.showErrorMessage( - `Vale Server could not connect: ${error}.`); - }) - .then((body) => { - response = fs.readFileSync(body.path).toString(); - }); - - return response; -}; + let server: string = vscode.workspace + .getConfiguration() + .get("vale.server.serverURL", "http://localhost:7777"); + let response: string = ""; + + await request + .post({ + uri: server + "/file", + qs: { + file: doc.fileName, + path: path.dirname(doc.fileName), + }, + json: true, + }) + .catch((error) => { + vscode.window.showErrorMessage( + `Vale Server could not connect: ${error}.` + ); + }) + .then((body) => { + response = fs.readFileSync(body.path).toString(); + }); -export const postString = async (content: string, ext: string): Promise => { - let server: string = vscode.workspace.getConfiguration().get( - 'vale.server.serverURL', - 'http://localhost:7777' - ); - let response: string = ""; - - await request - .post({ - uri: server + '/vale', - qs: { - text: content, - format: ext - }, - json: false - }) - .catch((error) => { - vscode.window.showErrorMessage( - `Vale Server could not connect: ${error}.`); - }) - .then((body) => { - response = body; - }); - - return response; + return response; }; -export const getStylesPath = async (): Promise => { - const configuration = vscode.workspace.getConfiguration(); +export const postString = async ( + content: string, + ext: string +): Promise => { + let server: string = vscode.workspace + .getConfiguration() + .get("vale.server.serverURL", "http://localhost:7777"); + let response: string = ""; + + await request + .post({ + uri: server + "/vale", + qs: { + text: content, + format: ext, + }, + json: false, + }) + .catch((error) => { + vscode.window.showErrorMessage( + `Vale Server could not connect: ${error}.` + ); + }) + .then((body) => { + response = body; + }); - let path: string = ""; - let server: string = configuration.get( - 'vale.server.serverURL', - 'http://localhost:7777' - ); + return response; +}; - await request.get({ uri: server + '/path', json: true }) - .catch((error) => { - throw new Error(`Vale Server could not connect: ${error}.`); - }) - .then((body) => { - path = body.path; - }); +export const getStylesPath = async (): Promise => { + const configuration = vscode.workspace.getConfiguration(); + + let path: string = ""; + let server: string = configuration.get( + "vale.server.serverURL", + "http://localhost:7777" + ); + + await request + .get({ uri: server + "/path", json: true }) + .catch((error) => { + throw new Error(`Vale Server could not connect: ${error}.`); + }) + .then((body) => { + path = body.path; + }); - return path; + return path; }; export const buildCommand = ( @@ -262,21 +280,22 @@ export const buildCommand = ( config: string, path: string ): Array => { - const configuration = vscode.workspace.getConfiguration(); + const configuration = vscode.workspace.getConfiguration(); - let command: Array = [exe, "--no-exit"]; - if (config !== "") { - command = command.concat(["--config", config]); - } + let command: Array = [exe, "--no-exit"]; + if (config !== "") { + command = command.concat(["--config", config]); + } - let minAlertLevel: string = configuration.get( - "vale.valeCLI.minAlertLevel", "inherited"); + let minAlertLevel: string = configuration.get( + "vale.valeCLI.minAlertLevel", + "inherited" + ); - if (minAlertLevel !== "inherited") { - command = command.concat(["--minAlertLevel", minAlertLevel]); - } + if (minAlertLevel !== "inherited") { + command = command.concat(["--minAlertLevel", minAlertLevel]); + } - command = command.concat(["--output", "JSON", path]); - return command; + command = command.concat(["--output", "JSON", path]); + return command; }; -