2

I set up this mapping in my .vimrc and it works great...

" Auto indent entire file
nmap <C-f> gg=G
imap <C-f> <ESC>gg=G

However, after the operation the cursor has moved to line 1, column 1.

Is there a way to do it so that if I'm in the middle of the file somewhere the cursor will remain where it is?

Ethan
  • 57,819
  • 63
  • 187
  • 237

5 Answers5

5

Sure, use marks (:help mark):

nmap <C-f> mtgg=G't
imap <C-f> <ESC><C-f>

Before executing gg=G, the current cursor position is saved to mark t. After the operation, 't jumps back to the mark.

a paid nerd
  • 30,702
  • 30
  • 134
  • 179
4

Ctrl+O is good for walking back through the jump list. '' will move you back to the last line in the jump list (or `` to go back to the last line and column).

Unfortunately, there isn't an "entire buffer" text object, so gg=G requires moving back two places in the jump list.

jamessan
  • 41,569
  • 8
  • 85
  • 85
2

Why not use ma to mark the current position in buffer a, and after the transformation use ``a(i.e.backtick+a`) to return to that position ? Here's an article on using marks to move around.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
  • The regular quote character ' also works and is easier to type than the backtick – Wim Coenen Oct 29 '09 at 22:18
  • 2
    Using ' to return to a mark only brings you back to the line of the mark. ` will bring you back to the line and column of the mark. – jamessan Oct 29 '09 at 22:20
2

Brian's solution above will work for a macro, but as a good tip, note that Ctrl+O will go to the previous cursor position in the jump list. So if you ever do an operation that moves away, you can step back to a previous position.

Peter
  • 127,331
  • 53
  • 180
  • 211
1

As jamessan wrote, Ctrl+o jumps back to the last posistion in the jumplist. After calling gg=G, this has to be called twice.

Thus, you can use a mapping without marks:

map <silent> <C-f> gg=G<C-o><C-o>
imap <silent> <C-f> <Esc> gg=G<C-o><C-o>
oliverguenther
  • 1,167
  • 1
  • 17
  • 31