import * as vscode from 'vscode' ; import { DefaultClient , FormatParams , FormatDocumentRequest } from '../client' ; import { CppSettings , getEditorConfigSettings } from '../settings' ; export class DocumentFormattingEditProvider implements vscode . DocumentFormattingEditProvider { private client : DefaultClient ; constructor ( client ) { this . client = client ; } public async provideDocumentFormattingEdits ( document , options , token ) { await this . client . awaitUntilLanguageClientReady ( ) ; const filePath = document . uri . fsPath ; const settings = new CppSettings ( this . client . RootUri ) ; const useVcFormat = settings . useVcFormat ( document ) ; const configCallBack = async ( editorConfigSettings ) => { const params = { editorConfigSettings : { ... editorConfigSettings } , useVcFormat : useVcFormat , uri : document . uri . toString ( ) , insertSpaces : options . insertSpaces , tabSize : options . tabSize , character : "" , range : { start : { character : 0 , line : 0 } , end : { character : 0 , line : 0 } } } ; const textEdits = await this . client . languageClient . sendRequest ( FormatDocumentRequest , params ) ; const results = [ ] ; textEdits . forEach ( ( textEdit ) => { results . push ( { range : new vscode . Range ( textEdit . range . start . line , textEdit . range . start . character , textEdit . range . end . line , textEdit . range . end . character ) , newText : textEdit . newText } ) ; } ) ; if ( document . lineCount > 0 && editorConfigSettings !== undefined && editorConfigSettings . insert_final_newline ) { const lastLine = document . lineAt ( document . lineCount - 1 ) ; if ( ! lastLine . isEmptyOrWhitespace ) { const endPosition = lastLine . range . end ; let lastEdit ; results . forEach ( edit => { if ( edit . range . end . isAfterOrEqual ( endPosition ) && ( ! lastEdit || edit . range . start . isAfterOrEqual ( lastEdit . range . start ) ) && edit . newText !== "" ) { lastEdit = edit ; } } ) ; if ( lastEdit === undefined ) { results . push ( { range : new vscode . Range ( endPosition , endPosition ) , newText : "\n" } ) ; } else { if ( ! lastEdit . newText . endsWith ( "\n" ) ) { lastEdit . newText += "\n" ; } } } } return results ; } ; if ( ! useVcFormat ) { return configCallBack ( undefined ) ; } else { const editorConfigSettings = getEditorConfigSettings ( filePath ) ; return configCallBack ( editorConfigSettings ) ; } } }