Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically indent code with broken indentation in vim

I am working with a CMS where the code's indentation is a mess. Is it possible to fix it automatically with vim, running some command?

like image 615
lyuba Avatar asked Dec 28 '22 03:12

lyuba


2 Answers

Generally you can use the = operation to indent.

See :help =

(You'll also need to have filetype indent on in your vimrc to enable different indentation rules for each type of file you'll edit)

gg=G will reindent a whole file. (gg move to beginning of the file, = will reindent every line under motion, G goes to the end of the file)

By default, Vim support well C and C like language. See :help C-indenting for options. You'll probably need to adjust these options before reformating your files. You'll have to define set cindent in your .vimrc if you want to use the "smart" indentations that is controlled by cinoptions.

See :help indent-expressionfor other languages.

In addition, you'll probably will have to fiddle withshiftwidth, expandtab and tabstop options if you want to use whitespaces or tab to indent.

For example, if you to replace all tab by 4 spaces, you 'll have to use:

set shiftwidth=4             " used by >>, << and tab.  
set tabstop=4                " number of space characters used when displaying TAB  
set expandtab                " replace TAB by spaces  
like image 120
Xavier T. Avatar answered Jan 05 '23 18:01

Xavier T.


I usually do this with ggVG=. gg = go to file start, V = mark lines, G = go to file end, = = indent.

Maybe it is not the fewest keystrokes to do this, but I think it's easy to remember.

like image 44
Johan Kotlinski Avatar answered Jan 05 '23 16:01

Johan Kotlinski