diff --git a/doc/LanguageClient.txt b/doc/LanguageClient.txt index e7d5c3e6a..196ba8b81 100644 --- a/doc/LanguageClient.txt +++ b/doc/LanguageClient.txt @@ -700,6 +700,24 @@ Default: [] For a full list of the possible token types (name) see the LSP documentation: https://microsoft.github.io/language-server-protocol/specifications/specification-current/ +2.48 g:LanguageClient_formatOnSave *g:LanguageClient_formatOnSave* + +A list of filetypes for which you want to run format after saving the buffer. +If you include '*' in this list, format will be run on any filetype, ignoring +any other values in the list. + +Default: [] + +Example: + +Format only go and rust filetypes: +> + let g:LanguageClient_formatOnSave = ['go', 'rust'] + +Format all filetypes: +> + let g:LanguageClient_formatOnSave = ['*'] + ============================================================================== 3. Commands *LanguageClientCommands* diff --git a/plugin/LanguageClient.vim b/plugin/LanguageClient.vim index 93a667fb9..3182226ee 100644 --- a/plugin/LanguageClient.vim +++ b/plugin/LanguageClient.vim @@ -175,6 +175,24 @@ function! s:OnFileType() call s:ConfigureAutocmds() endfunction +function! s:AfterFormat(...) abort + noautocmd w +endfunction + +function! s:FormatTextDocument(...) + if !LanguageClient#HasCommand(&filetype) + return + endif + + let l:format_on_save = get(g:, 'LanguageClient_formatOnSave', []) + echom index(l:format_on_save, '*') ==# -1 + if index(l:format_on_save, &filetype) ==# -1 && index(l:format_on_save, '*') ==# -1 + return + endif + + noautocmd call LanguageClient#textDocument_formatting({}, funcref('s:AfterFormat')) +endfunction + function! s:ConfigureAutocmds() augroup languageClient autocmd! @@ -197,6 +215,10 @@ function! s:ConfigureAutocmds() autocmd CompleteChanged call LanguageClient#handleCompleteChanged(deepcopy(v:event)) endif + if len(get(g:, 'LanguageClient_formatOnSave', [])) != 0 + autocmd BufWritePre call s:FormatTextDocument() + endif + nnoremap (lcn-menu) :call LanguageClient_contextMenu() nnoremap (lcn-hover) :call LanguageClient_textDocument_hover() nnoremap (lcn-rename) :call LanguageClient_textDocument_rename()