How to run `go fmt` on save, in Visual Studio Code?
I'm not familiar with 'go fmt' specifically, but you can create a simple vscode extension to handle on save event and execute any arbitrary command passing the file path as an argument.
Here's a sample that just calls echo $filepath
:
import * as vscode from 'vscode';
import {exec} from 'child_process';
export function activate(context: vscode.ExtensionContext) {
vscode.window.showInformationMessage('Run command on save enabled.');
var cmd = vscode.commands.registerCommand('extension.executeOnSave', () => {
var onSave = vscode.workspace.onDidSaveTextDocument((e: vscode.TextDocument) => {
// execute some child process on save
var child = exec('echo ' + e.fileName);
child.stdout.on('data', (data) => {
vscode.window.showInformationMessage(data);
});
});
context.subscriptions.push(onSave);
});
context.subscriptions.push(cmd);
}
And the package file:
{
"name": "Custom onSave",
"description": "Execute commands on save.",
"version": "0.0.1",
"publisher": "Emeraldwalk",
"engines": {
"vscode": "^0.10.1"
},
"categories": [
"Other"
],
"activationEvents": [
"onCommand:extension.executeOnSave"
],
"main": "./out/src/extension",
"contributes": {
"commands": [{
"command": "extension.executeOnSave",
"title": "Execute on Save"
}]
},
"scripts": {
"vscode:prepublish": "node ./node_modules/vscode/bin/compile",
"compile": "node ./node_modules/vscode/bin/compile -watch -p ./"
},
"devDependencies": {
"typescript": "^1.6.2",
"vscode": "0.10.x"
}
}
The extension is enabled via cmd+shift+p then typing "Execute on Save", but it could be reconfigured to start via another command including "*" which would cause it to load any time VSCode loads.
Once the extension is enabled, the event handler will fire whenever a file is saved (NOTE: this doesn't appear to work when file is first created or on Save as...)
This is just a minor modification of a yo code scaffolded extension as outlined here: https://code.visualstudio.com/docs/extensions/example-hello-world
Update
Here's a Visual Studio Code extension I wrote for running commands on file save. https://marketplace.visualstudio.com/items/emeraldwalk.RunOnSave.
Now, the feature has been implemented, you can enable format on save:
- Open Settings (
Ctrl + ,
) - Search for
editor.formatOnSave
and set it totrue
Your Go code will be formatted automatically on Ctrl + s
Its not possible at the moment but its being worked on https://github.com/Microsoft/vscode-go/issues/14