≡ Menu

Vi and Vim Autocommand: 3 Steps to Add Custom Header To Your File Automatically

Vim Editor LogoThis is a guest post written by Lakshmanan G.

This article is part of the ongoing Vi / Vim Tips & Tricks series. Using autocommand feature in Vi / Vim, you can specify some Vim commands to be executed automatically while reading or writing a file, or while entering/leaving a buffer/window, or while exiting Vim.

In this article, using 3 simple steps, let us review how to use this powerful autocmd feature of Vim to create a header section inside a file (for example, header in a C programming code) with file name, creation date, last modified date/time automatically populated when you open a file in vi.

Vim autocmd syntax:

autocmd  {event} {pattern} {cmd}


Events: There are more than 40 autocmd events. Following are few sample autocmd events.

BufNewFile	- Starting to edit a file that doesn't exist.
FileReadPre	- Before reading a file with a ":read" command.
BufWritePre	- Starting to write the whole buffer to a file.
FileWritePre	- Starting to write part of a buffer to a file.
BufDelete	- Before deleting a buffer from the buffer list.
BufWipeout	- Before completely deleting a buffer.
BufNew	- Just after creating a new buffer.
BufEnter	- After entering a buffer.
BufLeave	- Before leaving to another buffer.
SwapExists	- Detected an existing swap file.


Most of the developers want some default header for their programs. Lets take an example. When opening a “.c” file, you need a file header which has author, filename etc.. Consider that I need the following template to be loaded automatically while opening a new “.c” file. You can achieve this in three steps as mentioned below.

/* -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.

* File Name : 1.c

* Purpose :

* Creation Date : 22-12-2008

* Last Modified : Mon 22 Dec 2008 10:36:49 PM PST

* Created By :  

_._._._._._._._._._._._._._._._._._._._._.*/

Step 1: Create a template file

Save the above template in a text file with “:insert” in the first line, followed by the template and a “.”(dot) in the last line as shown below.

$ cat c_header.txt
:insert
/* -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.

* File Name :

* Purpose :

* Creation Date :

* Last Modified :

* Created By :  

_._._._._._._._._._._._._._._._._._._._._.*/
.

Step 2: Add autocmd commands to ~/.vimrc

Add the following lines in the ~/.vimrc file.

$ cat ~/.vimrc
autocmd bufnewfile *.c so /home/jsmith/c_header.txt
autocmd bufnewfile *.c exe "1," . 10 . "g/File Name :.*/s//File Name : " .expand("%")
autocmd bufnewfile *.c exe "1," . 10 . "g/Creation Date :.*/s//Creation Date : " .strftime("%d-%m-%Y")
autocmd Bufwritepre,filewritepre *.c execute "normal ma"
autocmd Bufwritepre,filewritepre *.c exe "1," . 10 . "g/Last Modified :.*/s/Last Modified :.*/Last Modified : " .strftime("%c")
autocmd bufwritepost,filewritepost *.c execute "normal `a"

Step 3: Create a new *.c file with automatic header

Now, when you create a new *.c file using vim, this will automatically add the header defined in the Step1 and populate the File Name and Creation Date automatically as shown below.

$ vi myfile.c
/* -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.

* File Name : myfile.c

* Purpose :

* Creation Date : 20-12-2008

* Last Modified :

* Created By :

_._._._._._._._._._._._._._._._._._._._._.*/


When you save the myfile.c file, it will automatically update the Last Modified field accordingly as shown below.

$ vi myfile.c
/* -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.

* File Name : myfile.c

* Purpose :

* Creation Date : 20-12-2008

* Last Modified : Sat 20 Dec 2008 09:37:30 AM PST

* Created By :

_._._._._._._._._._._._._._._._._._._._._.*/

Explanation of the autocmd commands inside ~/.vimrc

$ cat -n ~/.vimrc
     1  autocmd bufnewfile *.c so /home/jsmith/c_header.txt
     2  autocmd bufnewfile *.c exe "1," . 10 . "g/File Name :.*/s//File Name : " .expand("%")
     3  autocmd bufnewfile *.c exe "1," . 10 . "g/Creation Date :.*/s//Creation Date : " .strftime("%d-%m-%Y")
     4  autocmd Bufwritepre,filewritepre *.c execute "normal ma"

     5  autocmd Bufwritepre,filewritepre *.c exe "1," . 10 . "g/Last Modified :.*/s/Last Modified :.*/Last Modified : " .strftime("%c")
     6  autocmd bufwritepost,filewritepost *.c execute "normal `a"

  • Line 1 defines the template file. This indicates that for *.c file, /home/jsmith/c_header.txt template file should be used.
  • Line 2 will search for the pattern “File Name :” from the 1st line to 10th line. If found, it will write the current filename in that line.
  • Line 3 will update the Creation Date field.
  • Line 5 will update the Last Modified field with the current date and time when you save the file.
  • Line 4 & 6: While saving the file, the cursor will move to the “Last modified :” (because of last write operation). If you want the cursor back to the previous position then, you need to add Line 4 and 6 to the .vimrc file.
  • Line 4 will mark the current cursor position before updating.
  • Line 6 will restore the cursor position back to its previous position.

Final Note:

  • Verify whether autocmd is enabled in Vi / Vim – Execute :version from vi / vim. If autocommand feature is enabled, it will display +autocmd.
  • Autocommand help – Execute :help au from vi / vim, to get quick help on vim autocmd features.

Recommended Reading

Learning the Vi and Vim Editors, by Arnold Robbins. I’m a command-line junkie. So, naturally I’m a huge fan of Vi and Vim editors. Several years back, when I wrote lot of C code on Linux, I used to carry the Vi editor pocket reference with me all the times. Even if you’ve been using Vi and Vim Editors for several years and have not read this book, please do yourself a favor and read this book. You’ll be amazed with the capabilities of Vim editor.

 


This article is part of the ongoing Vi / Vim Tips and Tricks series. Please subscribe to TheGeekStuff and don’t miss any future Vi and Vim editor tips and tricks.


This article was written by Lakshmanan G. He is working in bk Systems (p) Ltd, and interested in contributing to the open source. The Geek Stuff welcomes your tips and guest articles.

Add your comment

If you enjoyed this article, you might also like..

  1. 50 Linux Sysadmin Tutorials
  2. 50 Most Frequently Used Linux Commands (With Examples)
  3. Top 25 Best Linux Performance Monitoring and Debugging Tools
  4. Mommy, I found it! – 15 Practical Linux Find Command Examples
  5. Linux 101 Hacks 2nd Edition eBook Linux 101 Hacks Book

Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book

Comments on this entry are closed.

  • N.Abubacker December 25, 2008, 10:05 pm

    This article is very interesting as well as very useful
    the step by step approach is appreciable.
    it will avoid the usage of plugin where the minimal c usage is there.

  • SathiyaMoorthy December 29, 2008, 6:32 am

    Nice Article.,

    This knowledge is the basic for writing templates for the routine works., which makes the daily task’s simpler.

    And also this, pre-requisite knowledge required for writing a VIM plugin.

  • byguess March 1, 2013, 5:38 am

    You have lost a ‘/’ in line 5. It should be like that “g/Last Modified :.*/s//Last Modified : ”
    And the number should be 1 and 7, not 10. Otherwise, the vim will show you an error!
    Thanks for this passage. It’s really a good one anyhow!

  • Anonymous March 30, 2016, 6:45 am

    Thanks for the article. Was usefull

  • Anonymous March 6, 2017, 1:00 pm

    Awesome, thank you