In Vim, can I format a whole file and end with the cursor where it started?
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开发者_如何学Python 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?
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.
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.
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.
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.
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>
加载中,请稍侯......
精彩评论