3

For some time I have used tabstop=4 in my source files. Now that I write lot of javascript that has deep indentations, a tabstop of 4 seems wasteful, so I want to convert it to 2. The problem is I use "set expandtab" too. So merely setting tabstop=2, won't help.

Any suggestions on how I can convert all my files quickly to tabstop 2?

My current relevant .vimrc settings are

set tabstop=4
set shiftwidth=4
set expandtab
Jayesh
  • 51,787
  • 22
  • 76
  • 99

2 Answers2

12

You can do

" convert spaces to tabs first
set noexpandtab
set tabstop=4
set shiftwidth=4
retab!
" now you have tabs instead of spaces, so insert spaces according to
" your new preference
set tabstop=2
set shiftwidth=2
set expandtab
retab!

in a vim window, and it will retab according to your preferences. You can probably create a mapping to make this easier, or record a macro. There might be another way, but the above should work. (" is comment)

Alok Singhal
  • 93,253
  • 21
  • 125
  • 158
6

You can change your settings, select all, and hit the = key to indent it:

ggVG=

I also recommend using ftplugin to specify settings per file type.

Merlyn Morgan-Graham
  • 58,163
  • 16
  • 128
  • 183
  • 1
    I *knew* there was an easy way! – Alok Singhal Aug 19 '10 at 03:45
  • @Alok: You may want to leave your answer anyhow. Looking at the VIM docs, it may be fundamentally different than applying indent. I guess he should try both to find out. – Merlyn Morgan-Graham Aug 19 '10 at 03:53
  • Well, your method reindents everything, which is, as you said, different from preserving the intent of the indent already in the code. Good point, I will undelete my answer. – Alok Singhal Aug 19 '10 at 04:00
  • I tried this, it does reduce the indentation, but it doesn't work quite right. I think it recalculates indents instead of only changing existing tabs. – Jayesh Aug 19 '10 at 04:20
  • @Jayesh: That's exactly what = does: reindent according to your settings; see :help =. –  Aug 19 '10 at 05:32