I was reading that the way to indent in vim is a
gg=G sequence. This however loses my cursor position.
How can I indent my file without losing my cursor position?
Vi and Vim Stack Exchange is a question and answer site for people using the vi and Vim families of text editors. It only takes a minute to sign up.Sign up to join this community
Expanding on Karl Yngve Lervåg's answer:
ma - Set mark 'a' H - Jump to the top of the window mb - Set mark 'b' gg=G - Indent from the first line to the last `b - Jump to mark 'b' zt - Scroll the cursor line to the top of the window `a - Jump to mark 'a'
This will preserve your scroll position after indenting.
If you want to preserve the relative cursor position after the cursor line has been indented, you have to update the new cursor position after indenting. The following script expands on romainl's answer:
function! s:reindent(line1, line2) let view = winsaveview() let text = getline('.') execute a:line1.','.a:line2.'normal! ==' let view.col -= strchars(text) - strchars(getline(view.lnum)) call winrestview(view) endfunction command! -range=% Reindent call s:reindent(<line1>, <line2>)
You should use a mark, e.g.:
ma will set the
a mark at the current position, then
gg=G indents the file, and
`a will jump to the mark.
In order to put the cursor at the center of the screen afterwards, you could finish this off with
:h scroll-cursor for more info and for similar scroll mappings.