Set Vim Shift Width

I have had a problem with vim for a while. Although I have my tabstop set to 4, when I use >> or << to indent or undent (technical term) my code, it moves the code by 8 characters. As I'm now working with phpcodesniffer, I’m pretty motivated to get my editor set correctly so I don’t waste time on formatting.

The setting I want is the shift width. I added this in my .vimrc file:

set sw=4

Hopefully this will help someone else with the same issues. I’ve been grappling with the tab/space/indentation settings for vim as long as I’ve been using it and I don’t think I’m done yet. Maybe one day I’ll solve it and write a big overview but for now, you can read the previous installment and pass on any tips you may have via the comments!

As an aside, I now completely understand why projects have vim settings in their files – I’ve got different coding standards going on inside different projects so I’m spending a lot of time fiddling with .vimrc these days!

7 thoughts on “Set Vim Shift Width

  1. I have loads of trouble with tabs and indentation in vim too.

    I currently have:

    set expandtab
    set tabstop=4
    set softtabstop=4
    set shiftwidth=4

    In my .vimrc, which appears to work.

    What I need to know is how to reformat a file to fix the indentation throughout the file.



    • The equals symbol (=) re-indents code based on your indent settings. Depending on your coding style, if you have smartindent or cindent enabled, the following may be all you need: ggVG=

      This visually selects every line in the file and then re-indents them.

      This won’t be smart enough to preserve any personal formatting styles, such as aligning arguments of a function call underneath the opening bracket.

  2. I’ve been enjoying having phpcodesniffer running against projects, it clearly shows up where spacing isn’t quite right. Its not going to magically fix existing indents but it makes it easy for developers to check files, so at least your team have the info they need in order to fix, even if it takes a bit of time :)

Leave a Reply

Please use [code] and [/code] around any source code you wish to share.

This site uses Akismet to reduce spam. Learn how your comment data is processed.