首页 > 解决方案 > 为 vim 编辑器定义默认文本

问题描述

我希望 vim 可以选择每当我用 vim 创建一个新的 c++ 文件时,它会自动在其中写入我的基本代码文本。如 :

#include<bits/stdc++.h>

using namespace std;
int main(){
}

请帮忙!对不起,因为我的英语不好

标签: vim

解决方案


Noah Frederick 写了一篇关于如何使用 ultisnips 创建“骨架”文件的优秀文章:

基本上,他的脚本检测文件何时创建并触发预定义的片段。当然,您还必须安装ultisnips

有人可能会问:为什么不创建文件模板并通过自动命令触发呢?答案很简单,ultisnips 解决方案允许您按需更改模板,它不仅仅是一个静态模板,您可以看到Noah 解释他的解决方案背后的想法。

"             File: ultisnips_custom.vim - Custom UltiSnips settings
"       Maintainer: Sergio Araújo
" Oririnal Creator: Noah Frederick
"        Reference: https://noahfrederick.com/log/vim-templates-with-ultisnips-and-projectionist
"      Last Change: out 11, 2020 - 17:18
"      Place it at: after/plugin/ultisnips_custom.vim

" We need python or python3 to run ultisnips
if !has("python") && !has("python3")
  finish
endif

" This function is called by the autocommand at the end of the file
function! TestAndLoadSkel() abort
  let filename = expand('%')
  " Abort on non-empty buffer or extant file
  if !(line('$') == 1 && getline('$') == '') || filereadable('%')
    return
  endif

  " Load UltiSnips in case it was deferred via vim-plug
  if !exists('g:did_plugin_ultisnips') && exists(':PlugStatus')
    call plug#load('ultisnips')
    doautocmd FileType
  endif

  " the function feedkys simulates the insert key sequence in order to call
  " the template (skel)
  execute 'call feedkeys("i_skel\<C-r>=UltiSnips#ExpandSnippet()\<CR>")'
endfunction
" remember to create a _skel snippet with your header for each file you
" want a autosnippet 

augroup ultisnips_custom
  autocmd!
  au Bufnewfile *.sh,*.zsh,*.html,*.css,*.py,*.tex,*.txt,*.md,*.vim :call TestAndLoadSkel()
augroup END

" vim: fdm=marker:sw=2:sts=2:et

推荐阅读