Using vifm to attach files to emails in Mutt

2019-02-15

I’ve found that the default file attachment browser in mutt is very lacking, it requires lots of manually traversing directories to find the file I want, and it doesn’t look great, it’s essentially an interactive ls -l. I’ve started using vifm as a file manager in the terminal for those rare occassions when I need a full file manager, so I thought I would try to integrate that into my mutt, vim workflow.

Mutt file selector

I couldn’t figure out how to change the file browser that appears when you type a on the composer view in Mutt, but I had read about using external commands in Vim so thought maybe I could use those to access vifm in the vim composer. I have Mutt setup so that when I open a new email composer in Vim with c from the browser view, it’s populated with some default headers, To:, Cc: and so on. To activate these headers, add set edit_headers = yes to your .muttrc. Mutt also has some “pseudo-headers” which trigger special behaviour in Mutt when it reads the file back. One of those is Attach:.

Vifm has the ability to pipe the name of the selected file to standard output by using vifm --choose-files -. - is what tells vifm not to send the output to a file, but instead to standard output. I wrote a small shell script which pipes the output of vifm using the above command and adds Attach: to the start of the line, and echoes that whole line. This is the shell script:

#!/bin/bash

file="$(vifm --choose-files -)"

echo "Attach: $file"

Then it’s easy enough to call this shell script (which is stored in my $PATH) in vim and paste the output to line 7 in the vim email composer, which is the line directly below the final header. This is the relevant .vimrc section:

nnoremap <Leader>A :6r !vifm_attach <CR>

The nice thing about this method is that I can add multiple files by simply running the command again. There can be multiple lines with the header Attach: and all of them will be read by Mutt. I can also leverage all the normal functionality of vifm, like jumping to directories, regex, sorting etc.

Mutt attachement pseudo-header

Next, I might try to improve the shell script so that I can select multiple files in vifm and have each of them appear as their own Attach: line in vim.