mhinz / vim-mix-format

Vim integration for the Elixir formatter.
MIT License
222 stars 13 forks source link

Synchronous formatting #35

Open michaeljones opened 4 years ago

michaeljones commented 4 years ago

I've found myself being caught out by the asynchronous nature of the formatting. I sometimes save and then continue editing and the formatting job will come back and overwrite my edits. It is a little confusing and I find myself wishing the editor would just wait until the formatting was done. I realise this might not be a common request but it seems to suit me well.

I've ended up adding the following minor change directly to my vim-mix-format plugin folder but I thought I'd share it here in case it is of use to others:

diff --git a/ftplugin/elixir.vim b/ftplugin/elixir.vim
index 8a6ac57..4801727 100644
--- a/ftplugin/elixir.vim
+++ b/ftplugin/elixir.vim
@@ -226,6 +226,7 @@ function! s:mix_format(diffmode) abort
           \ 'on_exit':   function('s:on_exit'),
           \ 'detach':    !has('nvim-0.3.6'),
           \ }))
+    call jobwait([s:id], -1)
   else
     silent! call job_stop(s:id)
     let s:id = job_start(cmd, extend({

Thank you for the project!

Edit: I should note this is explicitly for the nvim branch of the logic.

theirishpenguin commented 7 months ago

Heya @michaeljones thanks a million for the above snippet. I like your synchronous formatting idea and had a similar issue.

I wasn't using neovim - just regular vim. So I wrote a solution for the non-nvim branch of the logic above. Here it is...

diff --git a/ftplugin/elixir.vim b/ftplugin/elixir.vim
index 0e92cfa..b44c1aa 100644
--- a/ftplugin/elixir.vim
+++ b/ftplugin/elixir.vim
@@ -234,6 +234,24 @@ function! s:mix_format(diffmode) abort
           \ 'out_cb':  function('s:on_stdout_vim', options),
           \ 'exit_cb': function('s:on_exit', options),
           \ }, has_key(options, 'cwd') ? {'cwd': options.cwd} : {}))
+
+    echo 'Formatting...'
+
+    while job_status(s:id) ==# 'run'
+        echon '.'
+        sleep 1
+    endwhile
+
+    echo 'Formatting complete!'
+
+    " I think this blank echo is needed to establish a newline. Otherwise the
+    " previous message may get masked by other output from vim (such as
+    " messages to say the file has been written). I assume that is the
+    " reason anyway.
+    echo ''
+
+    return s:id
   endif
 endfunction

It also displays an indication that the formatter is in progress (adds a dot each second to indicate) and displays a completion message at the end. Perhaps slightly overengineered :smile: