如何让vim在调用函数后仅为下一行插入4个空格(一个缩进级别)?

6 投票
2 回答
1316 浏览
提问于 2025-04-18 02:22

在输入括号并按下回车后,下一行会有8个空格的缩进:

        print conn.generate_url(
                seconds,
                'GET',

而不是4个:

        print conn.generate_url(
            seconds,
            'GET',

我的 ~/.vimrc 文件是: https://github.com/quantonganh/salt-states/blob/master/vim/vimrc.jinja2

我是不是漏掉了什么?

这是我插件的列表:

├── ctrlp.vim
├── gundo.vim
├── jedi-vim
├── nerdtree
├── powerline
├── salt-vim
├── supertab
├── syntastic
├── ultisnips
├── vim-fugitive
├── vim-indent-guides
├── vim-surround
├── vim-yankstack
└── vundle

更新于 2014年4月12日 星期六 10:00:55

我在想:这是不是遵循了 PEP8 的规范呢?

        print conn.generate_url(
                seconds,
                'GET',
                bucket,
                key,
                response_headers={
                    'response-content-type': 'application/octet-stream'
                })

续行应该对齐,使用 Python 的隐式行连接,比如在括号、方括号和大括号内,或者使用悬挂缩进。当使用悬挂缩进时,应该注意以下几点:第一行不能有参数,后面的缩进应该更明显,以便清楚地区分它是续行。

在一个函数中,我们会有一些东西来区分连续的行,但这里只是一个 print,那应该是4个空格还是8个空格呢?

PEP8的E128:续行缩进不足以进行视觉缩进是什么?


更新于 2014年4月12日 星期六 23:09:27

看起来 jedi-vim 对 Python 的缩进没有影响。所以我的问题应该改成这样:

在定义一个函数时,下一行在括号后加8个空格(2个缩进级别)是可以的:

# More indentation included to distinguish this from the rest.
def long_function_name(
        var_one, var_two, var_three,
        var_four):
    print(var_one)

但我在调用它时只想加4个空格(一个缩进级别):

# Extra indentation is not necessary.
foo = long_function_name(
    var_one, var_two,
    var_three, var_four)

我该怎么做呢?

2 个回答

0

可以试试这个设置:let g:pyindent_open_paren = 'shiftwidth()',具体可以参考这个链接 https://vi.stackexchange.com/questions/8757/how-to-set-the-relative-indent-after-breaking-python-lines。另外,你也可以使用这个工具 https://github.com/Vimjas/vim-python-pep8-indent 来改善代码的缩进效果。还有这个讨论也很有帮助 https://vi.stackexchange.com/questions/38823/how-to-set-gpython-indent-disable-parentheses-indenting

1

正如你提到的,PEP8关于缩进的章节建议在参数前面加两个缩进级别,而不是一个(当第一行没有参数时),这样可以和其他部分区分开来。

但它也提到,在一些情况下,如果额外的缩进不是必须的,那就可以选择是否加。你的编辑器决定加上这个缩进,但根据PEP8,你可以自己选择。

撰写回答