How do I fix the indentation of an entire file in Vi?

Viewed 331162

In Vim, what is the command to correct the indentation of all the lines?

Often times I'll copy and paste code into a remote terminal and have the whole thing messed up. I want to fix this in one fell swoop.

16 Answers

=, the indent command can take motions. So, gg to get the start of the file, = to indent, G to the end of the file, gg=G.

Before pasting into the terminal, try :set paste and then :set nopaste after you're done. This will turn off the auto-indent, line-wrap and other features that are messing up your paste.

edit: Also, I should point out that a much better result than = indenting can usually be obtained by using an external program. For example, I run :%!perltidy all the time. astyle, cindent, etc. can also be used. And, of course, you can map those to a key stroke, and map different ones to the same keystroke depending on file type.

You can use tidy application/utility to indent HTML & XML files and it works pretty well in indenting those files.

Prettify an XML file

:!tidy -mi -xml %

Prettify an HTML file

:!tidy -mi -html %

1G=G. That should indent all the lines in the file. 1G takes you the first line, = will start the auto-indent and the final G will take you the last line in the file.

if you do not want to use :set paste, middle-click, set nopaste, you can also paste the content of the clipboard:

"*p
"+p

That way you don't have to leave normal mode. if you have to paste + or * depends on how you selected the text, see :help quoteplus.

In Vim, use :insert. This will keep all your formatting and not do autoindenting. For more information help :insert.

:set paste is your friend I use putty and end up copying code between windows. Before I was turned on to :set paste (and :set nopaste) copy/paste gave me fits for that very reason.

Just go to visual mode in vim , and select from up to down lines after selecting just press = , All the selected line will be indented.

Related