All files / languages/sparql/providers sparql-code-formatting-provider.ts

100% Statements 7/7
100% Branches 0/0
100% Functions 2/2
100% Lines 7/7

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47                                    10x   10x       9x 9x   9x                       9x         9x    
import * as vscode from 'vscode';
import { SparqlFormatter } from '@faubulous/mentor-rdf-serializers';
import { getConfig, resolveFormattingConfig, resolveFormattingIndent } from '@src/utilities/vscode/config';
 
/**
 * Provides formatting edits for SPARQL documents in VS Code.
 */
export class SparqlCodeFormattingProvider implements vscode.DocumentFormattingEditProvider {
    /**
     * The formatter, created on first use: it builds a SPARQL lexer, which would
     * otherwise run when the extension is activated.
     */
    private _formatter: SparqlFormatter | undefined;
 
    /**
     * Returns the formatter, creating it on first use.
     */
    private _getFormatter(): SparqlFormatter {
        this._formatter ??= new SparqlFormatter();
 
        return this._formatter;
    }
 
    provideDocumentFormattingEdits(document: vscode.TextDocument, options: vscode.FormattingOptions, token: vscode.CancellationToken): vscode.TextEdit[] {
        const text = document.getText();
        const config = getConfig('formatting.sparql');
 
        const result = this._getFormatter().formatFromText(text, {
            indent: resolveFormattingIndent(document, options),
            prettyPrint: true,
            uppercaseKeywords: config.get('uppercaseKeywords', false),
            alignPatterns: config.get('alignPatterns', true),
            sameBraceLine: config.get('sameBraceLine', true),
            separateClauses: config.get('separateClauses', true),
            maxLineWidth: resolveFormattingConfig('sparql', 'maxLineWidth', 120),
            spaceBeforePunctuation: resolveFormattingConfig('sparql', 'spaceBeforePunctuation', true),
            blankLinesBetweenSubjects: resolveFormattingConfig('sparql', 'blankLinesBetweenSubjects', true),
        });
 
        const fullRange = new vscode.Range(
            document.positionAt(0),
            document.positionAt(text.length)
        );
 
        return [vscode.TextEdit.replace(fullRange, result.output)];
    }
}