4

Everytime I write a new python program, I find myself writing the same initial lines over and over again:

#!/usr/bin/env python
'''
Description of the program
'''
import always, the, same, libraries

def helper_function(helpers_args):
'''
A function that is called in get_main_output, but that someone might want to import too.
'''
    continue

def get_main_output(program_arguments):
'''
Description of the main function
'''
    continue

if __name__ == '__main__':
    output = get_main_output(sys.argv)

I don't want to have to do it by hand everytime. I would like vim to show me this file everytime I open a nonexistent file with the extension .py, so that I can modify it as needed and then save it to my newly created source file.

How can I achieve this?

Apologies if the answer is already somewhere. I thought it would be, but I couldn't find it anywhere.

2
  • each new py file you want those stuff? like if __name__ == '__main__'? Commented Feb 27, 2018 at 15:27
  • No, OP need the whole skeleton script (check my answer) Commented Feb 27, 2018 at 15:38

1 Answer 1

6

In /etc/vim/vimrc or /etc/vimrc or ~/.vimrc

" python skeleton
autocmd BufNewFile *.py 0r ~/.vim/skeleton.py

skeleton file:

~/.vim/skeleton.py

Put the python code from your original post inside this file as simple-user

Vim documentation:

skeleton/template within autocmd.txt

Sign up to request clarification or add additional context in comments.

3 Comments

Works great! Just one thing - it works for me only if the 2 lines are added to ~/.vimrc, not to ~/.vim/vimrc. You might want to mention that too.
@FerdinandoRandisi Yes, it should be ~/.vimrc. ~/.vim/vimrc will only work if you make vimrc and gvimrc symlinks to files within ~/.vim/ using ln -s ~/.vim/vimrc ~/.vimrc and ln -s ~/.vim/gvimrc ~/.gvimrc. Such symlinking can keep your Vim configuration more organized.
Note, ~/.vim/vimrc is automatically sourced by Vim if no ~/.vimrc exists since 7.3.1178

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.