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

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

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                                    12x   12x               9x 9x               9x         9x    
import * as vscode from 'vscode';
import { TurtleFormatter } from '@faubulous/mentor-rdf-serializers';
import { resolveFormattingConfig, resolveFormattingIndent } from '@src/utilities/vscode/config';
 
/**
 * Provides formatting edits for Turtle documents using the TurtleFormatter.
 */
export class TurtleCodeFormattingProvider implements vscode.DocumentFormattingEditProvider {
    /**
     * The formatter, created on first use: it builds a Turtle lexer, which would
     * otherwise run when the extension is activated.
     */
    private _formatter: TurtleFormatter | undefined;
 
    /**
     * Returns the formatter, creating it on first use.
     */
    private _getFormatter(): TurtleFormatter {
        this._formatter ??= new TurtleFormatter();
 
        return this._formatter;
    }
 
    provideDocumentFormattingEdits(
        document: vscode.TextDocument,
        options: vscode.FormattingOptions,
        token: vscode.CancellationToken
    ): vscode.TextEdit[] {
        const text = document.getText();
        const result = this._getFormatter().formatFromText(text, {
            indent: resolveFormattingIndent(document, options),
            prettyPrint: true,
            maxLineWidth: resolveFormattingConfig('turtle', 'maxLineWidth', 120),
            spaceBeforePunctuation: resolveFormattingConfig('turtle', 'spaceBeforePunctuation', true),
            blankLinesBetweenSubjects: resolveFormattingConfig('turtle', 'blankLinesBetweenSubjects', true),
        });
 
        const fullRange = new vscode.Range(
            document.positionAt(0),
            document.positionAt(text.length)
        );
 
        return [vscode.TextEdit.replace(fullRange, result.output)];
    }
}