16

Is there any way to fix ONLY unused imports in Rust automatically? I have seen cargo fix, which does work, but it makes a whole bunch of other fixes too. Is there any way to tell cargo fix to only fix unused imports (preferably in a specified file) and nothing else?

Side question: Is there any way to make IntelliJ do this? The usual shortcut (Cmd+Option+O) works in other languages, but for Rust, it just re-orders the imports.

Akshay
  • 1,606
  • 3
  • 17
  • 32

3 Answers3

11

According to this pull request, JetBrains' Rust plugin should be able to remove unused imports already but it is not enabled by default. According to this comment, it seems like the dev team need to wait until org.rust.macros.proc (currently an experimental feature disabled by default) to be enabled by default.

Leung Yau Ming
  • 141
  • 1
  • 4
  • 12
    To enable it, go to `Settings` > `Editor` > `Inspections` > `Rust` > `Lints` > `Unused Import`, enable it, and now `CTRL+ALT+O` will remove unused imports! – serg06 Feb 14 '22 at 15:35
  • did not found the setting.@serg06 I am using the latest clion and rust plugin at 2022.03 – Dolphin Mar 14 '22 at 03:26
  • 1
    @Dolphin Here's a picture https://i.imgur.com/bgQbXsg.png – serg06 Apr 24 '22 at 03:32
  • 2
    It's correct to say that there is an option for removing unused imports. However, when you enable that option and run 'optimize imports' it doesn't actually remove unused imports. At least as of version 0.4.180.4890-222-nightly. – James Moore Sep 22 '22 at 16:08
  • 1
    @serg06 I have this option enabled but its not removing unused imports on `CTRL + ALT + O` – Michael Pacheco Jan 01 '23 at 00:36
  • @serg06 Which hot key in mac os with CTRL+ALT+O, I can not find what this hot key does – The Sun Mar 15 '23 at 09:33
  • @TheSun CTRL+Option+O I believe – serg06 Mar 16 '23 at 16:45
  • I was able to get this working by unchecking the option "Enable inspection only if procedural macros are enabled". Presumably, "procedural macros" aren't enabled by default. – allidoiswin Jul 05 '23 at 18:34
10

Individual lints are currently only configurable via attributes in your source code. There is no way to tell cargo check or cargo fix to ignore certain lint rules through the command line tool.

From my experience with JetBrains tools, it's unlikely that they'd use cargo fix under the hood anyway. They have built their own Rust tooling for parsing and analysing code, and that is where this feature would go.

I suggest submitting a feature request to JetBrains.

Peter Hall
  • 53,120
  • 14
  • 139
  • 204
  • FYI the JetBrains rust plug now supports rustfmt, but not by default for some reason. – gak Sep 13 '21 at 02:26
7
  1. Enable Settings > Editor > Inspections > Rust > Lints > Unused Import.
  2. Disable Enable inspection only if procedural macros are enabled in the same section.

Versions

  • IntelliJ IDEA Build #IU-223.7571.182
  • Rust Plugin 0.4.185.5086-223
Khongor Bayarsaikhan
  • 1,644
  • 1
  • 16
  • 19