27

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

Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146
matiux
  • 493
  • 1
  • 6
  • 16

3 Answers3

44

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
Hardik Modha
  • 12,098
  • 3
  • 36
  • 40
TehSphinX
  • 6,536
  • 1
  • 24
  • 34
  • Hi, 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" – matiux Aug 09 '17 at 12:25
  • This 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… – mat007 Jun 12 '19 at 07:40
  • Goland 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. – TehSphinX Jun 27 '19 at 10:25
  • 1
    You have to install [File Watchers](https://plugins.jetbrains.com/plugin/7177-file-watchers) plugin if you are using IntelliJ IDEA with Go plugin – s0xzwasd Sep 28 '21 at 07:15
  • 1
    Thank you! The code style settings are what I was missing. I couldn't figure out why it wasn't organizing imports. – James Sumners Aug 15 '23 at 16:21
10

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

Elon Than
  • 9,603
  • 4
  • 27
  • 37
7

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)

user229044
  • 232,980
  • 40
  • 330
  • 338
Jordan Lam
  • 71
  • 1
  • 1