I already know that gg=G
can indent the entire file on Vim. But this will make me go to the beginning of the file after indent. How can I indent the entire file and maintain the cursor at the same position?

- 23,850
- 22
- 76
- 100
-
See also https://stackoverflow.com/q/1646850/ – user90726 Sep 02 '22 at 13:36
5 Answers
See :h ''
This will get you back to the first char on the line you start on:
gg=G''
and this will get you back to the starting line and the starting column:
gg=G``
I assume the second version, with the backtick, is the one you want. In practice I usually just use the double apostrophe version, since the backtick is hard to access on my keyboard.

- 21,858
- 9
- 50
- 54
-
1Awesome. The second version is what I was looking for. The only negative point is that the current line will be at the end of the screen then. – Fábio Perez Aug 17 '11 at 02:07
-
1Great. Try adding a `zz` if you want to reposition line at middle of screen: `gg=G``zz` – Herbert Sitz Aug 17 '11 at 02:19
-
5That keeps the screen unchanged: `mqHmwgg=G\`wzt\`q`. Note it uses `q` and `w` marks. – Fábio Perez Aug 18 '11 at 01:57
-
@FábioPerez "The only negative point is that the current line will be at the end of the screen then." - This seems to be the middle line in Vim 9. Hello from 2022, ha ha – user90726 Sep 02 '22 at 14:18
-
Add this to your .vimrc
function! Preserve(command)
" Preparation: save last search, and cursor position.
let _s=@/
let l = line(".")
let c = col(".")
" Do the business:
execute a:command
" Clean up: restore previous search history, and cursor position
let @/=_s
call cursor(l, c)
endfunction
nmap <leader>> :call Preserve("normal gg>G")<CR>
You can also use this on any other command you want, just change the argument to the preserve function. Idea taken from here: http://vimcasts.org/episodes/tidying-whitespace/

- 14,973
- 13
- 59
- 94
-
3Replace all of the lets at the beginning with `let w = winsaveview()` and the let and call at the end with `call winrestview(w)` and you restore even the scroll position. – dash-tom-bang Aug 18 '11 at 00:47
In a similar spirit to Alex's answer I use the following mapping in vimrc.
nnoremap g= :let b:PlugView=winsaveview()<CR>gg=G:call winrestview(b:PlugView) <CR>:echo "file indented"<CR>
by pressing g=
in normal mode the whole buffer is indented, and the scroll/cursor position is retained.

- 43
- 7
Following on top of Herbert's solution, the reader can also use <C-o>
In vim script
exe "norm! gg=G\<C-o>"
Or mapping
:nnoremap <F10> gg=G\<C-o>

- 1,522
- 14
- 19
You can set a bookmark for the current position with the m command followed by a letter. Then after you run the indent command, you can go back to that bookmark with the ` (backtick) command followed by the same letter.

- 2,186
- 13
- 14