tags:

views:

75

answers:

4

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?

+3  A: 

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
The regular quote character ' also works and is easier to type than the backtick
Wim Coenen
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
+3  A: 

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
+3  A: 

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
+4  A: 

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