2

我正在学习 Vim,并且我已经成功地设置了我的 .vimrc 文件,这样每当我创建一个新的 python .py 文件时,就会自动生成相应的 shebang 和 header。耶我!

但是,在构建终端管道时,我并不总是喜欢为我管道到的程序包含 .py 扩展名。因此,shebang 不会自动生成。伤心!

在不重复我为 autocmd 编写的内容的情况下(因为这是我学习的方式,我需要大量的尝试和错误才能编写),我可以在 INSERT 模式下映射一个像“pyhead”这样的字符串,或者创建一个与 autocmd 相关联的宏以轻松实现当我选择不使用 .py 扩展名时,我的 shebangbang?我觉得对已经存在的命令的简单映射应该可以防止混乱的 .vimrc。我已将我的 autocmd 放在一个 augroup 中,如下所示:

    augroup Shebang
        autocmd BufNewFile *.py 0put =\"#!/usr/bin/env python\<nl>...
                                     ...# -*-coding: utf-8 -*-\
                                     ...<nl>\<nl>\"
                                     ...|put ='#'.expand('%:t')
                                     ...|put =\"#<My_NAME>\"
                                     ...|put ='#LAST UPDATED: '.strftime('%m-%d-%Y')\|$ 
    augroup end

为了清楚起见,autocmd 都在一行上,但我包括三个点来表示继续(这样您就不需要滚动)。如果这是一个愚蠢的要求,并且有一个简单的答案,请谴责。谢谢!

4

1 回答 1

2

您可以将长:put命令提取到一个函数中,然后:call:autocmd.

function! InsertPythonShebang()
    0put =...
endfunction

autocmd BufNewFile *.py call InsertPythonShebang()

You can then reuse the function in a mapping:

nnoremap <Leader>py :call InsertPythonShebang()<CR>

Or a custom command:

command! -bar PyBang call InsertPythonShebang()

Your suggestion of reacting on insertion of a special keyword would be possible, too, but I won't provide a solution because I think it's un-idiomatic, and the implementation would be more involved (especially if you want to reuse the :put, and not just the generated text). Also note that there are several snippets plugins that offer similar functionality (but again reusing the same string for your :autocmd would be a challenge).

I would recommend a trigger on setting the python filetype on an empty buffer. In order to have syntax highlighting, you need to :setf python, anyway. (The built-in filetype detection would need the .py file extension, or an existing shebang line to work. Catch-22.)

autocmd FileType python if line('$') == 1 && empty(getline(1)) | call InsertPythonShebang() | endif
于 2018-02-16T09:22:42.237 回答