This article demonstrates a technique for automatically hiding license text that might appear at the start of a source file. This lets you concentrate on the important content and ignore repeated boilerplate text.

I have my MIT License text at the top of my (published) Java source files.

/*
Copyright (c) 2010 Geoff Lewis <gsl@gslsrc.net>

Permission is hereby granted, free of charge, to any person obtaining a copy
...
*/

package net.gslsrc.dmex.exercise;
...

This means I have 21 lines of comment text at the top of each file. Using my editor-of-choice, Vim, I can fold the license text to a single line by positioning on the start of the commented license (ie., first line of the file) and using the command zf]* which means “create a fold (zf) to the next comment close (]*)”.

Now I see instead:

+-- 21 lines: Copyright (c) 2010 Geoff Lewis <gsl@gslsrc.net>-------------------

package net.gslsrc.dmex.exercise;
...

I don’t want to have to manually fold the license comment each time. Instead I want Vim to fold it for me when I open a Java source file. I can use the following Vim script:

let s:line = getline(1)             " read the text of the first line
if s:line == "/*"                   " if the text matches comment open...
    let s:savepos = getpos(".")     " save the cursor position
    call cursor(1, 1)               " move to the first line & column
    execute "normal" "zf]*"         " execute the 'fold comment' command
    call setpos(".", s:savepos)     " restore the cursor position
endif

In my .vimrc file I use autocmd to load Vim settings for Java source files:

autocmd BufNewFile,BufReadPre   *.java source ~/.vim/java.vim

I can add my auto-fold script to this java.vim but I have java.vim set up to exit if it has already been sourced. So if I open multiple files simultaneously, only the first Java file will have its license comment folded. Instead I put my auto-fold script in a java-buffer.vim file and add an autocmd to load it. I can do this from my main java.vim file using:

autocmd BufEnter *.java source ~/.vim/java-buffer.vim

This java-buffer.vim script is now run any time I enter a buffer containing a Java source file. This means if I open (unfold) the comment (zo), leave the buffer, and come back, the comment will be closed again. I am happy with that (plus I can’t work out a way around it).