Z Space Blog

your source for Game Z

Counting Lines of Code in Vim

Vim is a wonderfully extensible text editor. I use it to work with all sorts of text. While I was browsing reddit, I saw a thread asking for a way to prevent :number from counting blank lines. I checked it out to see if there were any cool answers. None of what I saw were adequate. For instance, :%s/\S\+//n makes every match highlight, clobbering the last text that was searched for. I figured it was time for me to learn a little more about Vimscript, and so I wrote a function that will tell you how many actual lines of code are in your file:

" Count the number of source lines in a file
function! <SID>CountCodeLines()
    let code_count = 0
    for line in getbufline("%", 1, "$")
        if (len(line) > 0 && match(line, '\S\+') > -1)
            if (s:IsCommentLine(line) == 1)
                continue
            endif
            let code_count += 1
        endif
    endfor
    echo code_count . ' lines of code.'
endfunction

" To be used with CountCodeLines()
function! s:IsCommentLine(line)
    let l:comtypes = []
    let l:comlist = split(&comments, ',')
    for i in comlist
        let l:type = split(i, ':')
        if len(type) > 1
            let l:opt = type[1]
        else
            let l:opt = type[0]
        endif
        call add(comtypes, opt)
    endfor
    let i = 0
    while i < len(comtypes)
        if match(a:line, '^\s*' . escape(comtypes[i], '/*')) > -1
            return 1
        endif
        let i += 1
    endwhile
    return 0
endfunction

Put that in your ~/.vimrc or another similar location and have at it! I chose to map it to <leader>c with:

nnoremap <leader>c :call <SID>CountCodeLines()<CR>

I'm releasing these functions under the WTFPL to contribute another mini-feature to Vim and the free, open source software community. It was a fun (if slightly aggravating) exercise in Vimscript.