]> Sergey Matveev's repositories - dotfiles.git/blob - vim/.vim/ftplugin/go/fmt.vim
9ed68ad6c401c3a65895925924562adb448db55c
[dotfiles.git] / vim / .vim / ftplugin / go / fmt.vim
1 " Copyright 2011 The Go Authors. All rights reserved.
2 " Use of this source code is governed by a BSD-style
3 " license that can be found in the LICENSE file.
4 "
5 " fmt.vim: Vim command to format Go files with gofmt.
6 "
7 " This filetype plugin add a new commands for go buffers:
8 "
9 "   :Fmt
10 "
11 "       Filter the current Go buffer through gofmt.
12 "       It tries to preserve cursor position and avoids
13 "       replacing the buffer with stderr output.
14 "
15 " Options:
16 "
17 "   g:go_fmt_commands [default=1]
18 "
19 "       Flag to indicate whether to enable the commands listed above.
20 "
21 "   g:gofmt_command [default="gofmt"]
22 "
23 "       Flag naming the gofmt executable to use.
24 "
25 if exists("b:did_ftplugin_go_fmt")
26     finish
27 endif
28
29 if !exists("g:go_fmt_commands")
30     let g:go_fmt_commands = 1
31 endif
32
33 let g:gofmt_command = get(g:, "gofmt_command", "goimports")
34
35 if g:go_fmt_commands
36     command! -buffer Fmt call s:GoFormat()
37 endif
38
39 function! s:GoFormat()
40     let view = winsaveview()
41     silent execute "%!" . g:gofmt_command
42     if v:shell_error
43         let errors = []
44         for line in getline(1, line('$'))
45             let tokens = matchlist(line, '^\(.\{-}\):\(\d\+\):\(\d\+\)\s*\(.*\)')
46             if !empty(tokens)
47                 call add(errors, {"filename": @%,
48                                  \"lnum":     tokens[2],
49                                  \"col":      tokens[3],
50                                  \"text":     tokens[4]})
51             endif
52         endfor
53         if empty(errors)
54             % | " Couldn't detect gofmt error format, output errors
55         endif
56         undo
57         if !empty(errors)
58             call setqflist(errors, 'r')
59         endif
60         echohl Error | echomsg "Gofmt returned error" | echohl None
61     endif
62     call winrestview(view)
63 endfunction
64
65 let b:did_ftplugin_go_fmt = 1
66
67 " vim:ts=4:sw=4:et