6

Similar to Visual Studio, when working with Rust programs, I'd like to press F5 to save the current file, compile it, and run it.

What's a good way to do this?

2 Answers 2

6

Below is one approach for Windows. If you're in a rust project, it'll run cargo run. Otherwise, it'll use rustc.

(defun rust-save-compile-and-run ()
  (interactive)
  (save-buffer)

  (if (locate-dominating-file (buffer-file-name) "Cargo.toml")

      (compile "cargo run")

    (compile
     (format "rustc %s & %s"
         (buffer-file-name)
         (file-name-sans-extension (buffer-file-name))))))

(add-hook 'rust-mode-hook
      (lambda ()
        (define-key rust-mode-map (kbd "<f5>") 'rust-save-compile-and-run)))
2
  • How much harder would it be to make this work with cargo projects with multiple bins? I think it can be done by invoking just cargo once this PR PR is merged.
    – Dogbert
    Oct 14, 2014 at 8:14
  • How does locate-dominating-file work here? Does it scan all parent directories to the file you're in to check for Cargo.toml?
    – ruscur
    Oct 15, 2014 at 0:24
5

Here my version of compile:

(global-set-key (kbd "<f5>") (lambda ()
                               (interactive)
                               (save-buffer)
                               (setq-local compilation-read-command nil)
                               (call-interactively 'compile)))

Basically it reuses previously executed compile command; if you supply with a prefix argument, you are prompted for a new compile command for future reuse.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.