如何在vim中使用pythontidy

时间:2010-10-02 05:16:35

标签: vim

我现在使用的是,

autocmd BufWritePost *.py !python PythonTidy.py % %

它真的称之为整洁的程序并更改文件,但vim不会重新加载新文件。

而且我不想为它安装另一个插件。

======================= 注意:我发现这个功能很危险,如果命令faild,PythonTidy将输出一个空文件,这意味着如果你有语法错误,你将丢失你的文件,除非按“u”得到​​它,但你无法保存在修复语法错误之前。

我现在调用:!PythonTidy%%在pylint完成后手动完成。

3 个答案:

答案 0 :(得分:2)

使用BufWritePre代替BufWritePost,并将Vim范围过滤与PythonTidy的stdin / stdout模式结合使用。

autocmd FileType python autocmd BufWritePre <buffer> let s:saveview = winsaveview() | exe '%!python PythonTidy.py' | call winrestview(s:saveview) | unlet s:saveview

(使用autocmd FileType python autocmd BufWritePre <buffer>使得这比在glob模式上匹配更准确:它意味着“任何时候检测到Python文件,为该缓冲区安装此autocmd” - 因此它独立于文件工作名。)

不幸的是,如果撤消过滤,则无法保留光标位置。 (您正在过滤整个文件范围;撤消过滤操作时,光标会跳转到范围中的第一行;因此您最终会在文件的顶部。)我希望找到一种方法来创建一个no -op撤消状态,之前,所以你可以点击 u 两次并回到正确的位置,但我还不能做到这一点。也许别人知道怎么做。

答案 1 :(得分:1)

基于:help:e:

                                                        *:e* *:edit*
:e[dit] [++opt] [+cmd]  Edit the current file.  This is useful to re-edit the
                        current file, when it has been changed outside of Vim.
                        This fails when changes have been made to the current
                        buffer and 'autowriteall' isn't set or the file can't
                        be written.
                        Also see |++opt| and |+cmd|.
                        {Vi: no ++opt}

因此,您需要在外部更新文件后使用:e。但是,:!不允许你使用|通常(参见:help:!),所以你需要包装它:

autocmd BufWritePost *.py execute "!python PythonTidy.py % %" | e

(:autocmd也不正常解释,这就是为什么你不需要再次转义它。)

答案 2 :(得分:1)

以下修复了光标位置问题

function! PythonTidySaver()
    let oldpos=getpos('.')
    %!PythonTidy    
    call setpos('.',oldpos)
endfunction

autocmd! bufwritepost *.py call PythonTidySaver()