Improve autocommand to indent and return to line on BufLeave and FocusLost

141 views Asked by At

I was looking for an autocommand to make Vim do a gg=G on BufLeave and FocusLost so that it would indent the buffer I wasn't using. I didn't like the idea of doing this when I open or save a file because I figured I would get impatient of the larger files. But I think I dislike the autocommand I tried even more:

:autocmd BufLeave,FocusLost * :normal gg=G

So I was wondering if anyone had any suggestions to avoid the following problems:

  • The biggest problem is that I lose what line I am on.
  • Also it seemed like I was having to wait for the indenting to finish to begin editing another buffer. (I imagine just about any solution would at least make Vim slower in other buffers probably.)

I don't necessarily need the entire autocommand code itself, but more an idea for an autocommand that would accomplish the indenting without causing bigger issues. Hopefully the answer won't be too above my head as I am still reading through Learn Vimscript the Hard Way. I have been wanting to get involved on stackoverflow and this seemed like a fairly interesting and unlikely duplicated question to ask.

1

There are 1 answers

2
Kent On BEST ANSWER

for the problem 1, there is solution: You could save the cursor position before you do re-indent (gg=G), and after that restore the position. vim has build-in getpos() and setpos(), which could help you in this case. For example, you could create a function:

   function! Hook()
      let p = getpos(".")
      normal! gg=G
      call setpos(".",p)
   endfunction

and in your autocmd, you call the function:

:autocmd BufLeave,FocusLost * :call Hook()

This should make your vim re-indent and keep the original when you leave and back to a buffer.

However for the problem 2, it seems that there is no good solution with vimscript. Because vimscript doesn't support multi-threading. If the reindent will take 30s, you have to wait when the autocmd was triggered. There could be a solution to implement multi-threads by python/perl. However I haven't tested. Vim 7.4 has improved python interface, you may want to give the multi-threading in python a try.