Running 'goimports' on save in GoLand
Solution 1
As of version 2021.3
Two separate entries where added to the File Watchers that are enabled by default. One for formatting the code on save, one for optimising the imports on save:
How the imports are sorted, grouped, etc. can be further defined in the Code Style settings for Go:
There is another small option to run gofmt
on reformat in the Other
tab of Go's Code Style settings:
Before version 2021.3
The setting to set up gofmt
or goimports
on save is in the File Watchers. Here you can add a new file watcher at the bottom and select gofmt
or goimports
from the list.
Setting this to goimports
will do both:
- code formatting (
gofmt
) - updating, sorting and grouping imports
Solution 2
"On Save" tab was removed in GogLand EAP 16.
In newer versions you have to go to Settings
-> Tools
-> File Watchers
and add goimports
there.
Solution 3
For those fighting with gofmt on Goland autosave (mat007 comment)
You can double click the item in file watchers to show an edit watcher menu.
Uncheck Auto-save edited files to trigger watcher and it should now only trigger on manual save:
Related videos on Youtube
![matiux](https://i.stack.imgur.com/yUbcq.jpg?s=256&g=1)
matiux
Updated on July 12, 2022Comments
-
matiux almost 2 years
I'm using GoLand IDE to code in Go. When I save a file, I'd like that the unused imports disappear (like VS code)
I have enable "Optimize imports" in "Code" -> "Show reformat file dialog". But when I save the file, imports it's still present
-
matiux almost 7 yearsHi, I have already see that option but I have setting it on "go ftm" to format code.. Unfortunately it can have only one action during "on save"
-
mat007 about 5 yearsThis is really impossible to use as with Goland constantly saving the source file I'm editing I'm effectively fighting
goimports
all the time: if I don't type quick enough (and I mean reeeally quick)goimports
will just delete the code as I'm typing it… -
TehSphinX about 5 yearsGoland shouldn't autosave while you are typing. Or maybe you changed that setting? I think the default is: autosave after 15sec inactivity. But I had that issue sometimes as well. Not seen it lately though. Maybe my new Notebook is too fast.
-
s0xzwasd almost 3 yearsYou have to install File Watchers plugin if you are using IntelliJ IDEA with Go plugin