Vim: changing tabs to spaces
Matthew Martinez
I know this question has been asked many times, but I'm not finding a solution to my problem in particular, mostly because I can't even really identify the problem.
Here's the timeline of events:
- open old python file (written with python2.7) - everything is fine
- change key bindings to execute .py files with python3 instead of python2.7 - as expected, lot's of
IndentErrors, but file is still the same structure/layout/number of spaces/tabs - added
expandtabto my .vimrc - no moreIndentErrors do to inconsistency anymore, but newIndentErrors all over the place because the structure of my source code is now all out of whack. - I remove
expandtabfrom my .vimrc and I still get the same out of whack source, even if I kill-session, quite iTerm, pull the source fresh from github...WHY!?
Just to be clear, there are only TWO things that have been altered in my vimrc in like the past few months and both alterations were made this morning. The first was remaping <F9> to issue a shell command for python3 instead of 2.7, which DID NOT affect the structure of my source code. The second change was adding expandtab which messed everything up...removing expandtab doesn't return my vim experience to the way it was prior to adding it.
The structural alterations to my source are semi-uniform, so let me try and explain what's actually happening.
What used to look like:
class GUI(): def __init__(self): suite of codenow looks like:
class GUI(): def __init__(self): suite of codeand it's like this across the board for what seems like all nested suites of code...in other words, the first expansion of tabs into 4 spaces works fine, but instead of expanding tabs nested further within the first tab, it looks like it just deletes the tab instead.
There are other weird things going on, but I can't really see a pattern.
Any ideas what's going on?
51 Answer
This appearance, with every other indent level dropped, is usually (and seems to be the case in your code) a symptom of looking at code which has 4 spaces per indent, but 8-space tabs tabs on every other line (e.g. 4s, 1t, 1t4s, 2t), with a tabstop setting of 4.
For Python code, you should simply replace all tabs in the code with eight spaces, since that was how the interpreter was treating it. In general you could deal with situations like this by using the :retab command after setting tabstop to the value the source code was originally written with, so e.g.
:set ts=8
:retab 4If expandtab is set, retab will replace tabs with spaces.