Skip to content

Commit

Permalink
adjust imports on save
Browse files Browse the repository at this point in the history
Introduce a new option, g:go_imports_autosave, to allow imports to be
adjusted even when g:go_fmt_command is not set to goimports.

Closes #2795
  • Loading branch information
bhcleek committed Apr 2, 2020
1 parent d2e82b5 commit f77d1aa
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 3 deletions.
21 changes: 19 additions & 2 deletions autoload/go/auto.vim
Original file line number Diff line number Diff line change
Expand Up @@ -133,11 +133,28 @@ function! s:handler(timer_id)
endfunction

function! go#auto#fmt_autosave()
if !(go#config#FmtAutosave() && isdirectory(expand('%:p:h')) && expand('<afile>:p') == expand('%:p'))
if !(isdirectory(expand('%:p:h')) && expand('<afile>:p') == expand('%:p'))
return
endif

if !(go#config#FmtAutosave() || go#config#ImportsAutosave())
return
endif

if go#config#ImportsAutosave() && !(go#config#FmtAutosave() && go#config#FmtCommand() == 'goimports')
call go#fmt#Format(1)

" return early when the imports mode is goimports, because there's no need
" to format again when goimports was run
if go#config#ImportsMode() == 'goimports'
return
endif
endif

if !go#config#FmtAutosave()
return
endif

" Go code formatting on save
call go#fmt#Format(-1)
endfunction

Expand Down
4 changes: 4 additions & 0 deletions autoload/go/config.vim
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,10 @@ function! go#config#FmtAutosave() abort
return get(g:, "go_fmt_autosave", 1)
endfunction

function! go#config#ImportsAutosave() abort
return get(g:, 'go_imports_autosave', 1)
endfunction

function! go#config#SetFmtAutosave(value) abort
let g:go_fmt_autosave = a:value
endfunction
Expand Down
8 changes: 7 additions & 1 deletion doc/vim-go.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1401,7 +1401,13 @@ it's causing problems on some Vim versions. This has no effect if
<

*'g:go_imports_mode'*
*'g:go_imports_autosave'*

Use this option to auto |:GoImports| on save. By default it's enabled.
>
let g:go_imports_autosave = 1
<
*'g:go_imports_mode'*

Use this option to define which tool is used to adjust imports. Valid options
are `goimports` and `gopls`. By default `goimports` is used.
Expand Down

0 comments on commit f77d1aa

Please sign in to comment.