tags:

views:

113

answers:

2

Is it possible to have VIM auto populate a file based on the extension?

For example, when I open a new .sh file, I would like VIM to automatically type

#!/bin/bash

as the first line. (This example simplified down to the essentials)

+9  A: 

Check the section on "skeleton" in the vim help section:

:help skeleton

For your case, you should add a line like the following to your .vimrc:

autocmd BufNewFile *.sh 0r ~/vim/skeleton.sh
William Pursell
Hmm. I don't currently have ~/vim/skeleton.sh Is that something I need to create (and populate)?
David Oneill
I can't seem to get this working. I've tried adding:autocmd BufNewFile *.sh as well as ~/vim/skeleton.sh to my vimrc, but when opening new .sh files it echoes a message and then doesn't do anything.
b14ck
@David Oneill: Yes, you need to give vim the template you want to use. What's it going to do, guess?
Jefromi
@b14ck: That's not an "or". That's `0r`, as in "read in the contents of this file at the zeroth line of the current file".
Jefromi
@Jefromi: So the skeleton.sh in my case would just contain `#!/bin/bash` on the first line (if that's what I want in the file)? [I didn't know if that was something it pulled from automatically]
David Oneill
Also is there a way to customize it? By example, on a C header file named foo.h the skeleton should something like:/* ...License and stuff... */#ifndef __defined_foo_h#define __defined_foo_h#endifWhich depends on the file name.
Dacav
@David Oneill: It doesn't pull from it automatically. That's why you have to add this autocommand, telling it to read the contents of that file whenever you create a file named *.sh.
Jefromi
@Dacav: Clearly, with this approach, you're just reading the template in directly. If you want to do more, the answer depends on how you want to set it up. A very simple example would be to have the autocommand run: `0r ~/vim/skeleton.sh | %s/FILENAME/\=expand("%:h")/g` to read in the template, then substitute the actual filename (directories stripped) for FILENAME everywhere. For a very complex example (fancy templates) see bash-support-vim: http://www.vim.org/scripts/script.php?script_id=365
Jefromi
+1  A: 

Vim can do this for sure, and more than what you expect.

Please refer to the popular "bash-support" plugin :

http://www.vim.org/scripts/script.php?script_id=365

for details.

Zhaojun
Thanks for this link, I will check that out.
David Oneill