rustrust-cargoliterate-programming

Literate Programming with rust and org mode


So I am trying to use rust in org mode, and it works fine after installing ob-rs and cargo-script. But the problem is, I can't figure out how to use other crates(like rand) from the source code blocks. I tried just converting the main project into a cargo one and tangle all the blocks to the main file, but well, I might as well use a normal rust project at that point. So is there a way to use external crates inside org mode blocks. It would be kinda difficult to use rust in org mode otherwise because a lot to basic functionality is defined in external crates.


Solution

  • Ok, so I found out that we can use external crates with rust in org mode with rustic. Here is the procedure to do that from the main README.

    Org-babel

    Blocks run asynchronously and a running babel process is indicated by a spinner in the mode-line. It's possible to use crates in babel blocks.

    Execute babel block with org-babel-execute-src-block

    #+BEGIN_SRC rustic :crates '((regex . 0.2))   extern crate regex;
    
      use regex::Regex;
    
      fn main() {
          let re = Regex::new(r"^\d{4}-\d{2}-\d{2}$").unwrap();
          assert!(re.is_match("2014-01-01"));   }
    #+END_SRC
    

    Supported org babel parameters:

    Write to file :results file :file ~/babel-output

    Customization:

    rustic-babel-format-src-block format block after successful build
    rustic-babel-display-compilation-buffer display compilation buffer of babel process
    rustic-display-spinner turn off spinner in the mode-line
    

    It is not perfect as using rustic as the src type means no syntax highlighting in github rendering of the org document. Also, we can't share fucntions between blocks but it is an open issue which can be found here, so hopefully we should get that ability at some point.