2

I'd like to use vim's builtin indent fix feature on an entire file. I have looked up answers, but all I found were suggestions to type gg=G, the only problem being that it brings your cursor to the top of the file.

How could I easily indent a whole file without changing my cursor's position?

3

All "long" jump commands, such as gg, automatically save the bookmark for the previous poisition (note that G here is a "motion", so it does not overwrite the bookmark again), so all you have to do is to go back by that bookmark with two backticks:

nnoremap <leader>= gg=G``

Or you can use CTRLO and CTRLI to navigate through the jumplist (:h jumplist) to and fro.

0

If you are willing to dedicate a keybinding to it (let's say \G for concreteness), then it's possible to set a mark and return to it in your keybinding.

nnoremap \G mpgg=G`p

mp set mark. A lowercase letter means that mark is associated with the current buffer. The mark P is universal, p is not.

gg=G move to the top of the buffer and indent down to the bottom, as you mentioned in the question.

`p return to the mark.

This solution is not ideal because your cursor might still jump around because of things like scrolloff, but it does minimize how visually distracting it is to re-indent a file fairly well in practice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.