import * as vscode from "vscode" ; import { setupOutputHandler , addToOutput } from "./outputHandler" ; import { formatSql , IOptions , CaseOptionEnum } from "psqlformat" ; function fullDocumentRange ( document ) { const lastLineId = document . lineCount - 1 ; return new vscode . Range ( 0 , 0 , lastLineId , document . lineAt ( lastLineId ) . text . length ) ; } export { WorkspaceConfiguration , FormattingOptions } from "vscode" ; export function getFormattedText ( text , config , options ) { try { let formattingOptions = < any > Object . assign ( { } , config ) ; formattingOptions . maxLength = null ; if ( config . functionCase != null ) { formattingOptions . functionCase = CaseOptionEnum [ < keyof typeof CaseOptionEnum > config . functionCase ] ; } if ( config . keywordCase != null ) { formattingOptions . keywordCase = CaseOptionEnum [ < keyof typeof CaseOptionEnum > config . keywordCase ] ; } if ( ! formattingOptions . spaces ) { if ( options . tabSize ) { formattingOptions . spaces = Number ( options . tabSize ) ; } if ( formattingOptions . tabs === undefined ) { formattingOptions . tabs = options . insertSpaces === false ; } } addToOutput ( `Formatting with options ${ JSON . stringify ( formattingOptions ) }:` ) ; let formatted = formatSql ( text , formattingOptions ) ; return formatted ; } catch ( err ) { addToOutput ( `ERROR: ${ err }` ) ; } } export function activate ( context ) { context . subscriptions . push ( vscode . languages . registerDocumentFormattingEditProvider ( [ { language : "sql" } , { language : "pgsql" } , { language : "postgres" } ] , { provideDocumentFormattingEdits } ) , setupOutputHandler ( ) ) ; } export async function provideDocumentFormattingEdits ( document , options , token ) { const edits = [ ] ; if ( document . lineCount >= 1 ) { let firstLine = document . lineAt ( 0 ) ; if ( firstLine . text . indexOf ( "pgFormatter-ignore" ) == - 1 ) { const text = document . getText ( ) ; let config = vscode . workspace . getConfiguration ( "pgFormatter" ) ; let formattedText = getFormattedText ( text , config , options ) ; if ( formattedText && formattedText . length > 0 ) { edits . push ( vscode . TextEdit . replace ( fullDocumentRange ( document ) , formattedText ) ) ; } } } return edits ; } export function deactivate ( ) { }