mhartington/formatter.nvim

[Feature] wait for formatting on `:wq` and similar actions

Opened this issue · 3 comments

Original request:
I think it looks good for most cases but it doesn't solve the problem of opening a file, making a change that needs formatting and then running :wq. If the format isn't instant you end up with an unformatted file which is a bit of a pain.

It almost needs something like a sync on exiting neovim to wait for any outstanding async format jobs?

TODO:

  • try detect :wq and similar actions
  • wait for jobs only when we're formatting and exiting after that
  • add config option to enable/disable feature

I think that this may be causing:

Buffer changed while formatting, not applying formatting

Message appears when doing :wq with enabled formatting.

This is a quick hack I just put in my config for this issue. I haven't tested it a ton since I just added it, so user beware. It isn't very granular. If the formatter fails to run due to an undefined variable, or syntax error, then the file will still exit if it is the last window. To address that, the User autocmd in the plugin would most likely have to be split up into FormatterPostSuccess/Error so one could branch on what to do if contributors think that would be helpful. Anyway, this can be used as stopgap if one finds the behavior acceptable.

function! s:QuitAfterFormatting()
    :q
endfunction

function! s:WaitFormatQuit()
    let l:openwinnr = len(getwininfo())
    if l:openwinnr == 1
        autocmd! User FormatterPost call s:QuitAfterFormatting()
        :silent! w
    else
        :silent! wq
    endif
endfunction

cnoremap <silent> wq call <sid>WaitFormatQuit()<CR>

Why not just add sync formatting to formatter.nvim @mhartington? Async formatting is convenient in some cases only.
I didn't look at the code yet. Is there an obstacle that you know of that makes sync formatting difficult to implement?