matiux
matiux

Reputation: 513

Running 'goimports' on save in GoLand

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

Upvotes: 28

Views: 27337

Answers (3)

TehSphinX
TehSphinX

Reputation: 7440

As of version 2021.3

Two separate entries were added to the File Watchers that are enabled by default. One for formatting the code on save, one for optimising the imports on save:

enter image description here

How the imports are sorted, grouped, etc. can be further defined in the Code Style settings for Go:

enter image description here

There is another small option to run gofmt on reformat in the Other tab of Go's Code Style settings:

enter image description here

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.

enter image description here

Setting this to goimports will do both:

  • code formatting (gofmt)
  • updating, sorting and grouping imports

Upvotes: 48

Jordan Lam
Jordan Lam

Reputation: 71

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:

enter image description here (Goland 2020.3)

Upvotes: 7

Elon Than
Elon Than

Reputation: 9765

"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.

Upvotes: 10

Related Questions