0

I want to add shebang when creating anew python file.

.vimrc:

autocmd BufNewFile *.py exec ":call SetTitle_py(0)"
func SetTitle_py(line_num)
    let boilerplate = [
        \"#!/usr/bin/env python3",
        \"# -*- coding:utf-8 -*- "
        \]
    call append(a:line_num, boilerplate)
endfunc

It works fine, everytime I create a new python file, the following two lines are inserted as the first two lines:

#!/usr/bin/env python3
# -*- coding:utf-8 -*- 

I want to add more lines such as below:

#!/usr/bin/env python3
# -*- coding:utf-8 -*- 
"""

"""

Add some comments in the .vimrc:

.vimrc:

autocmd BufNewFile *.py exec ":call SetTitle_py(0)"
func SetTitle_py(line_num)
    let boilerplate = [
        \"#!/usr/bin/env python3",
        \"# -*- coding:utf-8 -*- "
        \"""
        \
        \"""
        \]
    call append(a:line_num, boilerplate)
endfunc

I have the error info when to re-create new python file:

Error detected while processing BufNewFile Autocommands for "*.py"..function SetTitle_py:
line    1:
E696: Missing comma in List: """"""]
line    8:
E121: Undefined variable: boilerplate
E116: Invalid arguments for function append

How can fix it?

1

1 Answer 1

0

Function append works with list of lines which you initially had in your boilerplate variable. Then you have added to the second line something that vim can't understand presumably you wanted to add more elements to the list but ended up with something that looks like a list but not the proper list.

Try to make boileplate a proper list:

autocmd BufNewFile *.py exec ":call SetTitle_py(0)"
func SetTitle_py(line_num)
    let boilerplate = [
        \"#!/usr/bin/env python3",
        \"# -*- coding:utf-8 -*- ",
        \'"""',
        \'',
        \'"""'
        \]
    call append(a:line_num, boilerplate)
endfunc

It looks better using vim9script style functions:

autocmd BufNewFile *.py call SetTitle_py(0)

def g:SetTitle_py(line_num: number)
    var boilerplate = [
        "#!/usr/bin/env python3",
        "# -*- coding:utf-8 -*- ",
        '"""',
        '',
        '"""'
        ]
    append(line_num, boilerplate)
enddef
1
  • I might highlight the difference between your list with commas and OPs without since it's subtle but major.
    – D. Ben Knoble
    Mar 12 at 16:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.