0

I want to add some comment lines when to edit python file:

vim  .vimrc
autocmd BufNewFile *.py exec ":call SetTitle_py()"
func SetTitle_py()
        call append(line("."),   "#!/usr/bin/env python3" )
        call append(line(".")+1, "# -*- coding:utf-8 -*- ")
endfunc

The title is set at the second line when to edit a py file with vim test.py ,instead of the first line?

enter image description here

1

2 Answers 2

0

First, you should :help append() a list instead of calling append() several times and keeping track of the current line and all:

let boilerplate = [
    \ "#!/usr/bin/env python3",
    \ "# -*- coding:utf-8 -*- "
    \]
call append(line("."), boilerplate)

Second, append() adds lines after the given line. Since you are on line 1, line(".") returns 1 and the text ends up on line 2, as expected. If you want the text to appear on line 1, you will have to do:

let boilerplate = [
    \ "#!/usr/bin/env python3",
    \ "# -*- coding:utf-8 -*- "
    \]
call append(0, boilerplate)

Third, :help setline() might be a more intuitive alternative:

let boilerplate = [
    \ "#!/usr/bin/env python3",
    \ "# -*- coding:utf-8 -*- "
    \]
call setline(1, boilerplate)
1

I came up with a solution that coexists with the XDG file template mechanism.

Part 1: create a file template containing the shebang etc.

File ~/Templates/python.py:

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

Part 2: read from this file

In my vimrc:

autocmd BufNewFile *.py 0r ~/Templates/python.py

This will read the template file when creating a new file. Added benefit is that it allows me to create a new file from template in one of these new fashioned graphical file manager programs, e.g. Right click -> New Document -> python

I extended this for a number of other languages and find it scales well. Each language takes up one dedicated file template and one line of vimrc.

Your Answer

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

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