如何自动缩进在 github 上看起来不错但在编辑器中缩进得可怕的代码?

How to autoindent code that looks fine on github, but horribly indented in the editor?

我需要在 Sublime 和 PyCharm(大型源文件的一小部分)中编辑一段代码:

我不确定作者使用的是哪种现代代码编辑器(以及要求在一行中混合制表符和空格的创新方法),但不知何故他们的缩进在 github 上看起来合理(所以我猜所有团队成员都在使用 Atom?) - 我检查了一下,页面源代码仍然包含 \t 个符号。

python -m py_compile 命令似乎对这段代码很满意,所以我尝试用 8 spaces 替换制表符,但看起来仍然很糟糕。任何用 'fixed number' 个空格替换它们的尝试也没有用,包括 5 个空格,这可能是数字或 &nbsp 浏览器应该使用的)。该文件没有 CRLF 结尾,我检查过。

我尝试使用内部使用 Python 2.7 AST 的 formatter,它说缩进是错误的,所以还是不行。

我试图找到制表符数量和假定的空格数量背后的一些逻辑,导致以下观察结果:

2 spaces + tab + 4 spaces => 12 spaces
sstssss ->
ssssssssssss (12 spaces) => t = 6 spaces
example
        for |<- these pipes should be one on top of the other
        |correct_t

sst ->
ssssssss (8 spaces) => t = 6 spaces
example
        |writer.add_scalar('eval/acc', acc, epoch)
    |if acc >= best_acc:

but

ssstsssss ->
sssssssssssss (13 spaces) => t = 5 spaces

         |best_acc = acc
             |model.save_networks('best'+str(epoch))

哦,我想出办法了!我在 sublime 中将制表符宽度设置为 8 个空格,然后它按预期工作,即不是用 8 个空格替换每个 \t,而是 'tabs' 它们最多 8 个空格!

在 linux 中,可以通过 expand -t 8 <filename> 做同样的事情。