Vim tip: How to fix Python exception IndentationError

The problem is usually with mixup in tabs and spaces –

Solution 1

1. Apply following command in Vim to highlight tabs, spaces and other whitespace differently.

:set listchars=tab:>-,trail:-,eol:$ list

2. Apply the following to set correct width

:set shiftwidth=4 tabstop=4 expandtab 

3. running


to fix the problem,Vim automatically fixes all indentation space and tab mix ups.

Solution 2

1. set ‘list’, so that you can see the whitespace and change.

Have the following mapping in .vimrc for this:

nnoremap    <F2> :<C-U>setlocal lcs=tab:>-,trail:-,eol:$ list! list? <CR>

2. Ensure ‘expandtab’ is reset, check using following command –

:verbose set ts? et? 

3. To expand all leading spaces (wider than ‘tabstop’), use retab.

retab takes a range, so specify % to mean “the whole file”.

:set tabstop=4      " To match the python file
:set noexpandtab    " Use tabs, not spaces
:%retab!            " Retabulate the whole file

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 )

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