代码之家  ›  专栏  ›  技术社区  ›  Yedhin

如何将模板代码自动插入到在特定目录中创建的具有特定扩展名的新文件中?

  •  0
  • Yedhin  · 技术社区  · 6 年前

    我有一个项目目录在 ~/project . 在这个项目目录下也有许多子目录。我试图做的是,每当我创建一个C++文件(这意味着在特定目录中带有扩展名.cc,.cp,.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  
    

    如何有效地添加检查在我的 ~/项目 目录或其子目录中的任何一个,用C++文件的扩展并插入上面的模板,带有特定的日期和格式?另外,如何只在创建新文件而不是现有文件时插入它?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Ralf    6 年前

    首先:有模板插件,你应该在网上搜索“vim模板插件”。也许你会发现一些有用的东西。

    如果你想自己动手:

    创建这样的模板文件(我想 ~/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