title: inverted reindent.py (spaces to tabs)
body: <p>afaik <code>reindent.py</code> (available in the standard python examples) has a tokenizer allowing it to do smart reindenting based on the indentation level rather than on the number of spaces osed per level (which can vary in bad code)</p>
  
  <p>unfortunately it enforces 4-space indentation, but i want tabs, because 1 tab == 1 indentation level is more logical than x spaces.</p>
  
  <p><a href="https://stackoverflow.com/questions/338767/tool-to-convert-python-indentation-from-spaces-to-tabs">this</a> question has no suitable answer:</p>
  
  <ul>
  <li>i don’t care about pep-8 (i know how to write my code)</li>
  <li>vim is installed, but <code>:retab!</code> doesn’t handle inconsistent indentation</li>
  <li>all tools convert spaces used for alignment (!= indentation) to tabs, too.</li>
  </ul>
  
  <p>one way would be to use reindent.py and afterwards doing sth. like:</p>
  
  <pre><code>#!/usr/bin/env python3
  from re import compile
  from sys import argv
  
  spaces = compile("^ +")
  multistr = False
  for line in open(argv[1]):
      num = 0
      if not multistr:
          try:
              num = len(spaces.search(line).group(0)) // 4
          except AttributeError:
              pass
      print("\t"*num + line[num*4:-1])
      if line.count('"""') % 2 == 1:
          multistr = not multistr
  </code></pre>
  
  <p>but that’s rather hacky. is there no non-zealot version of reindent.py?</p>
  
  <p>PS: why suggests the highlighting that <code>// 4</code> is a comment instead of a truncating division?</p>
  
  <hr>
  
  <p>The following script should do the trick, but either i missed sth., or tokenize is buggy (or the example in the python documentation)</p>
  
  <pre><code>#!/usr/bin/env python3
  
  from tokenize import *
  from sys import argv
  
  f = open(argv[1])
  def readline():
      return bytes(f.readline(), "utf-8")
  
  tokens = []
  ilvl=0
  for token in tokenize(readline):
      if token.type == INDENT:
          ilvl+=1
          tokens.append((INDENT, "\t"*ilvl))
      else:
          if token.type == DEDENT:
              ilvl-=1
          tokens.append(token)
  
  print(untokenize(tokens).decode('utf-8'))
  </code></pre>