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?

Malabarba
  • 22,878
  • 6
  • 78
  • 163
dharmatech
  • 1,212
  • 7
  • 19

2 Answers2

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)))
dharmatech
  • 1,212
  • 7
  • 19
  • 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](https://github.com/rust-lang/cargo/pull/702) PR is merged. – Dogbert Oct 14 '14 at 08: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 '14 at 00: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.

Tu Do
  • 6,772
  • 20
  • 39