| 199 | self.newlines = f.newlines |
| 200 | |
| 201 | def run(self): |
| 202 | tokens = tokenize.generate_tokens(self.getline) |
| 203 | for _token in tokens: |
| 204 | self.tokeneater(*_token) |
| 205 | # Remove trailing empty lines. |
| 206 | lines = self.lines |
| 207 | while lines and lines[-1] == "\n": |
| 208 | lines.pop() |
| 209 | # Sentinel. |
| 210 | stats = self.stats |
| 211 | stats.append((len(lines), 0)) |
| 212 | # Map count of leading spaces to # we want. |
| 213 | have2want = {} |
| 214 | # Program after transformation. |
| 215 | after = self.after = [] |
| 216 | # Copy over initial empty lines -- there's nothing to do until |
| 217 | # we see a line with *something* on it. |
| 218 | i = stats[0][0] |
| 219 | after.extend(lines[1:i]) |
| 220 | for i in range(len(stats) - 1): |
| 221 | thisstmt, thislevel = stats[i] |
| 222 | nextstmt = stats[i + 1][0] |
| 223 | have = getlspace(lines[thisstmt]) |
| 224 | want = thislevel * 4 |
| 225 | if want < 0: |
| 226 | # A comment line. |
| 227 | if have: |
| 228 | # An indented comment line. If we saw the same |
| 229 | # indentation before, reuse what it most recently |
| 230 | # mapped to. |
| 231 | want = have2want.get(have, -1) |
| 232 | if want < 0: |
| 233 | # Then it probably belongs to the next real stmt. |
| 234 | for j in range(i + 1, len(stats) - 1): |
| 235 | jline, jlevel = stats[j] |
| 236 | if jlevel >= 0: |
| 237 | if have == getlspace(lines[jline]): |
| 238 | want = jlevel * 4 |
| 239 | break |
| 240 | if want < 0: # Maybe it's a hanging |
| 241 | # comment like this one, |
| 242 | # in which case we should shift it like its base |
| 243 | # line got shifted. |
| 244 | for j in range(i - 1, -1, -1): |
| 245 | jline, jlevel = stats[j] |
| 246 | if jlevel >= 0: |
| 247 | want = have + (getlspace(after[jline - 1]) - |
| 248 | getlspace(lines[jline])) |
| 249 | break |
| 250 | if want < 0: |
| 251 | # Still no luck -- leave it alone. |
| 252 | want = have |
| 253 | else: |
| 254 | want = 0 |
| 255 | assert want >= 0 |
| 256 | have2want[have] = want |
| 257 | diff = want - have |
| 258 | if diff == 0 or have == 0: |