space/tab conversion utility?

Grant Edwards grante at visi.com
Wed Jul 28 19:15:02 EDT 2004


In article <mailman.898.1091055734.5135.python-list at python.org>, Brian van den Broek wrote:

>> "unexpand" will do dumb conversion, but what's required is
>> something that understands Python block syntax.  Something
>> similar to C's "indent" program.
> 
> OK, sorry. I'm still pretty new to Python and programming in general. But 
> I would have thought that the recipe I pointed to could be used as the 
> basis of a script that would uniformly replace all leading tabs with a set 
> number of spaces, thus preserving relative indents. (On the assumption 
> that the code being transformed is all tabs.)

1) The conversion I need to do is the other direction spaces->tabs.

2) Simply converting all leading spaces to the right number of
   tabs (unexpand knows how to do that) isn't correct.  Only
   the spaces that are block-indent spaces should be converted.

For example:

1 ....if (asfsadfsadf and qwerqwrwer and
2 ........(asdf or qwer)):
3 ........doThis()
4 ........doThat()

Let's say we want to convert the lines above (indented with
groups of 4 spaces) into tab-indented code. In line 2, only the
first 4 spaces should be converted into a tab.  The second set
of 4 spaces aren't block-indent spaces they're visual alignment
spaces used to line up the sub-expression, and they need to
remain 4 spaces regardless of the indentation level chosen by
the person viewing the tab-indented code. 
   
> Still, the approach of replacing only leading tabs seems to me
> like it would work. I did up a script and from my testing it
> appears to preserve block structure. But I hesitate to post
> code; one gaff a day is enough ;-)
> 
> If there's a subtlety that is blowing past me in my
> newbieness, enlightenment would be appreciated. On the other
> hand, if you'd like to see the code, I'd be happy to share.

The problem is that sometimes lines contain leading spaces that
shouldn't be converted to tabs.

-- 
Grant Edwards                   grante             Yow!  All right, you
                                  at               degenerates! I want this
                               visi.com            place evacuated in 20
                                                   seconds!



More information about the Python-list mailing list