goimports is a Go tool to remove unused and add missing imports. It also formats your code the same as
This is one solution for running goimports when saving *.go files in Intellij IDEA. If you have a better way (not involving snark about emacs), please comment.
- You have goimports installed. If not, install with:
go get code.google.com/p/go.tools/cmd/goimports
- You’re probably using the golang plugin. That plugin isn’t necessary for this goimports-on-save business, but if you’re using Intellij to write Go code then you might as well use the plugin, too.
- Create a shell script to run goimports against the incoming file name if it is a .go file
- Add an external tool to Intellij that runs that shell script against the current file
- Record a macro that runs that tool and then saves the file
ctrl/cmd+Swith that macro
1. Create the shell script, like so:
2. Add a new external tool to Intellij
ctrl/cmd+,to open up Settings
- Filter on “external tools”
- Click the “+” icon to add a tool
- Name the tool, uncheck “open console”, paste the full path to your shell script in the “Program” field, and add
$FilePath$in the “Parameters” field.
- Save the tool
- Optionally, in Keymap, give this a keyboard shortcut
- This will now show up in the “Tools” menu
3. Record a macro that runs the tool and saves the file
- “Edit” menu — “Macros” — “Start recording macro”
- “Tools” menu, then click your new tool
- “File” menu, then “Save all”
- Finish recording your macro, and give it a name, such as “go_imports_on_save”
ctrl/cmd+S with that macro
ctrl/cmd+,to open Settings, then filter on “Keymap”
- In the keymap, filter on your new macro name, such as “go_imports_on_save”
- Double-click it, select “Add keyboard shortcut”, and then hit your normal save combination on the keyboard, such as
- It’ll prompt you to remove the default. Accept it.
That’s it. Now, when you save your .go files, goimports will run and overwrite the contents of your editor. All other files are left alone.
Hat tip to this stackoverflow answer for inspiration.