Format Ruby code in Vim

Just moving over to Vim at the moment. In TextMate I could format code by hitting Cmd-Alt-[. How do I achieve the same in Vim?


See the answer below for the command. I found I also needed the following in my .vimrc so that Vim knew how to autoindent Ruby.

if has("autocmd")
  filetype indent on
endif

Answers


Vimcasts has a useful screencast on this subject that you may be interested in

gg=G

gg => go to start of file
=  => apply autoformatting
G  => ... to the end of file

When I see questions about Vim and reformatting and reindenting, I usually feel confusion. But it is pretty easy.

Reindenting, done with = key, is a process of shifting line indetation without inserting any line ends - no hard wrapping. Simply put, beginning columns of the selected lines can change, but the content cannot.

On the other hand, reformatting is complete rewrite of a selected piece of code. Simply put, everything is deleted and written again according to the language rules defined in Vim. Easy, huh?

The usual patern for reindentation is to go to the beginning of the file (gg), change to line selection (V), go to the end of the file (G) and perform reidentation (=).

That's indenting in vim: ggVG=

Reformatting pattern starts with the very same keys (ggVG), but instead of equal key, you do gq - reformat Vim command.

That's formatting in vim: ggVGgq

This works out-of-box in every Vim instance, even with plain text. Only when Vim does not understand the programming language you need to provide it with correct formatting rules (usually bunch of .vim files which have to go to the .vim directory structure).

Reformatting for Ruby works only when plugin vim-ruby is installed.

I had to publish this on my blog ;-) Isn't Vim cool? It is.


Try:

gg=G

in normal mode.


If you're looking for more than just indentation, have a look at ruby-beautify. It can be integrated with vim through vim-autoformat.


ggVGgq will reformat the entire file according to the current filetype


I released a VIM plugin that will do some more comprehensive formatting for Ruby files. In addition to indenting, it does things like remove trailing whitespace, and consistently spaces out method declarations:

vim-autoformat-rails


For small indentation, try: =}, =)


Need Your Help

Enabling Camera Flash While Recording Video

java android c++ process android-camera

I need a way to control the camera flash on an Android device while it is recording video. I'm making a strobe light app, and taking videos with a flashing strobe light would result in the ability to