title: vim - automatically formatting golang source code when saving
body: <p>I'm using vim with the <a href="https://github.com/jnwhiteh/vim-golang">vim-golang</a> plugin. This plugin comes with <a href="https://github.com/jnwhiteh/vim-golang/blob/master/ftplugin/go/fmt.vim">a function called :Fmt</a> that "reformats" the source code using <a href="http://gofmt.com/">gofmt</a>, a command-line executable.</p>
  
  <p>I want to invoke the :Fmt function each time that I save the file, so it is continuously re-formatted. I think this should be done with a <a href="http://vimdoc.sourceforge.net/htmldoc/autocmd.html">autocmd</a> directive. But I have two doubts:</p>
  
  <ol>
  <li>I could not find a way to execute the function. I tried writting Fmt and :Fmt at the end of the autocmd line, but it didn't seem to work. I think I miss something, like "call".</li>
  <li>I want this to happen only when saving a file of filetype 'go'. I don't know how to combine those two conditions - I can activate variables depending on the file type, and I can do small stuff, like removing trailing spaces, whenever a file is saved, but separatedly.</li>
  </ol>
  
  <p>So this is what I have so far:</p>
  
  <pre><code>" I can set variables for go like this
  autocmd FileType go setlocal noexpandtab shiftwidth=4 tabstop=4 softtabstop=4 nolist
  
  " I can clean trailing spaces(conserving cursor position) on save like this
  autocmd BufWritePre * kz|:%s/\s\+$//e|'z
  
  " None of these worked:
  autocmd BufWritePre,FileType go Fmt
  autocmd BufWritePre,FileType go :Fmt
  </code></pre>