Wednesday, December 22, 2010

Vim indentation for C/C++ explained

SkyHi @ Wednesday, December 22, 2010
In today’s early morning post, I’m going give a short crash course about Vim settings for indentation. Every programmer knows how source code indentation important is. There is no discussion about it. Vim, my favourite text editor, provides programmer with rich indetation features set. You can customize almost all aspects of code formating. So, let’s see what kind of indentation features Vim provides and how they affect indentation.

General Indentation Settings

:set autoindent
If set, Vim automatically indents a new line to the same indentation used by previous line. In other words ViM automatically tabs a new line. smartindent and cindent are autoindent variations and changes the way indentation and formatting more precisely.
:set smartindent
Context-sensitive autoindent, great when coding, makes intendation aware of C-like syntax.
:set shiftwidth
Using this option you can define number of spaces placed on every indentation step i.e. :set shiftwidth=3 will instruct Vim to indent with 3 spaces for every TAB command.

TAB Settings

:set expandtab
Use this option if you want every TAB to be expanded to spaces.
:set smarttab
If this option is set, then TAB command shifts line to right and BACKSPACE shifts line to left, both inserting number of blanks as defined in shiftwidth. If smarttab is not set, then TAB inserts blanks according to tabstop.
:set softtabstop
This one tells Vim to interpret TAB as an indent command instead of insert-a-TAB command.
:set tabstop
Simply, it instructs Vim how many space characters Vim counts for every TAB command. According to Vim manual it’s recommended to leave default tabstop=8, what means every TAB is displayed with 8 space characters, and adjust only softtabstop and shiftwidth.

C-style Indent

:set cindent
This sets autoindent to even more smart and strict mode for C and C++ source code.
:set cinoptions
Simply, it sets cindent configuration options.


To learn how to use Vim commands and how to set indentation settings refer to online VimDoc or run open help :h where option is one of Vim command. I also recommend to take a look at the Vim website with documentation and huge database of tips.

Online Resources

Vi and Vim in Linux Productivity Magazine, Volume 1 Issue 5
Introduction to Programming in C/C++ with Vim by Kmj
VIM (Vi IMproved)
The Vi/Ex Editor by Walter Alan Zintz
Vi for programmers, part 1 and part 2