From b296d30266c0cbc2b1143718bb6048f523392d71 Mon Sep 17 00:00:00 2001 From: Sam Hedin Date: Sat, 10 Oct 2020 14:10:44 +0200 Subject: [PATCH] rustic-cargo-add-missing-imports (#161) * Extract crate name from error message * Build list from missing imports * update name * Add all missing imports in current buffer * Let the user select one import with prefix arg * Check for cargo-edit and handle no missing imports * Mention function in readme --- README.md | 1 + rustic-cargo.el | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/README.md b/README.md index 2b865566..8a47e20a 100644 --- a/README.md +++ b/README.md @@ -464,6 +464,7 @@ modify the parameters of a command. - `rustic-cargo-add` Add crate to Cargo.toml using 'cargo add' - `rustic-cargo-rm` Remove crate from Cargo.toml using 'cargo rm' - `rustic-cargo-upgrade` Upgrade dependencies as specified in the local manifest file using 'cargo upgrade' +- `rustic-cargo-add-missing-imports ` Add the missing imports for the current buffer to `cargo.toml`. This function requires `lsp-mode`. ### Test diff --git a/rustic-cargo.el b/rustic-cargo.el index 34e146cc..6da513e8 100644 --- a/rustic-cargo.el +++ b/rustic-cargo.el @@ -709,6 +709,25 @@ If running with prefix command `C-u', read whole command from minibuffer." (read-from-minibuffer "Crate: "))))) (rustic-run-cargo-command command)))) +(defun rustic-cargo-add-missing-imports () + "Add missing imports to Cargo.toml. +Adds all missing imports by default. +Use with 'prefix-arg` to select imports to add." + (interactive) + (when (rustic-cargo-edit-installed-p) + (let ((missing-imports (delete-dups + (seq-reduce (lambda (missing-crates errortable) + (if (string= "E0432" (gethash "code" errortable)) + (cons (nth 3 (split-string (gethash "message" errortable) "`")) missing-crates) + missing-crates)) + (gethash (buffer-file-name) (lsp-diagnostics t)) '())))) + (if missing-imports + (rustic-run-cargo-command (format "cargo add %s" + (if current-prefix-arg + (completing-read "Select import to add to Cargo.toml" missing-imports) + (mapconcat 'identity missing-imports " ")))) + (message "Couldn't find any imports to add. If this was a mistake, make sure your language server is running properly."))))) + ;;;###autoload (defun rustic-cargo-rm (&optional arg) "Remove crate from Cargo.toml using 'cargo rm'.