Indent the entire file in Vim without leaving the current cursor location

I already know that gg=G can backtrack the entire file on Vim. But this will make me jump to the beginning of the file after the indent. How can I postpone the whole file and keep the cursor in the same position?

+6
source share
4 answers

See :h ''

This will return you to the first char in the line where you start:

 gg=G'' 

and this will return you to the start line and start column:

 gg=G`` 

I assume that the second version, on the flip side, is the one you want. In practice, I usually just use the double apostrophe version, since the back link is hard to get on my keyboard.

+13
source

Add this to your .vimrc

 function! Preserve(command) " Preparation: save last search, and cursor position. let _s=@ / let l = line(".") let c = col(".") " Do the business: execute a:command " Clean up: restore previous search history, and cursor position let @/=_s call cursor(l, c) endfunction nmap <leader>> :call Preserve("normal gg>G")<CR> 

You can also use this for any other command you want, just change the argument to a save function. The idea is taken here: http://vimcasts.org/episodes/tidying-whitespace/

+2
source

You can bookmark the current position with the m command followed by a letter. Then, after running the indent command, you can return to this bookmark with the `(backtick) command, followed by the same letter.

+1
source

In the same vein as Alex's answer, I use the following mapping in vimrc.

nnoremap g= :let b:PlugView=winsaveview()<CR>gg=G:call winrestview(b:PlugView) <CR>:echo "file indented"<CR>

by pressing g= in normal mode, the entire buffer is indented, and the scroll / cursor position is saved.

0
source

Source: https://habr.com/ru/post/895206/


All Articles