Skip to content

Instantly share code, notes, and snippets.

@Nixinova
Last active June 3, 2023 23:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nixinova/34fdf36a8435ff8cf5dd64d76edafa97 to your computer and use it in GitHub Desktop.
Save Nixinova/34fdf36a8435ff8cf5dd64d76edafa97 to your computer and use it in GitHub Desktop.
VSCode Formatter Extension Example
var vscode = require("vscode")
function activate(context) {
console.log('Formatter activated') // formatting only works once activated
const formatter = vscode.languages.registerDocumentFormattingEditProvider(
'language-id', // set this to the language ID of the language to format (the bit in brackets in the vscode language menu)
{
provideDocumentFormattingEdits: function (document) {
const output = document.getText()
//add your formatting replacements here
.replace('text!', 'replacement1')
.replace(/regex/, 'replacement2')
// condense the following lines if you like
const startOfDocument = document.lineAt(0).range.start
const endOfDocument = document.lineAt(document.lineCount-1).range.end
const documentRange = new vscode.Range(startOfDocument, endOfDocument)
const replacedFileContent = vscode.TextEdit.replace(documentRange, output)
return [replacedFileContent]
}
}
);
context.subscriptions.push(formatter) // let vscode know about the formatter
}
exports.__esModule = true
exports.activate = activate
// actual filename package.json
{
//: ...
"main": "./formatter", //formatter.js
"activationEvents": [
"onLanguage:language-id" // activate extention for files set to this language
],
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment