Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/vim/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Templates 打开具有特定扩展名的新文件时的默认文本(例如:.cpp)_Templates_Vim_Atom Editor - Fatal编程技术网

Templates 打开具有特定扩展名的新文件时的默认文本(例如:.cpp)

Templates 打开具有特定扩展名的新文件时的默认文本(例如:.cpp),templates,vim,atom-editor,Templates,Vim,Atom Editor,我想要一些默认文本,如: #include <iostream> using namespace std; int main() { // code return 0; } #包括 使用名称空间std; int main() { //代码 返回0; } 在Vim或Atom中打开.cpp文件时出现。我在各种论坛上搜索了很多,但除了Visual Studio之外,没有找到答案,但Vim或Atom没有找到答案。Vim有多个事件,我们可以在这些事件中发现是否创建了新文件或打开

我想要一些默认文本,如:

#include <iostream>
using namespace std;
int main()
{
   // code
   return 0;
}
#包括
使用名称空间std;
int main()
{
//代码
返回0;
}

在Vim或Atom中打开
.cpp
文件时出现。我在各种论坛上搜索了很多,但除了Visual Studio之外,没有找到答案,但Vim或Atom没有找到答案。

Vim有多个事件,我们可以在这些事件中发现是否创建了新文件或打开了文件:

if has("autocmd")   
    au BufNewFile,BufRead *.cpp "Do something
endif
我们要检查打开的文件是否为空,检查文件是否具有文件系统位置,让我们将其放入函数中,以便更易于读取:

function! EmptyFile()
    if (line('$') == 1 && getline(1) == '')
        "Do something
    endif
endfunction
我们要做的最后一件事是基于现有文件插入一些模板:

function! LoadTemplate(template)
    let fl = readfile(template)
    call append('', fl)
endfunction
现在,将所有内容放在一起(您应该将其添加到
.vimrc
):


这假设您在Vim可以找到的文件夹中有文件。

这就是代码片段的用途。使用代码段插件,例如。您还需要一组代码片段,例如。

您可能需要阅读@Bo Persson。。谢谢你的链接。。。。更新的hanks,这很有帮助。尽管我遇到了一个问题……如果我将cpp模板放在某个文件夹(比如home)中,那么在打开另一个文件夹中的.cpp文件时,我将无法访问该模板,除非我在该文件夹中复制粘贴相同的模板尝试使用
BufRead,BufNewFile
<无论何时切换缓冲区,都会调用code>BufEnter,这绝对不是您想要的。编辑:通过在readfile中使用glob命令并在AddEmptyTemplate()函数中不保留任何参数,问题得到了解决。虽然这消除了功能的多功能性,但它修复了无法在不同文件夹中打开模板的问题
function! AddEmptyTemplate(template)
    if (line('$') == 1 && getline(1) == '')
        let fl = readfile(a:template)
        call append('', fl)
    endif
endfunction

if has("autocmd")   
    au BufNewFile,BufRead *.cpp call AddEmptyTemplate("cpp-template.cpp")
    au BufNewFile,BufRead *.c call AddEmptyTemplate("c-template.c")
endif