Auto-folding D unit tests in vim

The last couple of weeks, I’ve been playing with D ( for a side project. One very nice feat is that unit tests can be written directly into the codebase. Inline unit testing allows for a lot less files to be written, and makes it easy to spot where a possible test has been overlooked. As such, having your unit tests immediately available in your source code file, can be a motivator for a more robust codebase.

However, there is a downside too: placing your unit tests inside your code feels clutterish. Navigating your code will without a doubt take a bit more time, as scrolling or jumping to snippet X or method Y will have you travel a greater vertical distance.

To improve readability, I wrote a small function in VimScript to autofold the unit tests, effectively reducting their vertical footprint to only one line:

function! DlangUnitTestFold(lnum)
    if getline(a:lnum) =~ '^\s*unittest\s{\s*$'
        return "a1"
    elseif getline(a:lnum) =~ '^\s*}\s*$'
        return "s1"
        return "="

When editing a D buffer, it suffices to set the fold method to foldexpr, calling the above mentioned function:

au BufNewFile,BufRead *.d setlocal
 \ foldexpr=DlangUnitTestFold(v:lnum)

Short explanation of the function:


You can find the code as a vim plugin on Github. To install, simply add it as a Vundle/Bundle package in your .vimrc. In Vim 8 you can also manually clone the git repository without having to fiddle with your .vimrc:

cd $HOME/.vim/pack/plugins/start
git clone