How to indent lines automatically?

Tag: vim Author: zhaoyingjie747 Date: 2009-08-07

Quick newbie question. Let's say I have the following code in Vim:

void main()


    int i = i + 1;

    return i;

I have the cursor on the empty line between the two lines of code. When I press i (or a) to enter text I want to cursor to indent to the right position (i.e. below the i in "int i..."). Any ideas how it can be done?

Best Answer

:set cindent


It's not working. I ":set cindent" and as I press a (or i) I begin to enter text on the first column and not on the 4th (or any other column). BTW, I have these in my .Vimrc set autoindent set smartindent set tabstop=4 set shiftwidth=4 Any ideas?
Ah, sorry, missed part of the question. i and a will never autoindent immediately; their defined behavior is inserting at and after, respectively, the cursor. If you hit enter it will indent, though what I'd recommend you do is use o and O for starting new lines; that's so ingrained to me that I didn't notice you were doing something else.
So what is the solution? I have an empty line and I want to start typing on the right (indented) position. Any ideas?
I don't understand why I deserve you last comment. I asked a simple question, which I don't think is contrary to vim's way of thinking. The situation I describe is simple and happens once in a while. Empty lines (God forbid) do happen in source code once in a while. I perfectly accept that vim can't do everything and what I ask for is not possible. Thank you again.
Okay, then let me rephrase. Positioned on your empty line, type ddO.

Other Answer1

Like @chaos mentioned, cindent is probably what you're looking for.

There's also autoindent, smartindent, and indentexpr, which are all quite configurable and documented at the Vim documentation on indent.

Here's a snippet of how configurable they can be:

{N    Place opening braces N characters from the prevailing indent.
              This applies only for opening braces that are inside other
              braces.  (default 0).

                cino=               cino={.5s           cino={1s
                  if (cond)           if (cond)           if (cond)
                  {                     {                     {
                      foo;                foo;                foo;

Other Answer2

just use cc on blank lines and o for new lines


I checked this answer. cc works with cindent turned on, ddO works even without. Interesting.

Other Answer3

You can try typing 3>> while on the int i... line. Not exactly automatic, but it saves time.