Python source file vim editing indent

When editing Python source file in vim, we may want to use tab to add indent. Below shows how to use vim autocommand to add the indent automatically for*py, *pyw, *.c and *.h files.

Change the vim setting in .vimrc, add the content in  “vimrc file for following the coding standards specified in PEP 7 & 8” to the .vimrc file.

Once done, open vim to edit a new .py file, enter tab will add 8 spaces as the indent. Above Python vimrc file do more things actually, like show red when there is a invalid indent, etc.

The indent work done in the Python vimrc file is, below line of script will set tabstop=8 for new added and existing *py, *pyw, *.c and *.h file(it doesn’t touch other files other than these 4 files)

au BufRead,BufNewFile *py,*pyw,*.c,*.h set tabstop=8
au BufRead,BufNewFile *.py,*.pyw set expandtab

Details of autocommand can be found at,
autocommand tabstop
autocommand expandtab

And, there is another page show helpful info about Vi Improved, and the vim syntax config.

However, there is some confusions here, Python prefer 4 spaces for the indent, so the correct & convenient indent way is in the description here. Basically, if the tabstop is 8, set softtabstop and shiftwidth to 4, and set use noexpandtab.

tabstop is used for how to display tab(how many spaces counts for).
softtabstop is used for how many spaces will be perform when tab key entered in insert mode.
expandtab, when it is set, there will be no tab character in the insert mode, all are spaces, if softtabstop set, softtabstop spaces will be inserted, otherwise tabstop spaces will be inserted.


Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s