Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tab key == 4 spaces and auto-indent after curly braces in Vim

How do I make vi-Vim never use tabs (converting spaces to tabs, bad!), makes the tab key == 4 spaces, and automatically indent code after curly brace blocks like Emacs does?

Also, how do I save these settings so I never have to input them again?

I've seen other questions related to this, but it always seems to be a little off from what I want.

like image 735
mmcdole Avatar asked Oct 24 '08 17:10

mmcdole


People also ask

How do I set tab 4 spaces in Vim?

Within Vim, type a colon and then "set tabstop=4" which will set the tabs to display as four spaces. Hit colon again and type "set expandtab" which will insert spaces for tabs.

How do I set auto tab in Vim?

How to Turn On Auto Indent in Vim. To automatically indent when editing a file in Vim, enable the auto indenting feature using the :set autoindent flag in command mode: Press Enter, and this will auto-indent the file you are currently editing.


2 Answers

As has been pointed out in a couple of other answers, the preferred method now is NOT to use smartindent, but instead use the following (in your .vimrc):

filetype plugin indent on " show existing tab with 4 spaces width set tabstop=4 " when indenting with '>', use 4 spaces width set shiftwidth=4 " On pressing tab, insert 4 spaces set expandtab 

In your [.vimrc:][1] file:
set smartindent set tabstop=4 set shiftwidth=4 set expandtab 

The help files take a bit of time to get used to, but the more you read, the better Vim gets:

:help smartindent 

Even better, you can embed these settings in your source for portability:

:help auto-setting 

To see your current settings:

:set all 

As graywh points out in the comments, smartindent has been replaced by cindent which "Works more cleverly", although still mainly for languages with C-like syntax:

:help C-indenting 
like image 64
Ken Avatar answered Sep 21 '22 13:09

Ken


Related, if you open a file that uses both tabs and spaces, assuming you've got

set expandtab ts=4 sw=4 ai 

You can replace all the tabs with spaces in the entire file with

:%retab 
like image 37
netjeff Avatar answered Sep 18 '22 13:09

netjeff