如何在使用vim创建新文件时自动添加一些样板代码

35

Vim创建新文件时,我希望能自动添加一些模板代码。

例如,创建新的xml文件时,我想添加第一行:

<?xml version="1.0" encoding="UTF-8"?>

  <?xml version="1.0"?>

或者在创建 HTML 文件时,我想要添加:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
  <head>
    <title></title>
  </head>
  <body>
  </body>
</html>
8个回答

29

我在我的 .vimrc 文件中有类似以下的内容:

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

诸如此类,无论你需要什么。


16

你可以将骨架/模板保存到一个文件中,例如~/vim/skeleton.xml

然后在你的.vimrc文件中添加以下内容:

augroup Xml
    au BufNewFile *.xml 0r ~/vim/skeleton.xml
augroup end

这里的 0r 是什么意思? - crisron
2
@crison 关于 0r 的含义。0 将插入位置定位到第一行,r 命令 vim 在插入位置读取文件内容。 - erichui
感谢您的解释。 - crisron

8

非常抱歉晚了,但我觉得我的方法可能对一些人有用。它使用文件类型,使其比传统方法更短、更动态。仅在Vim 7.3上进行过测试。

if has("win32") || has ('win64')
    let $VIMHOME = $HOME."/vimfiles/"
else
    let $VIMHOME = $HOME."/.vim/"
endif

" add templates in templates/ using filetype as file name
au BufNewFile * :silent! exec ":0r ".$VIMHOME."templates/".&ft

@orftz - 我刚刚用你的文件类型方法替换了我长期使用的配置。更加简洁。在此之后列出文件类型非常有用。在vim中,如果你执行:echo glob($VIMRUNTIME . '/ftplugin/*.vim')或者:echo glob($VIMRUNTIME . '/syntax/*.vim'),它会列出vim所知道的所有类型。 - J.Zimmerman

5
如果你想要根据上下文或用户选择来适应你的框架,请查看列在vim.wikia上的模板扩展插件。

1
这是两个使用Python脚本的例子。
在您的 .vimrc 文件或其他由 .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">', "<html>", "<head>", "  <title></title>", "</head>", "<body>", "", "</body>", "</html>"]
  python del vim
endfu

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

1

您可以在读取或创建文件时添加各种钩子。

:help event

阅读并理解其中的内容。你想要的是

:help BufNewFile

0

它也可以与snipmate一起使用:

augroup documentation
    au!
    au BufNewFile *.py :call ExecuteSnippet('docs')
augroup END

function! ExecuteSnippet(name)
    execute "normal! i" . a:name . "\<c-r>=TriggerSnippet()\<cr>"
endfunction

使用“docs”片段来触发。

它可以与多个片段一起使用,但是会出现“:messages”窗口,这很麻烦。


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接