rustvimrust-cargoneovim

How to run Cargo in Vim?


I want to run Rust code with a keybinding such as <F5>.

I tried the command :!cargo run --bin %, but in that case the % equals to src/bin/test.rs, instead of the wanted filename without suffix (which is test).

So how could I edit the command to cater to my needs?


Solution

  • As you can read in the vim help on filename-modifiers:

      :t  Tail of the file name (last component of the name).  Must
          precede any :r or :e.
      :r  Root of the file name (the last extension removed).  When
          there is only an extension (file name that starts with '.',
          e.g., ".vimrc"), it is not removed.  Can be repeated to remove
          several extensions (last one first).
    

    You can get the file name with path and extension removed by appending :t:r to the % register. so

    :!cargo run --bin %:t:r
    

    This will run the binary of the current file for single file binaries.

    If you need the last directory name (multi file binaries) you can use :h:

      :h  Head of the file name (the last component and any separators
          removed).  Cannot be used with :e, :r or :t.
          Can be repeated to remove several components at the end.
          When the file name ends in a path separator, only the path
          separator is removed.  Thus ":p:h" on a directory name results
          on the directory name itself (without trailing slash).
          When the file name is an absolute path (starts with "/" for
          Unix; "x:\" for Win32; "drive:" for Amiga), that part is not
          removed.  When there is no head (path is relative to current
          directory) the result is empty.
    

    Like this:

    :!cargo run --bin %:h:t