如何将模板代码自动插入到在特定目录中创建的具有特定扩展名的新文件中?
How to auto insert a template code into a new file of particular extension, that is created in a particular directory?
我在 ~/project
有一个项目目录。在这个项目目录下也有很多子目录。我试图做的是,每当我在特定目录中创建一个 c++ 文件(这意味着扩展名为 .cc、.cpp、.h 等的文件)时,自动将某些代码模板插入到该文件中。
模板为给定形式:
/*
* Author : Name
* Date : Sat Jan 19 12:42:56 IST 2019 (:r!date)
*/
通常日期是该文件的创建日期,可以使用 :r!date
插入。
到目前为止,我的想法是创建一个 template.vim
文件,其中包含以下内容:
call setline(1, '/*')
call setline(2, 'Author : ')
" the line below is a blunder. but i hope you get the gist of what im trying.
call setline(3, 'Date : '+ execute "normal! :r!date")
call setline(4, '*/')
然后直到在创建新的 c++ 文件时获取模板文件,如下所示:
autocmd BufNewFile *.cc,*.cpp,*.h source ~/.vim/ftplugin/template.vim
我如何有效地添加条件以检查我的 ~/project 目录或其任何子目录中文件的创建,扩展名为 c++ 文件并插入上面的模板有具体的日期和格式吗?另外如何仅在创建新文件而不是现有文件时插入它?
首先:模板插件是有的,你去网上搜一下"vim template plugin"。也许你会发现一些有用的东西。
如果你想自己做:
像这样创建模板文件(我假设 ~/tmpl/tmpl.cpp
作为名称):
/*
* Author : <<name>>
* Date : <<date>>
*/
在你的 vimrc 中:
function AddTemplate(tmpl_file)
exe "0read " . a:tmpl_file
let substDict = {}
let substDict["name"] = $USER
let substDict["date"] = strftime("%Y %b %d %X")
exe '%s/<<\([^>]*\)>>/\=substDict[submatch(1)]/g'
set nomodified
normal G
endfunction
autocmd BufNewFile *.c,*.cc,*.cpp,*.h call AddTemplate("~/tmpl/tmpl.cpp")
set nomodified
告诉 Vim 该文件未被修改。这样,只要不添加其他文本,您就可以使用 :q
退出文件。如果您输入了错误的文件名,这很有用。
如果只想对特殊目录~/project
中的文件进行操作,可以在函数的开头添加以下内容AddTemplate
:
let fully_qualified_file = expand('%:p')
if 0 != match(fully_qualified_file, $HOME . '/project/.*')
return
endif
我在 ~/project
有一个项目目录。在这个项目目录下也有很多子目录。我试图做的是,每当我在特定目录中创建一个 c++ 文件(这意味着扩展名为 .cc、.cpp、.h 等的文件)时,自动将某些代码模板插入到该文件中。
模板为给定形式:
/*
* Author : Name
* Date : Sat Jan 19 12:42:56 IST 2019 (:r!date)
*/
通常日期是该文件的创建日期,可以使用 :r!date
插入。
到目前为止,我的想法是创建一个 template.vim
文件,其中包含以下内容:
call setline(1, '/*')
call setline(2, 'Author : ')
" the line below is a blunder. but i hope you get the gist of what im trying.
call setline(3, 'Date : '+ execute "normal! :r!date")
call setline(4, '*/')
然后直到在创建新的 c++ 文件时获取模板文件,如下所示:
autocmd BufNewFile *.cc,*.cpp,*.h source ~/.vim/ftplugin/template.vim
我如何有效地添加条件以检查我的 ~/project 目录或其任何子目录中文件的创建,扩展名为 c++ 文件并插入上面的模板有具体的日期和格式吗?另外如何仅在创建新文件而不是现有文件时插入它?
首先:模板插件是有的,你去网上搜一下"vim template plugin"。也许你会发现一些有用的东西。
如果你想自己做:
像这样创建模板文件(我假设 ~/tmpl/tmpl.cpp
作为名称):
/*
* Author : <<name>>
* Date : <<date>>
*/
在你的 vimrc 中:
function AddTemplate(tmpl_file)
exe "0read " . a:tmpl_file
let substDict = {}
let substDict["name"] = $USER
let substDict["date"] = strftime("%Y %b %d %X")
exe '%s/<<\([^>]*\)>>/\=substDict[submatch(1)]/g'
set nomodified
normal G
endfunction
autocmd BufNewFile *.c,*.cc,*.cpp,*.h call AddTemplate("~/tmpl/tmpl.cpp")
set nomodified
告诉 Vim 该文件未被修改。这样,只要不添加其他文本,您就可以使用 :q
退出文件。如果您输入了错误的文件名,这很有用。
如果只想对特殊目录~/project
中的文件进行操作,可以在函数的开头添加以下内容AddTemplate
:
let fully_qualified_file = expand('%:p')
if 0 != match(fully_qualified_file, $HOME . '/project/.*')
return
endif