Skip to content

Instantly share code, notes, and snippets.

@lostsnow
Created August 3, 2018 19:11
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 lostsnow/4748401164ed35ebf6d6766e9f1dea81 to your computer and use it in GitHub Desktop.
Save lostsnow/4748401164ed35ebf6d6766e9f1dea81 to your computer and use it in GitHub Desktop.
const vscode = require('vscode'),
childProcess = require('child_process'),
fs = require('fs');
// Global vars
// Status bar
const statusBar = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
// Show message in StatusBar
function checkStatusBar(text, delay) {
statusBar.text = text;
statusBar.show();
setTimeout(() => statusBar.hide(), delay);
}
function activate(context) {
const disposable = vscode.commands.registerCommand('extension.aformat', function () {
// Get current editor
const activeTextEditor = vscode.window.activeTextEditor,
// Current document
document = activeTextEditor.document,
// Path to current file
currentFilePath = document.fileName,
// Get extension configuration
configuration = vscode.workspace.getConfiguration('astyleFormat'),
// Config: show message box about formatting
showMessages = configuration['show-message'],
// Where is .astylerc file
astylerc = configuration.astylerc,
// Where is astyle program
astyle = configuration.astyle || "astyle",
// Timeout for message box
delay = configuration.messageTimeout,
// Format function
aformatFunc = () => {
let args = [];
args.push(astyle);
if (astylerc) {
args.push("--options=\"" + astylerc + "\"");
}
args.push("\"" + currentFilePath + "\"");
let defaultMaxBufferSize = 200 * 1024;
let maxBufferMultiplierSize = fs.statSync(currentFilePath).size * 2;
// Assume that the formatting/expansion of the document could double it's size
// Make sure the minimum size is still the default for execFile::maxBuffer
let maxBufferSize = Math.max(defaultMaxBufferSize, maxBufferMultiplierSize);
childProcess.exec(args.join(' '), {maxBuffer: maxBufferSize}, (error, out, err) => {
checkStatusBar('$(pencil) Formatted', delay);
if (showMessages) {
error ? vscode.window.showErrorMessage('Some error while formatting: (reason: "' + err.split(/\r\n|\r|\n/g).join(',') + ' ' + error + '")')
: vscode.window.showInformationMessage('Formatted!');
}
});
};
// If document is editing now
if (document.isDirty) {
// Then save the document and make format
document.save().then(() => {
aformatFunc();
});
} else {
// Else just formatting
aformatFunc();
}
});
context.subscriptions.push(disposable);
}
exports.activate = activate;
// this method is called when your extension is deactivated
function deactivate() {}
exports.deactivate = deactivate;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment