Skip to content

Instantly share code, notes, and snippets.

@exceedsystem
Created June 4, 2021 11:28
Show Gist options
  • Save exceedsystem/e599761de3da49662b753fa91475f660 to your computer and use it in GitHub Desktop.
Save exceedsystem/e599761de3da49662b753fa91475f660 to your computer and use it in GitHub Desktop.
An example of 'Format selected SQL' macro for VSCodeMacros extension
// [VSCode Macros] extension
// https://marketplace.visualstudio.com/items?itemName=EXCEEDSYSTEM.vscode-macros
// License:MIT
const vscode = require('vscode');
const formatter = require('sql-formatter');
/**
* Macro configuration
*/
module.exports.macroCommands = {
FormatSQL: {
no: 1,
func: FormatSQL,
},
};
/**
* Format selected SQL
*/
function FormatSQL() {
const editor = vscode.window.activeTextEditor;
if (!editor) {
vscode.window.showWarningMessage('Editor not found.');
return;
}
const document = editor.document;
if (!document) {
vscode.window.showWarningMessage('Document not found.');
return;
}
const selection = editor.selection;
// Get selected SQL
let text = document.getText(selection);
// Format SQL (language=db2, mariadb, mysql, n1ql, plsql, postgresql, redshift, spark, sql, tsql)
const replacedText = formatter.format(text, {
language: 'plsql',
indent: ' ',
uppercase: true
});
// Replace with formatted SQL
editor.edit((editBuilder) => {
editBuilder.replace(selection, replacedText);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment