You are here

Configuring Vim/Gvim to use spaces instead of TABs for indentation

Submitted by Druss on Wed, 2011-08-10 03:00

Some people like to indent their code using TABs. I used to like doing this. I still think that it's a good idea. But circumstances have dictated for the past several years that I need to indent using spaces instead. My favourite command-line editor in Linux and text editor in Windows is VIM / Gvim (where Gvim is basically Vim with a GUI). To configure this editor to override its default and use spaces instead of TABs for indentation, perform the following steps:

  • Locate or create the VIM configuration file. On Windows (7), this file should be located in your home folder, for e.g., C:\Users\Jubal\ and named _vimrc. The equivalent in Linux is ~/.vimrc .
  • Copy and paste the following directives into this file:
    set tabstop=2
    set shiftwidth=2
    set expandtab

    The above settings set the indentation to be 2 spaces wide and expands TABs to spaces.
  • Save the file and exit the editor.
  • Open a new instance of Gvim to test things out.

It should be noted that our changes will not affect any pre-existing tabs in a file. If you are interested in converting them as well, just type :retab when in Gvim and press the Enter key. This should replace any tabs with spaces. You can also do this with a find and replace using the following directive: :%s/\t/ /g.

Hope this helps somebody out there :)