Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
9 changes: 8 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
28 changes: 27 additions & 1 deletion src/extension.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}