4

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?

lyuba
  • 6,250
  • 7
  • 27
  • 37

2 Answers2

9

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  
Xavier T.
  • 40,509
  • 10
  • 68
  • 97
  • Thank you! I had these options enabled and just tried that with simple html files - it works fine. However if the file is a mess like smarty view file that I work with now looks like I need to deep into the indent-expression theory.. ) – lyuba Jan 05 '11 at 10:21
1

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.

Johan Kotlinski
  • 25,185
  • 9
  • 78
  • 101
  • And what does = exactly do? The result isn't completely the one I expected. I am trying to indent the view file, and all html in it is now clipped to the left, but not indented. This could help a bit but still requires manual indentation after. – lyuba Jan 05 '11 at 10:02
  • 1
    If you want to reformat html, see the answer to that question : http://stackoverflow.com/questions/815548/how-do-i-tidy-up-an-html-files-indentation-in-vi/815560#815560 – Xavier T. Jan 05 '11 at 10:10