08 Jan 2012

Auto-completing Google Contacts in Vim

This short post covers completing your Google contacts using goobook, when authoring e-mail messages in Mutt via Vim.

It does not cover:

  • Setting up mutt with your GMail. This topic is covered in many other blog posts, often in extreme detail.
  • Installing goobook, which can be done easily via pypi.

Most Mutt/Gmail tutorials which include goobook offer the following to enable goobook in Mutt's editor:

set query_command = "goobook query '%s'"
bind editor <Tab> complete-query
bind editor ^T complete

Now, I don't know enough about Mutt to know what magic (if any) it attempts to do within Vim to bind <Tab> (or any other key), but it didn't work for me. Instead, I chose to use Vim's built-in filetype completion mechanism—omnicomplete—for the task. Save the following as $VIMRUNTIME/autoload/mailcomplete.vim:

function! mailcomplete#Complete(findstart, base)
    if a:findstart == 1
        let line = getline('.')
        let idx = col('.')
        while idx > 0
            let idx -= 1
            let c = line[idx]
            " break on header and previous email
            if c == ':' || c == '>'
                return idx + 2
        return idx
        let trim="sed '/^$/d' | cut -f1,2"
        let fmt='awk ''BEGIN{FS=OFS="\t"}{printf "%s <%s>\n", $2, $1}'''
        if exists("g:goobookrc")
            let goobook="goobook -c " . g:goobookrc
            let goobook="goobook"
        return split(system(goobook . ' query ' . a:base . '|' . trim . '|' . fmt ), '\n')

Next, drop the following line in $VIMRUNTIME/ftplugin/mail.vim:

set omnifunc=mailcomplete#Complete

During mail composition you will be able to use <C-x><C-o> to complete e-mail addresses in mail headers! Note that the current version will not complete addresses outside of headers. Secondarily, it uses sed and awk, which sometimes have incompatibilities between platforms; completion was only tested on Linux.

Multiple Addresses

Like most people, you probably have multiple email addresses—and multiple groups of contacts to auto-complete. To compensate for this, the above function looks for g:goobookrc in your Vim environment and uses that as the path to the goobook config. You can have Mutt set this for you by adding the following to your .muttrc or other file sourced within it:

set editor="vim --cmd 'let g:goobookrc=\"/path/to/goobookrc"'"

That's all for now—happy new year!

Tagged: vim mutt