3

I use gg=G to auto-format the whole file in VIM. After the whole file is indented, the cursor is returned to the begining of the file.

How can I do so that VIM returns the cursor to the last position? Say I called the command in the line 45, I want VIM to return me to this line after indenting the file.

Edit: if anyone is interested, I did add the following command to my .vimrc

" Autoformat document                                                                                                                     
nnoremap F gg=G''

So by using Shit+f I can now reformat the whole document and stay at the same cursor.

Omar Abid
  • 15,753
  • 28
  • 77
  • 108
  • You could create a mapping to : 1) mark the current position 2) do gg=G 3) go back to marked position. I use to have such a thing but I cannot fund the corresponding config anymore :( – SylvainD Mar 10 '14 at 10:53

2 Answers2

10

As stated by /u/nemo157, in an answer comment in How do I fix the indentation of an entire file in Vi?, issueing '' returns you to your last position. As per vim docs:

                            *''* *``*
''  ``      To the position before the latest jump, or where the
            last "m'" or "m`" command was given.  Not set when the
            |:keepjumps| command modifier was used.
            Also see |restore-position|.

So if you do gg=G'' you're back where you started.

Community
  • 1
  • 1
plc
  • 864
  • 8
  • 20
0

You can manually set a named mark (e.g. ma) and return to that position after the reindenting with `a.

Alternatively, the anwolib plugin provides a :KeepView command that makes any (Ex) command (so you need to translate with :normal! here) keep the current view:

:KeepView normal! gg=G
Ingo Karkat
  • 167,457
  • 16
  • 250
  • 324