15

I read this about shiftwidth option on Google: To change the number of space characters inserted for indentation, use the 'shiftwidth' option.

Ok Ok, but what's that more exactly? How can I try this to see what really happens? I created a new C file then added an IF confition, but nothing happens during identation:

if (a > 0) { nothing happens here }

Thank you!

1
  • 2
    Vim comes with an extensive documentation, try :h shiftwidth.
    – romainl
    May 12, 2013 at 11:19

3 Answers 3

13

Lets say you have set shiftwidth=2

Firstly, you need to make sure that the file that a .c extension. Either by using

$ vim foo.c

for a new file or saving the file with a .c extension.

Now type

if (a > 0) {

and press enter. The next line will automatically be indented.

if (a > 0) {
  foo();

when you put a matching '}', vim will indent it properly.

if (a > 0) {
  foo();
}

Read this documentation for more clarity.

6
  • 2
    I tried it, but affter pressing enter at the curly brace, it puts the cursor to the beginning of the line.
    – user223787
    May 12, 2013 at 11:25
  • are you typing the closing curly brace before pressing enter? Is there a plugin that auto closes brackets enabled?
    – draxxxeus
    May 12, 2013 at 11:31
  • 1
    yes. No plugins
    – user223787
    May 12, 2013 at 12:02
  • 1
    I dind't type the closing }. Anyway, thanks for your help. I don't know what does that option do, but I will add it to .vimrc :)
    – user223787
    May 12, 2013 at 12:22
  • 1
    shiftwidth says the number of columns to be indented when you do >> or <<
    – draxxxeus
    May 12, 2013 at 12:26
7

I can recommend this screencast by Drew Neil which will explain how tabstop, softtabstop, shiftwidth and expandtab work together.

1
  • 3
    I just want to say thank you. This is the most wonderful VIM website I have ever seen, yet never heard of. Today I found this thread and scrolled down and went to this screencast and configured my vim and now it works beautifully.
    – jreyes
    Jan 7, 2021 at 2:22
0

Another important use of shiftwidth is to provide proper indentation to the code. Lets suppose we are using a.yaml file in which we wish to indent few lines of code together.

we set the shiftwidth with

esc:set shiftwidth=2

Now select the that you wish to indent with key

shift + v

Now, to indent the code right we use

shift + >

And, To indent the code left we use

shift + <

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .