Different TAB settings in Vim based on filetype

Posted: September 2, 2010 in C/C++, Python, Vim
Tags: , , ,

In this post, we will explore how to set different TAB settings while editing C/C++ and Python code. For C/C++, we want 2 spaces for indendation, while for Python, we will stick to PEP 8 recommendations (4 spaces for indendation, 8 spaces for TAB, 4 spaces for expandtab). Vim being such a powerful and versatile editor, there are many ways to achieve this. We will explore the most portable way – with changes just to the .vimrc.

" Python options
let python_highlight_all = 1
function! s:set_python_settings()
  set tabstop=8
  set softtabstop=4
  set shiftwidth=4
function! s:unset_python_settings()
  set tabstop=2
  set softtabstop=2
  set shiftwidth=2
autocmd BufNewFile,BufEnter *.{py} call set_python_settings()
autocmd BufLeave *.{py} call unset_python_settings()

What we are doing here is define two functions, set_python_settings() which will change tab settings as per PEP 8 recommendations and unset_python_settings() which will default to our C/C++ settings. Autocmd upon entering a new buffer (BufEnter) or a new file is opened (BufNewFile) of type *py, we call set_python_settings() to set tab settings for Python. When we leave a buffer (BufLeave) of type *.py, we get back to original settings by calling unset_python_settings().


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s