bardia nasiri
bardia nasiri

Reputation: 5

define default text for vim editor

I want vim to have the option that whenever I make a new c++ file with vim , it writes my base code text in it automatically . such as :

#include<bits/stdc++.h>

using namespace std;
int main(){
}

please help! sorry because of my bad English

Upvotes: 0

Views: 535

Answers (2)

SergioAraujo
SergioAraujo

Reputation: 11830

Noah Frederick wrote an excellent article on how to use ultisnips to create "skeleton" files:

Basically, his script detects when a file is created and triggers a pre defined snippet. Of course you have also to install ultisnips.

Someone could ask: Why do not create a file template and trigger it via autocommands? The answer is simple, the ultisnips solution allows you to change your template on demand, it is no just a static template and you can see Noah explaining the ideas behind his solution.

"             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

Upvotes: 2

Jens
Jens

Reputation: 72756

Just save that file as a vim template to $HOME/.vim/templates/cc.tpl. Whenver you edit a new file named foo.cc -- voilà!

Upvotes: 1

Related Questions