Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indenting entire file in Vim without leaving current cursor location

I already know that gg=G can indent the entire file on Vim. But this will make me go to the beginning of the file after indent. How can I indent the entire file and maintain the cursor at the same position?

like image 405
Fábio Perez Avatar asked Aug 16 '11 23:08

Fábio Perez


People also ask

How do I tab all lines in Vim?

To tab or add the indentation at multiple lines, try “shift+dot” i.e., “.” Shortcut once. You will see it will add an indentation of one character at each selected line from the start. If you want to add indentation without stopping, then you have to try the “.” Key from the keyword after using “shift+.”.

What is smart indent in Vim?

autoindent essentially tells vim to apply the indentation of the current line to the next (created by pressing enter in insert mode or with O or o in normal mode. smartindent reacts to the syntax/style of the code you are editing (especially for C). When having it on you also should have autoindent on.

How do I turn off auto indent in Vim?

To turn off autoindent when you paste code, there's a special "paste" mode. Then paste your code. Note that the text in the tooltip now says -- INSERT (paste) -- . After you pasted your code, turn off the paste-mode, so that auto-indenting when you type works correctly again.


2 Answers

See :h ''

This will get you back to the first char on the line you start on:

gg=G''

and this will get you back to the starting line and the starting column:

gg=G``

I assume the second version, with the backtick, is the one you want. In practice I usually just use the double apostrophe version, since the backtick is hard to access on my keyboard.

like image 188
Herbert Sitz Avatar answered Oct 16 '22 08:10

Herbert Sitz


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 on any other command you want, just change the argument to the preserve function. Idea taken from here: http://vimcasts.org/episodes/tidying-whitespace/

like image 32
Alex Avatar answered Oct 16 '22 08:10

Alex