Jakub Wagner
Jakub Wagner

Reputation: 458

Automatic first line in vim

Is it possible to make vim write something on the first line (or on few first lines) automatically everytime when I create file with a specific extension?

For example (and this is only an example) if I create .txt file I would like vim to write "Hello" on the first line.

Is it possible? If it is, how?

Upvotes: 2

Views: 798

Answers (3)

SergioAraujo
SergioAraujo

Reputation: 11810

In my case, to bash files, I have this on my ~/.vimrc

augroup sh
  au BufNewFile *.sh 0r ~/.vim/skel/template.sh
 "au BufWritePost *.sh,*.pl,*.py,*.cgi :silent !chmod a+x <afile>
augroup end

If I create a new file "BufNewFile" vim opens at the line zero "0" by reading "r" the content of the file template.sh, on that file I can put wherever I want.

If I uncoment the seccond line removing the " at beginning I have also a change on file permission automatically

Upvotes: 0

SnoringFrog
SnoringFrog

Reputation: 1509

The docs give an idea of how to do this in :h skeleton. Essentially, you just need a BufNewFile autocommand in your .vimrc.

The docs assume you'll be reading your initial content from a file. So, for your example, assuming skeleton.txt contains the text "Hello":

autocmd BufNewFile *.txt 0r ~/vim/skeleton.txt

Alternatively, if your first line is relatively simple, you can always hardcode it by just entering insert mode and adding the text you need.

au BufNewFile *.txt normal iHello

This answer from vi.stackexchange provides a couple examples that call functions and are a bit more complex.

Upvotes: 3

DJMcMayhem
DJMcMayhem

Reputation: 7679

Yes, you can achieve this with autocommands. The general structure of an autocommand is

au event filetype command

In your specific case, you want

au BufNewFile *.txt normal iHello

Explanation:

au            "Define a new autocommand
BufNewFile    "When you create a new file
*.txt         "With the extension '.txt'
normal iHello "Execute the command 'normal iHello', which is like typing 'iHello' manually

Upvotes: 5

Related Questions