Howto add license to sourcefiles automatically(vi)ΒΆ

Updated: May 07, 2024

Hi guys,

After 2 hours of learning, I finally wrote a .vimrc file which will add contents of my license file. Here is my license file file,

/*
* <currentfilename>
* Copyright (C) <date> Mohan Raman
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*
*/

and here is my .vimrc file

" Set column to 80
set columns=80

" Insert License

let licensefile = $HOME."/Development/License/GPL_v2.txt"
let currentfile = expand("%")

if filereadable(licensefile)

     let license = system("grep Copyright ".currentfile)

     if(!len(license))

             execute "0r ".licensefile

             let startline = 1
             let endline = system("wc -l ".licensefile." | tr -s ' ' | cut -d' ' -f1")
             let endline = substitute(endline,"\n","","g")
             let linerange = startline.",".endline

             let command = linerange."s/<currentfilename>/".currentfile."/g"
             execute command

             let currentyear = strftime("%Y")
             let command = linerange."s/<date>/".currentyear."/g"
             execute command

     endif
endif

First it will set column to 80. Then It will search for license file. If the file present, then It will check whether the present file already contains Copyright line or not. If the present fine contains Copyright, then it will not do anything, else, it will read the license file contents into the current file.

It also adds the filename and the current year automatically. Hope this small .vimrc will fit into your needs.

Screenshot of my newfile.c file which is processed by new .vimrc

../../_images/vi_autolicense.png