diff --git a/README.md b/README.md index c498df1..243263a 100644 --- a/README.md +++ b/README.md @@ -9,3 +9,9 @@ Format SQL files using the [sql-formatter-plus](https://github.com/kufii/sql-for **`sql-formatter.uppercase`**: Convert keywords to uppercase. Defaults to false. **`sql-formatter.linesBetweenQueries`**: Number of linebreaks between queries. Defaults to 2. + +## Commands +The following command is also added to VS Code: + +`vscode-sql-formatter.format-selection (Format the selected SQL using the configured settings)` +- Formats the selected text based on the current settings, regardless of the editor's Language Mode. diff --git a/package.json b/package.json index 6273ca5..70f813c 100644 --- a/package.json +++ b/package.json @@ -22,9 +22,16 @@ "pl/sql" ], "activationEvents": [ - "onLanguage:sql" + "onLanguage:sql", + "onCommand:vscode-sql-formatter.format-selection" ], "contributes": { + "commands": [ + { + "command": "vscode-sql-formatter.format-selection", + "title": "SQL Formatter: Format the selected SQL using the configured settings" + } + ], "configuration": { "type": "object", "title": "SQL Formatter", diff --git a/src/extension.js b/src/extension.js index c3196fd..6ad37ab 100644 --- a/src/extension.js +++ b/src/extension.js @@ -21,11 +21,37 @@ const getConfig = ({ insertSpaces, tabSize }) => ({ linesBetweenQueries: getSetting('sql-formatter', 'linesBetweenQueries', 2) }); +const formatSelection = () => { + const editor = vscode.window.activeTextEditor; + + if (editor) { + const document = editor.document; + const selection = editor.selection; + const text = document.getText(selection); + const options = { + insertSpaces: editor.insertSpaces, + tabSize: editor.tabSize, + }; + + if(text) { + const formatted = format(text, getConfig(options)); + editor.edit(editBuilder => { + editBuilder.replace(selection, formatted); + }); + } + } +}; + const format = (text, config) => sqlFormatter.format(text, config); -module.exports.activate = () => +module.exports.activate = (context) => { + const formatSelectionCommand = vscode.commands.registerCommand('vscode-sql-formatter.format-selection', formatSelection); + vscode.languages.registerDocumentRangeFormattingEditProvider('sql', { provideDocumentRangeFormattingEdits: (document, range, options) => [ vscode.TextEdit.replace(range, format(document.getText(range), getConfig(options))) ] }); + + context.subscriptions.push(formatSelectionCommand); +}