views:

902

answers:

5

When creating a new file with vim, I would like to automatically add some skeleton code.

For example, when creating a new xml file, I would like to add the first line:

  <?xml version="1.0"?>

Or when creating an html file, I would like to add:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;
<html>
  <head>
    <title></title>
  </head>
  <body>
  </body>
</html>
+1  A: 

Here are two examples using python scripting.

Add something like this in your .vimrc or another file sourced by your .vimrc:

augroup Xml
  au BufNewFile *.xml :python import vim
  au BufNewFile *.xml :python vim.current.buffer[0:0] = ['<?xml version="1.0"?>']
  au BufNewFile *.xml :python del vim
augroup END

fu s:InsertHtmlSkeleton()
  python import vim
  python vim.current.buffer[0:0] = ['<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;', "<html>", "<head>", "  <title></title>", "</head>", "<body>", "", "</body>", "</html>"]
  python del vim
endfu

augroup Html
  au BufNewFile *.html call <SID>InsertHtmlSkeleton()
augroup END
Oli
A: 

You can add various hooks when files are read or created. to

:help event

and read what's there. What you want is

:help BufNewFile
davetron5000
+10  A: 

I got something like this in my .vimrc:

au BufNewFile *.xml 0r ~/.vim/xml.skel | let IndentStyle = "xml"
au BufNewFile *.html 0r ~/.vim/html.skel | let IndentStyle = "html"

And so on, whatever you'll need.

kender
+7  A: 

You can save your skeleton/template to a file, for example ~/vim/skeleton.xml

Then add the following to your .vimrc

augroup Xml
    au BufNewFile *.xml 0r ~/vim/skeleton.xml
augroup end
erichui
+4  A: 

If you want to adapt your skeleton to the context, or to the user choices, have a look at the template-expander plugins listed on vim.wikia

HTH,

Luc Hermitte